diff --git a/README.md b/README.md index de1b4d6..92db6e2 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,8 @@ bridge is measured and bounded, and nothing is recorded that should not be. Claude Code ─┐ Codex ─┤ spawns ┌──────────────┐ Grok ─┼──────► agentpet-hook ───►│ socket │ - Pi ─┘ (~5 ms) └──────┬───────┘ + Pi ─┤ (~5 ms) └──────┬───────┘ + Oh My Pi ─┘ │ │ ┌──────────────────────────▼──────────────────────┐ │ normalize → activity engine → animation → pet │ @@ -81,7 +82,7 @@ Sessions running long jobs are not interrupted. (Verified by adding `SubagentStart`/`SubagentStop` to a session that had been running for hours and watching them fire.) -All five agents are configurable today. Codex's hooks carry one extra step: +All six agents are configurable today. Codex's hooks carry one extra step: Codex skips a hook until you review and trust it in Codex's own `/hooks` panel, and the runtime says so — and nothing else about the pet — the moment it configures them. @@ -95,11 +96,15 @@ plus one appended switch, `[compat.claude] hooks = false` in `~/.grok/config.toml`, which stops Grok's Claude-compatibility scan from firing the Claude hooks a second time. Pi gets one TypeScript extension of the runtime's own, `~/.pi/agent/extensions/agentpet.ts`, also deleted on removal. -Codex gets hook lines in `~/.codex/hooks.json`, merged around whatever is -already there — other tools' hooks are left alone, and so are they on -removal. Antigravity gets one named hook in `~/.gemini/config/hooks.json`, -merged around any other named hooks (its schema is not uniform: tool events -take matcher groups, the rest take flat handler lists): +Oh My Pi gets the same shape of file at +`~/.omp/agent/extensions/agentpet.ts` — one extension the runtime owns +outright, taken back on removal, and in force from the next session rather +than the running one. Codex gets hook lines in `~/.codex/hooks.json`, merged +around whatever is already there — other tools' hooks are left alone, and so +are they on removal. Antigravity gets one named hook in +`~/.gemini/config/hooks.json`, merged around any other named hooks (its schema +is not uniform: tool events take matcher groups, the rest take flat handler +lists): - **Backed up first.** The previous file is copied to the runtime's backup directory before anything is written. @@ -108,9 +113,15 @@ take matcher groups, the rest take flat handler lists): - **Idempotent.** Running Configure twice changes nothing. - **Reversible.** Remove Integration deletes only the lines the runtime wrote. Hook lines belonging to other tools — and there are usually several — are - left alone, and the appended switch is removed byte for byte. -- **Concurrency-aware.** The file's owner writes it too. If it changes - between read and write, the edit is abandoned rather than clobbering it. + left alone, and the appended switch is removed byte for byte. An extension + file is deleted whole, and only while it still carries the marker line the + record says was written into it: replace that line, or write your own file + under that name, and nothing is touched. A copy is taken first either way, so + even a file you had added to comes back. +- **Concurrency-aware.** The file's owner writes it too. If it changes between + read and write, the edit is abandoned rather than clobbering it. An extension + file has no second writer to race with: it is checked for the runtime's own + marker, written atomically and read back. It never touches model settings, credentials, or prompts. @@ -159,6 +170,48 @@ Configuring Grok appends `[compat.claude] hooks = false` to still checks `GROK_HOOK_NAME` and would re-label anything the scan delivered anyway. +### Oh My Pi's mapping + +Oh My Pi has no hook table, so the table above is Claude Code's. The extension +the runtime installs listens for eight events — and sends a ninth, the context +reading it takes at each settle — and they map like this: + +| Extension says | Pet shows | Why | +|---|---|---| +| `tool_approval_requested` | **waiting** | A tool is held until you approve it — the counterpart of a permission prompt | +| `tool_execution_start` carrying `ask` | **waiting** | The `ask` tool *is* a question put to you; nothing proceeds until it is answered | +| `agent_start`, any other tool call | running | Work in progress | +| `tool_execution_end`, `tool_approval_resolved` | running | Also what takes the pet off *Needs input* once you have answered | +| `agent_end` | celebrating, then idle | Fires once per prompt — and not when the payload says `willContinue`, which means a retry is already scheduled | +| `session_start` | *(nothing yet)* | Same reasoning as Claude Code's: a process started, so the session appears at its first real event | +| `session_shutdown` | *(removed)* | Session over | +| `context_update` (sent at each settle, not an event of its own) | *(described, not moved)* | Model, context usage — the same reduced shape the status-line taps deliver | + +Deliberately unmapped: `turn_start`/`turn_end` — Oh My Pi's turn is one model +call, not one prompt, so a turn boundary is not a finished piece of work — and +the message events, which carry model output and are not read at all. + +Two properties of that extension are worth knowing, and both are stated in the +file itself: + +**It reports and never gates.** It registers no handler that can block a tool, +rewrite an argument, or answer an approval, and every step is wrapped so a +failure cannot reach the agent. The one thing it does change is documented: Oh +My Pi skips its experimental speculative local reads +(`tools.speculativeExecution.enabled`, off by default) while any extension +handles one of the four *tool-lifecycle* events — `tool_call`, `tool_result`, +the two approval events — and this file takes the approval pair, which is what +shows an approval as **Needs input**. Removing the file restores them. + +**Its payload travels in the environment, not down a pipe.** The extension runs +inside the agent's own runtime, where a write to a pipe waits its turn on an +event loop the agent may be holding. Measured on this machine: 30ms of a busy +loop between spawning the shim and writing to it was enough for the shim's +stdin deadline to expire, and the event then arrived with no session id at all — +a row the pet could never fill. The environment is handed to a process by the +kernel at spawn time, so there is nothing to be late for. (`AGENTPET_PAYLOAD_BASE64` +in `Sources/agentpet-hook/main.swift`, and the test that covers it.) + --- ## How the pet animates @@ -292,6 +345,11 @@ The runtime reads session ids, working directories, and event names. It does read. The integration records it writes to disk contain hook commands and timestamps, and nothing else. +The Oh My Pi extension is held to the same allowlist from the other side: the +file the runtime installs sends a session id and a working directory for every +event, a tool name on the events that carry one, and there is no code in it +that touches a prompt, a tool argument, or any output. + When the app is not running — a relaunch, or the moment `brew upgrade` takes to replace the bundle — the hook writes undelivered events to `pending-events/` so the next launch can pick up where it left off. Those files are held to the @@ -314,7 +372,7 @@ whole of the network surface — nothing else here talks to anything. ## Development ```bash -swift build && swift test # 401 tests +swift build && swift test # 547 tests swift run AgentPet # run it swift run AgentPet --diagnose # what pets are discoverable, and why @@ -361,7 +419,7 @@ corrected specification. | Tuck the pet away and wake it again | done — the menu bar item, remembered across launches | | Event bridge, verified against the real binary | done | | Pet Manager: list Codex's pets, preview, pick one | done — read-only; pets are installed with Codex's own tooling | -| Agent Integrations: detect, configure, remove | Claude Code, Grok, Pi, Codex, and Antigravity | +| Agent Integrations: detect, configure, remove | Claude Code, Grok, Pi, Codex, Antigravity, and Oh My Pi | | Activity Center, Settings, diagnostics export | done | | Session panel: one row per session, configurable items | done | | Context usage from the status line | done — opt-in: wraps Claude Code's, hidden row for Grok, plain replacement row for Antigravity | diff --git a/README.zh-CN.md b/README.zh-CN.md index 7958d67..30dec41 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -16,7 +16,8 @@ Claude Code 弹权限请求,它抬爪子。任务做完,它庆祝一下再 Claude Code ─┐ Codex ─┤ spawn ┌──────────────┐ Grok ─┼──────► agentpet-hook ───►│ socket │ - Pi ─┘ (~5 ms) └──────┬───────┘ + Pi ─┤ (~5 ms) └──────┬───────┘ + Oh My Pi ─┘ │ │ ┌──────────────────────────▼──────────────────────┐ │ 归一化 → Activity 引擎 → 动画 → 宠物 │ @@ -74,17 +75,17 @@ swift run AgentPet --unconfigure claude-code # 精确移除它写过的东西 **不需要重启。** Claude Code 在**每次派发 hook 时**重新读取 `~/.claude/settings.json`,所以会话运行中途加的 hook 下一个事件就生效,正在跑长任务的会话不会被打断。(实测方式:给一个已经跑了好几个小时的会话新增 `SubagentStart`/`SubagentStop`,然后看它们触发。) -五个 agent 现在都可配置。Codex 多一步:它的 hooks 要你在 Codex 自己的 `/hooks` 面板里 review 并信任一次才会生效——配置完成的那一刻,运行时会直接把这句话打给你。 +六个 agent 现在都可配置。Codex 多一步:它的 hooks 要你在 Codex 自己的 `/hooks` 面板里 review 并信任一次才会生效——配置完成的那一刻,运行时会直接把这句话打给你。 ### 配置到底做了什么 -配置做什么因 agent 而异,除此之外一概不碰:Claude Code 是往 `~/.claude/settings.json` 加 hook 行;Grok 是写运行时自己的 `~/.grok/hooks/agentpet.json`(移除时整个删掉),并在 `~/.grok/config.toml` 末尾追加一个开关 `[compat.claude] hooks = false`——否则 Grok 的 Claude 兼容扫描会把 Claude 的 hook 再放一遍;Pi 是写运行时自己的一个 TypeScript 扩展 `~/.pi/agent/extensions/agentpet.ts`(同样删除即卸载);Codex 是往 `~/.codex/hooks.json` 加 hook 行,与已有条目合并(比如 Otty 的四条原样保留,卸载时也只删自己写的);Antigravity 是往 `~/.gemini/config/hooks.json` 写一个命名钩子(工具事件用 matcher 分组、其余事件是扁平 handler 列表——它的 schema 并不统一),与其它命名钩子合并、卸载只删自己: +配置做什么因 agent 而异,除此之外一概不碰:Claude Code 是往 `~/.claude/settings.json` 加 hook 行;Grok 是写运行时自己的 `~/.grok/hooks/agentpet.json`(移除时整个删掉),并在 `~/.grok/config.toml` 末尾追加一个开关 `[compat.claude] hooks = false`——否则 Grok 的 Claude 兼容扫描会把 Claude 的 hook 再放一遍;Pi 是写运行时自己的一个 TypeScript 扩展 `~/.pi/agent/extensions/agentpet.ts`(同样删除即卸载);Oh My Pi 同理,写 `~/.omp/agent/extensions/agentpet.ts`(同样删除即卸载;装完要新起一个 omp 会话才生效,正在跑的那个不算);Codex 是往 `~/.codex/hooks.json` 加 hook 行,与已有条目合并(比如 Otty 的四条原样保留,卸载时也只删自己写的);Antigravity 是往 `~/.gemini/config/hooks.json` 写一个命名钩子(工具事件用 matcher 分组、其余事件是扁平 handler 列表——它的 schema 并不统一),与其它命名钩子合并、卸载只删自己: - **先备份。** 动笔之前先把原文件复制到运行时备份目录。 - **原子写入。** 写临时文件再 rename,读者要么看到旧文件要么看到新文件,不会看到写了一半的。 - **幂等。** 连点两次 Configure 什么都不会变。 -- **可逆。** Remove Integration 只删运行时自己写的行。**其他工具的 hook 行原样保留**——而你机器上通常有好几个;追加的开关按字节精确删回。 -- **检测并发修改。** 文件的主人自己也会写它。如果读和写之间它变了,就放弃这次编辑而不是覆盖它。 +- **可逆。** Remove Integration 只删运行时自己写的行。**其他工具的 hook 行原样保留**——而你机器上通常有好几个;追加的开关按字节精确删回。扩展文件则整个删掉,且只在文件里还留着记录中那行标记时才删:把那行换掉、或同名换成你自己写的文件,运行时不会碰它。两种情况都先留一份备份,所以即使你在它基础上加过东西也拿得回来。 +- **检测并发修改。** 文件的主人自己也会写它。如果读和写之间它变了,就放弃这次编辑而不是覆盖它。扩展文件没有第二个写入方:它只校验是不是运行时自己写的、原子写入、再读回验证。 它永远不碰模型配置、凭据和 prompt。 @@ -114,6 +115,30 @@ Agent 状态是一个由 hook 事件驱动的小型状态机。**映射是最容 **Grok 会读 Claude Code 的配置,所以运行时把这个扫描关掉。** Grok Build 会扫描并信任 `~/.claude/settings.json`,那会让每个 Grok 事件被 Claude 的 hook 再放一遍。配置 Grok 时会往 `~/.grok/config.toml` 追加 `[compat.claude] hooks = false`,并改为安装 Grok 自己的 hooks 文件。shim 仍检测 `GROK_HOOK_NAME`,万一仍有扫描来的事件也会被改判成 Grok。 +### Oh My Pi 的映射 + +Oh My Pi 没有 hook 表,所以上面那张表是 Claude Code 的。运行时装的扩展监听八个事件、另发一条上下文读数(第九个事件名),映射如下: + +| 扩展说 | 宠物显示 | 依据 | +|---|---|---| +| `tool_approval_requested` | **等待** | 工具被扣住等你批准——对应 Claude Code 的权限提示 | +| `tool_execution_start` 且 toolName 是 `ask` | **等待** | `ask` 工具本身就是问用户一个问题,不答就走不下去 | +| `agent_start`、其他工具调用 | 工作中 | 正在干活 | +| `tool_execution_end` / `tool_approval_resolved` | 工作中 | 也是你答完问题、或审批通过后,把宠物从「等待输入」上取下来的信号 | +| `agent_end` | 庆祝一下,然后发呆 | 每轮 prompt 触发一次;payload 里 `willContinue` 为真时说明已经排好了重试,这时不报 | +| `session_start` | *(不出行)* | 与 Claude Code 同理:只说明有进程启动,会话在第一个真实事件时出现 | +| `session_shutdown` | *(移除)* | 会话结束 | +| `context_update`(结算时发送,不是独立监听的事件) | *(只描述,不改变状态)* | 模型与上下文占用——与状态栏 tap 同一归约形状 | + +故意不映射的:`turn_start`/`turn_end`(Oh My Pi 的一个 turn 是一次模型调用,不是一轮 prompt,所以 turn 边界不代表干完了一段活),以及各种 message 事件(它们携带模型输出,本项目根本不读)。 + +这个扩展有两个值得知道的性质,都写在装出来的文件里: + +**它只上报,永不设卡。** 它没有注册任何能拦截工具、改写参数或代答审批的 handler,每一步都包了 try/catch,出错也传不到 Agent 身上。它唯一会改变的东西也写明了:只要**任意扩展**在处理四个工具生命周期事件(`tool_call`、`tool_result`、`tool_approval_requested`、`tool_approval_resolved`)之一,Oh My Pi 就会跳过实验性推测本地读(`tools.speculativeExecution.enabled`,默认关闭);本文件占的是后两个——审批之所以能显示成 **Needs input**,靠的正是它们。删掉文件即恢复。 + +**它的 payload 走环境变量,不走管道。** 这个扩展跑在 Agent 自己的运行时里,往管道写数据的动作要排在事件循环上,而 Agent 可能正占着它。本机实测:spawn 之后忙等 30ms 再写,就足以让 shim 的 stdin 等待超时,事件到达时**没有任何 session id**——宠物上会出现一行永远填不上的东西。环境变量由内核在 spawn 时交给子进程,没有可迟到的余地。(见 `Sources/agentpet-hook/main.swift` 里的 `AGENTPET_PAYLOAD_BASE64`,以及覆盖它的测试。) + + --- ## 动画是怎么播的 @@ -180,6 +205,8 @@ shim 跑在 Agent 的关键路径上,每次工具调用一次,所以这个 运行时读取 session id、工作目录、事件名。它**不读** prompt、模型输出、源码——不是过滤掉,是根本不读。写到磁盘的集成记录里只有 hook 命令和时间戳,没别的。 +Oh My Pi 的扩展从另一侧遵守同一份白名单:运行时装进去的文件每个事件只发 session id、工作目录和工具名,里面没有任何一行代码会碰 prompt、工具参数或输出。 + App 没运行时(重启,或 `brew upgrade` 替换 bundle 的那几秒),hook 会把未送达的事件写进 `pending-events/`,供下次启动回放。这些文件与事件日志同一条白名单(session id、目录、事件名与工具**名**;绝不包含 prompt、参数、输出、源码),权限 `0600`,上限 200 条,回放后即删。 `--log-events` 会写诊断抓包,**默认关闭**。它只保留诊断需要的字段,丢弃 `tool_input`、`tool_response`、`transcript_path`——用的是白名单,所以未来 Agent 版本新增的字段也不会默认泄漏进日志。文件权限 `0600`。 @@ -191,7 +218,7 @@ App 没运行时(重启,或 `brew upgrade` 替换 bundle 的那几秒),h ## 开发 ```bash -swift build && swift test # 401 个测试 +swift build && swift test # 547 个测试 swift run AgentPet # 跑起来 swift run AgentPet --diagnose # 发现了哪些宠物,以及为什么 @@ -232,12 +259,11 @@ Sources/agentpet-hook/ Agent 执行的 shim。必须永远 exit 0。 | 收纳 / 唤醒宠物 | 完成——菜单栏项,跨重启记住 | | 事件桥接,已对着真实二进制验证 | 完成 | | Pet Manager:列出 Codex 的宠物、预览、选用 | 完成——只读;宠物由 Codex 自己的工具链安装 | -| Agent 集成:检测、配置、移除 | **仅 Claude Code** | +| Agent 集成:检测、配置、移除 | Claude Code、Grok、Pi、Codex、Antigravity 与 Oh My Pi | | Activity Center、设置、诊断导出 | 完成 | | 会话面板:每会话一行,各项可配置 | 完成 | | 上下文占用(读取 Claude Code 状态栏) | 完成——可选开启,包裹你已有的状态栏命令 | | 重启/升级后不丢回合中的会话 | 完成——未送达事件在下次启动时回放 | -| Grok / Codex / Pi 配置 | 未做——各自需要专属配置器(TOML、argv 数组、扩展包) | | 聚焦到终端窗口 | 改为打开项目目录;hook payload 里没有终端标识 | --- diff --git a/Sources/AgentPetApp/AgentGlyph.swift b/Sources/AgentPetApp/AgentGlyph.swift index 08d0e39..2b2762e 100644 --- a/Sources/AgentPetApp/AgentGlyph.swift +++ b/Sources/AgentPetApp/AgentGlyph.swift @@ -20,6 +20,7 @@ enum AgentGlyph { case "grok": return "bolt" case "pi": return "function" case "antigravity": return "sparkles" + case "omp": return "sum" default: return "pawprint" } } diff --git a/Sources/AgentPetApp/CommandLine.swift b/Sources/AgentPetApp/CommandLine.swift index fb7c681..0efc953 100644 --- a/Sources/AgentPetApp/CommandLine.swift +++ b/Sources/AgentPetApp/CommandLine.swift @@ -18,10 +18,10 @@ enum CommandLineTool { AGENTS --status Show each agent's detection and integration - --configure Install hooks for an agent - --unconfigure Remove exactly the hooks it wrote + --configure Install the integration for an agent + --unconfigure Remove exactly what it wrote - Agents: claude-code, grok, codex, pi, antigravity + Agents: claude-code, grok, codex, pi, antigravity, omp DIAGNOSTICS --diagnose Report what is discoverable, and why @@ -121,7 +121,9 @@ enum CommandLineTool { if let version = detection.version { print(" version: \(version)") } - print(" hooks: \(record.entries.count)") + let installed = profile.mechanism == .extensionFile ? "extension:" : "hooks:" + print(" " + installed.padding(toLength: 13, withPad: " ", startingAt: 0) + + "\(record.entries.count)") print(" last event: \(record.lastEventAt.map(Self.timestamp) ?? "never")") print(" configurable:\(profile.configurator == nil ? " no" : " yes")") } @@ -164,10 +166,18 @@ enum CommandLineTool { try store.save(outcome.record) print("\(profile.displayName): \(outcome.didChange ? "configured" : "already configured")") - print(" shim: \(shim)") - print(" hooks: \(outcome.record.entries.count)") - for file in outcome.changedFiles { print(" wrote: \(file)") } - for backup in outcome.backupURLs { print(" backup: \(backup)") } + // One slot, as wide as the longest label here ("extension:"), so + // every value in this block starts in the same column — the same + // rule --status follows. + func field(_ label: String, _ value: String) -> String { + " " + label.padding(toLength: 10, withPad: " ", startingAt: 0) + " " + value + } + let installed = profile.mechanism == .extensionFile ? "extension:" : "hooks:" + + print(field("shim:", shim)) + print(field(installed, "\(outcome.record.entries.count)")) + for file in outcome.changedFiles { print(field("wrote:", file)) } + for backup in outcome.backupURLs { print(field("backup:", backup)) } if !outcome.didChange { print(" (nothing to change — running this again is always safe)") } @@ -183,6 +193,11 @@ enum CommandLineTool { print("\(path) is not valid JSON. The runtime will not overwrite a file it") print("cannot parse, because doing so would discard whatever is in it.") } + if case ConfigurationError.foreignFile(let path) = error { + print("") + print("\(path) exists but was not written by the runtime, so it is left") + print("alone. Move it aside if you want the pet to use that name.") + } return 1 } } @@ -206,8 +221,35 @@ enum CommandLineTool { print("\(profile.displayName): \(outcome.didChange ? "integration removed" : "nothing to remove")") for file in outcome.changedFiles { print(" wrote: \(file)") } - print(" Only the \(record.entries.count) hook(s) the runtime wrote were removed.") - print(" Anything you wrote yourself is untouched.") + let wrote = profile.mechanism == .extensionFile + ? "the extension file the runtime wrote" + : "the \(record.entries.count) hook(s) the runtime wrote" + let verb = profile.mechanism == .extensionFile ? "was" : "were" + print(" Only \(wrote) \(outcome.didChange ? verb : "would have been") removed.") + for backup in outcome.backupURLs { print(" backup: \(backup)") } + if profile.mechanism == .extensionFile { + // The whole file goes, including anything the user had added to + // it — saying "anything you wrote is untouched" here would be + // the opposite of what just happened. With nothing to remove + // there is no copy either, which is why both sentences live + // under the same condition as the `backup:` line above. + if outcome.didChange { + print(" The whole file was removed, including anything you had added to it.") + print(" A copy was kept in the backup directory before it went.") + } else { + // Four ways to land here, and all of them are real: the file + // is gone, it is not valid UTF-8, its marker line was + // rewritten, or this agent has no record to match against + // (the CLI does not gate on one — only the manager's card + // checks `isConfigured` first). Name them all rather than + // three of four, which would invite "then which is it?". + print(" Nothing was removed. The extension file is missing, is not") + print(" readable as UTF-8, no longer carries the recorded marker, or") + print(" this agent has no recorded marker to look for.") + } + } else { + print(" Anything you wrote yourself is untouched.") + } return 0 } catch { print("Could not remove the \(profile.displayName) integration: \(error)") diff --git a/Sources/AgentPetApp/UI/ActivityView.swift b/Sources/AgentPetApp/UI/ActivityView.swift index 96b62b4..93c9529 100644 --- a/Sources/AgentPetApp/UI/ActivityView.swift +++ b/Sources/AgentPetApp/UI/ActivityView.swift @@ -22,7 +22,7 @@ struct ActivityView: View { VStack(spacing: 8) { Text("No agent sessions") .foregroundStyle(.secondary) - Text("Run an agent with its hooks configured, or send a test event from the Agents tab.") + Text("Run a configured agent, or send a test event from the Agents tab.") .font(.caption) .foregroundStyle(.tertiary) .multilineTextAlignment(.center) diff --git a/Sources/AgentPetApp/UI/AgentPetModel.swift b/Sources/AgentPetApp/UI/AgentPetModel.swift index c75503a..a5a8f14 100644 --- a/Sources/AgentPetApp/UI/AgentPetModel.swift +++ b/Sources/AgentPetApp/UI/AgentPetModel.swift @@ -372,8 +372,9 @@ final class AgentPetModel: ObservableObject { shimPath: shimPath, transaction: transaction ) + let what = status.profile.mechanism == .extensionFile ? "extension" : "hooks" var message = outcome.didChange - ? "Wrote hooks to \(outcome.changedFiles.joined(separator: ", "))" + ? "Wrote the \(what) to \(outcome.changedFiles.joined(separator: ", "))" : "Already configured — nothing to change." // Codex's file alone is not enough: its hooks stay skipped until // the user trusts them in Codex itself. @@ -391,9 +392,11 @@ final class AgentPetModel: ObservableObject { agentID: status.profile.agentID, transaction: transaction ) - statusMessage = outcome.didChange - ? "Removed hooks. A backup of the previous file was kept." - : "Nothing to remove." + let what = status.profile.mechanism == .extensionFile ? "extension" : "hooks" + // A file that did not exist had nothing to copy: the transaction + // says so by reporting no backup, and the message follows it. + let kept = outcome.backupURLs.isEmpty ? "" : " A backup of the previous file was kept." + statusMessage = outcome.didChange ? "Removed the \(what).\(kept)" : "Nothing to remove." refreshAgents() } } @@ -511,6 +514,8 @@ final class AgentPetModel: ObservableObject { return "Could not read \(path): \(detail)" case let ConfigurationError.unknownAgent(id): return "No configurator exists for \(id)." + case let ConfigurationError.foreignFile(path): + return "\(path) exists but was not written by the runtime. It is left alone." case let PetPackageError.manifestInvalid(name, detail): return "“\(name)” has an unusable pet.json: \(detail)" case let PetPackageError.manifestNotFound(name): diff --git a/Sources/AgentPetApp/UI/AgentsView.swift b/Sources/AgentPetApp/UI/AgentsView.swift index b49cb28..dcbf14c 100644 --- a/Sources/AgentPetApp/UI/AgentsView.swift +++ b/Sources/AgentPetApp/UI/AgentsView.swift @@ -9,7 +9,7 @@ struct AgentsView: View { var body: some View { ScrollView { VStack(alignment: .leading, spacing: 12) { - Text("Each agent reports its own status. Configuring writes hook lines to that agent's config file and keeps a backup; removing deletes only the lines the runtime wrote.") + Text("Each agent reports its own status. Configuring installs the integration that agent takes — hook lines in its config file, or one extension file — and keeps a backup; removing deletes only the integration the runtime installed, after taking a copy.") .font(.callout) .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) @@ -110,7 +110,12 @@ struct AgentsView: View { private func configSummary(_ status: AgentStatus) -> String { guard status.record.isConfigured else { return "not configured" } let count = status.record.entries.count - return "\(count) hook\(count == 1 ? "" : "s") installed" + switch status.profile.mechanism { + case .hookTable: + return "\(count) hook\(count == 1 ? "" : "s") installed" + case .extensionFile: + return "extension installed" + } } private func lastEventSummary(_ status: AgentStatus) -> String { @@ -124,15 +129,26 @@ struct AgentsView: View { private func problem(_ status: AgentStatus) -> String? { switch status.health { case .disconnected: - return "The hooks the runtime wrote are no longer in the config file." + switch status.profile.mechanism { + case .hookTable: + return "The hooks the runtime wrote are no longer in the config file." + case .extensionFile: + return "The extension the runtime wrote is missing, or no longer matches what it recorded." + } case .failed(let message): return message case .degraded where status.record.isConfigured: // Not "no events recently" — an idle agent is silent, and saying // otherwise made a working setup look broken. This fires only // when nothing has ever arrived since the hooks were installed. - return "Hooks are installed, but no event has ever reached the pet. " - + "Agents read their hooks at startup, so restart it once." + switch status.profile.mechanism { + case .hookTable: + return "Hooks are installed, but no event has ever reached the pet. " + + "Agents read their hooks at startup, so restart it once." + case .extensionFile: + return "\(status.displayName) reads its extensions when a session starts, " + + "so the pet appears the next time you start one." + } default: return nil } diff --git a/Sources/AgentPetCore/Bridge/AgentProfiles.swift b/Sources/AgentPetCore/Bridge/AgentProfiles.swift index 08b46c0..56ac554 100644 --- a/Sources/AgentPetCore/Bridge/AgentProfiles.swift +++ b/Sources/AgentPetCore/Bridge/AgentProfiles.swift @@ -552,6 +552,120 @@ public enum AgentProfiles { fallbackSessionID: "antigravity-default" ) + /// Oh My Pi reports through the extension the manager installs into + /// `~/.omp/agent/extensions/`, which spawns the shim once per event with a + /// payload of its own making — `session_id`, `cwd`, and a `toolName` where + /// one applies. Nothing else is read, so the event names below are the + /// extension's, not omp's. + /// + /// The mapping against the installed build (18.1.22) is: + /// + /// - `tool_approval_requested` is omp's approval gate — the one signal + /// that a tool is held up waiting for the user, and the counterpart of + /// Claude Code's `PermissionRequest`. + /// - `tool_execution_start` carrying `ask` is the other: omp's `ask` tool + /// is a question put to the user, and the session cannot proceed until + /// it is answered. Every other tool is just work. + /// - `agent_end` fires once per prompt, and means a turn is over — + /// *unless* the payload says `willContinue`, which the session sets when + /// it has already scheduled a retry. The extension drops those rather + /// than reporting a settle that never happened. + /// - `tool_execution_end` keeps a long tool call from looking idle and is + /// what clears an `ask` wait once the answer lands. + /// - Deliberately absent: `turn_start`/`turn_end` (omp's turn is one model + /// call, not one prompt, so both would mean "still working" at best), + /// `message_*`, and the session-tree events. `session_start` is mapped + /// for the same reason Claude Code's is: it refreshes a session that is + /// already known, and one that has only announced itself never becomes a + /// row at all — the engine drops a lone `session_start` for every agent + /// (the pre-warmed-session rule), not just this one. + public static let ohMyPi = AgentProfile( + agentID: "omp", + displayName: "Oh My Pi", + rules: [ + // --- Blocked on the user: the only sticky attention state. --- + + // The `ask` tool is a question, so it is matched before the + // general tool rule below. + NormalizationRule( + matches: ["tool_execution_start"], + kind: .waitingInput, + summaryField: "toolName", + toolNameField: "toolName", + sessionIDField: "session_id", + workingDirectoryField: "cwd", + whenToolName: "ask" + ), + NormalizationRule( + matches: ["tool_approval_requested"], + kind: .waitingApproval, + summaryField: "toolName", + toolNameField: "toolName", + sessionIDField: "session_id", + workingDirectoryField: "cwd" + ), + + // --- Working. --- + + NormalizationRule( + matches: ["agent_start"], + kind: .working, + sessionIDField: "session_id", + workingDirectoryField: "cwd" + ), + NormalizationRule( + matches: ["tool_execution_start"], + kind: .working, + summaryField: "toolName", + toolNameField: "toolName", + sessionIDField: "session_id", + workingDirectoryField: "cwd" + ), + // The answer to an `ask` arrives as the end of that tool call, so + // this is what takes the pet off "Needs input" while the agent + // carries on with what it was told. + NormalizationRule( + matches: ["tool_execution_end", "tool_approval_resolved"], + kind: .working, + sessionIDField: "session_id", + workingDirectoryField: "cwd" + ), + + // --- Finished. --- + + NormalizationRule( + matches: ["agent_end"], + kind: .completed, + sessionIDField: "session_id", + workingDirectoryField: "cwd" + ), + + // --- Lifecycle. --- + + NormalizationRule( + matches: ["session_start"], + kind: .sessionStarted, + sessionIDField: "session_id", + workingDirectoryField: "cwd" + ), + NormalizationRule( + matches: ["session_shutdown"], + kind: .sessionClosed, + sessionIDField: "session_id", + workingDirectoryField: "cwd" + ), + + // The reduced reading the extension sends at each settle — session + // id, model, how full the context window is. It describes a + // session rather than moving it, like the status-line taps. + NormalizationRule( + matches: ["context_update"], + kind: .contextUpdate, + sessionIDField: "session_id" + ), + ] + ) + /// Fallback for anything reached by process observation alone. public static let genericCLI = AgentProfile( agentID: "generic-cli", @@ -566,7 +680,7 @@ public enum AgentProfiles { confidence: .low ) - public static let all: [AgentProfile] = [claudeCode, grok, codex, pi, antigravity, genericCLI] + public static let all: [AgentProfile] = [claudeCode, grok, codex, pi, antigravity, ohMyPi, genericCLI] public static func profile(for agentID: String) -> AgentProfile? { all.first { $0.agentID == agentID } diff --git a/Sources/AgentPetCore/Bridge/EventNormalizer.swift b/Sources/AgentPetCore/Bridge/EventNormalizer.swift index 3fb427a..bc5951e 100644 --- a/Sources/AgentPetCore/Bridge/EventNormalizer.swift +++ b/Sources/AgentPetCore/Bridge/EventNormalizer.swift @@ -52,6 +52,17 @@ public struct NormalizationRule: Codable, Sendable, Equatable { /// second as one resurrects a session that has already closed. public let whenReason: String? + /// Only applies when the payload's tool name equals this. + /// + /// Read from this rule's own `toolNameField` through the same reader the + /// engine uses, so a nested path (`toolCall.name`, as Antigravity spells + /// it) works here too. The same kind of condition as `whenReason`, one + /// field over: an agent that reports *every* tool through a single event + /// needs the payload's tool name to say which of them is the one that + /// blocks on the user. Order matters as everywhere else — the narrow rule + /// is written before the general one for the same event. + public let whenToolName: String? + /// Skips the rule when the payload lists a still-running background task. /// /// Claude Code fires `Stop` when the main agent yields, which happens while @@ -87,6 +98,7 @@ public struct NormalizationRule: Codable, Sendable, Equatable { whenNotificationType: String? = nil, notificationTypeField: String? = nil, whenReason: String? = nil, + whenToolName: String? = nil, suppressedByRunningBackgroundTask: Bool = false, backgroundTasksField: String? = nil, suppressedWhenFalseField: String? = nil, @@ -102,6 +114,7 @@ public struct NormalizationRule: Codable, Sendable, Equatable { self.whenNotificationType = whenNotificationType self.notificationTypeField = notificationTypeField self.whenReason = whenReason + self.whenToolName = whenToolName self.suppressedByRunningBackgroundTask = suppressedByRunningBackgroundTask self.backgroundTasksField = backgroundTasksField self.suppressedWhenFalseField = suppressedWhenFalseField @@ -160,6 +173,18 @@ public extension NormalizationRule { guard actual == required else { return false } } + if let required = whenToolName { + // Through the shared reader, not `payload[field]`: it resolves + // dotted paths and the first entry of a string array, which is how + // an agent whose tool name is nested spells it. + // + // No field to read it from means the condition cannot be met, so + // the rule does not apply — rather than silently matching every + // payload, which would turn a typed mistake into a wrong state. + guard let field = toolNameField, + EventNormalizer.string(payload, field) == required else { return false } + } + if suppressedByRunningBackgroundTask, EventNormalizer.hasRunningBackgroundTask( payload, field: backgroundTasksField ?? "background_tasks" diff --git a/Sources/AgentPetCore/Integration/AgentConfigurator.swift b/Sources/AgentPetCore/Integration/AgentConfigurator.swift index 3e7df21..53391ec 100644 --- a/Sources/AgentPetCore/Integration/AgentConfigurator.swift +++ b/Sources/AgentPetCore/Integration/AgentConfigurator.swift @@ -4,6 +4,10 @@ public enum ConfigurationError: Error, Equatable, Sendable { case unknownAgent(String) case noConfigurationTarget(String) case transactionFailed(String) + /// A file the runtime would have to replace or delete exists, but was not + /// written by it. Carries the path. Refusing beats clobbering somebody + /// else's file — see `ExtensionFileConfigurator`. + case foreignFile(String) } public struct ConfigurationOutcome: Sendable, Equatable { diff --git a/Sources/AgentPetCore/Integration/AgentIntegrationRegistry.swift b/Sources/AgentPetCore/Integration/AgentIntegrationRegistry.swift index a5bd04a..23c2590 100644 --- a/Sources/AgentPetCore/Integration/AgentIntegrationRegistry.swift +++ b/Sources/AgentPetCore/Integration/AgentIntegrationRegistry.swift @@ -12,6 +12,11 @@ public struct AgentIntegrationProfile: Sendable { /// The UI shows it as detectable but not configurable. public let configurator: (any AgentConfigurator)? public let capabilities: Set + /// What the runtime's integration *is* for this agent, so the wording on + /// every surface can match it. A user told to check "the hooks in the + /// config file" when their integration is a single file in a directory + /// would go looking for something that does not exist. + public let mechanism: IntegrationMechanism /// Why there is no configurator, in the words that fit this agent. /// /// No agent lacks a configurator today (2026-09-15), but the field stays: @@ -32,6 +37,7 @@ public struct AgentIntegrationProfile: Sendable { detection: AgentDetector.Specification, configurator: (any AgentConfigurator)?, capabilities: Set, + mechanism: IntegrationMechanism = .hookTable, configurationNote: String? = nil, postConfigureHint: String? = nil ) { @@ -40,11 +46,26 @@ public struct AgentIntegrationProfile: Sendable { self.detection = detection self.configurator = configurator self.capabilities = capabilities + self.mechanism = mechanism self.configurationNote = configurationNote self.postConfigureHint = postConfigureHint } } +/// How the runtime installs itself into an agent. +public enum IntegrationMechanism: String, Codable, Sendable, Equatable { + /// Lines inside a configuration file the agent owns and writes itself — + /// Claude Code's `hooks` table, and Grok's. Installing means editing + /// somebody else's file, so it is transactional; removing means deleting + /// exactly the lines that were recorded. + case hookTable + /// One file the runtime owns outright, in a directory the agent scans — + /// Pi's and Oh My Pi's extensions. Installing is a write, removing is a + /// delete, and the file is only touched while it still identifies itself as + /// ours. + case extensionFile +} + public enum IntegrationCapability: String, Codable, Sendable, CaseIterable { case detect case configure @@ -158,7 +179,10 @@ public enum AgentIntegrationRegistry { configFiles: [home().appendingPathComponent(".pi/agent/settings.json")] ), configurator: PiConfigurator(transaction: transaction), - capabilities: [.detect, .configure, .uninstall, .liveEvents, .testEvent] + capabilities: [.detect, .configure, .uninstall, .liveEvents, .testEvent], + // The same shape as Oh My Pi's: one file the runtime owns in a + // directory the agent scans, not lines inside a file it owns. + mechanism: .extensionFile ) } @@ -183,6 +207,40 @@ public enum AgentIntegrationRegistry { ) } + /// Oh My Pi is one of the two agents here extended by a *file* (Pi is the + /// other): it loads every `*.ts` in `~/.omp/agent/extensions/` at session + /// start, so the integration is one file the runtime owns outright rather + /// than lines inside a file somebody else owns. Installing it is a write, removing it + /// is a delete, and nothing in omp's own configuration is touched. + /// + /// It is also why the note below is absent: this agent *is* configurable. + /// Its session events arrive from the extension (`--agent omp`), not from + /// a hook table, so there is no config file for the JSON transaction to + /// edit and none is needed. + public static func ohMyPi(transaction: ConfigTransaction) -> AgentIntegrationProfile { + let agentDirectory = home().appendingPathComponent(".omp/agent") + return AgentIntegrationProfile( + agentID: "omp", + displayName: "Oh My Pi", + detection: .init( + agentID: "omp", + displayName: "Oh My Pi", + executableNames: ["omp"], + configFiles: [ + agentDirectory.appendingPathComponent("config.yml"), + agentDirectory.appendingPathComponent("extensions"), + ] + ), + configurator: ExtensionFileConfigurator( + agentID: "omp", + directory: agentDirectory.appendingPathComponent("extensions"), + transaction: transaction + ), + capabilities: [.detect, .configure, .uninstall, .liveEvents, .testEvent], + mechanism: .extensionFile + ) + } + public static func all(transaction: ConfigTransaction) -> [AgentIntegrationProfile] { [ claudeCode(transaction: transaction), @@ -190,6 +248,7 @@ public enum AgentIntegrationRegistry { codex(transaction: transaction), pi(transaction: transaction), antigravity(transaction: transaction), + ohMyPi(transaction: transaction), ] } diff --git a/Sources/AgentPetCore/Integration/ConfigTransaction.swift b/Sources/AgentPetCore/Integration/ConfigTransaction.swift index cebd9d0..e129418 100644 --- a/Sources/AgentPetCore/Integration/ConfigTransaction.swift +++ b/Sources/AgentPetCore/Integration/ConfigTransaction.swift @@ -374,7 +374,10 @@ public struct ConfigTransaction: Sendable { } } - private func backUp(_ snapshot: ConfigSnapshot) throws -> URL? { + /// Not private: the extension-file configurators back a file up through + /// the same directory and the same naming, so one retention policy covers + /// every edit the runtime makes. + func backUp(_ snapshot: ConfigSnapshot) throws -> URL? { guard snapshot.existed else { return nil } let fileManager = FileManager.default try fileManager.createDirectory(at: backupDirectory, withIntermediateDirectories: true) diff --git a/Sources/AgentPetCore/Integration/ExtensionConfigurator.swift b/Sources/AgentPetCore/Integration/ExtensionConfigurator.swift new file mode 100644 index 0000000..77a3129 --- /dev/null +++ b/Sources/AgentPetCore/Integration/ExtensionConfigurator.swift @@ -0,0 +1,235 @@ +import Foundation + +/// The extension file the runtime installs into an agent that is extended by +/// dropping one file into a directory, rather than by editing a table in a +/// configuration file. +/// +/// Oh My Pi is the first of these: it loads every `*.ts` in +/// `~/.omp/agent/extensions/` at session start, so the integration is a file +/// rather than an edit — which makes install a write and removal a delete, and +/// makes "did we write this?" a question about the file's own contents. +/// +/// Generated in code rather than shipped as a resource, for the same reason +/// `HookSetup` assembles Claude Code's hooks in code: the exact text can be +/// asserted in tests and read without installing anything. +public enum AgentPetExtension { + + /// The name the runtime installs under. One file per extension, so the + /// name *is* the identity — a second copy would be a second extension. + public static let fileName = "agentpet.ts" + + /// A line present in every file the runtime writes, and therefore the only + /// evidence it accepts that such a file is its own before replacing it. + /// Removal asks a different question — whether the file still carries the + /// `// shim:` line the *record* holds — so a file that lost that line is + /// left alone even though this marker still identifies it. Stable across + /// versions on purpose: the shim line below moves when the app does, and a + /// file written by an older build still has to be recognisable as ours. + public static let ownershipMarker = "// agentpet-runtime extension" + + /// The line naming the shim and the agent this copy reports to. + /// + /// Recorded verbatim in the `IntegrationRecord`, so removal matches on + /// content rather than on a rule — the same contract the hook lines have, + /// and what lets an install made by a since-moved runtime still be + /// recognised (and replaced) later. + public static func markerLine(agentID: String, shimPath: String) -> String { + ExtensionTemplate.markerLine(agentID: agentID, shimPath: shimPath) + } + + /// Whether a file's text is one of ours. + public static func owns(_ text: String) -> Bool { + text.contains(ownershipMarker) + } + + /// Every event the installed extension listens for. + /// + /// Kept here — rather than only inside the generated source — so a test can + /// prove the two agree, and that the normalizer has a rule for each of + /// them. An event with no rule would be a process spawned per occurrence + /// for a state change that cannot happen. + public static let listenedEvents: [String] = [ + "session_start", + "agent_start", + "tool_execution_start", + "tool_execution_end", + "tool_approval_requested", + "tool_approval_resolved", + "agent_end", + "session_shutdown", + ] + + /// Every event the extension actually reports, which is one more than it + /// listens for: the context reading rides out of the settle handler rather + /// than off an event of its own. + public static let reportedEvents = listenedEvents + ["context_update"] + + + + /// The extension's source for this agent, through the template both + /// extension-file integrations share (`ExtensionTemplate`); `PiConfigurator` + /// enters it at `.pi`. + /// + /// Every handler reports and returns nothing: + /// omp runs extension handlers in-process, `tool_call` handlers fail + /// *closed* (a throw blocks the tool), and a pet that changed what the + /// agent does would be a far worse bug than one that misses an event. So + /// no handler here is registered for an event that can block, the two + /// registrations that do have a cost are called out in the file itself, + /// and every step is wrapped so a failure cannot reach the agent. + public static func source(agentID: String, shimPath: String) -> String { + ExtensionTemplate.source( + agentID: agentID, + shimPath: shimPath, + events: .ohMyPi, + marker: "\(ownershipMarker) — installed by Agent Pet Runtime." + ) + } + + /// A JavaScript string literal, escaped rather than interpolated. + /// + /// Paths are the only thing here that comes from outside, and a path can + /// legally contain a quote or a backslash. Building the literal by + /// concatenation is how a path with an apostrophe silently breaks a + /// generated file; escaping is how it does not. + static func jsStringLiteral(_ value: String) -> String { + ExtensionTemplate.jsStringLiteral(value) + } +} + +/// Installs the runtime's extension for agents whose integration is one file +/// in an extensions directory. +/// +/// The JSON transaction cannot do this — its whole job is editing a table +/// inside a file somebody else owns, and this file is *ours*, whole. What it +/// keeps is the discipline: snapshot, back up before changing anything, +/// write atomically, read back and prove the result, and never touch a file +/// that is not ours. +public struct ExtensionFileConfigurator: AgentConfigurator { + + public let agentID: String + /// The directory the agent scans, e.g. `~/.omp/agent/extensions`. + public let directory: URL + public let fileName: String + private let transaction: ConfigTransaction + + public init( + agentID: String, + directory: URL, + fileName: String = AgentPetExtension.fileName, + transaction: ConfigTransaction + ) { + self.agentID = agentID + self.directory = directory + self.fileName = fileName + self.transaction = transaction + } + + public var fileURL: URL { directory.appendingPathComponent(fileName) } + + public func configurationTargets() -> [URL] { [fileURL] } + + /// True when the file exists and still carries every line the record says + /// the runtime wrote into it — the shim line included, so a file whose + /// marker line was rewritten (by hand, or by a later Configure with a + /// different shim path) is reported as disconnected until Configure runs + /// again. A moved app is deliberately *not* one of these cases: nothing + /// compares the path in the record with the path in use, and the record and + /// the file are written together, so they agree until something rewrites + /// one of them. + public func entriesPresent(in record: IntegrationRecord) -> Bool { + guard !record.entries.isEmpty else { return false } + guard let text = try? String(contentsOf: fileURL, encoding: .utf8) else { return false } + return record.entries.allSatisfy { text.contains($0.command) } + } + + public func configure( + shimPath: String, + replacing previous: IntegrationRecord?, + now: Date + ) throws -> ConfigurationOutcome { + + let source = AgentPetExtension.source(agentID: agentID, shimPath: shimPath) + let entry = WrittenEntry( + file: fileURL.path, + event: fileName, + command: AgentPetExtension.markerLine(agentID: agentID, shimPath: shimPath) + ) + + let record = IntegrationRecord( + agentID: agentID, + status: .configured, + configuredAt: previous?.configuredAt ?? now, + lastValidatedAt: now, + shimPath: shimPath, + entries: [entry] + ) + + // A file we did not write is somebody's extension — and one we cannot + // even read as text certainly is: `String(decoding:)` substitutes + // replacement characters for anything that is not UTF-8, so a marker + // cannot survive the trip and this refuses it either way. + if let data = try? Data(contentsOf: fileURL), + !AgentPetExtension.owns(String(decoding: data, as: UTF8.self)) { + throw ConfigurationError.foreignFile(fileURL.path) + } + + // The same text transaction the other extension integration uses: + // snapshot, back up, write atomically, read back, and restore on any + // failure. It also decides idempotency, so a second Configure with the + // same shim path changes nothing at all, not even a rewrite. + let outcome = try transaction.performText( + on: fileURL, + transform: { text in text = source }, + verify: { + AgentPetExtension.owns($0) + && $0.contains(AgentPetExtension.jsStringLiteral(shimPath)) + } + ) + + return ConfigurationOutcome( + record: record, + changedFiles: outcome.didChange ? [fileURL.path] : [], + backupURLs: outcome.backupURL.map { [$0.path] } ?? [] + ) + } + + public func uninstall(_ record: IntegrationRecord, now: Date) throws -> ConfigurationOutcome { + let updated = IntegrationRecord( + agentID: agentID, + status: .notConfigured, + configuredAt: record.configuredAt, + lastValidatedAt: now, + shimPath: record.shimPath, + entries: [] + ) + + let snapshot = try transaction.snapshot(fileURL) + guard snapshot.existed, + let text = String(data: snapshot.contents, encoding: .utf8), + !record.entries.isEmpty, + record.entries.allSatisfy({ text.contains($0.command) }) + else { + // Already gone, or replaced by hand: there is nothing of ours left + // to remove, and that is not a failure. + return ConfigurationOutcome(record: updated, changedFiles: [], backupURLs: []) + } + + // Kept even though the file is ours: a backup is what makes deleting a + // file reversible, and the user may have added to it since. + var backups: [String] = [] + if let backup = try transaction.backUp(snapshot) { backups.append(backup.path) } + + do { + try FileManager.default.removeItem(at: fileURL) + } catch { + throw ConfigurationError.transactionFailed( + "could not remove \(fileURL.path): \(error)" + ) + } + + // The directory itself is left alone: the agent scans it, an empty + // extensions directory means "no extensions", and it may predate us. + return ConfigurationOutcome(record: updated, changedFiles: [fileURL.path], backupURLs: backups) + } +} diff --git a/Sources/AgentPetCore/Integration/ExtensionTemplate.swift b/Sources/AgentPetCore/Integration/ExtensionTemplate.swift new file mode 100644 index 0000000..2a1a67c --- /dev/null +++ b/Sources/AgentPetCore/Integration/ExtensionTemplate.swift @@ -0,0 +1,286 @@ +import Foundation + +/// The TypeScript both extension-file integrations install. +/// +/// Pi and Oh My Pi share the extension API — omp is Pi rebranded — but not the +/// events the pet needs; those events, the agent's id, its ownership marker and +/// the cost note are what vary between the two generated files: +/// +/// | what it is for | Pi 0.85 | Oh My Pi 18 | +/// |---|---|---| +/// | "blocked on you" | `ui_prompt_start` (its own prompt is on screen) | `tool_approval_requested` / the `ask` tool | +/// | a finished turn | `agent_settled` | `agent_end`, minus the ones carrying `willContinue` | +/// +/// A plain `agent_end` is not a settle on Pi (an auto-retry or a queued +/// follow-up may still run), and `agent_settled` does not exist on omp at all +/// (checked against 18.1.22), so one file cannot be right for both. Everything +/// else is shared: the shim invocation, the session id, the reduced context +/// reading, and the environment payload channel. +public enum ExtensionTemplate { + + /// Which events the agent's runtime actually fires. + public enum EventSet: Sendable { + case pi + case ohMyPi + } + + /// The line naming the shim and the agent a generated file reports to. + /// + /// Written into the file and recorded verbatim in the `IntegrationRecord`, + /// so presence and removal are one question: is every recorded line still + /// there? Comment-safe, because this line is a comment and a path can + /// contain a line separator. + public static func markerLine(agentID: String, shimPath: String) -> String { + "// shim: \(commentSafe(shimPath)) --agent \(commentSafe(agentID))" + } + + /// The path as it may appear inside a `//` comment line. + /// + /// A path can contain a line separator (legal on APFS), and one inside a + /// comment ends it — the rest of the path is then parsed as code and the + /// file does not load, while the record still claims it is present, so + /// nothing reports it. The recorded marker line goes through the same + /// transformation, or removal would stop matching the file it wrote. + public static func commentSafe(_ value: String) -> String { + value + .replacingOccurrences(of: "\n", with: " ") + .replacingOccurrences(of: "\r", with: " ") + .replacingOccurrences(of: "\u{2028}", with: " ") + .replacingOccurrences(of: "\u{2029}", with: " ") + } + + /// A JavaScript string literal, quoted and escaped. + /// + /// Paths are the only thing here that comes from outside, and a path can + /// legally contain a quote or a backslash. Building the literal by + /// concatenation is how a path with an apostrophe silently breaks a + /// generated file; escaping is how it does not. Quotes included, because + /// callers also use this to ask "is the recorded path still in the file?". + public static func jsStringLiteral(_ value: String) -> String { + var out = "\"" + for scalar in value.unicodeScalars { + switch scalar { + case "\"": out += "\\\"" + case "\\": out += "\\\\" + case "\n": out += "\\n" + case "\r": out += "\\r" + case "\t": out += "\\t" + default: + if scalar.value < 0x20 { + out += String(format: "\\u%04x", scalar.value) + } else { + out.unicodeScalars.append(scalar) + } + } + } + return out + "\"" + } + + /// The whole file: a marker line, the shim call, and the handlers for + /// `events`. + /// + /// Plain JavaScript (valid TypeScript), node built-ins only, and fire and + /// forget — the same contract the hooks keep. The pet missing an event is + /// invisible; an extension that stalls the agent is not. + public static func source( + agentID: String, + shimPath: String, + events: EventSet, + marker: String + ) -> String { + let shim = jsStringLiteral(shimPath) + let agent = jsStringLiteral(agentID) + + return """ + \(marker) + \(markerLine(agentID: agentID, shimPath: shimPath)) + // + // Remove with: AgentPet --unconfigure \(agentID) + // (or the manager window's Remove Integration) + // + // What it does: reports session state to the desktop pet by spawning + // the runtime's hook shim, once per event, with a small JSON payload in + // the environment — the session id, the working directory, and, on the + // tool events that carry one, the tool's name — plus one reduced + // context reading per finished turn. Prompts, tool arguments, tool + // output, and model output are never read, and nothing is written + // anywhere. + // + \(costNote(for: events)) + // + // It is deliberately a report and never a gate. Every step is wrapped + // so a failure cannot reach the agent, the child is detached and + // unref'd so it can neither hold up a turn nor outlive the session, + // and it is told to touch nothing but its own arguments and the one + // environment variable carrying this event. + + import { spawn } from "node:child_process"; + import { basename } from "node:path"; + + const SHIM = \(shim); + const AGENT = \(agent); + + // The session id is what the pet draws a row from, so it has to be the + // same for every event of one session and different between sessions. + // The session manager's id is preferred (the bare one, not the session + // file's `_` name); a session that has not been persisted + // yet falls back to its file's name, and a sessionless process to its + // pid, rather than sharing a row with every other session. + function sessionIdFor(ctx) { + try { + const id = ctx && ctx.sessionManager ? ctx.sessionManager.getSessionId() : null; + if (id) return String(id); + const file = ctx && ctx.sessionManager && ctx.sessionManager.getSessionFile + ? ctx.sessionManager.getSessionFile() + : null; + if (file) { + const name = basename(String(file)); + return name.endsWith(".jsonl") ? name.slice(0, -6) : name; + } + } catch {} + return "pid-" + process.pid; + } + + function send(event, payload) { + try { + // The payload goes through the environment, not stdin. This code + // runs inside the agent's own runtime, where a write to a pipe is + // queued on an event loop the agent may be holding: measured, a + // busy stretch of 30ms between spawning the shim and writing to it + // is enough for the shim to give up waiting and report the event + // with no session at all. The environment is delivered at spawn + // time by the kernel, so there is nothing to be late for. + const env = { ...process.env }; + env.AGENTPET_PAYLOAD_BASE64 = Buffer.from(JSON.stringify(payload), "utf8").toString("base64"); + + const child = spawn(SHIM, ["--agent", AGENT, "--event", event], { + // The shim never prints, and this process runs inside a terminal + // the agent is drawing: nothing it says may reach that terminal. + stdio: ["ignore", "ignore", "ignore"], + detached: true, + env, + }); + child.on("error", () => {}); + child.unref(); + } catch {} + } + + function report(event, ctx, toolName) { + try { + const payload = { session_id: sessionIdFor(ctx), cwd: (ctx && ctx.cwd) || "" }; + if (toolName) payload.toolName = String(toolName); + send(event, payload); + } catch {} + } + + // The same reduced shape the status-line taps deliver: session id, + // percentage, window, tokens, model. Nothing else leaves this process. + function contextPayload(ctx) { + try { + const usage = ctx.getContextUsage ? ctx.getContextUsage() : null; + const tokens = usage && usage.tokens; + if (typeof tokens !== "number") return null; + const model = ctx.model; + const window = model && model.contextWindow; + const payload = { + session_id: sessionIdFor(ctx), + tokens: Math.round(tokens), + model: model ? (model.name || model.id) : undefined, + }; + if (typeof window === "number" && window > 0) { + payload.window = window; + payload.used_percentage = Math.round((tokens / window) * 1000) / 10; + } + return payload; + } catch { + return null; + } + } + + function reportContext(ctx) { + const context = contextPayload(ctx); + if (context) send("context_update", context); + } + + export default function (pi) { + pi.on("session_start", (_event, ctx) => report("session_start", ctx)); + pi.on("agent_start", (_event, ctx) => report("agent_start", ctx)); + pi.on("session_shutdown", (_event, ctx) => report("session_shutdown", ctx)); + + // One event per tool, so the panel can name the tool being used. The + // shim always exits 0 and this handler returns nothing: neither can + // change what the agent does. + pi.on("tool_execution_start", (event, ctx) => + report("tool_execution_start", ctx, event && event.toolName)); + \(registrations(events)) + } + """ + } + + /// What the installed file costs, stated where the user can read it. + /// + /// Not shared between the two: the cost belongs to the agent that charges + /// it, and a note that described one of them in the other's file would be + /// false twice over (omp's gate is on tool-lifecycle handlers, which the Pi + /// file does not register, and Pi has no speculative execution to lose). + static func costNote(for events: EventSet) -> String { + switch events { + case .ohMyPi: + return """ + // What it costs: omp will not run its experimental speculative local reads + // (settings: tools.speculativeExecution.enabled, off by default) while any + // extension has a handler on one of the four tool-lifecycle events — + // tool_call, tool_result, tool_approval_requested, tool_approval_resolved + // (src/speculation/host.ts). This file takes the last two, which is how an + // approval shows up as "Needs input". Uninstalling restores speculation. + """ + case .pi: + return """ + // What it costs: nothing. This file takes no tool_call, tool_result, or + // approval event and rewrites no argument, so the agent runs exactly as it + // would without it. + """ + } + } + + /// The handlers that differ between the two event sets. + private static func registrations(_ events: EventSet) -> String { + switch events { + case .pi: + return """ + // Pi raises this while one of its own prompts — a permission + // gate, a picker — is on screen: the one "it is waiting for you" + // signal the extension can draw from. + pi.on("ui_prompt_start", (_event, ctx) => report("ui_prompt_start", ctx)); + + // agent_settled, not agent_end: after agent_end Pi may still run an + // auto-retry or a queued follow-up, so a plain agent_end is not a + // finished turn. + pi.on("agent_settled", (_event, ctx) => { + report("agent_settled", ctx); + reportContext(ctx); + }); + """ + case .ohMyPi: + return """ + pi.on("tool_execution_end", (_event, ctx) => report("tool_execution_end", ctx)); + + // The approval gate: the tool is held until the user answers. + pi.on("tool_approval_requested", (event, ctx) => + report("tool_approval_requested", ctx, event && event.toolName)); + pi.on("tool_approval_resolved", (event, ctx) => + report("tool_approval_resolved", ctx, event && event.toolName)); + + // `willContinue` means a retry is already scheduled, so this is not + // the user-visible end of the turn — and omp has no agent_settled to + // prefer (checked against 18.1.22). + pi.on("agent_end", (event, ctx) => { + if (!event || !event.willContinue) { + report("agent_end", ctx); + reportContext(ctx); + } + }); + """ + } + } +} diff --git a/Sources/AgentPetCore/Integration/PiConfigurator.swift b/Sources/AgentPetCore/Integration/PiConfigurator.swift index 0bd34c1..c881f17 100644 --- a/Sources/AgentPetCore/Integration/PiConfigurator.swift +++ b/Sources/AgentPetCore/Integration/PiConfigurator.swift @@ -6,8 +6,8 @@ import Foundation /// Pi extensions run with the user's full permissions, so the file is written /// plainly — readable, marked at the top, and self-contained (node built-ins /// only, no package install, no settings edit). Uninstall deletes exactly that -/// file, and only while it still carries the marker; anything the user wrote -/// is refused rather than overwritten. +/// file, and only while it still carries every line the record says was +/// written into it; anything the user wrote is refused rather than overwritten. public struct PiConfigurator: AgentConfigurator { public let agentID = "pi" @@ -19,7 +19,6 @@ public struct PiConfigurator: AgentConfigurator { public let extensionURL: URL private let transaction: ConfigTransaction - private let backupDirectory: URL public init( home: URL = FileManager.default.homeDirectoryForCurrentUser, @@ -27,121 +26,39 @@ public struct PiConfigurator: AgentConfigurator { ) { self.extensionURL = home.appendingPathComponent(".pi/agent/extensions/agentpet.ts") self.transaction = transaction - self.backupDirectory = transaction.backupDirectory } public func configurationTargets() -> [URL] { [extensionURL] } // MARK: - Template - /// The path as it appears inside the template's JavaScript string literal. - static func jsStringLiteral(_ path: String) -> String { - path - .replacingOccurrences(of: "\\", with: "\\\\") - .replacingOccurrences(of: "\"", with: "\\\"") - } - + /// The generated file is shared with Oh My Pi's integration — one template, + /// with the event set and the ownership marker as its parameters + /// (`ExtensionTemplate`). public static func template(shimPath: String) -> String { - templateSource.replacingOccurrences( - of: "__AGENTPET_SHIM__", with: jsStringLiteral(shimPath) + ExtensionTemplate.source( + agentID: "pi", + shimPath: shimPath, + events: .pi, + marker: "\(marker) — installed by Agent Pet Runtime." ) } - /// Plain JavaScript (valid TypeScript), node built-ins only. Fire and - /// forget, the same contract the hooks keep: the pet missing an event is - /// invisible, an extension that stalls the agent is not. - static let templateSource = #""" - // agentpet-extension v1 — installed by Agent Pet Runtime. - // Reports session lifecycle and context usage to the pet, nothing else. - // Delete this file to remove the integration; the runtime deletes it too. - import { spawn } from "node:child_process"; - import { basename } from "node:path"; - - const SHIM = "__AGENTPET_SHIM__"; - - function sessionIdFor(ctx) { - try { - const file = ctx && ctx.sessionManager && ctx.sessionManager.getSessionFile - ? ctx.sessionManager.getSessionFile() - : null; - if (file) return basename(String(file)).replace(/\.jsonl$/, ""); - } catch {} - return `pid-${process.pid}`; - } - - // The payload goes through the environment, not stdin. This code runs - // inside the agent's own runtime, where a write to a pipe is queued on an - // event loop the agent may be holding: measured on the sibling extension - // (Oh My Pi, PR #1), a 30 ms busy stretch between spawning the shim and - // writing to it is enough for the shim's stdin deadline to expire, and the - // event then arrives with no session at all. The environment is handed to - // the child by the kernel at spawn time, so there is nothing to be late for. - function report(event, payload) { - try { - const env = { ...process.env }; - env.AGENTPET_PAYLOAD_BASE64 = Buffer.from(JSON.stringify(payload), "utf8").toString("base64"); - const proc = spawn(SHIM, ["--agent", "pi", "--event", event], { - stdio: ["ignore", "ignore", "ignore"], - detached: true, - env, - }); - proc.on("error", () => {}); - proc.unref(); - } catch {} - } - - // The same reduced shape the status-line taps deliver: session id, - // percentage, window, tokens, model. Nothing else leaves this process. - function contextPayload(ctx) { - try { - const usage = ctx.getContextUsage ? ctx.getContextUsage() : null; - const tokens = usage && usage.tokens; - if (typeof tokens !== "number") return null; - const model = ctx.model; - const window = model && model.contextWindow; - const payload = { - session_id: sessionIdFor(ctx), - tokens: Math.round(tokens), - model: model ? (model.name || model.id) : undefined, - }; - if (typeof window === "number" && window > 0) { - payload.window = window; - payload.used_percentage = Math.round((tokens / window) * 1000) / 10; - } - return payload; - } catch { - return null; - } - } - - export default function (pi) { - pi.on("session_start", (_e, ctx) => - report("session_start", { session_id: sessionIdFor(ctx), cwd: ctx.cwd })); - pi.on("agent_start", (_e, ctx) => - report("agent_start", { session_id: sessionIdFor(ctx), cwd: ctx.cwd })); - pi.on("tool_execution_start", (e, ctx) => - report("tool_execution_start", { session_id: sessionIdFor(ctx), cwd: ctx.cwd, toolName: e.toolName })); - pi.on("ui_prompt_start", (_e, ctx) => - report("ui_prompt_start", { session_id: sessionIdFor(ctx), cwd: ctx.cwd })); - pi.on("agent_settled", (_e, ctx) => { - report("agent_settled", { session_id: sessionIdFor(ctx), cwd: ctx.cwd }); - const context = contextPayload(ctx); - if (context) report("context_update", context); - }); - pi.on("session_shutdown", (_e, ctx) => - report("session_shutdown", { session_id: sessionIdFor(ctx), cwd: ctx.cwd })); - } - """# // MARK: - Reading + /// True while the file carries every line the record says was written into + /// it — the same rule the Oh My Pi configurator uses, deliberately. + /// + /// A v0.9.6 record reads correctly under it: its entry is the marker line, + /// which the file it wrote still contains. A record written from here on + /// carries the `// shim:` line instead, which the new files contain. public func entriesPresent(in record: IntegrationRecord) -> Bool { - guard let shimPath = record.shimPath, + guard !record.entries.isEmpty, let data = try? Data(contentsOf: extensionURL), let text = String(data: data, encoding: .utf8) else { return false } - return text.contains(Self.marker) - && text.contains(Self.jsStringLiteral(shimPath)) + return record.entries.allSatisfy { text.contains($0.command) } } // MARK: - Configure @@ -165,10 +82,11 @@ public struct PiConfigurator: AgentConfigurator { } let template = Self.template(shimPath: shimPath) + let recorded = ExtensionTemplate.markerLine(agentID: agentID, shimPath: shimPath) let outcome = try transaction.performText( on: extensionURL, transform: { text in text = template }, - verify: { $0.contains(Self.marker) && $0.contains(Self.jsStringLiteral(shimPath)) } + verify: { $0.contains(Self.marker) && $0.contains(recorded) } ) let record = IntegrationRecord( @@ -177,7 +95,7 @@ public struct PiConfigurator: AgentConfigurator { configuredAt: previous?.configuredAt ?? now, lastValidatedAt: now, shimPath: shimPath, - entries: [WrittenEntry(file: extensionURL.path, event: "extension", command: Self.marker)] + entries: [WrittenEntry(file: extensionURL.path, event: "extension", command: recorded)] ) return ConfigurationOutcome( @@ -193,26 +111,26 @@ public struct PiConfigurator: AgentConfigurator { _ record: IntegrationRecord, now: Date ) throws -> ConfigurationOutcome { - var changed = false - var backups: [String] = [] - - if let data = try? Data(contentsOf: extensionURL), - let text = String(data: data, encoding: .utf8), - text.contains(Self.marker) { - // Backed up before the delete, the same as every other edit here. - try FileManager.default.createDirectory( - at: backupDirectory, withIntermediateDirectories: true - ) - let backup = backupDirectory.appendingPathComponent( - "\(extensionURL.lastPathComponent)." - + "\(Int(Date().timeIntervalSince1970)).\(Hashing.sha256(data).prefix(8))" + guard entriesPresent(in: record), + let snapshot = try? transaction.snapshot(extensionURL) + else { + let updated = IntegrationRecord( + agentID: agentID, + status: .notConfigured, + configuredAt: record.configuredAt, + lastValidatedAt: now, + shimPath: record.shimPath, + entries: [] ) - try data.write(to: backup, options: .atomic) - backups.append(backup.path) - try FileManager.default.removeItem(at: extensionURL) - changed = true + return ConfigurationOutcome(record: updated, changedFiles: [], backupURLs: []) } + // Through the transaction, so the same retention policy bounds this + // backup — the file the record says is ours is the only thing removed. + var backups: [String] = [] + if let backup = try transaction.backUp(snapshot) { backups.append(backup.path) } + try FileManager.default.removeItem(at: extensionURL) + let updated = IntegrationRecord( agentID: agentID, status: .notConfigured, @@ -223,7 +141,7 @@ public struct PiConfigurator: AgentConfigurator { ) return ConfigurationOutcome( record: updated, - changedFiles: changed ? [extensionURL.path] : [], + changedFiles: [extensionURL.path], backupURLs: backups ) } diff --git a/Tests/AgentPetCoreTests/AgentConfiguratorTests.swift b/Tests/AgentPetCoreTests/AgentConfiguratorTests.swift index 5f91b4f..e4487d4 100644 --- a/Tests/AgentPetCoreTests/AgentConfiguratorTests.swift +++ b/Tests/AgentPetCoreTests/AgentConfiguratorTests.swift @@ -392,8 +392,9 @@ struct AgentIntegrationRegistryTests { where profile.configurator == nil { let note = profile.configurationNote ?? "" #expect(!note.isEmpty, "\(profile.agentID) is not configurable and says nothing about it") - // Only Codex has no configurator today; the uniqueness check - // stays armed for the next agent that does not. + // Every agent registered today has a configurator, so this loop is + // idle; the uniqueness check stays armed for the next agent that + // arrives without one. #expect(seen.insert(note).inserted, "\(profile.agentID) reuses another agent's note") } } diff --git a/Tests/AgentPetCoreTests/BridgeEndToEndTests.swift b/Tests/AgentPetCoreTests/BridgeEndToEndTests.swift index 11cb875..1ec3f4e 100644 --- a/Tests/AgentPetCoreTests/BridgeEndToEndTests.swift +++ b/Tests/AgentPetCoreTests/BridgeEndToEndTests.swift @@ -242,6 +242,53 @@ struct BridgeEndToEndTests { try #require(bound == 0) } + @Test("a real shim event from Oh My Pi drives the pet's state machine") + func ohMyPiReachesTheEngine() async throws { + // The whole chain for the new agent, with no stand-ins on either side: + // the shipped extension's payload shape, the real shim, a real bridge, + // the real normalizer, and the activity engine that decides what the + // pet shows. + let box = EnvelopeBox() + let (server, socket) = try makeServer(box) + defer { server.stop() } + + let clock = ManualActivityClock(Date(timeIntervalSince1970: 1_700_000_000)) + let engine = ActivityEngine(clock: clock) + let normalizer = EventNormalizer(profiles: AgentProfiles.all) + var expected = 0 + + func send(event: String, extra: String = "") async throws -> AgentEvent? { + let payload = #"{"session_id":"omp-session","cwd":"/tmp/project""# + extra + "}" + try runShim( + socket: socket, agent: "omp", event: event, + payload: payload, payloadViaEnvironment: true + ) + // The shim has exited, but the server appends on its own thread. + expected += 1 + let arrived = await waitForEnvelopes(box, count: expected) + #expect(arrived, "no envelope arrived for \(event)") + guard let envelope = box.envelopes.last else { return nil } + return normalizer.normalize(envelope).first + } + + let started = try await send(event: "agent_start") + #expect(started?.kind == .working) + if let started { engine.ingest(started) } + #expect(engine.currentFocus()?.state == .running) + + // The ask tool is a question put to the user: the pet must say so. + let asking = try await send(event: "tool_execution_start", extra: #","toolName":"ask""#) + #expect(asking?.kind == .waitingInput) + if let asking { engine.ingest(asking) } + #expect(engine.currentFocus()?.state == .waitingInput) + #expect(engine.currentFocus()?.toolName == "ask") + + // Answering it ends that tool call, and the agent carries on. + let answered = try await send(event: "tool_execution_end", extra: #","toolName":"ask""#) + if let answered { engine.ingest(answered) } + #expect(engine.currentFocus()?.state == .running) + } + @Test("a payload sent by the real shim arrives as a usable agent event") func fullRoundTrip() async throws { let box = EnvelopeBox() diff --git a/Tests/AgentPetCoreTests/ExtensionConfiguratorTests.swift b/Tests/AgentPetCoreTests/ExtensionConfiguratorTests.swift new file mode 100644 index 0000000..3c5594e --- /dev/null +++ b/Tests/AgentPetCoreTests/ExtensionConfiguratorTests.swift @@ -0,0 +1,306 @@ +import Foundation +import Testing +@testable import AgentPetCore + +private let ompEpoch = Date(timeIntervalSince1970: 1_700_000_000) +private let ompShim = "/Applications/AgentPet.app/Contents/MacOS/agentpet-hook" + +/// A throwaway home whose `.omp/agent/extensions` directory is the target. +private final class ExtensionSandbox { + let root: URL + let extensions: URL + + init() throws { + root = URL(fileURLWithPath: NSTemporaryDirectory()) + .appendingPathComponent("agentpet-omp-\(UUID().uuidString)") + extensions = root.appendingPathComponent(".omp/agent/extensions") + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + } + + deinit { try? FileManager.default.removeItem(at: root) } + + var transaction: ConfigTransaction { + ConfigTransaction(backupDirectory: root.appendingPathComponent("backups"), maxBackups: 5) + } + + func configurator() -> ExtensionFileConfigurator { + ExtensionFileConfigurator(agentID: "omp", directory: extensions, transaction: transaction) + } + + var fileURL: URL { extensions.appendingPathComponent(AgentPetExtension.fileName) } + + func text() -> String? { try? String(contentsOf: fileURL, encoding: .utf8) } + + func writeForeignFile() throws { + try FileManager.default.createDirectory(at: extensions, withIntermediateDirectories: true) + try Data("export default function (pi) { pi.on(\"session_start\", () => {}); }\n".utf8) + .write(to: fileURL) + } + + func backups() -> [URL] { + let directory = root.appendingPathComponent("backups") + return (try? FileManager.default.contentsOfDirectory( + at: directory, includingPropertiesForKeys: nil + )) ?? [] + } +} + +@Suite("Oh My Pi extension installation") +struct ExtensionInstallationTests { + + @Test("configuring writes one extension file, creating the directory") + func installsTheFile() throws { + let sandbox = try ExtensionSandbox() + let outcome = try sandbox.configurator().configure(shimPath: ompShim, replacing: nil, now: ompEpoch) + + #expect(outcome.didChange) + #expect(outcome.record.isConfigured) + #expect(outcome.changedFiles == [sandbox.fileURL.path]) + #expect(FileManager.default.fileExists(atPath: sandbox.fileURL.path)) + + let text = try #require(sandbox.text()) + #expect(text.contains(AgentPetExtension.ownershipMarker)) + #expect(text.contains(AgentPetExtension.markerLine(agentID: "omp", shimPath: ompShim))) + #expect(text.contains("--agent omp")) + // The loader imports the file and calls what it default-exports; a file + // without one is not an extension at all. + #expect(text.contains("export default function (pi)")) + } + + @Test("the extension reports and never gates, injects, or writes") + func reportsOnly() throws { + let sandbox = try ExtensionSandbox() + _ = try sandbox.configurator().configure(shimPath: ompShim, replacing: nil, now: ompEpoch) + let text = try #require(sandbox.text()) + + // The three ways an in-process extension could change the agent: block + // a tool (fail-closed), inject a message into the session, or touch the + // user's files. The blocking check is for the result shape omp honours + // — `{ block: true }` — since the prose above is allowed to say the + // word. + #expect(!text.contains("block:"), "the extension must never return a blocking result") + #expect(!text.contains("sendMessage"), "the extension must never inject messages") + #expect(!text.contains("writeFile") && !text.contains("node:fs")) + // No modal UI either: a pet that could open a prompt inside the agent + // would be running the agent rather than watching it. + #expect(!text.contains("ctx.ui")) + } + + @Test("the extension hands the payload over in the environment, not on a pipe") + func payloadGoesThroughTheEnvironment() throws { + let sandbox = try ExtensionSandbox() + _ = try sandbox.configurator().configure(shimPath: ompShim, replacing: nil, now: ompEpoch) + let text = try #require(sandbox.text()) + + #expect(text.contains("AGENTPET_PAYLOAD_BASE64")) + // A pipe write from inside the agent's runtime is queued on an event + // loop the agent may be holding, and the shim stops waiting for stdin + // after 20ms: an event whose payload misses that window arrives with no + // session id at all. Writing to stdin here would reintroduce exactly + // that (measured: 30ms of block was enough to lose it). + #expect(!text.contains("child.stdin"), "the payload must not depend on a pipe write") + } + + @Test("configuring twice rewrites nothing") + func idempotent() throws { + let sandbox = try ExtensionSandbox() + let configurator = sandbox.configurator() + + let first = try configurator.configure(shimPath: ompShim, replacing: nil, now: ompEpoch) + let before = try #require(sandbox.text()) + let second = try configurator.configure(shimPath: ompShim, replacing: first.record, now: ompEpoch) + + #expect(!second.didChange, "the second configure must be a no-op") + #expect(second.changedFiles.isEmpty) + #expect(sandbox.text() == before) + #expect(sandbox.backups().isEmpty, "a no-op must not leave a backup behind") + } + + @Test("a moved runtime replaces the file rather than adding a second one") + func relocationReplaces() throws { + let sandbox = try ExtensionSandbox() + let configurator = sandbox.configurator() + + let first = try configurator.configure( + shimPath: "/old/path/agentpet-hook", replacing: nil, now: ompEpoch + ) + let second = try configurator.configure( + shimPath: ompShim, replacing: first.record, now: ompEpoch + ) + + let text = try #require(sandbox.text()) + #expect(text.contains(ompShim)) + #expect(!text.contains("/old/path/agentpet-hook")) + #expect(configurator.entriesPresent(in: second.record)) + // One extension per file: a second copy under a second name is the + // failure mode this rules out. + let installed = try FileManager.default.contentsOfDirectory(atPath: sandbox.extensions.path) + #expect(installed == [AgentPetExtension.fileName]) + } + + @Test("a file the runtime did not write is refused, not clobbered") + func foreignFileRefused() throws { + let sandbox = try ExtensionSandbox() + try sandbox.writeForeignFile() + let before = try #require(sandbox.text()) + + #expect(throws: ConfigurationError.foreignFile(sandbox.fileURL.path)) { + _ = try sandbox.configurator().configure(shimPath: ompShim, replacing: nil, now: ompEpoch) + } + #expect(sandbox.text() == before, "somebody else's extension was overwritten") + } + + @Test("a file that is not even text is refused too") + func undecodableFileRefused() throws { + // It cannot be ours — ours is generated ASCII — so the ownership check + // must not be skipped just because it failed to decode. + let sandbox = try ExtensionSandbox() + try FileManager.default.createDirectory(at: sandbox.extensions, withIntermediateDirectories: true) + let bytes = Data([0xFF, 0xFE, 0x00, 0x41, 0x80]) + try bytes.write(to: sandbox.fileURL) + + #expect(throws: ConfigurationError.foreignFile(sandbox.fileURL.path)) { + _ = try sandbox.configurator().configure(shimPath: ompShim, replacing: nil, now: ompEpoch) + } + #expect(try Data(contentsOf: sandbox.fileURL) == bytes) + } + + @Test("a file an older runtime wrote is still recognised as ours") + func olderBuildIsOurs() throws { + // The ownership marker is version- and path-independent: a file written + // before the app moved must be replaceable, not refused. + let sandbox = try ExtensionSandbox() + try FileManager.default.createDirectory(at: sandbox.extensions, withIntermediateDirectories: true) + try Data("\(AgentPetExtension.ownershipMarker) — from an older build\n".utf8) + .write(to: sandbox.fileURL) + + let outcome = try sandbox.configurator().configure(shimPath: ompShim, replacing: nil, now: ompEpoch) + #expect(outcome.didChange) + #expect(try #require(sandbox.text()).contains(ompShim)) + } + + @Test("entriesPresent reports truthfully as the file is replaced") + func entriesPresentTracksContent() throws { + let sandbox = try ExtensionSandbox() + let configurator = sandbox.configurator() + + let first = try configurator.configure( + shimPath: "/old/path/agentpet-hook", replacing: nil, now: ompEpoch + ) + #expect(configurator.entriesPresent(in: first.record)) + + // The runtime moved and Configure was run again: the old record's shim + // line is gone, so that install is no longer reported as present — the + // same "disconnected until reconfigured" rule the hook installs follow. + let second = try configurator.configure(shimPath: ompShim, replacing: first.record, now: ompEpoch) + #expect(!configurator.entriesPresent(in: first.record)) + #expect(configurator.entriesPresent(in: second.record)) + + // And a record that claims an entry the file never had is not believed. + let fabricated = IntegrationRecord( + agentID: "omp", + status: .configured, + shimPath: ompShim, + entries: [WrittenEntry( + file: sandbox.fileURL.path, event: "agentpet.ts", command: "// shim: /nowhere" + )] + ) + #expect(!configurator.entriesPresent(in: fabricated)) + } + + @Test("a path with a quote or a backslash still produces a working file") + func awkwardPathEscaped() throws { + let sandbox = try ExtensionSandbox() + let awkward = "/tmp/o\"brien\\agent pet/agentpet-hook" + _ = try sandbox.configurator().configure(shimPath: awkward, replacing: nil, now: ompEpoch) + + let text = try #require(sandbox.text()) + let shimLine = try #require(text.split(separator: "\n").first { $0.hasPrefix("const SHIM") }) + #expect(shimLine.contains("\\\""), "the quote was not escaped: \(shimLine)") + #expect(shimLine.contains("\\\\"), "the backslash was not escaped: \(shimLine)") + } + + @Test("the string literal escapes exactly what JavaScript needs escaped") + func stringLiteralEscaping() { + #expect(AgentPetExtension.jsStringLiteral("/plain/path") == "\"/plain/path\"") + #expect(AgentPetExtension.jsStringLiteral("a\"b") == "\"a\\\"b\"") + #expect(AgentPetExtension.jsStringLiteral("a\\b") == "\"a\\\\b\"") + #expect(AgentPetExtension.jsStringLiteral("a\nb") == "\"a\\nb\"") + #expect(AgentPetExtension.jsStringLiteral("a\u{01}b") == "\"a\\u0001b\"") + } +} + +@Suite("Oh My Pi extension removal") +struct ExtensionRemovalTests { + + @Test("uninstalling deletes the file, keeping a copy of it") + func removesTheFile() throws { + let sandbox = try ExtensionSandbox() + let configurator = sandbox.configurator() + let outcome = try configurator.configure(shimPath: ompShim, replacing: nil, now: ompEpoch) + + let removal = try configurator.uninstall(outcome.record, now: ompEpoch) + #expect(removal.didChange) + #expect(removal.changedFiles == [sandbox.fileURL.path]) + #expect(!removal.record.isConfigured) + #expect(!FileManager.default.fileExists(atPath: sandbox.fileURL.path)) + #expect(sandbox.backups().count == 1, "deleting a file must be reversible") + #expect(!configurator.entriesPresent(in: outcome.record)) + // The directory is the agent's, not ours: an empty extensions + // directory is what "no extensions" looks like. + #expect(FileManager.default.fileExists(atPath: sandbox.extensions.path)) + } + + @Test("uninstalling twice is a safe no-op") + func uninstallWhenAlreadyGone() throws { + let sandbox = try ExtensionSandbox() + let configurator = sandbox.configurator() + let outcome = try configurator.configure(shimPath: ompShim, replacing: nil, now: ompEpoch) + + _ = try configurator.uninstall(outcome.record, now: ompEpoch) + let second = try configurator.uninstall(outcome.record, now: ompEpoch) + + #expect(!second.didChange) + #expect(second.changedFiles.isEmpty) + } + + @Test("a file that is no longer ours is left where it is") + func foreignFileSurvivesUninstall() throws { + let sandbox = try ExtensionSandbox() + let configurator = sandbox.configurator() + let outcome = try configurator.configure(shimPath: ompShim, replacing: nil, now: ompEpoch) + + // The user edited it into something of their own. + try Data("export default function (pi) { /* mine now */ }\n".utf8).write(to: sandbox.fileURL) + + let removal = try configurator.uninstall(outcome.record, now: ompEpoch) + #expect(!removal.didChange, "a file without our marker is not ours to delete") + #expect(FileManager.default.fileExists(atPath: sandbox.fileURL.path)) + } + + @Test("a moved runtime's install can still be removed") + func removesRecordedPathNotCurrentOne() throws { + let sandbox = try ExtensionSandbox() + let configurator = sandbox.configurator() + + // Installed from a path that no longer exists. + let old = try configurator.configure( + shimPath: "/Applications/Deleted AgentPet.app/agentpet-hook", + replacing: nil, now: ompEpoch + ) + _ = try configurator.uninstall(old.record, now: ompEpoch) + #expect(!FileManager.default.fileExists(atPath: sandbox.fileURL.path), + "removal must match the recorded marker, not the current shim path") + } + + @Test("a record with no entries removes nothing") + func emptyRecordRemovesNothing() throws { + let sandbox = try ExtensionSandbox() + let configurator = sandbox.configurator() + _ = try configurator.configure(shimPath: ompShim, replacing: nil, now: ompEpoch) + + let removal = try configurator.uninstall(IntegrationRecord(agentID: "omp"), now: ompEpoch) + #expect(!removal.didChange) + #expect(FileManager.default.fileExists(atPath: sandbox.fileURL.path)) + } +} diff --git a/Tests/AgentPetCoreTests/ExtensionTemplateSupport.swift b/Tests/AgentPetCoreTests/ExtensionTemplateSupport.swift new file mode 100644 index 0000000..68644d6 --- /dev/null +++ b/Tests/AgentPetCoreTests/ExtensionTemplateSupport.swift @@ -0,0 +1,15 @@ +import Foundation + +/// The events a generated extension registers, read off the file that will be +/// installed rather than from a list kept beside it. +/// +/// Shared by the two suites that own the two halves of one template: a second +/// copy of this parse would drift from the first the moment a registration +/// changed shape, and the suite that stopped parsing would keep passing. +func listenedEvents(inGeneratedFile source: String) -> Set { + Set( + source.components(separatedBy: "pi.on(\"").dropFirst().compactMap { chunk in + chunk.split(separator: "\"").first.map(String.init) + } + ) +} diff --git a/Tests/AgentPetCoreTests/OhMyPiTests.swift b/Tests/AgentPetCoreTests/OhMyPiTests.swift new file mode 100644 index 0000000..689e961 --- /dev/null +++ b/Tests/AgentPetCoreTests/OhMyPiTests.swift @@ -0,0 +1,234 @@ +import Foundation +import Testing +@testable import AgentPetCore + +private let ompEventEpoch = Date(timeIntervalSince1970: 1_700_000_000) +private let aShimPath = "/Applications/AgentPet.app/Contents/MacOS/agentpet-hook" + +/// The payload the installed extension writes: a session id, the working +/// directory, and a tool name where one applies. Nothing else is ever sent. +private func ompEnvelope(event: String, extra: String = "") -> BridgeEnvelope { + BridgeEnvelope( + agentID: "omp", + eventName: event, + receivedAt: ompEventEpoch, + proc: BridgeProcessInfo(pid: 2, ppid: 1, tty: "/dev/ttys004"), + rawPayload: Data(#"{"session_id":"s1","cwd":"/tmp/proj""#.utf8) + + Data(extra.utf8) + + Data("}".utf8) + ) +} + +@Suite("Oh My Pi normalization") +struct OhMyPiNormalizationTests { + + private let normalizer = EventNormalizer(profiles: AgentProfiles.all) + + @Test("the events the extension reports map to the states they mean", arguments: [ + (event: "session_start", extra: "", expected: AgentEventKind.sessionStarted), + (event: "agent_start", extra: "", expected: .working), + (event: "tool_execution_start", extra: #","toolName":"bash""#, expected: .working), + (event: "tool_execution_end", extra: #","toolName":"bash""#, expected: .working), + (event: "tool_approval_requested", extra: #","toolName":"write""#, expected: .waitingApproval), + (event: "tool_approval_resolved", extra: #","toolName":"write""#, expected: .working), + (event: "agent_end", extra: "", expected: .completed), + (event: "session_shutdown", extra: "", expected: .sessionClosed), + ]) + func eventMapping(event: String, extra: String, expected: AgentEventKind) { + let events = normalizer.normalize(ompEnvelope(event: event, extra: extra)) + #expect(events.first?.kind == expected, + "\(event) produced \(String(describing: events.first?.kind))") + } + + @Test("every event registered in the file has a rule in the profile") + func registeredEventsAreKnown() { + // The counterpart of the Claude Code check: an event that is reported + // but not normalized is a process spawned per occurrence for a state + // change that cannot happen. + let source = AgentPetExtension.source(agentID: "omp", shimPath: aShimPath) + let profile = AgentProfiles.profile(for: "omp") + let known = Set((profile?.rules ?? []).flatMap(\.matches)) + + // Every event the file listens for is one the profile knows. + for event in AgentPetExtension.listenedEvents { + #expect(source.contains("pi.on(\"\(event)\""), "\(event) is listed but never registered") + } + // And every event it *sends* has a rule, including the context reading + // that rides out of the settle handler. + for event in AgentPetExtension.reportedEvents { + #expect(known.contains(event), "\(event) is reported but no rule mentions it") + } + + // Nothing is registered behind the list's back. + let registered = listenedEvents(inGeneratedFile: source) + #expect(registered == Set(AgentPetExtension.listenedEvents), "registered: \(registered.sorted())") + } + + @Test("the keys the file writes are the keys the profile reads") + func payloadKeysMatchTheProfile() throws { + // The file and the profile are written separately, and a rename in one + // degrades every event to a pid-derived session without any test + // noticing. Both of the file's payload builders are checked, not the + // whole source: `session_id` appears in each of them, so a rename in + // one would otherwise be covered for by the other. + let source = AgentPetExtension.source(agentID: "omp", shimPath: aShimPath) + let profile = try #require(AgentProfiles.profile(for: "omp")) + + func region(from start: String, to end: String) throws -> String { + let lower = try #require(source.range(of: start)?.lowerBound) + let upper = try #require(source.range(of: end)?.lowerBound) + return String(source[lower.. = [ "session_start", "agent_start", "tool_execution_start", - "ui_prompt_start", "agent_settled", "session_shutdown", "context_update", + "ui_prompt_start", "agent_settled", "session_shutdown", ] - for event in emitted { - #expect(known.contains(event), "\(event) is sent but unknown to the normalizer") + let listened = listenedEvents(inGeneratedFile: source) + #expect(listened == pinned, "the file registers \(listened.sorted())") + for event in pinned { + #expect(known.contains(event), "\(event) is listened for but unknown to the normalizer") } + // The reading rides out of the settle handler rather than off an event + // of its own, so it is sent, not listened for. + #expect(source.contains("send(\"context_update\""), "the context reading is never sent") + #expect(known.contains("context_update"), "context_update is sent but unknown") } @Test("the extension hands the payload over in the environment, not on a pipe") @@ -63,7 +79,10 @@ struct PiConfigurationTests { // session at all. let template = PiConfigurator.template(shimPath: piShim) #expect(template.contains("AGENTPET_PAYLOAD_BASE64")) - #expect(!template.contains("proc.stdin"), "the payload must not depend on a pipe write") + // `child.stdin`, which is what a pipe write here would go through: + // asserting `proc.stdin` can never fail, because the generated file + // names no `proc` at all. + #expect(!template.contains("child.stdin"), "the payload must not depend on a pipe write") } @Test("configuring writes one marked file and nothing else") @@ -76,8 +95,20 @@ struct PiConfigurationTests { let text = try #require(sandbox.fileText()) #expect(text.contains(PiConfigurator.marker)) #expect(text.contains(piShim)) - #expect(text.contains("--agent") && text.contains("pi")) + // The spawned command names the agent, in both places it can: the + // argv the shim is called with, and the constant the file reads it + // from. Asserting only "--agent" and "pi" separately was true of any + // file at all (`export default function (pi)` carries "pi"). + #expect(text.contains("--agent pi")) + #expect(text.contains("const AGENT = \"pi\";")) #expect(sandbox.configurator().entriesPresent(in: outcome.record)) + // The record carries the line the file was written with. Without this, + // recording the bare marker again would keep every case here green + // while presence silently stopped looking at the file's own line. + #expect( + outcome.record.entries.first?.command + == ExtensionTemplate.markerLine(agentID: "pi", shimPath: piShim) + ) // The only thing under home is Pi's own directory: no settings edit, // no backup (nothing existed to back up), no package. @@ -97,11 +128,88 @@ struct PiConfigurationTests { @Test("a moved shim shows up as drift") func movedShimIsDrift() throws { let sandbox = try PiSandbox() - let outcome = try sandbox.configurator().configure(shimPath: piShim, replacing: nil, now: piNow) + let configurator = sandbox.configurator() + let outcome = try configurator.configure(shimPath: piShim, replacing: nil, now: piNow) + // The recorded entry is the line that carries the path, so a record + // written at the new location does not match the file the old one + // installed — which is what drift means now. var moved = outcome.record moved.shimPath = "/somewhere/else/agentpet-hook" - #expect(!sandbox.configurator().entriesPresent(in: moved)) + moved.entries = [WrittenEntry( + file: sandbox.extensionURL.path, + event: "extension", + command: ExtensionTemplate.markerLine( + agentID: "pi", shimPath: "/somewhere/else/agentpet-hook" + ) + )] + #expect(!configurator.entriesPresent(in: moved)) + #expect(configurator.entriesPresent(in: outcome.record), "the file it wrote still matches") + } + + @Test("a record written before the shared rule still reads present, and still removes") + func olderRecordStillWorks() throws { + // v0.9.6 recorded the marker line as the entry. The file it wrote still + // contains it, so presence and removal need no branch for that + // generation — one rule covers both. + let sandbox = try PiSandbox() + let configurator = sandbox.configurator() + _ = try configurator.configure(shimPath: piShim, replacing: nil, now: piNow) + + let old = IntegrationRecord( + agentID: "pi", + status: .configured, + shimPath: piShim, + entries: [WrittenEntry( + file: sandbox.extensionURL.path, + event: "extension", + // Spelled out rather than read from `PiConfigurator.marker`: the + // point is that the value v0.9.6 recorded still works, and a + // constant would move with the code and prove nothing. + command: "// agentpet-extension v1" + )] + ) + #expect(configurator.entriesPresent(in: old)) + + let removed = try configurator.uninstall(old, now: piNow) + #expect(removed.didChange) + #expect(!FileManager.default.fileExists(atPath: sandbox.extensionURL.path)) + } + + @Test("the uninstall backup goes through the retention policy") + func uninstallBackupIsPruned() throws { + // The copy this replaced wrote into the same directory under the same + // name, so only pruning tells the two apart: one stale backup beyond + // the limit, and the policy has to bring the directory back down. + let sandbox = try PiSandbox() + let backups = sandbox.home.appendingPathComponent("backups") + let configurator = PiConfigurator( + home: sandbox.home, + transaction: ConfigTransaction(backupDirectory: backups, maxBackups: 1) + ) + let installed = try configurator.configure(shimPath: piShim, replacing: nil, now: piNow) + + try FileManager.default.createDirectory(at: backups, withIntermediateDirectories: true) + for stale in ["settings.json.1.aaaaaaaa", "settings.json.2.bbbbbbbb"] { + try Data("stale".utf8).write(to: backups.appendingPathComponent(stale)) + } + + _ = try configurator.uninstall(installed.record, now: piNow) + + let kept = try FileManager.default.contentsOfDirectory(atPath: backups.path) + #expect(kept.count == 1, "the limit was not applied: \(kept.sorted())") + #expect(kept.allSatisfy { $0.hasPrefix("agentpet.ts.") }, "the newest backup went: \(kept)") + } + + @Test("a record with nothing in it removes nothing") + func emptyRecordRemovesNothing() throws { + let sandbox = try PiSandbox() + let configurator = sandbox.configurator() + _ = try configurator.configure(shimPath: piShim, replacing: nil, now: piNow) + + let outcome = try configurator.uninstall(IntegrationRecord(agentID: "pi"), now: piNow) + #expect(!outcome.didChange) + #expect(FileManager.default.fileExists(atPath: sandbox.extensionURL.path)) } @Test("a file the user wrote is refused, never overwritten") diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index fbeb0f8..0ecb46f 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -12,9 +12,9 @@ ``` ┌────────────────────────────────────────────────────────────────────┐ │ 外部 Agent 进程(不是我们启动的,在用户自己的终端里) │ -│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ -│ │Codex │ │Claude │ │Grok │ │Pi │ │ -│ └────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘ │ +│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌─────────────────┐ │ +│ │Codex │ │Claude │ │Grok │ │Pi / Oh My Pi │ │ +│ └────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬────────────┘ │ │ │notify │hook │hook │TS extension │ └───────┼────────────┼────────────┼────────────┼────────────────────┘ │ │ │ │ @@ -57,6 +57,8 @@ **关键差异**:Agent 从不连接我们。它们 `fork/exec` 一个 shim,shim 主动写 socket。App 未运行时,shim 把事件**减字段后落盘**(spool),下次启动回放(§5.4);在此之前这里是"静默丢弃",代价是升级/重启后宠物对正在运行的会话一无所知。 +第四列里的两个 Agent 是同一个家族:Pi 与 Oh My Pi 都是进程内 TS 扩展(后者是前者的重命名分支,扩展 API 相同,配置目录不同,事件集也不同,见下),也都由本项目的配置器写入各自目录下的一个文件(`~/.pi/agent/extensions/agentpet.ts`、`~/.omp/agent/extensions/agentpet.ts`),安装即写文件、移除即删文件。两者真正的差别是**事件集不同**(Pi 用 `agent_settled` + `ui_prompt_start`,omp 用 `agent_end`(−`willContinue`) + 审批事件),因此生成文件由同一个模板加事件集与所有权标记等显式参数产出,见 §8.8。 + --- ## 2. 模块结构(修正 §16) @@ -92,6 +94,8 @@ agent-pet-runtime/ │ │ │ └── EventDeduplicator.swift │ │ └── Integration/ │ │ ├── ConfigTransaction.swift +│ │ ├── ExtensionConfigurator.swift # 扩展文件类集成(Oh My Pi),见 §8.8 +│ │ ├── ExtensionTemplate.swift # 两个扩展文件共用的生成模板(事件集与所有权标记为参数) │ │ └── IntegrationState.swift │ ├── AgentPetApp/ # AppKit + SwiftUI │ └── agentpet-hook/ # shim CLI @@ -433,6 +437,8 @@ shim 投递的是**带版本的信封**,不是已解析的事件: `rawPayload` 用 base64 而非嵌套 JSON 的原因:Agent 的 payload 可能不是合法 JSON(有些 hook 传纯文本),嵌套会导致整个信封解码失败。 +**payload 有两个来源,不是一个**(2026-09-15 新增):hook 类 Agent 按契约把 payload 写在 stdin 上,shim 读它;**进程内的报送方**(Pi 与 Oh My Pi 的扩展,§8.8)改从环境变量 `AGENTPET_PAYLOAD_BASE64` 交给 shim,shim 优先读它——两个扩展都跑在 Agent 自己的运行时里,都有同一个竞态。原因是一次实测:扩展跑在 Agent 自己的运行时里,往管道写数据要排在事件循环上,而 Agent 可能正占着它——spawn 之后忙等 30ms 再写,shim 的 stdin 等待(20ms)就已经超时,事件到达时 payload 为空、**没有 session id**,宠物上会多出一行永远填不上的会话。环境变量由内核在 spawn 时交付,没有可迟到的余地;stdin 那条路照旧,Claude Code / Grok / Codex 一个字节都不变。覆盖测试:`BridgeEndToEndTests.environmentPayload`(stdin 保持打开且永不写入,事件仍须完整到达)。 + ### 5.1a 实测延迟(2026-09-12,arm64 / macOS 15.7.9) shim 位于 Agent 的关键路径上,因此这些数字是**决定方案是否可行**的指标,而不是参考值。 @@ -547,7 +553,8 @@ dedupeKey = hash(agentID, eventName, sessionID, payloadEventID) | 属性 | 取值 | 理由 | |---|---|---| | 位置 | `~/Library/Application Support/AgentPetRuntime/pending-events/` | 与 socket 同目录,测试可用 `AGENTPET_SPOOL` 覆盖 | -| 内容 | `EventCapture.sanitizedPayload` 减字段后的信封 | **落盘 = 必须过日志同一条白名单**:session_id、cwd、tool_name、notification_type 等;prompt、tool_input/response、last_assistant_message 一律不写 | +| 内容 | `EventCapture.sanitizedPayload` 减字段后的信封 | **落盘 = 必须过日志同一条白名单**:`session_id`/`sessionId`、cwd、`tool_name`/`toolName`、notification_type 等(两套拼写见下);prompt、tool_input/response、last_assistant_message 一律不写 | +| 白名单的两种拼写 | `session_id`/`tool_name`(Claude Code 的 hook)与 `sessionId`/`toolName`(camelCase 的线协议:Grok 实捕信封如此;Antigravity 用的是 `conversationId` 与嵌套 `toolCall.name`,不在这对里) | 2026-09-15 实测漏掉第二种的后果(收敛前 omp 扩展发的是 `sessionId`):spool 里的事件丢掉 session id,重启回放时该会话以进程名成行,**和它自己的真实行并列**(一行永远填不上)。白名单刻意保持手写而不从 profile 推导——`UserPromptSubmit` 的 `summaryField` 就是用户 prompt,推导式白名单会把 prompt 一起放上盘 | | 权限 | 文件 0600、目录 0700 | 与事件日志同一标准(不用 `Data.write(.atomic)`:原子写会先建临时文件,权限是 umask 而不是我们的) | | 上限 | 200 条,超出删最旧 | 文件名前缀是 16 位零填充毫秒时间戳(**不能用 `%016d`**:该格式读 32 位参数,毫秒时间戳会被截断成负数,排序反转、剪枝删掉最新的) | | 回放 | 启动时 drain,按 `receivedAt` 升序 | 与实时事件走同一条 `BridgeCoordinator.deliver`,因此计数、`--log-events`、归一化行为完全一致;读完即删 | @@ -722,7 +729,7 @@ Codex 的设置页有 `Tuck Away Pet` / `Wake Pet`(`petVisible`,默认 true ### 6.5d 面板里的 agent 列是字形,管理器窗口的侧边栏开关进了工具栏(2026-09-14) -**agent 列**:原来画的是 `displayName`("Claude Code" 在 11.5pt semibold 下约 75pt),在默认 112pt 宠物、200% 面板(224pt)里占掉三分之一。改成 **SF Symbols 字形**(claude-code `asterisk`、codex `terminal`、grok `bolt`、pi `function`、其余 `pawprint`),固定 13pt 宽;完整名字仍在 `Item.primary` 里,供 `--verbose` 的 `[pet] panel:` 行与图像的无障碍描述使用。 +**agent 列**:原来画的是 `displayName`("Claude Code" 在 11.5pt semibold 下约 75pt),在默认 112pt 宠物、200% 面板(224pt)里占掉三分之一。改成 **SF Symbols 字形**(claude-code `asterisk`、codex `terminal`、grok `bolt`、pi `function`、antigravity `sparkles`、omp `sum`、其余 `pawprint`),固定 13pt 宽;完整名字仍在 `Item.primary` 里,供 `--verbose` 的 `[pet] panel:` 行与图像的无障碍描述使用。 **为什么不用各家 logo**:Claude / OpenAI / xAI 的商标属于各自公司,第三方 app 把它们的标识画进 UI 会同时碰到商标(暗示背书/关联)与美术作品著作权两个问题——这类事要么拿到书面许可,要么别做。SF Symbols 是 Apple 授权给 Apple 平台 app 使用的通用字形,与任何厂商标识都不相像,所以没有这个问题。**同一条规则也适用于其它任何视图**(2026-09-14):本项目所有 UI 一律不用 emoji,字形只来自 SF Symbols(面板里的 agent 列、管理器 Activity 列、菜单栏兜底图标、菜单里的警告图标)。**这条是决定,不是权宜**:如果将来想用真 logo,先取得许可,别默默换上去。 @@ -758,11 +765,12 @@ statusLine.command = "" --agent claude-code --statusline --original ]]` 只是替代写法(`~/.grok/docs/user-guide/10-hooks.md`)。§6.7 表里"TOML 挡住 Grok"只对**状态行**成立。15 个事件,比 Claude 多 `StopCancelled`(中断)、`PostToolUseFailure`、`PermissionDenied`;`Stop.lastAssistantMessage` 就是面板要的正文(文档原话:hooks 不必解析 transcript);会话结束时额外一次 `Stop`(`reason != "end_turn"`)必须过滤。信封以 camelCase 为主但**别名并不统一**(实捕,2026-09-15):`session_id` / `hook_event_name` / `permission_mode` / `transcript_path` 有 snake 别名,tool 事件连 `tool_name` / `tool_input` / `tool_use_id` 都有;而 `lastAssistantMessage` / `backgroundTasks` / `notificationType` 是纯 camelCase。`AgentProfiles.swift` 的 grok profile 已按实捕字段换成独立规则表(2026-09-15 Phase 1;fixtures 在 `Tests/AgentPetCoreTests/Fixtures/grok/`)。 **compat 是否真的在跑:已定案(2026-09-15 实测)**——headless 会话用假 socket 截获 7 帧,全部经 shim 的 `GROK_HOOK_NAME` 改判以 `agent=grok` 投递(该改判早已在 shim 里,见 §5.1b 附近)。此前"查无痕迹"是因为 hook 成功不写日志、而 grok 无记录文件。**Phase 2 已接线(2026-09-15)**:`GrokConfigurator` 写 `~/.grok/hooks/agentpet.json`(14 个事件,含 `StopCancelled`),并在 `~/.grok/config.toml` 末尾追加 `[compat.claude] hooks = false`(`TOMLSectionEdit` + `ConfigTransaction.performText`:只追加、记录实际追加字节、按字节精确删除;用户自己已写的 `[compat.claude]` 表则拒绝并回滚这次调用写的 hooks 文件)。实机验收:`grok inspect --json` exit 0、`externalCompat` 里 claude/hooks `enabled: false`、14 条属于我们的 hooks 生效、真实会话后 `--status` 显示 Connected;`--unconfigure` 后 `config.toml` **字节级还原**(sha256 前后一致)。 **Phase 3 状态行已接线(2026-09-15)**:`GrokStatusLine`(独立 record `grok-statusline`、独立开关,同 Claude tap 的 opt-in 原则)往 `config.toml` 追加一个 `[ui.status_line]`(`type = "command"`,命令=`if [ -x shim ]; then shim --agent grok --statusline; fi`——**打印空**,行永不出现,终端外观零变化;自毁保护沿用 Claude tap 的写法)。shim 零改动:`runStatusLineTap` 无 `--original` 时打印空并正常投递,`reducedStatusPayload` 的键与 grok statusline payload 全部同名(实捕核对)。**已知验证边界**:状态行命令只在 TUI 的 agent view 活跃时被调用(官方文档),headless 会话不会触发——本机实测 `grok -p` 只产生钩子帧、无 Statusline 帧。因此这一跳由 shim 侧 e2e(`grokStatusLineMode`:打印空 + 投递 + contextUpdate 归一化)加金样块文本测试覆盖,grok 是否真的调用它属官方文档行为,留待用户的第一次真实 TUI 会话(面板出现 Grok 的 model/context 即验收)。 - **Pi 已接线(2026-09-15)**:`PiConfigurator` 写运行时独有的 `~/.pi/agent/extensions/agentpet.ts`——纯 JS(node 内建 `child_process`/`path`)、标记头、**无 npm、无 settings 编辑**(Otty 的 `otty-integration.ts` 是同款先例);卸载先备份再删该文件,且只认标记头——用户自己的文件拒绝覆盖、拒绝删除。扩展**只在结算点报 `agent_settled`**(`agent_end` 之后 Pi 还可能自动重试/压缩/续跑,profile 不再映射 `agent_end`/`turn_end`,改为覆盖扩展实际发送的事件集);上下文在结算时以 `{session_id, tokens, window, used_percentage, model}` 上报——与状态行 tap 同一归约形状,`used_percentage` 由 `ctx.getContextUsage()` ÷ `ctx.model.contextWindow` 自算。实机验收:真实 pi 会话(headless)经假 socket 截获 5 帧——`session_start` / `agent_start` / `agent_settled` / `context_update`(`{"tokens":6,"model":"Claude Opus 4.8","window":1000000}`)/ `session_shutdown`,模型调用因本机 provider bearer 过期报 401 而未能跑工具;工具分支由**假宿主 harness**(node 直接 drive 已安装的扩展文件)补齐 `tool_execution_start` 帧;真实投递后 `--status` 显示 Connected。**坑**:pi 的 `-p` 非交互模式会等待 stdin EOF——脚本里必须 `< /dev/null`,否则静默挂起。 - **吸收 PR #1 的三件机制(2026-09-15,作者 CaffreySun,均带回归测试)**:① `ConfigTransaction.pruneBackups` 改按**文件 mtime** 剪枝——按名字剪枝在多来源备份目录里会把本次调用刚生成的备份立刻删掉(`agentpet.json.*` 永远排在 `settings.json.*` 前;本仓库的备份目录从 Grok 接线起就是多来源,属活 bug);② `EventCapture.capturableKeys` 增加 `sessionId`/`toolName` camelCase 拼写——否则进程内扩展的事件落 spool 时丢 session id、回放时该会话以进程名多出一行填不上的行(白名单仍保持手写、不从 profile 推导,理由见注释);③ shim 的 payload 增加第二来源 `AGENTPET_PAYLOAD_BASE64`(**stdin 契约一字未动**,钩子类 agent 不受影响)——进程内扩展往管道写数据排在 agent 自己的事件循环上,实测忙 30ms 即错过 shim 的 20ms stdin 等待、事件丢 session id;环境变量在 spawn 时由内核交付,无此竞态。**Pi 扩展已切换到该机制**(模板测试钉住 `AGENTPET_PAYLOAD_BASE64` 且不含 `proc.stdin`)。Oh My Pi 本体支持仍等 PR #1 rebase 后并入。 + **Pi 已接线(2026-09-15)**:`PiConfigurator` 写运行时独有的 `~/.pi/agent/extensions/agentpet.ts`——纯 JS(node 内建 `child_process`/`path`)、标记头、**无 npm、无 settings 编辑**(Otty 的 `otty-integration.ts` 是同款先例);卸载按**记录条目**判定(与 Oh My Pi 同一条规则,见 §8.8)并先备份再删;覆盖前仍认标记头——用户自己的文件拒绝覆盖。扩展(与 Oh My Pi 的扩展同源同一个生成模板,见 §8.8)**只在结算点报 `agent_settled`**(`agent_end` 之后 Pi 还可能自动重试/压缩/续跑,profile 不再映射 `agent_end`/`turn_end`,改为覆盖扩展实际发送的事件集);上下文在结算时以 `{session_id, tokens, window, used_percentage, model}` 上报——与状态行 tap 同一归约形状,`used_percentage` 由 `ctx.getContextUsage()` ÷ `ctx.model.contextWindow` 自算。实机验收:真实 pi 会话(headless)经假 socket 截获 5 帧——`session_start` / `agent_start` / `agent_settled` / `context_update`(`{"tokens":6,"model":"Claude Opus 4.8","window":1000000}`)/ `session_shutdown`,模型调用因本机 provider bearer 过期报 401 而未能跑工具;工具分支由**假宿主 harness**(node 直接 drive 已安装的扩展文件)补齐 `tool_execution_start` 帧;真实投递后 `--status` 显示 Connected。**坑**:pi 的 `-p` 非交互模式会等待 stdin EOF——脚本里必须 `< /dev/null`,否则静默挂起。 + **吸收 PR #1 的三件机制(2026-09-15,作者 CaffreySun,均带回归测试)**:① `ConfigTransaction.pruneBackups` 改按**文件 mtime** 剪枝——按名字剪枝在多来源备份目录里会把本次调用刚生成的备份立刻删掉(`agentpet.json.*` 永远排在 `settings.json.*` 前;本仓库的备份目录从 Grok 接线起就是多来源,属活 bug);② `EventCapture.capturableKeys` 增加 `sessionId`/`toolName` camelCase 拼写——否则进程内扩展的事件落 spool 时丢 session id、回放时该会话以进程名多出一行填不上的行(白名单仍保持手写、不从 profile 推导,理由见注释);③ shim 的 payload 增加第二来源 `AGENTPET_PAYLOAD_BASE64`(**stdin 契约一字未动**,钩子类 agent 不受影响)——进程内扩展往管道写数据排在 agent 自己的事件循环上,实测忙 30ms 即错过 shim 的 20ms stdin 等待、事件丢 session id;环境变量在 spawn 时由内核交付,无此竞态。**Pi 扩展已切换到该机制**(模板测试钉住 `AGENTPET_PAYLOAD_BASE64`,并断言不含 `child.stdin`)。Oh My Pi 本体支持即 PR #1(本分支):§8.8 记其扩展文件类集成,§6.7 的 omp 行与两份 README 同步为「已接线」。 **Codex 已接线(2026-09-15)**:`JSONHookConfigurator` 直接复用——`~/.codex/hooks.json` 与 Claude 的 `settings.json` 是同一 schema(`{"hooks": {"": [{matcher, hooks: […]}]}}`),写入 12 个事件(`SessionStart/End`、`UserPromptSubmit`、`Pre/PostToolUse`、`PermissionRequest`、`Pre/PostCompact`、`SubagentStart/Stop`、`Stop`、`Interrupt`),与本机 Otty 已有的 4 条条目合并、卸载只删自己。profile 按二进制 wire structs 的字段重写(`session_id`/`hook_event_name`/`model`/`permission_mode`/`tool_*`;`cwd` 见官方字段表;`last_assistant_message` 未承诺——有则预览、无则无);`Interrupt` → completed;`Notification`/`TaskCompleted`/`StopFailure` 在 Codex 不存在,规则一并去除。新增 `AgentIntegrationProfile.postConfigureHint`:Codex 的信任门是用户自己的动作,configure 后 CLI 与管理器状态栏都会打印 "run /hooks to review and trust them once"。实机验收:`codex doctor` exit 0(22 ok · 0 warn · 0 fail)、合并/卸载/重装全过且 Otty 的条目逐字节保留。**待用户动作**:在 Codex TUI 里 `/hooks` 信任一次事件才会流动;之后可用假 socket 实捕信封,把 fixtures 从"二进制推导"升级为"实捕"。另注意 codex 会自动更新(本机在取证当天 0.153.4 → 0.154.0)。 - **Pi 0.85.1:可完整接线,改动最小。** 单个 `.ts` 放 `~/.pi/agent/extensions/` 即自动发现、可 `/reload`(pi 包内 `docs/extensions.md`);只用 node 内建模块,**不需要 npm 包**——registry 旧注"装包是重操作"不成立。事件全覆盖,`ctx.getContextUsage()`(`extensions.md:1066`)给上下文,`ctx.model` 给模型。注意 `agent_settled` 才是"真正停下"(`agent_end` 之后还可能自动重试/压缩/续跑),把完成映射到 `agent_end` 会在这些窗口误报。本机先例:Otty 的 `~/.pi/agent/extensions/otty-integration.ts`(detached spawn、session id 取会话文件 basename,可照抄)。 - **Codex 0.153.4:事件面已补全,两道坎。** `codex features list` 里 `hooks` 已是 `stable`;官方 hooks 在 `~/.codex/hooks.json`(JSON、Claude 同形 schema 与 payload;事件含 `PermissionRequest` / `Interrupt` / `Subagent*` / `Pre/PostCompact`)。坎一:非托管 hooks 必须在 TUI `/hooks` **人工 review + trust**,按 hook 内容 hash 记录、改动即失效重审,没有程序化信任(openai/codex#21615 仍开放)——"写完了配置"不等于"在跑";`allow_managed_hooks_only` 之类的企业策略可直接封掉用户钩子。坎二:仍无自定义状态行,§6.7 表里 Codex 那行(面板数据不可得)**继续成立**。另:`~/.codex/hooks.json` 本机已被 Otty 占用(`_otty` 标记),写入必须合并、不碰别人的条目。 - **Antigravity(2.0 + CLI,2026-05-19 I/O 起):官方接口存在,但只到"部分"。** 官方 hooks(antigravity.google/docs/hooks):`hooks.json`,全局 `~/.gemini/config/hooks.json`、工作区 `.agents/`;格式是命名映射(`{"<名>": {"PreToolUse": [...], …}}`),我们只占一个 key,合并与卸载语义最干净;只有 5 个事件:`PreToolUse` / `PostToolUse` / `PreInvocation` / `PostInvocation` / `Stop`。信封带 `conversationId`(=会话 id)、`workspacePaths`、`modelName`;`Stop` 带 `terminationReason`(`model_stop` / `max_steps_exceeded` / `error`,能分完成与失败)和 `fullyIdle`(后台未完,对应 Claude 的 background_tasks 抑制)。**没有 SessionStart/SessionEnd,没有等待输入事件**——宠物画不出"需要你",这是与 Claude 最主要的差距。官方状态行(/docs/cli/statusline):`~/.gemini/antigravity-cli/settings.json` 的 `statusLine`(`type = "command"`),payload 含 `session_id`、`model.display_name`、`context_window.used_percentage`——与 Claude 的状态行契约同形,shim 第三度复用。接口还年轻:2026-08 仍在改 hook 排序、同步 hooks、参数改写、compaction 钩子;全局路径近期从 `~/.gemini/antigravity-cli/hooks.json` 修到 `~/.gemini/config/hooks.json`(以装好的版本实测为准)。IDE 2.0 是否读同一 `hooks.json`:文档是产品级、changelog 有 IDE 生命周期 hook 条目,中高置信、待实测。已死的路:VS Code 扩展兼容在 2.0 被移除;语言服务器 `exa.language_server_pb` gRPC(需 CSRF token,本机旧日志可见该服务)是逆向面,**不做**。本机未装 CLI(`agy`,`~/.local/bin/agy`)。 - **Antigravity 已接线(2026-09-15 实测 + 实现)**:本机装 `agy` 1.2.3 并登录(免费档即可)。**未登录时 `agy -p` 停在鉴权环节、agent 循环不启动、任何 hook 都不触发**(实测:弹 OAuth URL 等 60 秒超时)。捕获用临时探针 hooks.json + 假 socket(事后全部清除、settings.json 按 sha256 逐字节还原),推翻/补足了官方文档:hooks.json 命名映射中**工具事件是 matcher 分组、其余是扁平 handler 列表**;payload 是 protojson camelCase;**`SessionStart` 真实存在**(二进制 proto 有、文档事件表没有,实测触发,载荷只带 common 字段);**`PostToolUse` 注册但从不触发**(3 个工具 0 次);`Stop` 的 `terminationReason` 实测为 `NO_TOOL_CALL`(不是文档示例的 `model_stop`),proto 里的 `finalModelOutput` 实捕没有;`ExecutionNum` 恒 0。其他实测:hook 失败 **fail-open**(一次脚本全丢失的运行里 agent 照样 SUCCESS、错误只进日志);钩子 stdout 契约"必须回 JSON"而 PreToolUse 无 no-op decision——**`{}` 经单命令 allowlist 的工具调用实测为无副作用答案**;钩子进程 cwd = hooks.json 所在目录;环境里注入 `ANTIGRAVITY_CONVERSATION_ID`(shim 据此改判,同 `GROK_HOOK_NAME` 的手法)。实现:`AntigravityConfigurator`(命名钩子 `agentpet`,7 事件,`SessionStart/PreInvocation/PostInvocation/Stop/SessionEnd` 扁平 + `Pre/PostToolUse` 分组)+ profile(点路径读 `toolCall.name`、数组取首读 `workspacePaths[]`、`fullyIdle: false` 抑制完成、`error` 非空判失败、`terminationReason` 不参与过滤)+ shim 对 antigravity 钩子回 `{}`(唯一允许写 stdout 的例外,注释写明契约)+ 状态行 tap(`--render-row` 渲染 `dir │ model │ N% ctx` 替代内置行;**headless 不触发状态行**,TUI 验收留给用户)。规则引擎为它扩了三个通用件:**点路径字段读取、数组取首、`suppressedWhenFalseField`/`requiresNonEmptyField` 两个条件**。实机验收:`--configure antigravity` 写入 hooks.json、真实会话经真 shim 投递 4 帧(SessionStart/PreInvocation/PostInvocation/Stop,全部 `agent=antigravity`)、卸载/重装干净(空文件壳 `{}` 与 grok 同款,注释在案)。 + **Antigravity 已接线(2026-09-15 实测 + 实现)**:本机装 `agy` 1.2.3 并登录(免费档即可)。**未登录时 `agy -p` 停在鉴权环节、agent 循环不启动、任何 hook 都不触发**(实测:弹 OAuth URL 等 60 秒超时)。捕获用临时探针 hooks.json + 假 socket(事后全部清除、settings.json 按 sha256 逐字节还原),推翻/补足了官方文档:hooks.json 命名映射中**工具事件是 matcher 分组、其余是扁平 handler 列表**;payload 是 protojson camelCase;**`SessionStart` 真实存在**(二进制 proto 有、文档事件表没有,实测触发,载荷只带 common 字段);**`PostToolUse` 注册但从不触发**(3 个工具 0 次);`Stop` 的 `terminationReason` 实测为 `NO_TOOL_CALL`(不是文档示例的 `model_stop`),proto 里的 `finalModelOutput` 实捕没有;`executionNum` 恒 0。其他实测:hook 失败 **fail-open**(一次脚本全丢失的运行里 agent 照样 SUCCESS、错误只进日志);钩子 stdout 契约"必须回 JSON"而 PreToolUse 无 no-op decision——**`{}` 经单命令 allowlist 的工具调用实测为无副作用答案**;钩子进程 cwd = hooks.json 所在目录;环境里注入 `ANTIGRAVITY_CONVERSATION_ID`(shim 据此改判,同 `GROK_HOOK_NAME` 的手法)。实现:`AntigravityConfigurator`(命名钩子 `agentpet`,7 事件,`SessionStart/PreInvocation/PostInvocation/Stop/SessionEnd` 扁平 + `Pre/PostToolUse` 分组)+ profile(点路径读 `toolCall.name`、数组取首读 `workspacePaths[]`、`fullyIdle: false` 抑制完成、`error` 非空判失败、`terminationReason` 不参与过滤)+ shim 对 antigravity 钩子回 `{}`(唯一允许写 stdout 的例外,注释写明契约)+ 状态行 tap(`--render-row` 渲染 `dir │ model │ N% ctx` 替代内置行;**headless 不触发状态行**,TUI 验收留给用户)。规则引擎为它扩了三个通用件:**点路径字段读取、数组取首、`suppressedWhenFalseField`/`requiresNonEmptyField` 两个条件**。实机验收:`--configure antigravity` 写入 hooks.json、真实会话经真 shim 投递 4 帧(SessionStart/PreInvocation/PostInvocation/Stop,全部 `agent=antigravity`)、卸载/重装干净(空文件壳 `{}` 与 grok 同款,注释在案)。 - §6.7 的旧注里唯一还站得住的:**Codex 的面板数据不可得**。"Grok 是 TOML 所以不能动""Codex 只有 notify""Pi 要装包"三条都已被上面的证据取代。 **接线时的先测清单(行为验证,全部留到实现时)**:Grok compat 是否在实际会话里重放我们的钩子(开 pet 跑一次 grok,看 Activity 是否出现贴错标签的会话);Codex `Stop` 是否带最后一条助手消息(官方字段表未列,旧版 notify 有 `last-assistant-message`);Pi 内置权限提示是否走 `ui_prompt_start`;Antigravity 的 IDE 2.0 是否读同一 `hooks.json`、状态行 payload 是否含 cost(2026-08-26 changelog 提到 cost metrics,文档示例未见)。 @@ -996,6 +1004,66 @@ UI 显示的组合状态: 另外 `Specification.extraSearchPaths` 此前是个**死字段**(声明、赋值、注释都在,没有读取方), 现已接上:先扫 agent 自己的 extra,再扫全局表。 +### 8.8 扩展文件类集成:Pi 与 Oh My Pi(2026-09-15 新增) + +前面七节讲的是**改别人的文件**(Claude Code 的 JSON hook 表)。Pi 与 Oh My Pi 是另一类:它们各自在会话启动时加载自己扩展目录下的 `*.ts`(`~/.pi/agent/extensions/`、`~/.omp/agent/extensions/`),所以集成是**一个完全属于运行时的文件**——安装即写、移除即删、不需要解析任何既有格式,也不可能与用户的配置打架。两者共用同一个生成模板(**事件集**与**所有权标记**为参数)。除路径、所有权标记的**字符串**、拒绝覆盖时抛出的错误值以及文件头那段代价说明外,本节细节对 Pi 同样成立;其余差别只在事件集那张表。 + +(本机实证:omp 18.1.22,`@oh-my-pi/pi-coding-agent`;扩展加载走 Bun 的原生 import,语法错误只跳过该文件,handler 抛错被框架吞掉并记录。Oh My Pi 是 Pi 的重命名分支,`piConfig.configDir` 从 `~/.pi/agent` 变成 `~/.omp/agent`,扩展 API 相同,但**事件集不同**——这正是生成文件以事件集为参数的原因。) + +#### 文件与所有权 + +| 项 | 取值 | +|---|---| +| 路径 | `~/.omp/agent/extensions/agentpet.ts`(由 `ExtensionFileConfigurator` 决定) | +| 所有权标记 | 文件头一行固定文本:omp 是 `// agentpet-runtime extension`,Pi 是 `// agentpet-extension v1`(模板参数之一)——**不含路径**,所以 App 搬家后旧文件仍被认作自己的;它只用于「覆盖前是否是自己人」 | +| 记录的条目 | `WrittenEntry(file:, event: "agentpet.ts", command: "// shim: --agent omp")`——两个 Agent 的条目都是这行注释(`ExtensionTemplate.markerLine`),判据是**这一整行是否还在文件里**,也就是文件是否仍与记录一致。文件里那行被改写(手工改、或被另一次 Configure 换成了别的 shim 路径)→ `entriesPresent` 为假 → 卡片报 disconnected,直到用户重新 Configure。**App 自己搬家不在其中**:记录与文件是同一次 Configure 一起写的,两者会一直一致;判定从不拿 `record.shimPath` 去和"当前 shim 路径"比对——该字段只在 uninstall 时用于保留原值 | +| 幂等 | 生成文本与磁盘内容逐字节相同 → 不写、不备份、`didChange = false` | +| 拒绝覆盖 | 目标文件存在但不带所有权标记 → 抛 `ConfigurationError.foreignFile`,原文件一字节不动 | +| 移除 | 只在文件仍含**记录里那行** `// shim:` 时才删(判据是那一行,不是"文件没被人动过":用户在其上追加内容并不会让它留下)。删除前先备份(走 `ConfigTransaction.backUp`,与 JSON 事务同一个备份目录、同一套命名:`<文件名>..`),所以连用户追加的部分也能取回。那行被改掉/删掉、或记录为空 → 不删,报 `didChange = false`。**这条规则两个 Agent 共用**(`PiConfigurator` 同样按记录条目判定存在与移除);v0.9.6 的旧记录无需分支:它记的是标记行,旧文件里仍有那一行,于是照样报存在、照样能干净移除 | + +生成文本由 `AgentPetExtension.source(agentID:shimPath:)` 拼出(不是随包资源):能被测试逐条断言,也能在不安装任何东西的情况下读全文——与 `HookSetup.claudeCodeJSON` 同样的理由。它自己只是把参数交给**两个扩展文件共用的模板** `ExtensionTemplate.source(agentID:shimPath:events:marker:)`:两个 Agent 的扩展 API 相同,事件集是显式参数(agent id 与所有权标记也是),其余(shim 调用、会话 id、上下文读数、环境变量通道)全部共享。Pi 的配置器(`PiConfigurator`)走同一个模板的 `.pi` 分支。 + +| 用途 | Pi 0.85 发 | Oh My Pi 18 发 | +|---|---|---| +| "被扣住了" | `ui_prompt_start`(自己的提示框在屏上) | `tool_approval_requested` / `ask` 工具 | +| 一轮结束 | `agent_settled` | `agent_end`(丢掉 `willContinue` 为真的那些) | + +一条普通 `agent_end` 在 Pi 上不是结算(之后还可能自动重试或续跑),而 `agent_settled` 在 omp 18.1.22 里**不存在**(逐事件核对过),所以一个文件不可能同时正确;模板按事件集参数化正是为此。写入走 `ConfigTransaction.performText`(快照 → 备份 → 原子写 → 读回验证 → 失败回滚),与 JSON 事务同一套纪律、同一份代码。 + +#### 上报什么 + +扩展监听八个事件、发送九个(多出来的是每次结算后那条上下文读数),全部由它自己发给 shim(`--agent omp --event <名>`)。payload 只有 `session_id` 与 `cwd`;带工具名的那几个事件(`tool_execution_start` 与两个审批事件)多一个 `toolName`。 + +| 扩展发 | 归一化为 | 依据 | +|---|---|---| +| `tool_approval_requested` | `.waitingApproval` | 工具被扣住等用户批准(对应权限提示) | +| `tool_execution_start` 且 toolName 为 `ask` | `.waitingInput` | `ask` 工具本身就是问用户 | +| `agent_start` / `tool_execution_start` / `tool_execution_end` / `tool_approval_resolved` | `.working` | 干活中;`tool_execution_end` 同时是"答完问题"的下落点 | +| `agent_end` | `.completed` | 每轮 prompt 一次;payload 里 `willContinue` 为真(已排好重试)时扩展**不发** | +| `session_start` | `.sessionStarted` | 引擎按 §4.5b 不建行,只刷新已知会话 | +| `session_shutdown` | `.sessionClosed` | 会话结束 | +| `context_update`(结算时发送,不监听事件) | `.contextUpdate` | 只描述会话:模型、上下文占用——与状态行 tap 同一归约形状,不改变状态 | + +`whenToolName` 是为这条映射新加的规则条件(`NormalizationRule` 上第三个"仅当某字段等于某值",前两个是 `whenNotificationType` 与 `whenReason`):同一事件的窄规则必须排在其通用规则**之前**。 + +不映射且**故意不订阅**:`turn_start`/`turn_end`(Oh My Pi 的 turn 是一次模型调用,不是一轮 prompt)、`message_*`、`session_compact` 等——后者携带模型输出,而本项目不读模型输出。 + +#### 只上报,不设卡 + +omp 的扩展是**进程内**的,能改 Agent 行为,所以边界必须写死:文件里没有注册任何 `tool_call`(该事件 fail-closed——handler 抛错会拦掉工具),没有 `sendMessage`(注入消息),没有 `node:fs`(碰用户文件),没有 `ctx.ui`(弹窗),所有 handler 都不返回值并各自 try/catch。注册集合本身由 `OhMyPiNormalizationTests.registeredEventsAreKnown` 钉住(源码里注册的事件必须逐字等于声明的八个,且每个都有归一化规则),四条"不设卡"的承诺由 `ExtensionInstallationTests.reportsOnly` 做文本断言。 + +**一处代价必须写明**:omp 的 `hasLifecycleHandlers`(`src/speculation/host.ts:60-67`)只看四个工具生命周期事件——`tool_call`、`tool_result`、`tool_approval_requested`、`tool_approval_resolved`;**任意扩展**在其中之一上有 handler,实验性的推测本地读(`tools.speculativeExecution.enabled`,默认 false)就不跑。本扩展占的是后两个(审批→`waitingApproval`/`Needs input`),所以代价是真实的;只注册 `session_start` 之类的扩展不会触发它。这条写进了装出来的文件头,以及 README。 + +#### 已知边界 + +- 子代理会话若也派发扩展事件,会作为独立 session 出现在面板上(本项目不读 Agent 内部状态,无法可靠区分主/子会话);实测 `-p` 模式下未出现。 +- 面板的**费用**一项对 Oh My Pi 没有数据源(扩展不发 `cost_usd`);模型与上下文占用随每次结算的 `context_update` 上报(§6.7)。 +- 扩展在**会话启动时**加载:装完要新起一个 omp 会话才生效。UI 的 degraded / disconnected 文案按机制分支,正是为这句话。 + +#### 真机验证(2026-09-15) + +`--configure omp` 写文件 → 起一个真实 omp 会话(`omp -p`,`AGENTPET_SOCKET` 指向一个打印信封的 UDS 监听)→ 得到按序的 `session_start / agent_start / tool_execution_start(bash) / tool_execution_end / agent_end / session_shutdown`,每个信封都带同一个 session id 与 `/tmp` 工作目录 → `--unconfigure omp` 后文件消失、目录里另外两个扩展原样、`--status` 回到 `extension: 0`。 + --- ## 9. 常量汇总 @@ -1047,6 +1115,10 @@ enum RuntimeConstants { static let lastEventPersistInterval : TimeInterval = 10 // 时间戳落盘的限流窗口 static let maxBackups : Int = 10 + // 扩展文件类集成(§8.8) + static let extensionFileName = "agentpet.ts" // /extensions/agentpet.ts + static let extensionOwnershipMarker = "// agentpet-runtime extension" // omp 用;Pi 用 "// agentpet-extension v1" + // 校验 static let maxPackageBytes = 64 * 1024 * 1024 } @@ -1066,3 +1138,5 @@ enum RuntimeConstants { | 卸载安全 | "不删源目录" | **不适用**:本项目不持有 pet,增删改都在 Codex 侧 | 自有存储已删除(§6.3) | | ADR-009 XPC | 保留 | **删除** | v0.1 无第三方代码需隔离 | | 开发顺序 | P0 状态机 → P2 Activity | **合并为一个里程碑** | 状态机的输入由 Activity Engine 决定,不能分开 | +| 集成机制 | 只有"编辑 agent 的配置文件"一种 | **两种**:hook 表(改别人的文件)与扩展文件(写自己的文件) | Oh My Pi 只支持后者;硬套 JSON 事务会被迫去改一个不存在的表(§8.8) | +| shim 的 payload 来源 | 只有 stdin | stdin **或** `AGENTPET_PAYLOAD_BASE64` | 进程内报送方写管道会被 Agent 的事件循环拖到超时,实测丢 payload(§5.1、§8.8) | diff --git a/homebrew/agent-pet-runtime.rb.template b/homebrew/agent-pet-runtime.rb.template index ffd0168..212e664 100644 --- a/homebrew/agent-pet-runtime.rb.template +++ b/homebrew/agent-pet-runtime.rb.template @@ -59,9 +59,13 @@ cask "agent-pet-runtime" do anything: "#{appdir}/AgentPet.app/Contents/MacOS/AgentPet" --configure claude-code - Uninstalling does not remove the hooks it wrote into your agents' - configuration files. Remove those first, or they will keep running a - shim that is no longer installed: + Uninstalling does not remove what it installed into your agents — the + hook lines it wrote into their configuration files, nor the extension + files it put in ~/.pi/agent/extensions and ~/.omp/agent/extensions. + Remove those first, or they will keep running a shim that is no longer + installed: "#{appdir}/AgentPet.app/Contents/MacOS/AgentPet" --unconfigure claude-code + "#{appdir}/AgentPet.app/Contents/MacOS/AgentPet" --unconfigure pi + "#{appdir}/AgentPet.app/Contents/MacOS/AgentPet" --unconfigure omp EOS end