@coda-console/antigravity 1.4.1 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,9 +1,9 @@
1
1
  # Antigravity
2
2
 
3
3
  把 [Google Antigravity](https://antigravity.google/cli) 的 Agent 接进 Coda。清单经一个薄转发入口(`agent/entry.mjs`)启动运行机上的 `agy acp`(Antigravity CLI 的 ACP 服务),
4
- 先找 `~/.local/bin/agy`,没有再用 PATH。每个会话一个进程,不登记等待项。
4
+ 先找 `~/.local/bin/agy`,没有再用 PATH。每个会话一个进程。
5
5
 
6
- 入口改四处,其余消息原样双向转发。第一处:把 `initialize` 答复里的 `additionalDirectories` 能力去掉,Coda 就不再给它传附加目录;
6
+ 入口改六处,其余消息原样双向转发。第一处:把 `initialize` 答复里的 `additionalDirectories` 能力去掉,Coda 就不再给它传附加目录;
7
7
  `session/new`、`session/load`、`session/resume` 里若仍带 `additionalDirectories` 也删掉。原因:agy 1.5.9 收到附加目录后,
8
8
  没给 Cwd 的命令默认跑在**字典序最前的附加根**,而不是会话的工作副本(实测规律,不是上游的保证;数组顺序、`session/load` 都不改变它);
9
9
  不传附加目录时命令就在工作副本里跑。
@@ -12,7 +12,12 @@
12
12
  带探测标记的 `session/new` 由入口用本机的目录缓存应答,不转给 agy,见「已知限制」的「配置探测」。
13
13
  第四处:agy 内部重试模型请求时会发一条 `agent_message_chunk`,整段文本形如 `⚠ API error (attempt 1): request failed: stream idle timeout (5m0s): context deadline exceeded`,
14
14
  Coda 会把它存成回复正文,像答到一半出错,其实这一轮还在跑。入口不转发这一种(整段去掉首尾空白后恰为单行此格式),原文写到插件自己的 stderr;
15
- 多行或夹在正文里的同样字样照常转发。最终失败怎样结束这一轮未查到实例,入口不改它(不改报 `session/prompt` 错误)。
15
+ 多行或夹在正文里的同样字样照常转发。重试用尽后最终失败的那一轮怎样结束,由第六处按会话记录判断,不由这条提示判断。
16
+
17
+ 第五处:agy 把跑得久的命令转到后台,ACP 上看不出来;入口只读 agy 自己的会话记录,把它们作为 `_coda/wait` 后台任务报给 Coda,见「已知限制」的「后台命令」。
18
+ agy 起的子 Agent 也同样只读它自己的文件,报成 `kind: subagent` 的 `_coda/wait`,见「已知限制」的「子 Agent」。
19
+
20
+ 第六处:agy 有时在上游模型请求最终失败后仍回 `end_turn`,ACP 上看起来像正常结束;入口只读会话记录,这一轮在 ACP 上没出过任何回复文字或成功的工具结果、且记录最后一步是上游错误时,才把这一轮改以错误结束,拿不准一律照转 `end_turn`,见「已知限制」的「隐藏的失败」。
16
21
 
17
22
  需要带会话指令兜底的 Coda(2026-11-13 部署版,coda#2500)或更新版本;旧版 Coda 不会给 Antigravity 送入会话指令。
18
23
 
@@ -80,13 +85,16 @@ Coda 会把它存成回复正文,像答到一半出错,其实这一轮还在
80
85
  | 会话指令 | Antigravity 只认私有的 `_meta.antigravity.systemPrompt`,不认 ACP 标准字段;插件不处理它,由 Coda 把指令作为单独一段放在新会话第一次非斜杠命令的用户输入前面,分量不如系统提示词 |
81
86
  | 插话 | 不声明:Antigravity 的原生插话会提前结束旧一轮的回复,由 Coda 停下这一轮再发出新消息 |
82
87
  | 额度的口径 | 报告按模型组给额度:同组模型共享每周与 5 小时限额,不是每个模型各算一份;报告里没有套餐名。第一次在某个目录运行 `/usage` 时,CLI 会在 `implicit/` 下留一个小文件;插件固定在系统临时目录运行,之后复用,不新增会话与项目记录 |
83
- | 等待项登记 `_coda/wait` | 不登记,会话底部不列它在等什么 |
88
+ | 后台命令 `_coda/wait` | agy 的 `run_command` 等 `WaitMsBeforeAsync` 毫秒后把命令转后台:ACP 上那张 execute 卡一直 `in_progress`、没有内容,agy 1.5.15 的 ACP 没有任何后台提示(文字或字段)。入口在 Coda 声明 `_meta.coda.waits` 时,对有未结束 execute 调用的会话每秒只读追加读 `~/.gemini/antigravity-cli/brain/<会话>/.system_generated/logs/transcript.jsonl`(从该会话第一次出现 execute 调用时的文件末尾起,更早的不看),按下面两种记录登记与结案,其余不碰。**开始**:状态 `RUNNING` 的步骤,正文 `Tool is running as a background task with task id: <会话>/task-N` 与 `Task Description: <命令>`(任务号不是 ACP 的 `toolCallId`);按命令对到仍未结束的 execute 调用:命令与描述完全相同;只有步骤带 `<truncated N bytes>` 标记(超长步骤的中段被 agy 换掉)时,才用命令的首尾分别对上标记前后两段;符合的调用不是恰好一个(没有,或同样的命令并发了几个)就不登记,保持纯 ACP。报 `waiting`:`waitId` 是任务号,`toolCallId` 是那次调用,标题是 agy 给的 `toolSummary`(没有就用命令首行),说明是命令,`outputFile` 是步骤里 `Task logs are available at:` 给的日志(步骤里没有就按目录布局推出 `.system_generated/tasks/task-N.log`),文件不存在就不带。**结束**:`SYSTEM` 步骤里 `Task id "…" finished with result:`(其后第一处 `Command exited with code N.` 非 0 报 `failed`,否则 `done`)或 `was canceled with result:`(`cancelled`);那次调用的 ACP 更新先到也算,按 `rawOutput.exit_code` 判:0 或没有(`completed`)报 `done`,-1(agy 取消命令的样子)报 `cancelled`,其他非 0,或 `failed`,报 `failed`;谁先到算谁,终态只报一次,ACP 更新引起的报在那张卡自己的更新之后。命令带 `IsDaemon: true`(常驻进程)的报 `awaited: false`:显示,但不挡调用完成与会话静止;其余按要等的。原来那张 execute 卡照 agy 报的样子留着,入口不替它编结果:Coda 对带 `toolCallId` 的后台任务把那张卡显示为「已转入后台」,不收束成结果未确认,工具卡本身也不挡静止(Coda 的 docs/session-contracts.md「会话静止」)。`session/close`、或 agy 进程自己退出(不是 Coda 停它)时还没结案的报 `cancelled`。读不到文件、路径不存在、不是 JSON 或格式不认识、读失败都安静地退回纯 ACP 转发,不写 stdout、不影响会话;入口只读这个文件(和下面「子 Agent」的 JSON),不读 agy 的 SQLite。不报 `handling`(任务结束后 agy 自己唤醒模型续说,入口分不清那是哪一轮);不声明 `stoppable`(ACP 没有停单个后台任务的方法,只能停这一轮,agy 取消命令后经 ACP 更新结案)。**会漏判**:Coda 没声明 `_meta.coda.waits`;会话记录不在 `~/.gemini/antigravity-cli/brain/` 下,或 agy 换了这两种记录的文字、字段;转后台时那次 ACP 调用的命令与记录里的描述对不上(改写过,或中段被截断后首尾太短认不出);入口启动前已在后台的任务(`session/load` 恢复的旧任务不登记);转后台的不是 `execute` 调用(`schedule`;子 Agent 见「子 Agent `_coda/wait`」一行);入口先于结案通知退出的任务(报 `cancelled`,不是真实结果)。记录只有 1.5.15 的样本;agy 升级后格式变了,表现是漏判,不是出错 |
89
+ | 隐藏的失败 | agy 的上游模型请求最终失败(容量、超时、断连……)时,ACP 仍可能回 `stopReason: end_turn`,Coda 看到的是一轮正常结束、没有回复。入口在 Coda 声明 `_meta.coda.waits` 与否都生效:每个 `session/prompt` 发给 agy 前记下会话记录(同上的 `transcript.jsonl`)的末尾,agy 回 `end_turn` 时读这之后新增的步骤,**最后一步**是 `source: SYSTEM`、`type: ERROR_MESSAGE` 且 `error` 有文字的,才不转 `end_turn`,改回 -32603 错误,`message` 是 `error` 原文,并在入口的 stderr 记一行。**保守判定,拿不准就照转 `end_turn`**(改成错误会让 Coda 续跑,答案已给出后再跑一轮可能重复有副作用的事):这一轮在 ACP 上已发过回复文字(`agent_message_chunk`,不含入口截下的重试提示)或成功的工具结果(`status: completed`)的,不改;收尾这一次读记录失败(文件没了、读不了)的,不改,不拿之前读到、缓存下来的错误顶替;错误步骤之前没出现这个 prompt 的用户输入步骤(`source: USER_EXPLICIT`、`type: USER_INPUT`)的,不改(上一轮晚写入的错误落在这个 prompt 开始之后,而新一轮什么都没写;没有用户输入步骤的轮次也不改)。依据:agy 内部重试时每次失败也会写一条 `ERROR_MESSAGE`(`API error (attempt N): …`),重试成功后模型的步骤接在后面,所以只有它是这一轮的最后一步才算最终失败;`stopReason` 不是 `end_turn`(取消等),或最后一步是别的(模型的回答;工具调用自己的 `status: ERROR` 步骤,如用户拒绝了权限,本机有一个会话就以它收尾),都不算。文字符合 `<状态> (code 5xx):`(1.5.15 的样本是 `UNAVAILABLE (code 503): No capacity available for model …`)的,错误带 `data._meta.coda.failure = {kind: "service_unavailable", input: "accepted"}`,由 Coda 按 15、30、60 秒重试;其余(超时、断连、额度……)是普通错误,不自动重试。**只认 1.5.15 的样本**:本机 115 个会话里有 34 条真实的 `ERROR_MESSAGE` 步骤(503 容量不足、流空闲 5 分钟超时、连接被重置、「The stream was interrupted」),它们后面全都接着模型的步骤(重试成功了);「最后一步就是它」的真实记录本机没有,这条判据来自 T3 Code 读 agy 数据库的同一做法(它的最后一步类型是 `CORTEX_STEP_TYPE_ERROR_MESSAGE`)。**会漏判**:agy 回 `end_turn` 时记录还没写到那一步(入口不等);这一轮已在 ACP 出声但随后真的失败(保守不改);轮次没有用户输入步骤(保守不改);agy 换了步骤类型或字段;会话记录读不到、格式不认识、读失败(都安静地照 ACP 的回答转发)。**会误判**:错误之后 agy 没再写步骤、这一轮却是它自己认为正常的结束(没见过) |
90
+ | 子 Agent `_coda/wait` | agy 的 `invoke_subagent` 起的子 Agent 在 ACP 上只有一张工具卡,卡结束了子 Agent 还在跑。入口在 Coda 声明 `_meta.coda.waits` 时,在一个 prompt 回答期间每秒、回答时、之后只要还有子 Agent 在跑每秒,只读会话目录 `.system_generated/` 下两处纯 JSON:`subagents/<子会话>.json`(`state` 为 `SUBAGENT_STATE_ALIVE` 或 `SUBAGENT_STATE_KILLED`,`subagentDescriptor.role`、`typeName`)和收件箱 `messages/*.json`。入口第一次看到这个会话的 prompt 时就已有的子 Agent 与消息不算(那是以前的)。新出现且 `ALIVE` 的报 `waiting`:`kind: subagent`,`awaited: false`(不挡会话静止:见下面「结案可能不到」),`waitId` 与 `childSessionId` 都是子会话 ID,标题是 `role`(没有就用 `typeName`),说明是子会话收件箱里 `invoke_subagent` 那条消息的正文(派给它的任务,读不到就不带)。结束只认明确的信号:系统发到本会话收件箱的 `Subagent <ID> has gone idle.` 报 `done`;子会话自己发来的消息(进展、提问、汇报)分不出是不是做完,不结案;记录里的 `state` 变成 `KILLED` 报 `cancelled`;变成没见过的值不结案(第一次看到时就不是 `ALIVE` 的,也不登记);`session/close` 或 agy 进程自己退出时还在跑的报 `cancelled`。不带 `toolCallId`(`invoke_subagent` 在 ACP 上的 `toolCallId` 与 agy 记录里的调用号是否一致没有样本),不带 `model`,不声明 `stoppable`(ACP 没有停一个子 Agent 的方法)。`childSessionId` 让 Coda 认得这个会话:agy 不经 ACP 报子会话的过程,入口也不替它编,所以委派清单里点开没有过程。**会漏判**:没声明 `_meta.coda.waits`;agy 换了这两处文件的位置或字段;子 Agent 闲置之后又被主 Agent 叫醒继续干(入口只登记一次,不按协议第 5 条用新 `waitId` 再登记);在 agy 自己唤醒模型的一轮(不是 Coda 发的 prompt)里起的子 Agent,要等下一个 prompt 才发现;入口启动前已在跑的子 Agent。**结案可能不到**:本机样本里五个子 Agent 都发了最终汇报,会话里只有一条 `gone idle` 通知(出在其中一个中途等指引时),记录里的 `state` 到样本时也仍是 `ALIVE`;这样的子 Agent 入口收不到结束信号,会一直报在等,直到 `session/close` 或 agy 进程结束(报 `cancelled`);所以一律报 `awaited: false`,它在委派清单里显示,但不挡会话静止,父会话可以照常结束这一轮。字段类型不对的记录:标题只取字符串字段,处理出错的那一条跳过,不影响会话与别的子 Agent。只有 1.5.15 的样本(一次起五个 `research` 子 Agent 的会话) |
91
+ | 没做:待回复、子会话过程、数据库 | **待回复**(agy 在任务或子 Agent 完成后自己唤醒模型续说,T3 Code 靠收件箱里未读的高优先级消息、或记录末尾没有后续模型步骤的 `SYSTEM_MESSAGE` 认出):Coda 的对应是 `handling`,要在 prompt 之外报「在处理哪一项」并在这一轮结束时放开,入口看不出 agy 的这一轮什么时候结束,也没有 agy 在 prompt 之外经 ACP 推更新的样本;报错了会让 Coda 一直占着一轮自主轮次、用户的消息排队。**子会话的过程**(子 Agent 自己的步骤作为那个会话的 `session/update`):要把子会话的 `transcript.jsonl` 翻成 ACP 更新,子会话能否经 ACP 恢复也未验证。**`conversations/<ID>.db`**(SQLite,步骤载荷是 Protobuf;T3 Code 靠它读 `INVOKE_SUBAGENT` 步骤里的子会话与启动文字、压缩步骤等):需要 `node:sqlite` 与手写的 Protobuf 字段号(来自 agy 私有的 `exa.cortex_pb`,没有公开定义,随版本变);现在要的信息都能从上面的 JSON 拿到,不值得吃下这份依赖和破损风险。「压缩上下文不上报 Coda」一行同理 |
84
92
  | Plan 模式 | 产出计划文件并要求审阅,审阅前不动手;plan 下只读的 shell 命令也按权限规则请求审批,这是 agy 的设计 |
85
93
  | 删除会话 | 不支持:agy 1.5.9 的 ACP 没有 `session/delete`(回 -32601),`session/close` 也不删除。在 agy 历史里留下零步空会话的只有两种:不支持配置探测的旧版 Coda 每次普通探测建的会话,和插件缓存采集目录时自己建的那条,见「配置探测」。插件不自己删文件:那会绕过 agy 的取消、摘要缓存和搜索索引,agy 运行中删也不安全;等上游提供删除接口再接 |
86
94
  | 附加目录 | 不交给 Antigravity:读工作副本外的附件、会话临时目录、skill 真实文件可能要审批;`.agents/skills` 的链接照旧 |
87
95
  | Coda 的 MCP 工具在 auto 下也要审批 | 无人值守的子会话、流程步骤调用它们会停下;「全部放行」下不会。要在 auto 下放行,写法是在运行机的 `~/.gemini/antigravity-cli/settings.json` 里加 `{"permissions": {"allow": ["mcp(coda/*)"]}}`,出处是官方[权限文档](https://antigravity.google/docs/permissions/);插件不替你改这个文件 |
88
96
  | 压缩上下文不上报 Coda | Antigravity 会压缩上下文:`/compact` 在 `agy acp` 1.5.9 上实测会跑一次摘要,对话库里留下摘要步骤;二进制里也有按 token 阈值触发的压缩配置,自动压缩没有实测触发。但 ACP 流和 `acp-server` 日志都不报压缩(没有 `compaction_update`,也没有专门的通知或工具调用),唯一的痕迹在它私有的对话库里,入口不读它,也不从文本或用量反推。所以依赖压缩的功能(如 Ultra 压缩后重发说明)在它上面压缩后不生效 |
89
- | 额度耗尽 | 没有真实样本,不做失败分类,Coda 只看到 Antigravity 给的错误文字 |
97
+ | 额度耗尽 | 没有真实样本,不做失败分类,Coda 只看到 Antigravity 给的错误文字(ACP 报出的,或「隐藏的失败」从会话记录里读出的) |
90
98
  | 没有桌面会话的 Linux 登录 | 未实测:Linux 用 Secret Service(D-Bus),二进制里有「keyring 失败就落文件」的回退,但文件路径与触发条件没查清。资源页在 Linux 上用 `secret-tool lookup service gemini username antigravity` 查条目(属性名按 go-keyring 的写法,未在真机上试过),没有 `secret-tool`、查不到条目,或登录落在文件里时,资源页当作未登录(只是仍在「添加资源」里出现,会话不受影响)。装了 `secret-tool` 却联系不上 Secret Service(典型是没有会话 D-Bus 的无桌面机器,它带错误信息退出)时,资源页读取失败,原因是「读不了 Secret Service」,在这样的机器上要在终端里运行 `agy acp --login` 登录 |
91
99
  | 第三方模型 | 账号里的 Claude、GPT-OSS 未实测 |
92
100
  | 配置探测 | Coda 读模型、思考档位与模式的目录时,入口用插件状态目录里的缓存(`$CODA_PLUGIN_STATE/catalog-v1.json`)答一个只在当前连接有效的虚拟会话(`coda-probe:` 开头,不接受 prompt、不能恢复、断线即释放):**缓存命中时不建 Antigravity 会话**。缓存不按天数过期:距上次采集或比对满 1 小时后,下一次探测先跑一次 `agy models`(不建会话,约 2~3 秒,限时 8 秒),把它列出的模型(ID 与名称)和采集时记下的清单比对,一样就只记下比对时间(`catalog-v1.check.json`),不一样才重读;`agy models` 失败(未登录、断网、超时)时照旧用缓存,5 分钟后再比对,不因此重读;旧版插件留下的没有清单的缓存,在 `agy models` 第一次答上时重读一次。此外 agy 的路径或版本、`~/.gemini/antigravity-cli/settings.json` 变化、真实会话报的配置与缓存对不上时也重读。重读用一个独立的 `agy acp` 建一条空会话逐个模型读一遍(agy 1.5.9 删不了会话,这条会留在 `~/.gemini/antigravity-cli/conversations/`,会话 ID 记在 `catalog-v1.log`)。读失败时这次探测报错、不改用普通会话,同样的 agy 与设置 5 分钟内不再重读(未登录除外);比对发现变化而重读失败时照旧用原缓存答。要支持配置探测的新版 Coda 才生效;旧版 Coda 每次探测仍各建一条空会话 |
@@ -0,0 +1,238 @@
1
+ // agy moves a `run_command` that is still running after its `WaitMsBeforeAsync` into the background. The ACP card then stays
2
+ // `in_progress` with no content (agy 1.5.15 says nothing of it on ACP: no text, no field), and the task id and log of the task
3
+ // are in agy's own transcript of the session only, so Coda could not list it. This reads that transcript, read-only, and tells
4
+ // Coda the task as a `_coda/wait` (docs/agent-protocol.md「_coda/wait」):
5
+ // start: a step of status RUNNING, "Tool is running as a background task with task id: <session>/task-N\nTask Description: <command>"
6
+ // and a "Task logs are available at: file://…" line after the command (a step over about 2.5 KB has its middle replaced by
7
+ // "\n<truncated N bytes>\n").
8
+ // The ACP call it belongs to is the one open `execute` call whose command is that description (when the step is cut, whose
9
+ // command has the two ends of it); none or several fit: not registered. The task id is not the toolCallId.
10
+ // end: a SYSTEM step, "content=Task id \"<task id>\" finished with result:\nCommand exited with code N." or "was canceled with
11
+ // result:\nTool execution was canceled". The call's own ACP update that ends it, when it comes, ends the task, too. A result with neither an exit code (read from its first 1000 characters) nor the cancelling ends nothing: the call's ACP update does.
12
+ // A command with `IsDaemon: true` is a server left running on purpose (T3 Code's reading of it, too): it is told with `awaited: false`.
13
+ // Its card is left as agy says it: a call that launched a wait is shown by Coda as moved to the background, and neither it nor a
14
+ // wait that is not awaited keeps the session from being at rest (docs/session-contracts.md「会话静止」), so no result is made up for it.
15
+ // The end by the card's ACP update: the exit code says the result (-1 is agy cancelling it).
16
+ // Two more things are read from the same file, and the same session directory: a turn that ACP ends with `end_turn` while its last step
17
+ // since the prompt is an upstream error (SYSTEM / ERROR_MESSAGE, `error` is the text) failed without saying so: `finish` returns the
18
+ // text, but only when the turn said nothing on ACP (`spoke`: a reply text, a tool that succeeded), because agy writes the transcript
19
+ // late and an error it got over could still be its last step; only when the error came after the user input step of this turn (an
20
+ // error written late for the turn before comes before it, or with none); and only from what this read got. And the
21
+ // sub-agents agy started (subagents.mjs) are told as `_coda/wait` of kind `subagent`.
22
+ // Whatever cannot be read (no file, another shape, a failed read) is skipped without a word: the session goes on as plain ACP.
23
+ import { closeSync, existsSync, openSync, readSync, statSync } from 'node:fs';
24
+ import { homedir } from 'node:os';
25
+ import { join } from 'node:path';
26
+ import { fileURLToPath } from 'node:url';
27
+ import { ALIVE, KILLED, children, idled, launch } from './subagents.mjs';
28
+
29
+ const START = /^(?:Created At: [^\n]*\n)?Tool is running as a background task with task id: (\S+)\nTask Description: /;
30
+ const END = /<SYSTEM_MESSAGE>\n\[Message\] [^\n]* content=Task id "([^"]+)" (finished|was canceled) with result:\n/;
31
+ const CUT = /\n<truncated \d+ bytes>\n/;
32
+ const EXIT = /^Command exited with code (-?\d+)\./m;
33
+ const TERMINAL = new Set(['completed', 'failed']);
34
+
35
+ export class Background {
36
+ // `send(params)` writes one `_coda/wait`; `home` is where agy keeps `.gemini`; `interval` is how often the transcript is read;
37
+ // `waits()` is whether Coda takes `_coda/wait` (the sub-agents are looked for only then).
38
+ constructor({ send, home = homedir(), interval = 1000, waits = () => true }) {
39
+ Object.assign(this, { send, home, interval, waits });
40
+ this.brain = join(home, '.gemini/antigravity-cli/brain');
41
+ this.sessions = new Map();
42
+ }
43
+
44
+ // A tool_call or tool_call_update of a session, as agy sent it.
45
+ observe(sessionId, update) {
46
+ const id = update.toolCallId;
47
+ let session = this.sessions.get(sessionId);
48
+ const call = session?.calls.get(id);
49
+ if (!call) {
50
+ const input = update.rawInput ?? update.args;
51
+ if (update.kind !== 'execute' || typeof input?.CommandLine !== 'string' || TERMINAL.has(update.status)) return;
52
+ session ??= this.open(sessionId);
53
+ session.calls.set(id, { command: input.CommandLine.trim(), summary: typeof input.toolSummary === 'string' ? input.toolSummary : '', daemon: [true, 'true'].includes(input.IsDaemon) });
54
+ this.watch(session);
55
+ return;
56
+ }
57
+ if (!TERMINAL.has(update.status)) return;
58
+ session.calls.delete(id);
59
+ if (call.waitId) {
60
+ const code = update.rawOutput?.exit_code;
61
+ const state = code === -1 ? 'cancelled' : update.status === 'failed' || (code !== undefined && code !== 0) ? 'failed' : 'done';
62
+ // After the card's own update, which the entry forwards when this returns.
63
+ queueMicrotask(() => this.end(session, call.waitId, state));
64
+ }
65
+ this.watch(session);
66
+ }
67
+
68
+ // The session ends: what it still has in the background is told cancelled.
69
+ closeSession(sessionId) {
70
+ const session = this.sessions.get(sessionId);
71
+ if (!session) return;
72
+ session.calls.clear();
73
+ for (const waitId of [...session.tasks]) this.end(session, waitId, 'cancelled');
74
+ for (const id of [...session.live]) this.finishChild(session, id, 'cancelled');
75
+ this.watch(session);
76
+ this.sessions.delete(sessionId);
77
+ }
78
+
79
+ closeAll() {
80
+ for (const sessionId of [...this.sessions.keys()]) this.closeSession(sessionId);
81
+ }
82
+
83
+ // What the transcript has gained since the first call of the session was seen (before that is not this run's). Whether it could be read.
84
+ scan(sessionId) {
85
+ const session = this.sessions.get(sessionId);
86
+ if (!session) return false;
87
+ let text = '', read = true;
88
+ try { text = this.read(session); } catch { read = false; }
89
+ for (const line of text.split('\n')) {
90
+ if (!line.trim()) continue;
91
+ let step; try { step = JSON.parse(line); } catch { step = null; }
92
+ // The last whole line that is not a step says that what the last step is cannot be told (`finish`).
93
+ session.unsure = !step || typeof step !== 'object';
94
+ if (session.unsure) continue;
95
+ if (step.source === 'USER_EXPLICIT' && step.type === 'USER_INPUT') session.input = true;
96
+ session.last = step;
97
+ session.lastAfterInput = session.input;
98
+ // What goes wrong with one step is skipped with that step.
99
+ if (typeof step.content === 'string') try { this.step(sessionId, session, step); } catch { /* this step only */ }
100
+ }
101
+ if (this.waits()) this.follow(session);
102
+ this.watch(session);
103
+ return read;
104
+ }
105
+
106
+ // A prompt of the session goes to agy: what is read from here is this turn's.
107
+ begin(sessionId) {
108
+ const known = this.sessions.get(sessionId);
109
+ if (known) this.scan(sessionId);
110
+ const session = known ?? this.open(sessionId);
111
+ session.last = null;
112
+ session.unsure = false;
113
+ session.input = false;
114
+ session.spoke = false;
115
+ session.prompting = true;
116
+ this.watch(session);
117
+ }
118
+
119
+ // The turn has said something on ACP: a reply text, or a tool that succeeded.
120
+ spoke(sessionId) {
121
+ const session = this.sessions.get(sessionId);
122
+ if (session) session.spoke = true;
123
+ }
124
+
125
+ // The prompt is answered. With `endTurn`, the text of the upstream error the turn stopped on, or null: also when the transcript
126
+ // could not be read just now, its end is a step still being written or a line that is not a step (the last step is not known),
127
+ // or the turn said something, which an error agy got over does not.
128
+ finish(sessionId, endTurn) {
129
+ const session = this.sessions.get(sessionId);
130
+ if (!session) return null;
131
+ const read = this.scan(sessionId);
132
+ session.prompting = false;
133
+ this.watch(session);
134
+ const step = session.last;
135
+ return endTurn && read && !session.rest.length && !session.unsure && !session.spoke && session.lastAfterInput && step?.source === 'SYSTEM' && step.type === 'ERROR_MESSAGE' && typeof step.error === 'string' ? step.error.trim() || null : null;
136
+ }
137
+
138
+ open(sessionId) {
139
+ const dir = join(this.brain, sessionId, '.system_generated');
140
+ const file = join(dir, 'logs/transcript.jsonl');
141
+ let offset = 0; try { offset = statSync(file).size; } catch { /* not there yet: all of it is new */ }
142
+ const session = { id: sessionId, dir, file, offset, rest: Buffer.alloc(0), calls: new Map(), tasks: new Set(), timer: null,
143
+ last: null, unsure: false, input: false, lastAfterInput: false, spoke: false, prompting: false, known: new Set(), live: new Set(), seen: new Set() };
144
+ // The sub-agents and notes there already are belong to before.
145
+ if (this.waits()) { session.known = new Set(children(dir).keys()); idled(dir, session.seen); }
146
+ this.sessions.set(sessionId, session);
147
+ return session;
148
+ }
149
+
150
+ // Read while a call, a task or a sub-agent is open, or a prompt is being answered.
151
+ watch(session) {
152
+ const busy = session.tasks.size > 0 || session.live.size > 0 || (session.prompting && this.waits()) || [...session.calls.values()].some(call => !call.waitId);
153
+ if (busy && !session.timer) session.timer = setInterval(() => this.scan(session.id), this.interval).unref();
154
+ else if (!busy && session.timer) { clearInterval(session.timer); session.timer = null; }
155
+ }
156
+
157
+ read(session) {
158
+ const size = statSync(session.file).size;
159
+ if (size <= session.offset) return '';
160
+ const buffer = Buffer.alloc(size - session.offset);
161
+ const fd = openSync(session.file, 'r');
162
+ let count; try { count = readSync(fd, buffer, 0, buffer.length, session.offset); } finally { closeSync(fd); }
163
+ session.offset += count;
164
+ const all = Buffer.concat([session.rest, buffer.subarray(0, count)]);
165
+ const end = all.lastIndexOf(10) + 1;
166
+ session.rest = all.subarray(end);
167
+ return all.subarray(0, end).toString('utf8');
168
+ }
169
+
170
+ step(sessionId, session, step) {
171
+ const started = step.source === 'MODEL' && step.status === 'RUNNING' ? START.exec(step.content) : null;
172
+ if (started) return this.start(sessionId, session, started[1], step.content.slice(started[0].length));
173
+ const ended = step.source === 'SYSTEM' ? END.exec(step.content) : null;
174
+ if (!ended || !session.tasks.has(ended[1])) return;
175
+ const exit = EXIT.exec(step.content.slice(ended.index + ended[0].length, ended.index + ended[0].length + 1000));
176
+ // Only an exit code or the cancelling says how it ended; a result that has neither is left to the ACP update that ends the call.
177
+ if (ended[2] === 'was canceled') this.end(session, ended[1], 'cancelled');
178
+ else if (exit) this.end(session, ended[1], exit[1] === '0' ? 'done' : 'failed');
179
+ }
180
+
181
+ start(sessionId, session, taskId, rest) {
182
+ const logged = /\nTask logs are available at: (file:\/\/\S+)/.exec(rest);
183
+ const text = logged ? rest.slice(0, logged.index) : rest;
184
+ // A step that is too long has its middle replaced by a marker: the command begins with what comes before it and ends with what follows.
185
+ const cut = CUT.exec(text);
186
+ const [head, tail] = (cut ? [text.slice(0, cut.index), text.slice(cut.index + cut[0].length)] : [text, '']).map(part => part.trim());
187
+ if (!head || taskId.length > 200) return;
188
+ // The whole command, or only when the step says it was cut, its two ends; with more than one call that fits, none is taken for it.
189
+ const fits = [...session.calls].filter(([, call]) => !call.waitId && (cut ? call.command.startsWith(head) && call.command.endsWith(tail) : call.command === head));
190
+ if (fits.length !== 1 || fits[0][0].length > 200) return;
191
+ const [[toolCallId, call]] = fits;
192
+ let log = join(session.dir, 'tasks', `${taskId.slice(taskId.lastIndexOf('/') + 1)}.log`);
193
+ try { if (logged) log = fileURLToPath(logged[1]); } catch { /* keeps the one the layout gives */ }
194
+ const params = { sessionId, waitId: taskId, kind: 'task', state: 'waiting', toolCallId,
195
+ title: (call.summary || call.command.split('\n')[0]).slice(0, 500), detail: call.command.slice(0, 4000),
196
+ ...(existsSync(log) && log.length <= 4096 ? { outputFile: log } : {}), ...(call.daemon ? { awaited: false } : {}) };
197
+ call.waitId = taskId;
198
+ session.tasks.add(taskId);
199
+ this.send(params);
200
+ }
201
+
202
+ end(session, waitId, state) {
203
+ if (!session.tasks.delete(waitId)) return;
204
+ this.send({ sessionId: session.id, waitId, state });
205
+ this.watch(session);
206
+ }
207
+
208
+ // New sub-agents are told as waiting, and not awaited: the session is at rest with them running (agy 1.5.15 sends nothing when one has
209
+ // done: its last report leaves the record ALIVE). Those the system says are idle, or whose record says KILLED, are ended. A message of
210
+ // a child that is not that idle note (progress, a question, a report), and a state not seen before, say nothing of its end. What goes
211
+ // wrong with one record is skipped with that record.
212
+ follow(session) {
213
+ const found = children(session.dir);
214
+ const idle = idled(session.dir, session.seen);
215
+ for (const [id, record] of found) {
216
+ if (session.known.has(id)) continue;
217
+ session.known.add(id);
218
+ if (record.state !== ALIVE) continue;
219
+ try {
220
+ const { role, typeName } = record.subagentDescriptor ?? {};
221
+ const detail = launch(join(this.brain, id, '.system_generated'), session.id);
222
+ this.send({ sessionId: session.id, waitId: id, kind: 'subagent', state: 'waiting', awaited: false, title: ([role, typeName].find(name => typeof name === 'string' && name) ?? id).slice(0, 500), childSessionId: id,
223
+ ...(detail ? { detail: detail.slice(0, 4000) } : {}) });
224
+ session.live.add(id);
225
+ } catch { /* this record only */ }
226
+ }
227
+ for (const id of [...session.live]) {
228
+ const state = found.get(id)?.state;
229
+ if (idle.has(id)) this.finishChild(session, id, 'done');
230
+ else if (state === KILLED) this.finishChild(session, id, 'cancelled');
231
+ }
232
+ }
233
+
234
+ finishChild(session, id, state) {
235
+ session.live.delete(id);
236
+ this.send({ sessionId: session.id, waitId: id, state });
237
+ }
238
+ }
package/agent/entry.mjs CHANGED
@@ -14,19 +14,26 @@
14
14
  // signal or a prompt unanswered, the log and the prompts still waiting say how (exit.mjs).
15
15
  // 5. agy's notice that it retries a model request ("⚠ API error (attempt N): ...", an agent_message_chunk) is not passed on: Coda
16
16
  // would keep it as the reply's text, while the turn goes on. The entry writes it to its own stderr instead (retry.mjs).
17
+ // 6. A command agy moves into the background, and a sub-agent it starts, is told to Coda as a `_coda/wait`, from agy's own files of the
18
+ // session, read only, for a Coda that declares `_meta.coda.waits` (background.mjs, subagents.mjs).
19
+ // 7. A prompt agy answers `end_turn` while the last step of the turn in its transcript is an upstream error is answered with that error
20
+ // instead (failure.mjs), unless the turn already said something on ACP (a reply text, a tool that succeeded) or the transcript could
21
+ // not be read. Nothing else of the relay changes.
17
22
  import { spawn } from 'node:child_process';
18
23
  import { agyBinary } from '../scripts/agy.mjs';
19
24
  import { createCatalog } from './catalog.mjs';
20
25
  import { PREFIX, Probes, probeMark } from './probe.mjs';
21
26
  import { describeExit, endedError } from './exit.mjs';
22
27
  import { retryNotice } from './retry.mjs';
28
+ import { Background } from './background.mjs';
29
+ import { failedError } from './failure.mjs';
23
30
 
24
31
  const binary = agyBinary() ?? 'agy';
25
32
  const agy = spawn(binary, ['acp'], { stdio: ['pipe', 'pipe', 'pipe'] });
26
33
  let stderr = '';
27
34
  agy.stderr.on('data', chunk => { process.stderr.write(chunk); stderr = (stderr + chunk).slice(-2048); });
28
- // The ids of the prompts Coda has asked and agy has not answered yet.
29
- const prompts = new Set();
35
+ // The prompts Coda has asked and agy has not answered yet: request id -> session.
36
+ const prompts = new Map();
30
37
  const initializing = new Set();
31
38
  const sessionRequests = new Set();
32
39
  const configRequests = new Map(); // request id -> { sessionId, was }: a set_config_option, whose answer lists the options; `was` for a mode switch, undone if agy refuses it
@@ -37,6 +44,8 @@ const catalog = createCatalog({ state: process.env.CODA_PLUGIN_STATE, binary });
37
44
  const probes = new Probes({ extraMode: { id: 'full', name: FULL_NAME, description: FULL_DESCRIPTION } });
38
45
  const answer = (id, reply) => process.stdout.write(`${JSON.stringify({ jsonrpc: '2.0', id, ...reply })}\n`);
39
46
  let stopping = false;
47
+ let waits = false; // Coda declared `_meta.coda.waits` in `initialize`
48
+ const background = new Background({ waits: () => waits, send: params => process.stdout.write(`${JSON.stringify({ jsonrpc: '2.0', method: '_coda/wait', params })}\n`) });
40
49
 
41
50
  // Only LF separates JSON messages; readline would also split literal Unicode line separators inside JSON strings.
42
51
  // A line that is not a JSON object passes through as it is. `change` returns false for a message that is not forwarded.
@@ -86,8 +95,12 @@ relay(process.stdin, agy.stdin, message => {
86
95
  if ('id' in message) answer(id, probes.handle(method, params));
87
96
  return false;
88
97
  }
89
- if (method === 'session/prompt' && 'id' in message) prompts.add(id);
90
- if (method === 'initialize' && 'id' in message) initializing.add(id);
98
+ if (method === 'session/prompt' && 'id' in message) {
99
+ prompts.set(id, params?.sessionId);
100
+ if (typeof params?.sessionId === 'string') background.begin(params.sessionId);
101
+ }
102
+ if (method === 'initialize' && 'id' in message) { initializing.add(id); waits = !!params?.clientCapabilities?._meta?.coda?.waits; }
103
+ if (method === 'session/close' && typeof params?.sessionId === 'string') background.closeSession(params.sessionId);
91
104
  if (['session/new', 'session/load', 'session/resume'].includes(method)) { delete params?.additionalDirectories; sessionRequests.add(id); }
92
105
  if (method === 'session/set_mode' && typeof params?.sessionId === 'string') {
93
106
  switchMode(message, params.modeId);
@@ -104,11 +117,19 @@ relay(process.stdin, agy.stdin, message => {
104
117
  relay(agy.stdout, process.stdout, message => {
105
118
  const { method, params, id } = message;
106
119
  if (!method) {
107
- prompts.delete(id);
120
+ if (prompts.has(id)) {
121
+ const failure = background.finish(prompts.get(id), message.result?.stopReason === 'end_turn');
122
+ prompts.delete(id);
123
+ if (failure) {
124
+ process.stderr.write(`agy 答 end_turn,但会话记录里这一轮最后一步是上游错误,改作这一轮的错误:${failure}\n`);
125
+ delete message.result;
126
+ message.error = failedError(failure);
127
+ }
128
+ }
108
129
  if (initializing.delete(id) && message.result?.agentCapabilities) {
109
130
  const capabilities = message.result.agentCapabilities;
110
131
  for (const key of ['sessionCapabilities', 'session_capabilities']) delete capabilities[key]?.additionalDirectories;
111
- capabilities._meta = { ...capabilities._meta, coda: { ...capabilities._meta?.coda, probe: {} } };
132
+ capabilities._meta = { ...capabilities._meta, coda: { ...capabilities._meta?.coda, probe: {}, waits: {} } };
112
133
  }
113
134
  if (sessionRequests.delete(id) && message.result) {
114
135
  catalog.observe(message.result);
@@ -131,6 +152,8 @@ relay(agy.stdout, process.stdout, message => {
131
152
  process.stderr.write(`agy 重试模型请求,提示不转给 Coda:${notice.trim()}\n`);
132
153
  return false;
133
154
  }
155
+ if (method === 'session/update' && typeof params?.sessionId === 'string' && (update?.sessionUpdate === 'agent_message_chunk' || (['tool_call', 'tool_call_update'].includes(update?.sessionUpdate) && update.status === 'completed'))) background.spoke(params.sessionId);
156
+ if (waits && method === 'session/update' && ['tool_call', 'tool_call_update'].includes(update?.sessionUpdate) && typeof params.sessionId === 'string') background.observe(params.sessionId, update);
134
157
  if (method === 'session/update' && update?.sessionUpdate === 'current_mode_update') {
135
158
  if (!full.has(params.sessionId)) return;
136
159
  if (update.currentModeId === 'default') update.currentModeId = 'full'; else full.delete(params.sessionId);
@@ -151,10 +174,11 @@ const stop = () => {
151
174
  agy.stdin.on('error', () => {});
152
175
  agy.on('error', () => process.exit(1));
153
176
  agy.on('close', (code, signal) => {
177
+ if (!stopping) background.closeAll();
154
178
  if (!stopping && (code !== 0 || prompts.size)) {
155
179
  const message = describeExit({ code, signal, stderr });
156
180
  process.stderr.write(`${message}\n`);
157
- for (const id of prompts) answer(id, { error: endedError(message) });
181
+ for (const id of prompts.keys()) answer(id, { error: endedError(message) });
158
182
  }
159
183
  process.stdout.write('', () => process.exit(stopping ? 0 : code ?? 1));
160
184
  });
@@ -0,0 +1,9 @@
1
+ // agy can end a prompt with `end_turn` after a model request failed for good (the transcript then ends with the error: background.mjs
2
+ // `finish`). That is told as the error of the prompt (docs/agent-protocol.md「执行失败」): the text is agy's, and only a
3
+ // server error agy words as "STATUS (code 5xx): message" (agy 1.5.15: "UNAVAILABLE (code 503): No capacity available for model ...")
4
+ // is marked a service failure, which Coda retries on its own schedule; the input was accepted, the model had read it. Any other error
5
+ // (a timeout, a reset connection, a quota) stays a plain error: nothing in it says the service is the cause.
6
+ const SERVER_ERROR = /\b[A-Z_]+ \(code 5\d\d\):/;
7
+
8
+ export const failedError = text => ({ code: -32603, message: text,
9
+ ...(SERVER_ERROR.test(text) && { data: { _meta: { coda: { failure: { kind: 'service_unavailable', input: 'accepted' } } } } }) });
@@ -0,0 +1,53 @@
1
+ // What agy 1.5.15 keeps of the sub-agents of a session, as plain JSON under the session's `.system_generated` (read only):
2
+ // subagents/<child id>.json {conversationId, subagentDescriptor: {typeName, role}, state: SUBAGENT_STATE_ALIVE | SUBAGENT_STATE_KILLED, ...}
3
+ // messages/<id>.json the inbox of a conversation: {sender, content, sourceMetadata: {tool: {toolCall: {name}}}, ...}
4
+ // the system's note that a child has nothing more to do is "Subagent <child id> has gone idle. ..."
5
+ // from sender "system"; the first message in a child's own inbox is its launch (the parent's
6
+ // `invoke_subagent` call, content = prompt). What a child itself sends to its parent (progress, a
7
+ // question, its report) is not told apart from one another, so it ends nothing.
8
+ // Reading those two (and not agy's SQLite database, which a launch is also written to) is what T3 Code's AntigravityChildWork.ts
9
+ // does for "detached" children, too. Whatever cannot be read is as if it was not there.
10
+ import { readdirSync, readFileSync } from 'node:fs';
11
+ import { join } from 'node:path';
12
+
13
+ export const ALIVE = 'SUBAGENT_STATE_ALIVE';
14
+ export const KILLED = 'SUBAGENT_STATE_KILLED';
15
+ const ID = /^[\w-]{1,64}$/;
16
+ const IDLE = /^Subagent ([\w-]{1,64}) has gone idle\./;
17
+
18
+ const json = file => { try { return JSON.parse(readFileSync(file, 'utf8')); } catch { return null; } };
19
+ const names = dir => { try { return readdirSync(dir); } catch { return []; } };
20
+
21
+ // The children of the session whose `.system_generated` is `dir`: id -> record.
22
+ export function children(dir) {
23
+ const found = new Map();
24
+ for (const name of names(join(dir, 'subagents'))) {
25
+ const id = name.endsWith('.json') ? name.slice(0, -5) : '';
26
+ const record = ID.test(id) ? json(join(dir, 'subagents', name)) : null;
27
+ if (typeof record?.state === 'string' && (record.conversationId ?? id) === id) found.set(id, record);
28
+ }
29
+ return found;
30
+ }
31
+
32
+ // The ids of the children the system says are idle, in the messages not in `seen` (which gains them). A message that is not whole
33
+ // yet is read again next time.
34
+ export function idled(dir, seen) {
35
+ const from = new Set();
36
+ for (const name of names(join(dir, 'messages'))) {
37
+ if (!name.endsWith('.json') || name === 'read.json' || seen.has(name)) continue;
38
+ const message = json(join(dir, 'messages', name));
39
+ if (!message) continue;
40
+ seen.add(name);
41
+ if (message.sender === 'system' && typeof message.content === 'string') { const idle = IDLE.exec(message.content); if (idle) from.add(idle[1]); }
42
+ }
43
+ return from;
44
+ }
45
+
46
+ // What the parent asked a child to do: the content of the `invoke_subagent` message in the child's inbox (`dir` is the child's).
47
+ export function launch(dir, parent) {
48
+ for (const name of names(join(dir, 'messages'))) {
49
+ const message = name.endsWith('.json') && name !== 'read.json' ? json(join(dir, 'messages', name)) : null;
50
+ if (message?.sender === parent && message.sourceMetadata?.tool?.toolCall?.name === 'invoke_subagent' && typeof message.content === 'string') return message.content;
51
+ }
52
+ return '';
53
+ }
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "id": "antigravity",
4
4
  "displayName": "Antigravity",
5
5
  "description": "用 Antigravity CLI 跑会话",
6
- "version": "1.4.1",
6
+ "version": "1.5.0",
7
7
  "engines": {
8
8
  "coda": 6
9
9
  },