pub use super::agy_window::project;
use super::agy_window::{self, Call};
use super::stage::{self, output_of, record_of, text};
use crate::conversation::Error;
use crate::profile::model::Capture;
use crate::record::land::{Landed, discard, land as file, only};
use crate::record::payload::{
PROMPT_EVENT, Payload, Record, SESSION_START_EVENT, STOP_EVENT, TOOL_EVENT,
};
use crate::record::settings::Settings;
use crate::record::spool::Spool;
use crate::store::grammar::Actor;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::io::{self, Write};
use std::path::PathBuf;
const IGNORED: &str = "AgyCallback";
const GAP: &str = "neosian: this Antigravity turn is not recorded";
pub fn payload(mut raw: Payload) -> Payload {
let event = text(&raw, "hookEventName");
let first = raw.get("invocationNum").and_then(Value::as_u64) == Some(0);
let mapped = match event.as_str() {
"SessionStart" => SESSION_START_EVENT,
"PreInvocation" if first => PROMPT_EVENT,
"PostToolUse" => TOOL_EVENT,
"Stop" => STOP_EVENT,
_ => IGNORED,
};
let call = raw.get("toolCall").cloned().unwrap_or(Value::Null);
let pairs = [
("session_id", raw.get("conversationId").cloned()),
("hook_event_name", Some(json!(mapped))),
("prompt", Some(json!(text(&raw, "lastUserInput")))),
("tool_use_id", call.get("id").cloned()),
("tool_name", call.get("name").cloned()),
("tool_input", call.get("args").cloned()),
("tool_response", Some(json!(""))),
("last_assistant_message", Some(json!(""))),
];
for (key, value) in pairs {
raw.insert(key.into(), value.unwrap_or(Value::Null));
}
raw
}
#[derive(Default, Serialize, Deserialize)]
struct Stage {
generation: Option<u64>,
digest: String,
length: usize,
pending: Option<Record>,
closing: bool,
closed: bool,
calls: Vec<Call>,
}
fn digest(prompt: &str) -> String {
crate::clients::receipt::sha256(prompt.trim().as_bytes())
}
fn gap(err: &mut dyn Write, reason: &str) -> Landed {
let _ = writeln!(err, "{GAP}: {reason}");
only("not_recorded")
}
struct Here<'a> {
settings: &'a Settings,
spool: &'a Spool,
id: &'a str,
actor: &'a Actor,
payload: &'a Payload,
policy: Option<&'a Capture>,
path: PathBuf,
}
impl Here<'_> {
fn save(&self, stage: &Stage) -> io::Result<bool> {
stage::save(self.settings, self.id, &self.path, stage)
}
fn end(&self, stage: &mut Stage) -> io::Result<()> {
*stage = Stage {
generation: stage.generation,
closed: true,
..Stage::default()
};
self.save(stage).map(|_| ())
}
fn file(&self, event: &str, record: &Record) -> Result<Landed, Error> {
file(
self.settings,
self.spool,
self.id,
self.actor,
event,
record,
)
}
fn prompt(&self, stage: &mut Stage) -> Result<Option<Landed>, Error> {
let Some(record) = stage.pending.clone() else {
return Ok(None);
};
let landed = if stage::holds(self.spool, self.id, "prompt", None)? {
None
} else {
Some(self.file(PROMPT_EVENT, &record)?)
};
stage.pending = None;
self.save(stage)?;
Ok(landed)
}
}
pub fn land(
settings: &Settings,
spool: &Spool,
(id, actor, event, payload): (&str, &Actor, &str, &Payload),
policy: Option<&Capture>,
err: &mut dyn Write,
) -> Result<Landed, Error> {
let path = stage::file(settings, id, "agy");
let here = Here {
settings,
spool,
id,
actor,
payload,
policy,
path,
};
let mut stage: Stage = stage::load(&here.path);
let open = stage.generation.is_some() && !stage.closed;
match event {
PROMPT_EVENT => {
let count = payload.get("initialNumSteps").and_then(Value::as_u64);
let Some(generation) = count.filter(|n| *n > 0) else {
return Ok(gap(err, "the first model call names no step count"));
};
if stage.generation == Some(generation) {
return Ok(here
.prompt(&mut stage)?
.unwrap_or_else(|| only("duplicate")));
}
if spool.file(id).try_exists()? {
spool.clear(id)?;
let _ = writeln!(err, "{GAP}: the earlier turn did not complete");
}
let prompt = text(payload, "prompt");
stage = Stage {
generation: Some(generation),
digest: digest(&prompt),
length: prompt.trim().chars().count(),
pending: record_of(payload, policy),
..Stage::default()
};
if !here.save(&stage)? {
return Ok(gap(err, "the keep limit left no room for the turn"));
}
Ok(here.prompt(&mut stage)?.unwrap_or_else(|| only("excluded")))
}
TOOL_EVENT => {
if !open || stage.closing {
return Ok(gap(err, "a tool call came outside an open turn"));
}
here.prompt(&mut stage)?;
let step = payload
.get("stepIdx")
.and_then(Value::as_u64)
.unwrap_or(u64::MAX);
if stage.calls.iter().any(|c| c.step == step) {
return Ok(only("duplicate"));
}
let call = match record_of(payload, policy) {
Some(record) => Call {
id: text(&record, "id"),
name: text(&record, "name"),
args: record.get("input").cloned().unwrap_or(Value::Null),
step,
error: output_of(&text(payload, "error"), policy),
kept: true,
},
None => Call {
step,
..Call::default()
},
};
stage.calls.push(call);
if !here.save(&stage)? {
discard(settings, spool, id)?;
here.end(&mut stage)?;
return Ok(gap(err, "the keep limit left no room for the turn"));
}
Ok(only("staged"))
}
STOP_EVENT if !open => Ok(only("duplicate")),
STOP_EVENT => stop(&here, stage, err),
_ => Ok(only("ignored")),
}
}
fn stop(here: &Here, mut stage: Stage, err: &mut dyn Write) -> Result<Landed, Error> {
let generation = stage.generation.expect("an open generation");
here.prompt(&mut stage)?;
let resumed = stage.closing;
if resumed && !here.spool.file(here.id).try_exists()? {
here.end(&mut stage)?;
return Ok(only("duplicate"));
}
let native = text(here.payload, "session_id");
let home = std::env::home_dir().ok_or_else(|| io::Error::other("no home directory"))?;
let (want, length) = (stage.digest.clone(), stage.length);
let verify = |request: &str| request.chars().count() == length && digest(request) == want;
let read = match agy_window::not_terminal(here.payload) {
Some(why) => Err(why),
None => agy_window::read(
&home,
&native,
&text(here.payload, "transcriptPath"),
generation - 1,
&verify,
&stage.calls,
),
};
let turn = match read {
Ok(turn) => turn,
Err(reason) => {
discard(here.settings, here.spool, here.id)?;
here.end(&mut stage)?;
return Ok(gap(err, &reason));
}
};
stage.closing = true;
here.save(&stage)?;
for (call, output) in stage.calls.iter().zip(turn.outputs) {
if !call.kept || (resumed && stage::holds(here.spool, here.id, "tool", Some(&call.id))?) {
continue;
}
let record = json!({"kind": "tool", "id": call.id, "name": call.name,
"input": call.args, "response": output_of(&output, here.policy)});
here.file(TOOL_EVENT, record.as_object().expect("an object"))?;
}
let end = json!({"hook_event_name": STOP_EVENT, "session_id": native,
"last_assistant_message": turn.answer, "status": "completed"});
let record = record_of(end.as_object().expect("object"), here.policy)
.ok_or_else(|| io::Error::other("a stop always reduces"))?;
let landed = here.file(STOP_EVENT, &record)?;
here.end(&mut stage)?;
Ok(landed)
}