SLOPSHOPPER

Oh My ClaudeAgent

Claude Code, with receipts. Plans with you, hands each task to a specialist agent, and keeps a session from calling work done until a verification is logged…

panebandspinnerrowsguardcommand
★ 3v3.3.0MITupdated 2026-10-25UtsavBalar1231/oh-my-claudeagent
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · oh-my-claudeagent
│ ┃ OMCA ✕ › fix the failing auth test and add an audit log call │ ┃ 1: Agents 2: Plan 3: Evidence 4: Notepad │ ┃ ──────────────────────────────────────────── ● oh-my-claudeagent: cannot read the plugin version: ENOENT: no such │ ┃ No subagent has run in this session yet. ● oh-my-claudeagent: the omca server is not connected (undefined), so │ ┃ Each subagent gets a lane here. Enter or a c ⏺ Read(src/auth.ts) │ ┃ opens its page. ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ │ ✻ Worked for 42s · done 8:53 AM · 97.4k in 1.5k out │ │ › /omca │ ● oh-my-claudeagent: cannot read the plugin version: ENOENT: no such │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · OMCA
1: Agents 2: Plan 3: Evidence 4: Notepad ───────────────────────────────────────────────────── No subagent has run in this session yet. Each subagent gets a lane here. Enter or a click opens its page.
Turn line
✻ Worked for 42s · done 8:53 AM · 97.4k in 1.5k out
README

oh-my-claudeagent

Claude Code, with receipts.

CI

<img src=".github/assets/hero.png" width="1000" alt="A Claude Code session on the left hands task 7 of the checkout plan to the executor, while the OMCA pane on the right shows the plan board at 6 of 14 tasks, with proof on the done tasks, the executor on task 7 and task 7's detail beside the list.">

oh-my-claudeagent (OMCA) coordinates specialist agents, plans and verification evidence in Claude Code and OpenCode V2. Both adapters share state formats, safety checks and durable operations. Claude Code also gates completion on logged verification; OpenCode labels the evidence without a Stop veto. The blog post Claude Code, with receipts describes the original workflow.

Requirements

  • Claude Code 2.1.300 or later. Tested with 2.1.308.
  • bun 1.4.2 or later, on the PATH Claude Code starts with. The omca server, its hooks and the status line run on bun.
  • ast-grep (or sg), optional. Only the structural code search tools need it.

CI runs on Linux, macOS and Windows.

Install

claude plugin install oh-my-claudeagent --marketplace UtsavBalar1231/oh-my-claudeagent

The command adds the omca marketplace when it is not added yet, then installs from it. The marketplace installs from the plugin branch, a packaged tree with no package.json or lockfile, so installing fetches no npm dependencies.

Inside a session, the same steps are /plugin marketplace add UtsavBalar1231/oh-my-claudeagent and /plugin install oh-my-claudeagent@omca. Then run /oh-my-claudeagent:omca-setup, which checks the requirements above and offers to point your status line at OMCA's renderer.

OpenCode V2

The OpenCode adapter requires OpenCode 2.0.29 or later in the 2.0 release line. It adds a selectable omca coordinator, native specialist tools, and a terminal panel opened with /omca. Build and Plan remain available. See OpenCode setup for installation and limits.

Your first plan

  1. Run /oh-my-claudeagent:plan add rate limiting to the login endpoint. The planner asks what it needs to know, has the plan reviewed, and writes it to your plans directory.
  2. Run /oh-my-claudeagent:start-work. The session hands each task to an executor, records a verification after each one, and checks the plan's boxes as tasks finish.
  3. Open /omca to watch the agents, the plan, the evidence and the notepad while it runs.

When the session tries to stop with tasks unchecked, or with every task checked and no final verification logged, OMCA sends it back to work with the reason.

Try it

  • /oh-my-claudeagent:plan add rate limiting to the login endpoint
  • Find where the session token is refreshed and explain the flow
  • /omca doctor

What you see

OMCA shows its work in Claude Code's own transcript. The line that closes each turn carries its tokens, its cost and a receipt for the verification it ran. An agent starts and finishes in its own color, the finish with its duration, tool calls, tokens and the first line of its reply. A test, build or lint run gets its result under the shell commands that ran it, and a screenshot Claude reads shows as a picture where the terminal draws them.

<img src=".github/assets/transcript.png" width="900" alt="A Claude Code turn on the checkout project: under Ran 1 shell command, a receipt reads just test, 42 passed. Two background agents start, and each reports as it finishes: the explorer on Map the validation messages and the architect on Review the checkout flow, each with its duration, tool calls and tokens flush right and the first line of its reply beneath. The dim line that closes each turn names the agents still running, then the turn's tokens and cost.">

The band above the prompt shows the bound plan's progress, the next open task, how many tasks are proven, unproven and failed, and a verification whose evidence was not logged. The numbered buttons fill the prompt with the next step.

<img src=".github/assets/band.png" width="680" alt="The band above the prompt reads 6/14, next 7 Wire the order summary panel, 6 proven, and warns that the evidence for just test was not logged, with the button 1: Log evidence below it. Above it, the receipt under the shell command reads just test, 42 passed, and the turn line ends with just test not logged.">

/omca plan opens the plan board: the tasks grouped by milestone, each with its state, its proof and the agent working on it. A wide pane shows the focused task's detail beside the list.

<img src=".github/assets/plan.png" width="680" alt="The Plan tab of the OMCA pane shows the checkout-redesign board at 6 of 14 tasks, with 6 proven and 4 blocked. Tasks 1 to 6 are done and proven, the executor is on task 7, tasks 8, 9 and 11 are open, and tasks 10, 12, 13 and 14 name the tasks that block them. Beside the list, task 6, Build the payment step, shows its steps, its done-when command, its dependencies, its file changed 3h ago and the passing runs since then. The keys for the focused task and the board fill one row under the list.">

The Evidence tab is the proof ledger: a verdict on the plan's final verification, then every logged run grouped by day.

<img src=".github/assets/evidence.png" width="680" alt="The Evidence tab opens on one line: the final verification for checkout-redesign is MISSING, and build, test, lint and manual each passed on their newest runs. Below it, fourteen runs are grouped under three days, each with its outcome, time, type and command. The focused run, a manual payment smoke test, is open in a card beside the list titled Manual run passed, with its exit code, time and agent, one secret masked, and its command and output wrapped under their own labels.">

The Agents tab gives each subagent a lane led by its mascot, with its task, current tool call, model, effort and tokens. The last wave's finished agents keep their lanes with their results, earlier ones shrink to a line, and in a short pane each lane keeps to two rows.

<img src=".github/assets/agents.png" width="680" alt="The Agents tab shows two running executors, each led by its mascot in a hard hat with a hammer: one on Wire the order summary panel and one on Persist the draft order, each beside its watch command, its count of tool calls, and its model, effort and tokens, with a blank row between them. Under a Finished label, an explorer from an earlier wave is one line with its task and the first line of its result.">

When the pane has room, each lane gets four rows of its own. The agent page opens a subagent's brief, tool calls, reply and cost, and toasts report failed verifications and a completed plan.

<img src=".github/assets/mascots.png" width="680" alt="The Agents tab with three agents running at once, each lane led by its pixel mascot: a green executor in a yellow hard hat with a hammer, a blue explorer in a safari hat with a spyglass, and a purple architect with a lit bulb beside its head. Beside each mascot, four rows give the agent's name with its running time, its task, its running Bash sleep with one call, and its model, effort and tokens, with a blank row between agents.">

The guard holds a destructive shell command for your review and shows what it would touch.

<img src=".github/assets/guard.png" width="680" alt="A dialog headed OMCA guard says OMCA held rm -rf build for review, that it would remove the build directory with 4 entries, and offers Refuse or Run it.">

/omca doctor checks the client, bun, the server, ast-grep, the options and the settings that change how OMCA runs. A check with a known fix offers a key that fills the prompt with it, and the passing checks fold into one line that o opens.

<img src=".github/assets/doctor.png" width="680" alt="The Doctor page, named after the four tabs in the tab bar, counts 1 warning, 1 info row and 11 passing checks. The warning says maxEffortLevel high holds the architect below the xhigh it declares, the info row offers a: Use /advisor fable, and one line beside o: Show passing folds the passing checks, naming OMCA, Claude Code, bun, the omca server, ast-grep, the options, the agent models and the mod policy before it is cut.">

The status line shows the session (model, agent and the plan's next task), the workspace (context window and git state) and usage (duration, usage limits, and cost for accounts billed by the token) on rows of their own, and fits itself to the terminal's width. The subagent status line gives each running agent a row.

<img src=".github/assets/statusline.png" width="900" alt="The OMCA status line under the prompt shows three rows: the model, effort and plan progress with the next task; a context bar, the git branch with change counts and the project; and the session cost and duration. Below it, one row for each of two running subagents shows its type, model, state, effort, context and task. Above, the turn line waits on the two executors.">

In motion: /omca plan opens the board, Down moves the focus, Enter opens the task as a page, and the number keys switch between the pane's tabs.

<img src=".github/assets/pane-tour.gif" width="900" alt="An animation: a prompt hands task 7 to the executor, then /omca plan opens the OMCA pane beside the session on the board with task 7 expanded, Down moves to task 8 and Enter opens it as a page, 1 switches to the Agents tab with the executor's lane led by its mascot, 3 to the Evidence tab, and 2 returns to task 8 on the Plan tab.">

The guard dialog arrives the moment the model asks for a destructive command.

<img src=".github/assets/guard-dialog.gif" width="680" alt="An animation: the prompt Clean the build is typed and sent, the model asks to run rm -rf build, and the OMCA guard dialog appears holding the command, listing the build directory it would remove, with Refuse selected.">

What OMCA runs, reads and writes

In Claude Code, OMCA runs locally: the omca MCP server on bun, a mod inside Claude Code, and, once you set it up, a status line renderer on bun. None of them makes a network call. Claude Code sends the conversation to Anthropic as it does without the plugin, and any MCP server you add follows its own policy. PRIVACY.md is the privacy policy.

In OpenCode, the native adapter runs in the connected server. Its terminal panel uses OpenCode's authenticated client for scoped snapshots; a remote server's project files stay on that server. OMCA adds no telemetry or external service.

Settings hooks. hooks/hooks.json registers SessionStart (only after /clear and compaction), UserPromptSubmit, UserPromptExpansion, SubagentStart, PreToolUse (only Write and Edit), PermissionDenied, PostToolUse, PostToolUseFailure, Stop and TaskCompleted. Each is an mcp_tool hook that calls omca_hook on the local server. They run in every session because the gates and the guidance need each turn's events: a plan-write guard and comment gate on writes, the verification recorder and rule injection after tool calls, failure advice, guidance and keyword hints on prompts, context for each subagent, an evidence check on task completion, and the Stop gates. A handler with nothing to do, such as one with no bound plan, returns nothing.

What they read. The prompt text, the inputs and outputs of Read, Write, Edit, Agent, Bash and PowerShell calls, and the tail of the transcript at Stop. The drift guard runs local git.

The mod. hooks/register.ts handles tool.check for Bash and PowerShell (the destructive-command guard), tool.call, session.start, turn.start, turn.step, turn.complete, agent.spawn, prompt.edit, prompt.change, prompt.autocomplete, ui.close, ui.focus, ui.scroll, command.run for /omca, ui.render and session.compact. claude plugin validate . lists them with the host calls the mod makes: the file system, the clock, local processes such as git, the settings file (read only), session information, the prompt box and the UI. It reads these environment variables: CLAUDE_AFK_TIMEOUT_MS, CLAUDE_CODE_DISABLE_ADVISOR_TOOL, CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC, CLAUDE_CODE_EFFORT_LEVEL, CLAUDE_CODE_SUBAGENT_MODEL_FORCE, CLAUDE_CONFIG_DIR, DISABLE_GROWTHBOOK, DISABLE_TELEMETRY, DO_NOT_TRACK, HOME, HOMEDRIVE, HOMEPATH, OMCA_DISABLED_HOOKS, OMCA_GLYPHS and USERPROFILE, and writes none.

What omca-setup writes. Only after it prints a diff and you confirm, it sets statusLine and subagentStatusLine in ~/.claude/settings.json, optionally env.OMCA_GLYPHS, and copies a launcher to ~/.claude/omca/statusline.ts. The previous file is kept as settings.json.omca-bak. --uninstall removes those entries and the launcher. The Doctor page's i fix adds refreshInterval: 5 the same way, with a backup.

State. The plan registry, the evidence ledger, notepads, session status files, mod markers, delegation metrics and the file-access log live in .omca/ in the project, never under ~/.claude/.

Switches. disableAllHooks and allowManagedHooksOnly turn the settings hooks off, allowManagedModsOnly turns the mod off, and OMCA_DISABLED_HOOKS turns off named handlers. The catastrophic-removal deny has no switch.

Optional search servers. OMCA ships no remote MCP server. To add documentation and code search yourself:

claude mcp add --scope user --transport http context7 https://mcp.context7.com/mcp
claude mcp add --scope user --transport http grep https://mcp.grep.app

The full lists are in the reference: hooks, state files and MCP tools.

Documentation

  • Usage: setup, planning, the band and pane, the guard, the doctor, the status line and troubleshooting.
  • Reference: agents, skills, MCP tools, hooks and kill switches, configuration, state files, where each feature works, and the comparison with similar plugins.
  • File formats: plan files, the evidence ledger, notepads and the plan registry, with JSON Schemas for the ledger and the registry.
  • Contributing: development setup, adding agents, skills and hooks, and the prose and comment policy.
  • Changelog.

Acknowledgments

Based on oh-my-openagent by @code-yeongyu.

License

MIT

Source 67 files
hooks/register.ts 229 lines
1import type { EngineInterface, EventResult, PluginOptions, Register } from "claude-code";
2import { agentRows } from "./agent-rows.ts";
3import { agentsTracker } from "./agents-tracker.ts";
4import { band } from "./band.ts";
5import { bashGuard } from "./bash-guard.ts";
6import { compact } from "./compact.ts";
7import { completion } from "./completion.ts";
8import { dispatch, dispatchStream, featuresFor } from "./dispatch.ts";
9import { footer } from "./footer.ts";
10import type { Host, Options } from "./host.ts";
11import { metrics } from "./metrics.ts";
12import { modMarker } from "./mod-marker.ts";
13import { router } from "./omca-router.ts";
14import { pane } from "./pane.ts";
15import { groupRows } from "./group-rows.ts";
16import { serverCheck } from "./server-check.ts";
17import { spinner } from "./spinner.ts";
18
19function bindHost($: EngineInterface, options: Options): Host {
20  return {
21    options,
22    plugin: { name: $.plugin.name, root: $.plugin.root },
23    log: (text) => $.ui.log(text, { to: "debug" }),
24    env: {
25      HOME: () => $.env.get("HOME"),
26      USERPROFILE: () => $.env.get("USERPROFILE"),
27      HOMEDRIVE: () => $.env.get("HOMEDRIVE"),
28      HOMEPATH: () => $.env.get("HOMEPATH"),
29      CLAUDE_CONFIG_DIR: () => $.env.get("CLAUDE_CONFIG_DIR"),
30      OMCA_GLYPHS: () => $.env.get("OMCA_GLYPHS"),
31      OMCA_DISABLED_HOOKS: () => $.env.get("OMCA_DISABLED_HOOKS"),
32      CLAUDE_CODE_SUBAGENT_MODEL_FORCE: () => $.env.get("CLAUDE_CODE_SUBAGENT_MODEL_FORCE"),
33      CLAUDE_CODE_DISABLE_ADVISOR_TOOL: () => $.env.get("CLAUDE_CODE_DISABLE_ADVISOR_TOOL"),
34      DISABLE_TELEMETRY: () => $.env.get("DISABLE_TELEMETRY"),
35      DO_NOT_TRACK: () => $.env.get("DO_NOT_TRACK"),
36      DISABLE_GROWTHBOOK: () => $.env.get("DISABLE_GROWTHBOOK"),
37      CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: () => $.env.get("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC"),
38      CLAUDE_CODE_EFFORT_LEVEL: () => $.env.get("CLAUDE_CODE_EFFORT_LEVEL"),
39      CLAUDE_AFK_TIMEOUT_MS: () => $.env.get("CLAUDE_AFK_TIMEOUT_MS"),
40    },
41    fs: {
42      read: (path) => $.fs.read(path),
43      readBytes: (path) => $.fs.read(path, { as: "bytes" }),
44      write: (path, text) => $.fs.write(path, text),
45      stat: (path, options) => $.fs.stat(path, options),
46      list: (path) => $.fs.list(path),
47      exists: (path) => $.fs.exists(path),
48    },
49    process: { run: (argv, init) => $.process.run(argv, init) },
50    mcp: { connect: (server) => $.mcp.connect(server) },
51    ui: {
52      say: (text) => $.ui.log(text),
53      open: (args) => $.ui.open(args),
54      panes: () => $.ui.panes(),
55      ask: (question, choices) => $.ui.ask(question, choices),
56      invalidate: () => $.ui.invalidate("ui.render"),
57      focus: (args) => $.ui.focus(args),
58      resolve: (e) => $.ui.resolve(e),
59      copy: (args) => $.ui.copy(args),
60      toast: (text, toastOptions) => $.ui.toast(text, toastOptions),
61      notify: (text, notifyOptions) => $.ui.notify(text, notifyOptions),
62      blit: (args) => $.ui.blit(args),
63      view: (args) => $.ui.view(args),
64    },
65    session: {
66      id: () => $.session.id(),
67      root: () => $.session.root(),
68      cwd: () => $.session.cwd(),
69      surfaces: () => $.session.surfaces(),
70      usage: (args) => $.session.usage(args),
71      version: () => $.session.version(),
72      transcript: (args) => $.session.messages(args),
73    },
74    settings: { read: (args) => $.settings.read(args) },
75    agent: { list: () => $.agent.list() },
76    command: { register: (spec) => $.command.register(spec) },
77    clock: {
78      now: () => $.clock.now(),
79      after: (ms, fn) => $.clock.after(ms, fn),
80      every: (ms, fn) => $.clock.every(ms, fn),
81    },
82    prompt: { fill: (args) => $.prompt.fill(args) },
83    state: {
84      agents: {
85        get: () => $.state.get({ plugin: "oh-my-claudeagent", key: "agents" }),
86        set: (value, setOptions) => $.state.set({ plugin: "oh-my-claudeagent", key: "agents" }, value, setOptions),
87      },
88      lanes: {
89        get: () => $.state.get({ plugin: "oh-my-claudeagent", key: "lanes" }),
90        set: (value, setOptions) => $.state.set({ plugin: "oh-my-claudeagent", key: "lanes" }, value, setOptions),
91      },
92      nextActions: {
93        get: () => $.state.get({ plugin: "oh-my-claudeagent", key: "nextActions" }),
94        set: (value, setOptions) =>
95          $.state.set({ plugin: "oh-my-claudeagent", key: "nextActions" }, value, setOptions),
96      },
97      band: {
98        get: () => $.state.get({ plugin: "oh-my-claudeagent", key: "band" }),
99        set: (value, setOptions) => $.state.set({ plugin: "oh-my-claudeagent", key: "band" }, value, setOptions),
100      },
101      pane: {
102        get: () => $.state.get({ plugin: "oh-my-claudeagent", key: "pane" }),
103        set: (value, setOptions) => $.state.set({ plugin: "oh-my-claudeagent", key: "pane" }, value, setOptions),
104      },
105      ledger: {
106        get: () => $.state.get({ plugin: "oh-my-claudeagent", key: "ledger" }),
107        set: (value, setOptions) => $.state.set({ plugin: "oh-my-claudeagent", key: "ledger" }, value, setOptions),
108      },
109      plan: {
110        get: () => $.state.get({ plugin: "oh-my-claudeagent", key: "plan" }),
111        set: (value, setOptions) => $.state.set({ plugin: "oh-my-claudeagent", key: "plan" }, value, setOptions),
112      },
113      stats: {
114        get: () => $.state.get({ plugin: "oh-my-claudeagent", key: "stats" }),
115        set: (value, setOptions) => $.state.set({ plugin: "oh-my-claudeagent", key: "stats" }, value, setOptions),
116      },
117      costSample: {
118        get: () => $.state.get({ plugin: "oh-my-claudeagent", key: "costSample" }),
119        set: (value, setOptions) =>
120          $.state.set({ plugin: "oh-my-claudeagent", key: "costSample" }, value, setOptions),
121      },
122      notices: {
123        get: () => $.state.get({ plugin: "oh-my-claudeagent", key: "notices" }),
124        set: (value, setOptions) => $.state.set({ plugin: "oh-my-claudeagent", key: "notices" }, value, setOptions),
125      },
126      turns: {
127        get: () => $.state.get({ plugin: "oh-my-claudeagent", key: "turns" }),
128        set: (value, setOptions) => $.state.set({ plugin: "oh-my-claudeagent", key: "turns" }, value, setOptions),
129      },
130      doctor: {
131        get: () => $.state.get({ plugin: "oh-my-claudeagent", key: "doctor" }),
132        set: (value, setOptions) => $.state.set({ plugin: "oh-my-claudeagent", key: "doctor" }, value, setOptions),
133      },
134      agentPage: {
135        get: () => $.state.get({ plugin: "oh-my-claudeagent", key: "agentPage" }),
136        set: (value, setOptions) => $.state.set({ plugin: "oh-my-claudeagent", key: "agentPage" }, value, setOptions),
137      },
138      pages: {
139        get: () => $.state.get({ plugin: "oh-my-claudeagent", key: "pages" }),
140        set: (value, setOptions) => $.state.set({ plugin: "oh-my-claudeagent", key: "pages" }, value, setOptions),
141      },
142    },
143  };
144}
145
146export function readOptions(options: PluginOptions): Options {
147  return {
148    showBand: options["showBand"] !== false,
149    guardMode: options["guardMode"] === "deny" ? "deny" : "dialog",
150    enableKeywordTriggers: options["enableKeywordTriggers"] === true,
151  };
152}
153
154const guardFailed = (reason: string): EventResult<"tool.check"> => ({
155  decision: "deny",
156  reason: `OMCA's Bash guard failed, so the command was refused: ${reason}`,
157});
158
159export const register: Register = (on, pluginOptions) => {
160  const options = readOptions(pluginOptions);
161  const bash = featuresFor("tool.check", { bashGuard });
162  const toolCall = featuresFor("tool.call", { agentsTracker });
163  const sessionStart = featuresFor("session.start", { pane, modMarker, band, serverCheck });
164  const turnStart = featuresFor("turn.start", { footer, modMarker });
165  const turnStep = featuresFor("turn.step", { metrics, agentsTracker });
166  const turnComplete = featuresFor("turn.complete", { band, agentsTracker, agentRows, metrics, pane, footer });
167  const agentSpawn = featuresFor("agent.spawn", { agentsTracker, metrics });
168  const promptEdit = featuresFor("prompt.edit", { band });
169  const promptChange = featuresFor("prompt.change", { band });
170  const promptAutocomplete = featuresFor("prompt.autocomplete", { completion });
171  const paneClose = featuresFor("ui.close", { pane });
172  const paneFocus = featuresFor("ui.focus", { pane });
173  const paneScroll = featuresFor("ui.scroll", { pane });
174  const omca = featuresFor("command.run", { router });
175  const bandRender = featuresFor("ui.render AbovePrompt", { band });
176  const paneRender = featuresFor("ui.render Pane", { pane });
177  const spinnerRender = featuresFor("ui.render Spinner", { spinner });
178  const turnRender = featuresFor("ui.render TurnDuration", { footer });
179  const noticeRender = featuresFor("ui.render UserMessage", { agentRows });
180  const launchRender = featuresFor("ui.render ToolUse", { agentRows });
181  const groupRender = featuresFor("ui.render ToolGroup", { groupRows });
182  const sessionCompact = featuresFor("session.compact", { compact });
183
184  on("tool.check", { tool: /^(?:Bash|PowerShell)$/ }, ($, e, next) =>
185    dispatch(bindHost($, options), "tool.check", bash, e, next, guardFailed),
186  ).catch((_$, _e, next) => guardFailed(next.error.message ?? next.error.kind));
187  on("tool.call", { agentId: /./ }, ($, e, next) => dispatch(bindHost($, options), "tool.call", toolCall, e, next)).catch((_$, e, next) => next(e));
188  on("session.start", ($, e, next) => dispatch(bindHost($, options), "session.start", sessionStart, e, next));
189  on("turn.start", ($, e, next) => dispatch(bindHost($, options), "turn.start", turnStart, e, next));
190  on("turn.step", async function* ($, e, next) {
191    return yield* dispatchStream(bindHost($, options), "turn.step", turnStep, e, next);
192  });
193  on("turn.complete", ($, e, next) => dispatch(bindHost($, options), "turn.complete", turnComplete, e, next));
194  on("agent.spawn", ($, e, next) => dispatch(bindHost($, options), "agent.spawn", agentSpawn, e, next)).catch((_$, e, next) => next(e));
195  on("prompt.edit", ($, e, next) => dispatch(bindHost($, options), "prompt.edit", promptEdit, e, next));
196  on("prompt.change", ($, e, next) => dispatch(bindHost($, options), "prompt.change", promptChange, e, next));
197  on("prompt.autocomplete", ($, e, next) => dispatch(bindHost($, options), "prompt.autocomplete", promptAutocomplete, e, next));
198  on("ui.close", ($, e, next) => dispatch(bindHost($, options), "ui.close", paneClose, e, next)).catch((_$, e, next) => next(e));
199  on("ui.focus", ($, e, next) => dispatch(bindHost($, options), "ui.focus", paneFocus, e, next)).catch((_$, e, next) => next(e));
200  on("ui.scroll", { component: "Pane" }, ($, e, next) =>
201    dispatch(bindHost($, options), "ui.scroll", paneScroll, e, next),
202  ).catch((_$, e, next) => next(e));
203  on("command.run", { command: "omca" }, ($, e, next) =>
204    dispatch(bindHost($, options), "command.run omca", omca, e, next),
205  ).catch((_$, e, next) => next(e));
206  on("ui.render", { component: "AbovePrompt" }, ($, e, next) =>
207    dispatch(bindHost($, options), "ui.render AbovePrompt", bandRender, e, next),
208  );
209  on("ui.render", { component: "Pane" }, ($, e, next) =>
210    dispatch(bindHost($, options), "ui.render Pane", paneRender, e, next),
211  );
212  on("ui.render", { component: "Spinner" }, ($, e, next) =>
213    dispatch(bindHost($, options), "ui.render Spinner", spinnerRender, e, next),
214  );
215  on("ui.render", { component: "TurnDuration" }, ($, e, next) =>
216    dispatch(bindHost($, options), "ui.render TurnDuration", turnRender, e, next),
217  );
218  on("ui.render", { component: "UserMessage" }, ($, e, next) =>
219    dispatch(bindHost($, options), "ui.render UserMessage", noticeRender, e, next),
220  );
221  on("ui.render", { component: "ToolUse", props: { tool: "Agent" } }, ($, e, next) =>
222    dispatch(bindHost($, options), "ui.render ToolUse", launchRender, e, next),
223  );
224  on("ui.render", { component: "ToolGroup" }, ($, e, next) =>
225    dispatch(bindHost($, options), "ui.render ToolGroup", groupRender, e, next),
226  );
227  on("session.compact", ($, e, next) => dispatch(bindHost($, options), "session.compact", sessionCompact, e, next)).catch((_$, e, next) => next(e));
228};
229
hooks/agent-rows.ts 82 lines
1import { lookOf } from "../src/core/agent-type.ts";
2import { type Launch, launchRow, type Notice, noticeRows, noticeStatus } from "../src/core/notice.ts";
3import { field, inputText } from "../src/core/tool-input.ts";
4import { glyphs } from "../src/core/ui-kit.ts";
5import type { Features } from "./dispatch.ts";
6import { resolvedSession, type State, update } from "./host.ts";
7import { kitOf, Line } from "./ui.ts";
8
9const KEPT_NOTICES = 50;
10// A cell kept free at the row's end, so the flush-right facts never touch a docked pane's border,
11// and a row no wider than this, so on a wide terminal the facts stay within a glance of the task.
12const GUTTER = 1;
13const MAX_COLUMNS = 100;
14
15const ENDED: Readonly<Record<string, Notice["status"]>> = { answer: "answer", aborted: "aborted", refusal: "refusal", error: "error" };
16
17function noticeOf(row: State["agents"][string], lane: State["lanes"][string] | undefined): Notice {
18  return {
19    type: lookOf(row),
20    description: row.description,
21    status: ENDED[row.status] ?? "gone",
22    durationMs: row.endedAt === null ? null : row.endedAt - row.startedAt,
23    calls: lane?.calls ?? 0,
24    tokens: row.inputTokens + row.outputTokens,
25    result: lane?.result ?? "",
26  };
27}
28
29function stateOf({ isRunning, isErrored, isInterrupted }: { isRunning: boolean; isErrored: boolean; isInterrupted: boolean }): Launch["state"] {
30  if (isInterrupted) return "stopped";
31  if (isErrored) return "failed";
32  return isRunning ? "running" : "done";
33}
34
35// The agent's own rows in Claude Code's transcript, on the terminal: an Agent call that draws a row
36// of its own, and the notice its agent's end sends. A launch of several agents at once is drawn by
37// the engine as one block no hook reaches. ctrl+o and every other surface keep the engine's rows.
38export const agentRows: Features = {
39  // Runs after the agents tracker has closed the agent's row and stored its reply's first line.
40  "turn.complete": {
41    async post(host, e) {
42      const { agentId } = e;
43      if (agentId === undefined) return undefined;
44      const [{ value: agents = {} }, { value: lanes = {} }] = await Promise.all([host.state.agents.get(), host.state.lanes.get()]);
45      const row = agents[agentId];
46      if (row === undefined || row.teammate) return undefined;
47      const notice = noticeOf(row, lanes[agentId]);
48      await update(host.state.notices, (all) =>
49        Object.fromEntries([...Object.entries(all ?? {}).filter(([id]) => id !== agentId), [agentId, notice] as const].slice(-KEPT_NOTICES)),
50      );
51      return undefined;
52    },
53  },
54  "ui.render ToolUse": {
55    pre(host, e) {
56      const type = inputText(e.props.input, "subagent_type");
57      if (e.surface !== "terminal" || e.props.isExpanded === true || type === "") return undefined;
58      const launch: Launch = {
59        type,
60        description: inputText(e.props.input, "description"),
61        isBackground: field(e.props.input, "run_in_background") === true,
62        state: stateOf(e.props),
63      };
64      const kit = kitOf(host.ui.resolve(e), e.surface);
65      const row = launchRow(launch, glyphs(resolvedSession().glyphTier), Math.min(MAX_COLUMNS, (e.viewport?.columns ?? 80) - GUTTER));
66      return { answer: kit.Box({ key: "omca-launch", marginTop: 1, children: [Line(kit, row)] }) };
67    },
68  },
69  "ui.render UserMessage": {
70    async pre(host, e) {
71      const { task, origin, isExpanded } = e.props;
72      if (e.surface !== "terminal" || isExpanded || origin.kind !== "task-notification" || task?.id === undefined) return undefined;
73      const notice = (await host.state.notices.get()).value?.[task.id];
74      if (notice === undefined) return undefined;
75      const shown: Notice = { ...notice, status: noticeStatus(task.status, notice.status), durationMs: task.durationMs ?? notice.durationMs };
76      const kit = kitOf(host.ui.resolve(e), e.surface);
77      const rows = noticeRows(shown, glyphs(resolvedSession().glyphTier), Math.min(MAX_COLUMNS, (e.viewport?.columns ?? 80) - GUTTER));
78      return { answer: kit.Box({ key: "omca-notice", flexDirection: "column", marginTop: 1, children: rows.map((pieces) => Line(kit, pieces)) }) };
79    },
80  },
81};
82
hooks/agents-tracker.ts 264 lines
1import type { AgentInfo, TurnUsage } from "claude-code";
2import { FORK, lookOf } from "../src/core/agent-type.ts";
3import { firstLine, lastLine, toolDetail } from "../src/core/mission.ts";
4import { taskReference } from "../src/core/plan-reader.ts";
5import { estimateCostUsd } from "../src/core/pricing.ts";
6import { fitEnd, glyphs, oneLine } from "../src/core/ui-kit.ts";
7import { redact } from "../src/core/visual.ts";
8import type { Features } from "./dispatch.ts";
9import { type Host, sessionOf, type State, update } from "./host.ts";
10
11type Row = State["agents"][string];
12type Lane = State["lanes"][string];
13type Page = State["pages"][string];
14type Call = Page["calls"][number];
15type Status = Row["status"];
16
17const PROMPT_CELLS = 400;
18const LINE_CELLS = 200;
19const MAX_BRIEF = 8 * 1024;
20const MAX_REPLY = 4 * 1024;
21const MAX_CALLS = 120;
22const MAX_PAGES = 20;
23const MAX_PENDING = 500;
24
25// A subagent's tool calls as `tool.call` saw them, the most recently calling agent last; the page atom is filled from it.
26const calls = new Map<string, Call[]>();
27// A call's start, dropped when its `post` runs; one whose `next` rejected never reaches `post`, so
28// the agent's `turn.complete` and the cap bound what such calls leave behind.
29const startedAt = new Map<string, { agentId: string; at: number }>();
30const carried = new Map<string, { inputTokens: number; outputTokens: number }>();
31
32// Secrets are masked before a lane is stored, and the excerpt is cut only after that, so a
33// cut can never leave half a key the masks no longer match.
34async function masked(host: Host, text: string, cells: number): Promise<string> {
35  const g = glyphs((await sessionOf(host)).glyphTier);
36  return fitEnd(redact(oneLine(text), "", g.mask).text, cells, g.ellipsis);
37}
38
39// A fork copies the loop that spawned it. The main loop runs as the `agent` setting, which OMCA's
40// own settings make the orchestrator; merged settings carry a plugin's value as well as the user's.
41async function forkedFrom(host: Host, parentAgentId: string | undefined): Promise<string | undefined> {
42  if (parentAgentId === undefined) {
43    const main = (await host.settings.read())["agent"];
44    return typeof main === "string" && main !== "" ? main : undefined;
45  }
46  const parent = (await host.state.agents.get()).value?.[parentAgentId];
47  const look = parent === undefined ? undefined : lookOf(parent);
48  return look === FORK ? undefined : look;
49}
50
51async function maskedText(host: Host, text: string, max: number): Promise<string> {
52  const g = glyphs((await sessionOf(host)).glyphTier);
53  return redact(text, "", g.mask).text.slice(0, max).replace(/[\uD800-\uDBFF]$/, "");
54}
55
56// Deleting first moves the agent to the newest end, so the cap drops the agent idle longest.
57function record(id: string, call: Call): void {
58  const kept = calls.get(id) ?? [];
59  calls.delete(id);
60  calls.set(id, [...kept, call].slice(-MAX_CALLS));
61  for (const oldest of calls.keys()) {
62    if (calls.size <= MAX_PAGES) break;
63    calls.delete(oldest);
64  }
65}
66
67/** Reads the agent's transcript and keeps its page: the brief, the recorded calls and the latest reply. */
68export async function loadPage(host: Host, id: string): Promise<void> {
69  const [found, { value: lanes }, { value: agents = {} }] = await Promise.all([
70    host.session.transcript({ agentId: id }),
71    host.state.lanes.get(),
72    host.state.agents.get(),
73  ]);
74  const messages = Array.isArray(found) ? found : [];
75  const brief = messages.find((message) => message.role === "user" && message.text !== "")?.text;
76  const reply = messages.findLast((message) => message.role === "assistant" && message.text !== "")?.text;
77  const lane = lanes?.[id];
78  const page: Page = {
79    brief: await maskedText(host, brief ?? lane?.prompt ?? "", MAX_BRIEF),
80    source: brief === undefined ? "prompt" : "messages",
81    calls: [...(calls.get(id) ?? [])],
82    reply: await maskedText(host, reply ?? (lane === undefined ? "" : lane.result || lane.output), MAX_REPLY),
83  };
84  const newest = (key: string) => agents[key]?.startedAt ?? 0;
85  await update(host.state.pages, (pages) => {
86    const kept = Object.entries(pages ?? {})
87      .filter(([key]) => key !== id)
88      .sort(([a], [b]) => newest(b) - newest(a))
89      .slice(0, MAX_PAGES - 1);
90    return Object.fromEntries([...kept, [id, page]]);
91  });
92}
93
94function editLane(host: Host, id: string, change: (lane: Lane) => Lane): Promise<void> {
95  return update(host.state.lanes, (lanes) => {
96    const lane = lanes?.[id];
97    if (lanes === undefined || lane === undefined) return lanes;
98    const next = change(lane);
99    return next === lane ? lanes : { ...lanes, [id]: next };
100  });
101}
102
103const inputTokens = (usage: TurnUsage) =>
104  usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens;
105
106function stepCost(total: number | null, usage: TurnUsage | null): number | null {
107  if (total === null || usage === null) return total;
108  const cost = estimateCostUsd(usage.model, usage);
109  return cost === null ? null : total + cost;
110}
111
112function edit(host: Host, id: string, change: (row: Row) => Row): Promise<void> {
113  return update(host.state.agents, (agents) => {
114    const row = agents?.[id];
115    if (agents === undefined || row === undefined || row.endedAt !== null) return agents;
116    return { ...agents, [id]: change(row) };
117  });
118}
119
120function endAgent(host: Host, id: string, status: Status, usage: TurnUsage | undefined, at: number): Promise<void> {
121  const before = carried.get(id);
122  carried.delete(id);
123  return edit(host, id, (row) => ({
124    ...row,
125    ...(row.teammate ? { status: "idle" as const } : { status, endedAt: at }),
126    ...(usage === undefined
127      ? {}
128      : {
129          inputTokens: (before?.inputTokens ?? 0) + inputTokens(usage),
130          outputTokens: (before?.outputTokens ?? 0) + usage.output_tokens,
131        }),
132  }));
133}
134
135const LISTED_STATUS: Readonly<Record<string, Status>> = { completed: "answer", failed: "error", killed: "aborted" };
136const LISTED_OPEN: Readonly<Record<string, Status>> = { running: "running", idle: "idle", waiting: "waiting", pending: "pending" };
137
138export async function reconcile(host: Host, listed: readonly AgentInfo[], at: number): Promise<void> {
139  await update(host.state.agents, (agents) => {
140    if (agents === undefined) return agents;
141    const changed = Object.entries(agents).flatMap(([id, row]) => {
142      if (row.endedAt !== null) return [];
143      const info = listed.find((agent) => agent.id === id);
144      const open = info === undefined ? undefined : LISTED_OPEN[info.status];
145      if (open !== undefined) return open === row.status ? [] : [[id, { ...row, status: open }] as const];
146      const status = info === undefined ? "gone" : (LISTED_STATUS[info.status] ?? "gone");
147      return [[id, { ...row, status, endedAt: at }] as const];
148    });
149    return changed.length === 0 ? agents : { ...agents, ...Object.fromEntries(changed) };
150  });
151}
152
153export const agentsTracker: Features = {
154  "agent.spawn": {
155    async post(host, e, result) {
156      if (result.deny !== undefined || result.agentId === undefined) return undefined;
157      const { agentId, model } = result;
158      const resumed = e.resume === undefined ? undefined : (await host.state.agents.get()).value?.[agentId];
159      if (resumed !== undefined) {
160        carried.set(agentId, { inputTokens: resumed.inputTokens, outputTokens: resumed.outputTokens });
161        await update(host.state.agents, (agents) => {
162          const row = agents?.[agentId];
163          return row === undefined ? agents : { ...agents, [agentId]: { ...row, status: "running", endedAt: null } };
164        });
165        await editLane(host, agentId, (lane) => ({ ...lane, tool: null, output: "", result: "" }));
166        return undefined;
167      }
168      const startedAt = await host.clock.now();
169      const task = taskReference(e.prompt, e.description);
170      const forkOf = e.subagentType === FORK ? await forkedFrom(host, e.parentAgentId) : undefined;
171      await update(host.state.agents, (agents) => ({
172        ...agents,
173        [agentId]: {
174          type: e.subagentType,
175          ...(forkOf === undefined ? {} : { forkOf }),
176          description: e.description,
177          model,
178          effort: null,
179          startedAt,
180          endedAt: null,
181          inputTokens: 0,
182          outputTokens: 0,
183          costUsd: 0,
184          status: "running",
185          teammate: e.isTeammate === true,
186          ...(task === undefined ? {} : { task }),
187        },
188      }));
189      const prompt = await masked(host, e.prompt, PROMPT_CELLS);
190      await update(host.state.lanes, (lanes) => ({
191        ...lanes,
192        [agentId]: { prompt, calls: 0, tool: null, output: "", result: "" },
193      }));
194      return undefined;
195    },
196  },
197  "turn.complete": {
198    async post(host, e) {
199      if (e.agentId === undefined) return undefined;
200      await endAgent(host, e.agentId, e.reason, e.usage, await host.clock.now());
201      const result = await masked(host, firstLine(e.answer), LINE_CELLS);
202      await editLane(host, e.agentId, (lane) => ({ ...lane, tool: null, result }));
203      for (const [callId, call] of startedAt) if (call.agentId === e.agentId) startedAt.delete(callId);
204      await loadPage(host, e.agentId);
205      return undefined;
206    },
207  },
208  "tool.call": {
209    async pre(host, e) {
210      if (e.agentId === undefined) return undefined;
211      startedAt.set(e.tool_use_id, { agentId: e.agentId, at: await host.clock.now() });
212      for (const oldest of startedAt.keys()) {
213        if (startedAt.size <= MAX_PENDING) break;
214        startedAt.delete(oldest);
215      }
216      return undefined;
217    },
218    async post(host, e, result) {
219      const { agentId } = e;
220      if (agentId === undefined) return undefined;
221      const [now, root] = await Promise.all([host.clock.now(), host.session.root()]);
222      const began = startedAt.get(e.tool_use_id)?.at;
223      startedAt.delete(e.tool_use_id);
224      record(agentId, {
225        tool: e.tool,
226        summary: await masked(host, toolDetail(e.tool, e, root), LINE_CELLS),
227        ok: result.deny === undefined && result.isError !== true,
228        durationMs: began === undefined ? null : now - began,
229      });
230      return undefined;
231    },
232  },
233  "turn.step": {
234    async post(host, e, result) {
235      if (e.agentId === undefined) return undefined;
236      const { usage } = result;
237      await edit(host, e.agentId, (row) => ({
238        ...row,
239        status: "running",
240        effort: e.effort ?? row.effort,
241        inputTokens: row.inputTokens + (usage === null ? 0 : inputTokens(usage)),
242        outputTokens: row.outputTokens + (usage?.output_tokens ?? 0),
243        costUsd: stepCost(row.costUsd, usage),
244      }));
245      const last = result.toolUses.at(-1);
246      const [detail, output] = await Promise.all([
247        last === undefined ? undefined : masked(host, toolDetail(last.name, last.input, await host.session.root()), LINE_CELLS),
248        masked(host, lastLine(result.answer), LINE_CELLS),
249      ]);
250      const names = result.toolUses.map((use) => use.name);
251      await editLane(host, e.agentId, (lane) => {
252        if (names.length === 0 && output === "" && lane.tool === null) return lane;
253        return {
254          ...lane,
255          calls: lane.calls + names.length,
256          tool: last === undefined || detail === undefined ? null : { name: last.name, detail },
257          output: output === "" ? lane.output : output,
258        };
259      });
260      return undefined;
261    },
262  },
263};
264
hooks/band.ts 266 lines
1import type { RenderElement } from "claude-code";
2import { type Band, bandView, BUTTON_GAP, planTally, type Proof, type Span, type Tone } from "../src/core/band-model.ts";
3import { allTasksDone } from "../src/core/checkboxes.ts";
4import { ledgerCoversSlot, readLedger } from "../src/core/evidence.ts";
5import { hasPassingFinalVerification, type NextAction, nextActions } from "../src/core/next-actions.ts";
6import { BOULDER, exitCodeOf, LEDGER, statusPath, verificationOf } from "../src/core/omca-paths.ts";
7import { boardOf, parsePlan } from "../src/core/plan-reader.ts";
8import { proofSummary, shownProof } from "../src/core/proof.ts";
9import { sha256Hex } from "../src/core/sha256.ts";
10import { fitEnd, type GlyphTier, glyphs, oneLine } from "../src/core/ui-kit.ts";
11import { TONE_KEYS } from "../src/core/visual.ts";
12import type { Features } from "./dispatch.ts";
13import { boundPlanOf, bytesOf, fillPrompt, type Host, ledgerWrittenAt, proofFacts, reason, sessionOf, stampOf, verdictFor } from "./host.ts";
14import { isRemote, type Kit, kitOf, Run, type TextStyle } from "./ui.ts";
15
16type Snapshot = { band: Band; hasFinalVerification: boolean; exitCode: number | null; planPath: string | undefined };
17
18let glyphTier: GlyphTier = "nerd";
19let shownActions = 0;
20let isAgentInView = false;
21let toastedVerificationAt = 0;
22let toastedPlan: { path: string; isDone: boolean } | undefined;
23let isBaselined = false;
24let planPath: string | undefined;
25let readStamps: string | undefined;
26
27const TOAST_MS = 6000;
28const COMMAND_CELLS = 30;
29
30// A bare digit in an empty composer reaches prompt.edit before the engine resolves it as the
31// band Button's hotkey, so clearing on that edit would take the Button away from its own press.
32const isShownHotkey = (text: string): boolean => {
33  const key = text.trim();
34  return /^[1-9]$/.test(key) && Number(key) <= shownActions;
35};
36
37async function readJson(host: Host, path: string): Promise<unknown> {
38  return (await host.fs.exists(path)) ? JSON.parse(await host.fs.read(path)) : undefined;
39}
40
41async function ledgerDocument(host: Host, path: string): Promise<unknown> {
42  if (!(await host.fs.exists(path))) return undefined;
43  const read = readLedger(await host.fs.read(path));
44  if (read.kind === "refused") throw new Error(read.reason);
45  return read.document;
46}
47
48async function readSnapshot(host: Host, within: object): Promise<Snapshot> {
49  const [root, sessionId, readAt] = await Promise.all([host.session.root(), host.session.id(), host.clock.now()]);
50  const ledgerPath = `${root}/${LEDGER}`;
51  const errors: string[] = [];
52  async function attempt<T>(what: string, read: () => Promise<T>): Promise<T | null> {
53    try {
54      return await read();
55    } catch (error) {
56      errors.push(`Cannot read ${what}: ${oneLine(reason(error))}`);
57      return null;
58    }
59  }
60
61  const bound = await attempt(BOULDER, async () => (await boundPlanOf(host)) ?? null);
62  const planBytes = bound === null ? null : await attempt(bound.path, () => bytesOf(host, bound.path));
63  const planText = planBytes === null ? null : new TextDecoder().decode(planBytes);
64  const plan = bound === null || planText === null ? null : { ...bound, ...planTally(planText) };
65
66  const statusFile = statusPath(root, sessionId);
67  let exitCode: number | null = null;
68  const verification =
69    statusFile === undefined
70      ? null
71      : await attempt(`the session status file`, async () => {
72          const status = await readJson(host, statusFile);
73          exitCode = exitCodeOf(status);
74          const slot = verificationOf(status);
75          if (slot === null) return null;
76          return { ...slot, isLogged: ledgerCoversSlot(await ledgerWrittenAt(host, root), slot.at) };
77        });
78
79  const hasFinalVerification =
80    plan !== null &&
81    planBytes !== null &&
82    allTasksDone(plan) &&
83    (await attempt(LEDGER, async () =>
84      hasPassingFinalVerification(await ledgerDocument(host, ledgerPath), sha256Hex(planBytes)),
85    )) === true;
86
87  const proof = bound === null || planText === null ? null : await attempt(LEDGER, () => proofOfPlan(host, bound.path, planText, within));
88  const band: Band = { plan, verification, ...(proof === null ? {} : { proof }), error: errors[0] ?? null, readAt };
89  return { band, hasFinalVerification, exitCode, planPath: bound?.path };
90}
91
92// The plan board's counts: each task's verdict is the newest test, build or lint run since its
93// listed files last changed, counting only changes since the plan's registered start. Null when no
94// task lists a file that changed.
95async function proofOfPlan(host: Host, planPath: string, planText: string, within: object): Promise<Proof | null> {
96  const { cards } = boardOf(parsePlan(planText));
97  const facts = await proofFacts(host, cards.flatMap((card) => card.files), planPath, within);
98  if (facts.ledgerError !== null) throw new Error(facts.ledgerError);
99  const counts = proofSummary(cards.map((card) => shownProof(card.done, verdictFor(facts, card.files)?.proof)));
100  return counts.proven + counts.unproven + counts.failed === 0 ? null : counts;
101}
102
103// What a snapshot is read from, besides the plan's listed files. A same-size edit, such as a
104// `[ ]` to `[x]` flip, inside one mtime tick of a coarse file system (2 s on exFAT) keeps the
105// plan's stamp, so a subagent's turn misses it until the next change; the main turn reads anyway.
106async function stampsOf(host: Host): Promise<string> {
107  const [root, sessionId] = await Promise.all([host.session.root(), host.session.id()]);
108  const status = statusPath(root, sessionId);
109  const paths = [`${root}/${BOULDER}`, `${root}/${LEDGER}`, planPath ?? "", status ?? ""];
110  return JSON.stringify(await Promise.all(paths.map((path) => (path === "" ? "none" : stampOf(host, path)))));
111}
112
113async function snapshotOf(host: Host, within: object): Promise<Snapshot> {
114  const stamps = await stampsOf(host);
115  const snapshot = await readSnapshot(host, within);
116  planPath = snapshot.planPath;
117  readStamps = stamps;
118  return snapshot;
119}
120
121// The first read after session.start only records what already happened; later reads toast what changed.
122async function toastChanges(host: Host, { band, exitCode }: Snapshot): Promise<void> {
123  const isBaseline = !isBaselined;
124  isBaselined = true;
125  const { plan, verification } = band;
126  const verifiedAt = verification?.at ?? 0;
127  if (!isBaseline && verification !== null && verifiedAt > toastedVerificationAt && exitCode !== null && exitCode !== 0) {
128    const { ellipsis } = glyphs(glyphTier);
129    host.ui.toast(`Verification failed: ${fitEnd(oneLine(verification.command), COMMAND_CELLS, ellipsis)} (exit ${exitCode})`, {
130      timeoutMs: TOAST_MS,
131    });
132  }
133  toastedVerificationAt = Math.max(toastedVerificationAt, verifiedAt);
134  const isDone = plan !== null && plan.total > 0 && plan.done === plan.total;
135  if (!isBaseline && plan !== null && isDone && toastedPlan?.path === plan.path && !toastedPlan.isDone) {
136    const text = `Plan complete: ${plan.name} ${plan.done}/${plan.total}`;
137    host.ui.toast(text, { timeoutMs: TOAST_MS });
138    // A plan run is the long unattended case, so its end also reaches the person's own notifications.
139    try {
140      await host.ui.notify(text, { title: "OMCA" });
141    } catch (error) {
142      host.log(`band: notifying failed: ${reason(error)}`);
143    }
144  }
145  toastedPlan = plan === null ? undefined : { path: plan.path, isDone };
146}
147
148async function actionsFor(host: Host, { band, hasFinalVerification }: Snapshot): Promise<NextAction[]> {
149  const agents = (await host.state.agents.get()).value ?? {};
150  return nextActions({
151    plan: band.plan,
152    verification: band.verification,
153    isAgentRunning: Object.values(agents).some((agent) => agent.status === "running"),
154    hasFinalVerification,
155  });
156}
157
158async function clearActionsFor(host: Host, text: string): Promise<void> {
159  if (isAgentInView || shownActions === 0 || text === "" || isShownHotkey(text)) return;
160  shownActions = 0;
161  await host.state.nextActions.set([]);
162}
163
164const withoutReadAt = (band: Band | undefined): string => JSON.stringify({ ...band, readAt: 0 });
165
166async function writeBand(host: Host, band: Band): Promise<void> {
167  const { value } = await host.state.band.get();
168  if (withoutReadAt(value) !== withoutReadAt(band)) await host.state.band.set(band);
169}
170
171async function writeActions(host: Host, actions: readonly NextAction[]): Promise<void> {
172  const { value = [] } = await host.state.nextActions.get();
173  shownActions = actions.length;
174  if (JSON.stringify(value) !== JSON.stringify(actions)) await host.state.nextActions.set(actions);
175}
176
177const TONES: Record<Tone, TextStyle> = {
178  title: { bold: true },
179  plain: {},
180  muted: { color: TONE_KEYS.muted },
181  ok: { color: TONE_KEYS.ok },
182  warn: { color: TONE_KEYS.warn },
183  fail: { color: TONE_KEYS.fail },
184  active: { color: TONE_KEYS.active },
185};
186
187const row = (kit: Kit, spans: readonly Span[]): RenderElement =>
188  Run(kit, spans.map(({ text, tone, ...keys }) => ({ style: { ...TONES[tone], ...keys }, text })));
189
190export const band: Features = {
191  "session.start": {
192    post: async (host, e) => {
193      glyphTier = (await sessionOf(host)).glyphTier;
194      shownActions = ((await host.state.nextActions.get()).value ?? []).length;
195      const snapshot = await snapshotOf(host, e);
196      toastedVerificationAt = 0;
197      toastedPlan = undefined;
198      isBaselined = false;
199      await toastChanges(host, snapshot);
200      await writeBand(host, snapshot.band);
201      return undefined;
202    },
203  },
204  "turn.complete": {
205    post: async (host, e) => {
206      if (e.agentId !== undefined && (await stampsOf(host)) === readStamps) return undefined;
207      const snapshot = await snapshotOf(host, e);
208      await toastChanges(host, snapshot);
209      await writeBand(host, snapshot.band);
210      if (e.agentId === undefined) await writeActions(host, await actionsFor(host, snapshot));
211      return undefined;
212    },
213  },
214  "prompt.edit": {
215    post: async (host, _e, result) => {
216      await clearActionsFor(host, result.text);
217      return undefined;
218    },
219  },
220  "prompt.change": {
221    post: async (host, e, result) => {
222      const isOwnFill = e.origin.kind === "plugin" && e.origin.name === host.plugin.name;
223      if (!isOwnFill) await clearActionsFor(host, result.text);
224      return undefined;
225    },
226  },
227  "ui.render AbovePrompt": {
228    post: async (host, e, beneath) => {
229      isAgentInView = e.props.view.agentId !== undefined;
230      if (!host.options.showBand || e.props.hasSurvey) return undefined;
231      const [{ value: snapshot }, { value: actions = [] }] = await Promise.all([host.state.band.get(), host.state.nextActions.get()]);
232      const view = bandView(snapshot, isAgentInView ? [] : actions, e.props.bodyColumns, glyphTier);
233      if (view === undefined) return undefined;
234      const kit = kitOf(host.ui.resolve(e), e.surface);
235      const { Box, Button } = kit;
236      const rows = view.status.length === 0 ? [] : [Box({ key: "status", children: [row(kit, view.status)] })];
237      if (view.buttons.length > 0) {
238        rows.push(
239          Box({
240            key: "actions",
241            gap: isRemote(kit) ? "lg" : BUTTON_GAP,
242            children: view.buttons.map((button) =>
243              Button({
244                key: button.key,
245                label: button.label,
246                hotkey: button.hotkey,
247                plain: true,
248                onPress: async () => {
249                  try {
250                    await fillPrompt(host, button.prompt);
251                  } catch (error) {
252                    host.log(`band: filling the prompt failed: ${reason(error)}`);
253                  }
254                },
255              }),
256            ),
257          }),
258        );
259      }
260      // The engine refuses the whole band when the Box holding `beneath`, or any Box around it,
261      // sets a size, a position, `display` or `overflow`.
262      return Box({ key: "omca-band", flexDirection: "column", children: [...rows, beneath] });
263    },
264  },
265};
266
hooks/bash-guard.ts 259 lines
1import type { EventResult } from "claude-code";
2import { type Context, classify, type GitFinding, type Reviewable, reasonFor } from "../src/core/destructive.ts";
3import { isHookDisabled } from "../src/core/kill-switch.ts";
4import { joinPath, toPosix } from "../src/core/path.ts";
5import { homeRest, platformOf } from "../src/core/targets.ts";
6import { cells, displayWidth, fitEnd, fitMiddle, type Glyphs, glyphs } from "../src/core/ui-kit.ts";
7import type { Features } from "./dispatch.ts";
8import { type Host, reason, sessionOf } from "./host.ts";
9
10const RUN = "Run it";
11const REFUSE = "Refuse";
12// The AskUserQuestion dialog's text column on an 80-column terminal, the narrowest supported:
13// its left rule takes 2 of the 80 (measured).
14const WIDTH = 78;
15const COMMAND_ROWS = 4;
16// The dialog's text rows on a 24-row terminal: the engine's frame and the Refuse and Run options take the other 12 (measured).
17const BODY_ROWS = 12;
18const GIT_TIMEOUT_MS = 5000;
19
20const deny = (reason: string): { answer: EventResult<"tool.check"> } => ({ answer: { decision: "deny", reason } });
21
22const commandOf = (input: unknown): string =>
23  typeof input === "object" && input !== null && "command" in input && typeof input.command === "string"
24    ? input.command
25    : "";
26
27const indent = (lines: readonly string[]): string[] => lines.map((line) => `  ${line}`);
28
29async function git(host: Host, argv: readonly string[]): Promise<string[]> {
30  const { exitCode, stdout, stderr } = await host.process.run(["git", ...argv], { timeoutMs: GIT_TIMEOUT_MS });
31  if (exitCode !== 0) throw new Error(stderr.split("\n")[0]?.trim() || `git ${argv[0]} exited ${exitCode}`);
32  return stdout.split("\n").filter((line) => line.trim() !== "");
33}
34
35function resolved(target: string, ctx: Context): string | undefined {
36  const platform = platformOf(ctx);
37  const rest = homeRest(target);
38  if (rest !== undefined) return ctx.home === undefined ? undefined : joinPath(platform, ctx.home, rest);
39  if (/[$`*?[~%]/.test(target)) return undefined;
40  return toPosix(platform, target);
41}
42
43async function kindOf(host: Host, target: string, ctx: Context): Promise<string> {
44  const path = resolved(target, ctx);
45  if (path === undefined) return "not expanded";
46  if (!(await host.fs.exists(path))) return "not found";
47  const stat = await host.fs.stat(path);
48  if (stat.isLink) return "link";
49  if (stat.kind === "dir") {
50    const count = (await host.fs.list(path)).length;
51    return `dir, ${count} ${count === 1 ? "entry" : "entries"}`;
52  }
53  return stat.kind;
54}
55
56// Breaks at the last space that fits, or mid-word when a row has none, so every character up to the row cap is kept.
57function commandRows(command: string, g: Glyphs): string[] {
58  const rows: string[] = [];
59  let rest = [...command.trim()];
60  while (rest.length > 0 && rows.length < COMMAND_ROWS) {
61    let end = 0;
62    let used = 0;
63    let space = 0;
64    for (const char of rest) {
65      used += cells(char.codePointAt(0) ?? 0);
66      if (char === "\n" || used > WIDTH - 2) break;
67      if (char === " ") space = end;
68      end += 1;
69    }
70    const cut = end < rest.length && rest[end] !== "\n" && space > 0 ? space : end;
71    const row = rest.slice(0, cut).join("").trimEnd();
72    if (row !== "") rows.push(row);
73    rest = rest.slice(cut);
74    if (rest[0] === "\n" || rest[0] === " ") rest = rest.slice(1);
75  }
76  const left = rest.length;
77  return left === 0 ? rows : [...rows, `${g.ellipsis} ${left} more ${left === 1 ? "character" : "characters"}`];
78}
79
80type Section = {
81  head: string[];
82  total: number;
83  items: (count: number) => string[];
84  foot: string[];
85  noun: string;
86};
87
88const note = (...head: string[]): Section => ({ head, total: 0, items: () => [], foot: [], noun: "" });
89
90async function removalSection(host: Host, targets: readonly string[], g: Glyphs, ctx: Context): Promise<Section> {
91  if (targets.length === 0) return note("It names no target.");
92  const pool = targets.slice(0, BODY_ROWS);
93  const kinds = await Promise.all(pool.map((target) => kindOf(host, target, ctx)));
94  const items = (count: number): string[] => {
95    const shown = pool.slice(0, count);
96    const kindWidth = Math.max(...kinds.slice(0, count).map(displayWidth));
97    const nameWidth = Math.min(Math.max(...shown.map(displayWidth)), WIDTH - 4 - kindWidth);
98    return shown.map((target, i) => {
99      const name = fitMiddle(target, nameWidth, g.ellipsis);
100      return `${name}${" ".repeat(nameWidth - displayWidth(name))}  ${kinds[i]}`;
101    });
102  };
103  return { head: ["It would remove:"], total: targets.length, items, foot: [], noun: "" };
104}
105
106const TREE_EFFECT: Record<Exclude<GitFinding["operation"], "reset --hard" | "push --force">, string> = {
107  stash: "git stash moves uncommitted changes out of the working tree.",
108  clean: "git clean deletes untracked files.",
109  restore: "git restore discards changes to the files it names.",
110  "rm -r": "git rm -r deletes tracked files from the working tree.",
111  "checkout --": "git checkout -- discards changes to the paths it names.",
112  "commit --no-verify": "git commit --no-verify skips the repository's pre-commit and commit-msg hooks.",
113};
114
115async function resetSection(host: Host): Promise<Section> {
116  const changed = (await git(host, ["status", "--porcelain"])).filter((line) => !line.startsWith("??"));
117  if (changed.length === 0) return note("git reset --hard: no uncommitted changes to tracked files.");
118  const stat = await git(host, ["diff", `--stat=${WIDTH - 2}`, "HEAD"]);
119  return {
120    head: [`git reset --hard discards ${changed.length} uncommitted ${changed.length === 1 ? "change" : "changes"}:`],
121    total: Math.max(0, stat.length - 1),
122    items: (count) => stat.slice(0, count),
123    foot: stat.slice(-1),
124    noun: "files",
125  };
126}
127
128async function pushSection(host: Host, push: GitFinding): Promise<Section> {
129  const ref =
130    push.remote === undefined
131      ? "@{push}"
132      : `${push.remote}/${push.branch ?? (await git(host, ["rev-parse", "--abbrev-ref", "HEAD"]))[0]}`;
133  const lost = await git(host, ["log", "--oneline", ref, "--not", "HEAD"]);
134  if (lost.length === 0) return note(`git push --force: ${ref} has no commits missing from HEAD.`);
135  const noun = lost.length === 1 ? "commit" : "commits";
136  return {
137    head: [`git push --force drops ${lost.length} ${noun} from ${ref}:`],
138    total: lost.length,
139    items: (count) => lost.slice(0, count),
140    foot: [],
141    noun: "commits",
142  };
143}
144
145const gitSection = (host: Host, finding: GitFinding): Promise<Section> | Section => {
146  switch (finding.operation) {
147    case "reset --hard":
148      return resetSection(host);
149    case "push --force":
150      return pushSection(host, finding);
151    default:
152      return note(TREE_EFFECT[finding.operation]);
153  }
154};
155
156async function gathered(gather: () => Promise<Section> | Section, g: Glyphs): Promise<Section> {
157  try {
158    return await gather();
159  } catch (error) {
160    return note(`${g.warn} Could not check what it would touch: ${reason(error)}`);
161  }
162}
163
164// A list that does not fit keeps its first entries and ends in `and N more`; each cut list keeps at least one entry.
165function shareRows(sections: readonly Section[], rows: number): number[] {
166  const wanted = sections.reduce((sum, section) => sum + section.total, 0);
167  return sections.map((section) => {
168    const share = Math.floor((rows * section.total) / Math.max(1, wanted));
169    return wanted <= rows || section.total <= share ? section.total : Math.max(2, share);
170  });
171}
172
173function drawn(section: Section, rows: number): string[] {
174  const shown = section.total <= rows ? section.total : rows - 1;
175  const more = section.total > shown ? [["and", section.total - shown, "more", section.noun].filter(Boolean).join(" ")] : [];
176  return [...section.head, ...indent([...section.items(shown), ...more, ...section.foot])];
177}
178
179async function question(host: Host, command: string, finding: Reviewable, g: Glyphs, ctx: Context): Promise<string> {
180  const shownCommand = commandRows(command, g);
181  const targets = finding.removals.flatMap((removal) => removal.targets);
182  const sections = await Promise.all([
183    ...(finding.removals.length > 0 ? [gathered(() => removalSection(host, targets, g, ctx), g)] : []),
184    ...finding.git.map((operation) => gathered(() => gitSection(host, operation), g)),
185  ]);
186  const fixed = sections.reduce((sum, section) => sum + section.head.length + section.foot.length, 0);
187  const rows = shareRows(sections, BODY_ROWS - 2 - shownCommand.length - fixed);
188  const lines = [
189    "OMCA held this command for your review:",
190    ...indent(shownCommand),
191    ...sections.flatMap((section, i) => drawn(section, rows[i] ?? 0)),
192    "Run it?",
193  ];
194  return lines.map((line) => fitEnd(line, WIDTH, g.ellipsis)).join("\n");
195}
196
197const shellOf = (tool: string): Context["shell"] => (tool === "PowerShell" ? "powershell" : "bash");
198
199const symbolicRef = (host: Host, name: string): Promise<string | undefined> =>
200  git(host, ["symbolic-ref", "--quiet", "--short", name]).then(
201    ([line]) => line,
202    () => undefined,
203  );
204
205// Read from local refs only, so deciding never waits on the network.
206async function branchesOf(host: Host): Promise<Pick<Context, "branch" | "defaultBranch">> {
207  const [branch, originHead] = await Promise.all([symbolicRef(host, "HEAD"), symbolicRef(host, "refs/remotes/origin/HEAD")]);
208  return {
209    ...(branch !== undefined && { branch }),
210    ...(originHead !== undefined && { defaultBranch: originHead.replace(/^origin\//, "") }),
211  };
212}
213
214async function contextOf(host: Host, shell: Context["shell"], isPush: boolean): Promise<Context> {
215  const [home, cwd, root, branches] = await Promise.all([
216    sessionOf(host).then(
217      (session) => session.home,
218      () => "",
219    ),
220    host.session.cwd().catch(() => undefined),
221    host.session.root().catch(() => undefined),
222    isPush ? branchesOf(host) : {},
223  ]);
224  return {
225    shell,
226    ...(home !== "" && { home }),
227    ...(cwd !== undefined && { cwd }),
228    ...(root !== undefined && { root }),
229    ...branches,
230  };
231}
232
233export const bashGuard: Features = {
234  "tool.check": {
235    pre: async (host, e) => {
236      const command = commandOf(e.input);
237      const shell = shellOf(e.tool);
238      const first = classify(command, { shell });
239      if (first === undefined) return undefined;
240      if (first.kind === "catastrophic") return deny(reasonFor(first));
241      // A disabled guard still classifies with the context, because the catastrophic deny has no switch.
242      const isDisabled = isHookDisabled(await host.env.OMCA_DISABLED_HOOKS(), "bash-guard");
243      const isPush = !isDisabled && first.git.some((finding) => finding.operation === "push --force");
244      const ctx = await contextOf(host, shell, isPush);
245      const finding = classify(command, ctx);
246      if (finding === undefined) return undefined;
247      if (finding.kind === "catastrophic") return deny(reasonFor(finding));
248      if (isDisabled) return undefined;
249      const refusal = reasonFor(finding);
250      const canAsk = host.options.guardMode === "dialog" && (await host.session.surfaces()).length > 0;
251      if (!canAsk) return finding.kind === "blocking" ? deny(refusal) : undefined;
252      const g = glyphs((await sessionOf(host)).glyphTier);
253      const text = await question(host, command, finding, g, ctx);
254      const answer = await host.ui.ask(text, { header: "OMCA guard", options: [REFUSE, RUN] }).catch(() => undefined);
255      return answer === RUN ? undefined : deny(refusal);
256    },
257  },
258};
259
hooks/compact.ts 32 lines
1import { planTasks } from "../src/core/checkboxes.ts";
2import { isHookDisabled } from "../src/core/kill-switch.ts";
3import type { Features } from "./dispatch.ts";
4import { boundPlanOf, type Host } from "./host.ts";
5
6// The summarizer needs the next steps, not the whole plan; the file keeps the rest.
7const MAX_OPEN_TASKS = 10;
8
9async function planInstructions(host: Host): Promise<string | undefined> {
10  const plan = await boundPlanOf(host);
11  if (plan === undefined || !(await host.fs.exists(plan.path))) return undefined;
12  const open = planTasks(await host.fs.read(plan.path)).flatMap((task) => (task.checked ? [] : [`- ${task.number}. ${task.label}`]));
13  const more = open.length - MAX_OPEN_TASKS;
14  return [
15    `Keep OMCA's active plan in the summary: ${plan.name} (${plan.path}).`,
16    open.length === 0 ? "Every numbered task is checked." : "Open tasks:",
17    ...open.slice(0, MAX_OPEN_TASKS),
18    ...(more > 0 ? [`- and ${more} more in the plan file`] : []),
19  ].join("\n");
20}
21
22export const compact: Features = {
23  "session.compact": {
24    pre: async (host, e) => {
25      if (e.agentId !== undefined || isHookDisabled(await host.env.OMCA_DISABLED_HOOKS(), "compact")) return undefined;
26      const plan = await planInstructions(host);
27      if (plan === undefined) return undefined;
28      return { event: { ...e, instructions: e.instructions ? `${e.instructions}\n\n${plan}` : plan } };
29    },
30  },
31};
32
hooks/completion.ts 21 lines
1import { matching, slotAt, SUBCOMMAND_WORDS, type Word } from "../src/core/completion.ts";
2import type { Features } from "./dispatch.ts";
3import type { Host } from "./host.ts";
4import { planNames } from "./tabs/plan.ts";
5
6async function wordsFor(host: Host, slot: NonNullable<ReturnType<typeof slotAt>>): Promise<readonly Word[]> {
7  if (slot === "subcommand") return SUBCOMMAND_WORDS;
8  return (await planNames(host)).map((name) => ({ text: name }));
9}
10
11export const completion: Features = {
12  "prompt.autocomplete": {
13    async post(host, e, result) {
14      const slot = slotAt(e.text, e.start);
15      if (slot === undefined) return undefined;
16      const mine = matching(await wordsFor(host, slot), e.token);
17      return mine.length === 0 ? undefined : { suggestions: [...result.suggestions, ...mine] };
18    },
19  },
20};
21
hooks/dispatch.ts 117 lines
1import type { Args, EventResult, Frozen, RenderElement, RenderInput } from "claude-code";
2import { type Host, reason } from "./host.ts";
3
4type Sites = {
5  "tool.check": [Args<"tool.check">, EventResult<"tool.check">];
6  "tool.call": [Args<"tool.call">, EventResult<"tool.call">];
7  "session.start": [Args<"session.start">, EventResult<"session.start">];
8  "turn.start": [Args<"turn.start">, EventResult<"turn.start">];
9  "turn.step": [Args<"turn.step">, EventResult<"turn.step">];
10  "turn.complete": [Args<"turn.complete">, EventResult<"turn.complete">];
11  "agent.spawn": [Args<"agent.spawn">, EventResult<"agent.spawn">];
12  "prompt.edit": [Args<"prompt.edit">, EventResult<"prompt.edit">];
13  "prompt.change": [Args<"prompt.change">, EventResult<"prompt.change">];
14  "prompt.autocomplete": [Args<"prompt.autocomplete">, EventResult<"prompt.autocomplete">];
15  "ui.close": [Args<"ui.close">, EventResult<"ui.close">];
16  "ui.focus": [Args<"ui.focus">, EventResult<"ui.focus">];
17  "ui.scroll": [Args<"ui.scroll">, EventResult<"ui.scroll">];
18  "command.run": [Args<"command.run">, EventResult<"command.run">];
19  "ui.render AbovePrompt": [RenderInput<"AbovePrompt">, RenderElement];
20  "ui.render Pane": [RenderInput<"Pane">, RenderElement];
21  "ui.render Spinner": [RenderInput<"Spinner">, RenderElement];
22  "ui.render TurnDuration": [RenderInput<"TurnDuration">, RenderElement];
23  "ui.render UserMessage": [RenderInput<"UserMessage">, RenderElement];
24  "ui.render ToolUse": [RenderInput<"ToolUse">, RenderElement];
25  "ui.render ToolGroup": [RenderInput<"ToolGroup">, RenderElement];
26  "session.compact": [Args<"session.compact">, EventResult<"session.compact">];
27};
28
29export type Site = keyof Sites;
30
31type Awaitable<T> = T | Promise<T>;
32
33export type Phase<E, A> = { event: E } | { answer: A };
34
35export type Feature<E, R, A = R, H = Host> = {
36  pre?: (host: H, e: E) => Awaitable<Phase<E, A> | undefined>;
37  post?: (host: H, e: E, result: R) => Awaitable<A | undefined>;
38};
39
40type Logs = { log: (text: string) => void };
41
42export type Input<S extends Site> = Frozen<Sites[S][0]>;
43
44export type Features = {
45  [S in Site]?: Feature<Input<S>, Sites[S][1], S extends "turn.step" ? never : Sites[S][1]>;
46};
47
48export type Entries<S extends Site> = readonly (readonly [string, NonNullable<Features[S]>])[];
49
50export function featuresFor<S extends Site>(site: S, modules: Readonly<Record<string, Features>>): Entries<S> {
51  return Object.entries(modules).flatMap(([name, module]) => {
52    const feature = module[site];
53    return feature === undefined ? [] : [[name, feature] as const];
54  });
55}
56
57async function attempt<T>(host: Logs, where: string, call: () => Awaitable<T>): Promise<{ value: T } | { reason: string }> {
58  try {
59    return { value: await call() };
60  } catch (error) {
61    const failure = reason(error);
62    host.log(`${where} failed: ${failure}`);
63    return { reason: failure };
64  }
65}
66
67export async function dispatch<H extends Logs, E, R>(
68  host: H,
69  where: string,
70  features: readonly (readonly [string, Feature<E, R, R, H>])[],
71  e: E,
72  next: (e: E) => Promise<R>,
73  failed?: (reason: string) => R,
74): Promise<R> {
75  const answers: R[] = [];
76  let event = e;
77  for (const [name, { pre }] of features) {
78    if (pre === undefined) continue;
79    const run = await attempt(host, `${name} pre ${where}`, () => pre(host, event));
80    if (!("value" in run)) {
81      if (failed !== undefined) answers.push(failed(run.reason));
82    } else if (run.value !== undefined && "answer" in run.value) answers.push(run.value.answer);
83    else if (run.value !== undefined) event = run.value.event;
84  }
85  const early = answers[0];
86  if (early !== undefined) return early;
87  const result = await next(event);
88  for (const [name, { post }] of features) {
89    if (post === undefined) continue;
90    const run = await attempt(host, `${name} post ${where}`, () => post(host, event, result));
91    if (!("value" in run)) {
92      if (failed !== undefined) answers.push(failed(run.reason));
93    } else if (run.value !== undefined) answers.push(run.value);
94  }
95  return answers[0] ?? result;
96}
97
98export async function* dispatchStream<H extends Logs, E, C, R>(
99  host: H,
100  where: string,
101  features: readonly (readonly [string, Feature<E, R, never, H>])[],
102  e: E,
103  next: (e: E) => AsyncGenerator<C, R>,
104): AsyncGenerator<C, R> {
105  let event = e;
106  for (const [name, { pre }] of features) {
107    if (pre === undefined) continue;
108    const run = await attempt(host, `${name} pre ${where}`, () => pre(host, event));
109    if ("value" in run && run.value !== undefined && "event" in run.value) event = run.value.event;
110  }
111  const result = yield* next(event);
112  for (const [name, { post }] of features) {
113    if (post !== undefined) await attempt(host, `${name} post ${where}`, () => post(host, event, result));
114  }
115  return result;
116}
117
hooks/footer.ts 168 lines
1import type { RenderElement, RenderInput } from "claude-code";
2import { ledgerCoversSlot } from "../src/core/evidence.ts";
3import { footerLine } from "../src/core/footer.ts";
4import { statusPath, verificationOf } from "../src/core/omca-paths.ts";
5import { turnFacts, type TurnRecord, turnLine } from "../src/core/turn-line.ts";
6import { glyphs, type Glyphs } from "../src/core/ui-kit.ts";
7import type { Piece } from "../src/core/visual.ts";
8import type { Features } from "./dispatch.ts";
9import { type Host, ledgerWrittenAt, reason, resolvedSession, sessionOf, update } from "./host.ts";
10import { type Kit, kitOf, Line } from "./ui.ts";
11
12type Receipt = NonNullable<TurnRecord["receipt"]>;
13
14const KEPT_TURNS = 20;
15const KEPT_LINES = 200;
16// The engine draws the line's mark in a column this wide.
17const MARK_CELLS = 2;
18
19// A line belongs to the main turn that started last before the line was first drawn, so a turn
20// that ends before the previous turn's facts land still gets its own. The starts are the main
21// turns' since the mod loaded; a line first drawn before any of them, as after /resume, keeps the
22// engine's drawing.
23const starts: { turnId: string; at: number }[] = [];
24const firstSeen = new Map<string, number>();
25const bound = new Map<string, string>();
26
27function kept<K, V>(map: Map<K, V>, most: number): void {
28  for (const oldest of map.keys()) {
29    if (map.size <= most) break;
30    map.delete(oldest);
31  }
32}
33
34// The status file times a run in whole seconds, so a turn that starts in the second a run ended
35// would see it again; a run already on an earlier turn's line belongs to that turn.
36async function receiptSince(host: Host, startMs: number, earlier: readonly TurnRecord[]): Promise<Receipt | null> {
37  const [root, sessionId] = await Promise.all([host.session.root(), host.session.id()]);
38  const statusFile = statusPath(root, sessionId);
39  if (statusFile === undefined || !(await host.fs.exists(statusFile))) return null;
40  const slot = verificationOf(JSON.parse(await host.fs.read(statusFile)));
41  if (slot === null || slot.at < Math.floor(startMs / 1000)) return null;
42  if (earlier.some(({ receipt }) => receipt?.at === slot.at && receipt.command === slot.command)) return null;
43  return { command: slot.command, at: slot.at, isLogged: ledgerCoversSlot(await ledgerWrittenAt(host, root), slot.at) };
44}
45
46function turnIdOf(requestId: string, now: number): string | undefined {
47  const known = bound.get(requestId);
48  if (known !== undefined) return known;
49  const seenAt = firstSeen.get(requestId) ?? now;
50  firstSeen.set(requestId, seenAt);
51  kept(firstSeen, KEPT_LINES);
52  const start = starts.findLast((turn) => turn.at <= seenAt);
53  if (start === undefined || [...bound.values()].includes(start.turnId)) return undefined;
54  bound.set(requestId, start.turnId);
55  kept(bound, KEPT_LINES);
56  return start.turnId;
57}
58
59const clockOf = (ms: number): string => new Date(ms).toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
60
61function lineRow(kit: Kit, pieces: readonly Piece[], g: Glyphs): RenderElement {
62  const { Box, Text } = kit;
63  return Box({
64    key: "omca-turn",
65    flexDirection: "row",
66    marginTop: 1,
67    width: "100%",
68    children: [Box({ minWidth: MARK_CELLS, children: [Text({ dimColor: true, children: [g.tier === "ascii" ? "*" : "✻"] })] }), Line(kit, pieces)],
69  });
70}
71
72async function turnOf(host: Host, e: RenderInput<"TurnDuration">) {
73  if (e.surface !== "terminal") return undefined;
74  const [{ value: turns = [] }, now] = await Promise.all([host.state.turns.get(), host.clock.now()]);
75  const turnId = turnIdOf(e.requestId, now);
76  const record = turnId === undefined ? undefined : turns.find((turn) => turn.turnId === turnId);
77  if (record === undefined) return undefined;
78  const { isExpanded, waitingFor } = e.props;
79  // The engine's own words stay where OMCA's line would drop something: the expanded view, a
80  // workflow, or agents the engine waits on without naming them.
81  const keepsEngine = isExpanded === true || (waitingFor === undefined ? record.waiting.length > 0 : waitingFor.workflows > 0);
82  return { record, keepsEngine, waiting: waitingFor?.agents.map((agent) => agent.agentType) ?? [] };
83}
84
85export const footer: Features = {
86  "turn.start": {
87    async pre(host, e) {
88      if (e.agentId !== undefined) return undefined;
89      const [usage, at] = await Promise.all([host.session.usage(), host.clock.now()]);
90      starts.push({ turnId: e.turnId, at });
91      starts.splice(0, starts.length - KEPT_TURNS);
92      await host.state.costSample.set({ turnId: e.turnId, usd: usage.cost?.usd ?? null, at });
93      return undefined;
94    },
95  },
96  "turn.complete": {
97    async post(host, e, result) {
98      if (e.agentId !== undefined) return undefined;
99      const [{ value: sample }, usage, now, { glyphTier }, surfaces, { value: agents = {} }, { value: earlier = [] }] = await Promise.all([
100        host.state.costSample.get(),
101        host.session.usage(),
102        host.clock.now(),
103        sessionOf(host),
104        host.session.surfaces(),
105        host.state.agents.get(),
106        host.state.turns.get(),
107      ]);
108      const isSampled = sample?.turnId === e.turnId;
109      const startedAt = isSampled ? sample.at : now - e.durationMs;
110      const before = isSampled ? sample.usd : null;
111      const after = usage.cost?.usd;
112      // A five-hour or seven-day window means a subscription, where the engine's dollar figure is not what the account pays.
113      const isSubscription = usage.rateLimits.some(({ kind }) => kind === "five_hour" || kind === "seven_day");
114      let receipt: Receipt | null = null;
115      try {
116        receipt = await receiptSince(host, startedAt, earlier);
117      } catch (error) {
118        host.log(`footer: cannot check this turn's verification: ${reason(error)}`);
119      }
120      const record: TurnRecord = {
121        turnId: e.turnId,
122        startedAt,
123        endedAt: now,
124        tokens:
125          e.usage === undefined
126            ? null
127            : {
128                input: e.usage.input_tokens + e.usage.cache_read_input_tokens + e.usage.cache_creation_input_tokens,
129                output: e.usage.output_tokens,
130              },
131        costUsd: isSubscription || before === null || after === undefined ? null : after - before,
132        receipt,
133        waiting: Object.values(agents).flatMap((agent) => (agent.status === "running" && !agent.teammate && agent.endedAt === null ? [agent.type] : [])),
134      };
135      await update(host.state.turns, (turns) => [...(turns ?? []), record].slice(-KEPT_TURNS));
136      // The terminal closes the turn with its own line, which OMCA draws; anywhere else the footer is a text row beneath the answer.
137      if (surfaces.includes("terminal")) return undefined;
138      const text = footerLine(
139        { durationMs: e.durationMs, tokens: record.tokens, costUsd: record.costUsd, unlogged: receipt === null || receipt.isLogged ? null : receipt.command },
140        glyphs(glyphTier),
141      );
142      return { ...result, text };
143    },
144  },
145  "ui.render TurnDuration": {
146    async pre(host, e) {
147      const turn = await turnOf(host, e);
148      if (turn === undefined || turn.keepsEngine) return undefined;
149      const g = glyphs(resolvedSession().glyphTier);
150      const { waiting } = turn;
151      const { word, durationMs } = e.props;
152      const doneAt = waiting.length > 0 ? null : clockOf(turn.record.endedAt);
153      const pieces = turnLine({ word, durationMs, doneAt, waiting, record: turn.record }, g, (e.viewport?.columns ?? 80) - MARK_CELLS);
154      return { answer: lineRow(kitOf(host.ui.resolve(e), e.surface), pieces, g) };
155    },
156    async post(host, e, result) {
157      const turn = await turnOf(host, e);
158      if (turn === undefined || !turn.keepsEngine) return undefined;
159      const facts = turnFacts(turn.record, glyphs(resolvedSession().glyphTier), (e.viewport?.columns ?? 80) - MARK_CELLS);
160      if (facts.length === 0) return undefined;
161      const kit = kitOf(host.ui.resolve(e), e.surface);
162      const { Box } = kit;
163      const tail = Box({ key: "omca-turn-facts", flexDirection: "row", paddingLeft: MARK_CELLS, children: [Line(kit, facts)] });
164      return Box({ key: "omca-turn", flexDirection: "column", children: [result, tail] });
165    },
166  },
167};
168
hooks/host.ts 284 lines
1import type { EngineInterface, FsBytes, PluginState, SessionMessage, Settings, SettingsReadArgs, StateRead, StateSetOptions, StateSetResult } from "claude-code";
2import { parseRegistry, resolveBoundPlan } from "../src/core/boulder.ts";
3import { BOULDER, LEDGER } from "../src/core/omca-paths.ts";
4import { configDir, type Env as PathEnv, homeDir, inferPlatform, isAbsolutePath, joinPath, type Platform, samePath } from "../src/core/path.ts";
5import { parseRuns, provingRuns, type Run, type Verdict, verdictFrom } from "../src/core/proof.ts";
6import { type GlyphTier, glyphTier } from "../src/core/ui-kit.ts";
7
8export type State = PluginState["oh-my-claudeagent"];
9
10export type AtomHost<K extends keyof State> = {
11  get: () => Promise<StateRead<State[K]>>;
12  set: (value: State[K], options?: StateSetOptions) => Promise<StateSetResult>;
13};
14
15export type Options = {
16  showBand: boolean;
17  guardMode: "dialog" | "deny";
18  enableKeywordTriggers: boolean;
19};
20
21type Env = () => Promise<string | undefined>;
22type Engine = EngineInterface;
23
24export type Host = {
25  options: Options;
26  plugin: { name: string; root: string };
27  log: (text: string) => void;
28  env: {
29    HOME: Env;
30    USERPROFILE: Env;
31    HOMEDRIVE: Env;
32    HOMEPATH: Env;
33    CLAUDE_CONFIG_DIR: Env;
34    OMCA_GLYPHS: Env;
35    OMCA_DISABLED_HOOKS: Env;
36    CLAUDE_CODE_SUBAGENT_MODEL_FORCE: Env;
37    CLAUDE_CODE_DISABLE_ADVISOR_TOOL: Env;
38    DISABLE_TELEMETRY: Env;
39    DO_NOT_TRACK: Env;
40    DISABLE_GROWTHBOOK: Env;
41    CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: Env;
42    CLAUDE_CODE_EFFORT_LEVEL: Env;
43    CLAUDE_AFK_TIMEOUT_MS: Env;
44  };
45  fs: {
46    read: (path: string) => Promise<string>;
47    readBytes: (path: string) => Promise<FsBytes>;
48    write: Engine["fs"]["write"];
49    stat: Engine["fs"]["stat"];
50    list: Engine["fs"]["list"];
51    exists: Engine["fs"]["exists"];
52  };
53  process: { run: Engine["process"]["run"] };
54  mcp: { connect: Engine["mcp"]["connect"] };
55  ui: {
56    say: (text: string) => void;
57    open: Engine["ui"]["open"];
58    panes: Engine["ui"]["panes"];
59    ask: Engine["ui"]["ask"];
60    invalidate: () => void;
61    focus: Engine["ui"]["focus"];
62    resolve: Engine["ui"]["resolve"];
63    copy: Engine["ui"]["copy"];
64    toast: Engine["ui"]["toast"];
65    notify: Engine["ui"]["notify"];
66    blit: Engine["ui"]["blit"];
67    view: Engine["ui"]["view"];
68  };
69  session: {
70    id: Engine["session"]["id"];
71    root: Engine["session"]["root"];
72    cwd: Engine["session"]["cwd"];
73    surfaces: Engine["session"]["surfaces"];
74    usage: Engine["session"]["usage"];
75    version: Engine["session"]["version"];
76    transcript: (args: { agentId: string }) => Promise<SessionMessage[] | { deny: string }>;
77  };
78  settings: { read: (args?: Pick<SettingsReadArgs, "source">) => Promise<Settings> };
79  agent: { list: Engine["agent"]["list"] };
80  command: { register: Engine["command"]["register"] };
81  clock: {
82    now: Engine["clock"]["now"];
83    after: Engine["clock"]["after"];
84    every: Engine["clock"]["every"];
85  };
86  prompt: { fill: Engine["prompt"]["fill"] };
87  state: { [K in keyof State]: AtomHost<K> };
88};
89
90// A write that loses its version means another landed, so a burst of n writers settles within n - 1
91// retries. Up to 20 subagents spawn at once, each also stepping; the bound only stops a runaway engine.
92const WRITE_ATTEMPTS = 64;
93
94// Several hooks write one atom between awaits, so each write is read, changed and set at the
95// version it read. A change that returns the value unchanged writes nothing and redraws nothing.
96export async function update<K extends keyof State>(
97  atom: AtomHost<K>,
98  change: (value: State[K] | undefined) => State[K] | undefined,
99): Promise<void> {
100  for (let attempt = 0; attempt < WRITE_ATTEMPTS; attempt += 1) {
101    const { value, version } = await atom.get();
102    const next = change(value);
103    if (next === undefined || next === value) return;
104    if ((await atom.set(next, { ifVersion: version })).isSet) return;
105  }
106  throw new Error(`the state changed under ${WRITE_ATTEMPTS} writes in a row`);
107}
108
109// The engine prefixes a refused call's message with the plugin and the call, `<plugin>: $.fs.read: `.
110export const reason = (error: unknown): string =>
111  (error instanceof Error ? error.message : String(error)).replace(/^[\w-]+: \$\.[\w.]+: /, "");
112
113export async function pluginVersion(host: Host): Promise<string | null> {
114  try {
115    const manifest: unknown = JSON.parse(await host.fs.read(`${host.plugin.root}/.claude-plugin/plugin.json`));
116    const version = typeof manifest === "object" && manifest !== null && "version" in manifest ? manifest.version : null;
117    return typeof version === "string" ? version : null;
118  } catch (error) {
119    host.log(`cannot read the plugin version: ${reason(error)}`);
120    return null;
121  }
122}
123
124export type Session = { env: PathEnv; platform: Platform; home: string; config: string | undefined; glyphTier: GlyphTier };
125
126const UNRESOLVED: Session = { env: {}, platform: "linux", home: "", config: undefined, glyphTier: "nerd" };
127let session: Session | undefined;
128
129async function resolveSession(host: Host): Promise<Session> {
130  const [root, HOME, USERPROFILE, HOMEDRIVE, HOMEPATH, CLAUDE_CONFIG_DIR, glyphs] = await Promise.all([
131    host.session.root(),
132    host.env.HOME(),
133    host.env.USERPROFILE(),
134    host.env.HOMEDRIVE(),
135    host.env.HOMEPATH(),
136    host.env.CLAUDE_CONFIG_DIR(),
137    host.env.OMCA_GLYPHS(),
138  ]);
139  const env = { HOME, USERPROFILE, HOMEDRIVE, HOMEPATH, CLAUDE_CONFIG_DIR };
140  const home = homeDir(env) ?? "";
141  const config = configDir(env);
142  return { env, platform: inferPlatform(root, home, config ?? ""), home, config, glyphTier: glyphTier(glyphs) };
143}
144
145// The environment holds for the life of the session, so it is read once, outside any drawing.
146export async function sessionOf(host: Host): Promise<Session> {
147  session ??= await resolveSession(host);
148  return session;
149}
150
151/** What `sessionOf` resolved, for a drawing that must not wait on the engine. */
152export const resolvedSession = (): Session => session ?? UNRESOLVED;
153
154/** The file's raw bytes, so a digest covers exactly what the server hashes. */
155export async function bytesOf(host: Host, path: string): Promise<Uint8Array> {
156  const { base64 } = await host.fs.readBytes(path);
157  return Uint8Array.fromBase64(base64);
158}
159
160/**
161 * Puts `text` in the prompt box. Where the box does not take it, as on a surface that draws its
162 * own composer, a toast carries the text so the person can type it.
163 */
164export async function fillPrompt(host: Host, text: string): Promise<void> {
165  const { isFilled, refusal } = await host.prompt.fill({ text });
166  if (isFilled) return;
167  host.ui.toast(refusal === "dialog" ? `Close the open dialog, then type: ${text}` : `The prompt box cannot be filled here. Type: ${text}`);
168}
169
170/** The plan this session is bound to, undefined when none is; throws when the registry is not JSON. */
171export async function boundPlanOf(host: Host): Promise<{ name: string; path: string } | undefined> {
172  const [root, sessionId] = await Promise.all([host.session.root(), host.session.id()]);
173  const registry = `${root}/${BOULDER}`;
174  if (!(await host.fs.exists(registry))) return undefined;
175  const parsed = parseRegistry(await host.fs.read(registry));
176  if (parsed.kind === "refused" && parsed.code === "unparseable") throw new Error(parsed.reason);
177  const plan = parsed.kind === "ok" ? resolveBoundPlan(parsed.registry, sessionId, true) : undefined;
178  return plan === undefined || plan.active_plan === "" ? undefined : { name: plan.plan_name, path: plan.active_plan };
179}
180
181/** The evidence ledger's modification time in whole seconds, 0 when there is none. */
182export async function ledgerWrittenAt(host: Host, root: string): Promise<number> {
183  const path = `${root}/${LEDGER}`;
184  return (await host.fs.exists(path)) ? Math.floor((await host.fs.stat(path)).mtimeMs / 1000) : 0;
185}
186
187/** `mtimeMs:size`, or `absent` when the file cannot be stated. */
188export const stampOf = (host: Host, path: string): Promise<string> =>
189  host.fs.stat(path).then(
190    ({ mtimeMs, size }) => `${mtimeMs}:${size}`,
191    () => "absent",
192  );
193
194type Ledger = { path: string; seen: string; proving: readonly Run[]; error: string | null };
195
196// The ledger is rewritten whole and only ever appended to, so every write moves its size and a
197// read at an unchanged stamp would parse the same text.
198let ledger: Ledger | undefined;
199
200/** The ledger's test, build and lint runs newest first, read again only when its stamp moves. */
201async function ledgerOf(host: Host, root: string): Promise<Ledger> {
202  const path = `${root}/${LEDGER}`;
203  const seen = await stampOf(host, path);
204  if (ledger?.path === path && ledger.seen === seen) return ledger;
205  let runs: Run[] = [];
206  let error: string | null = null;
207  if (seen !== "absent") {
208    try {
209      runs = parseRuns(await host.fs.read(path));
210    } catch (failure) {
211      error = reason(failure);
212    }
213  }
214  ledger = { path, seen, proving: provingRuns(runs), error };
215  return ledger;
216}
217
218/**
219 * What proves a plan's tasks: each listed file's modification time, null for one that cannot be
220 * stated, and the ledger's test, build and lint runs newest first, or why the ledger could not be
221 * read. `ledgerSeen` changes when the ledger does.
222 */
223export type ProofFacts = {
224  changes: ReadonlyMap<string, number | null>;
225  proving: readonly Run[];
226  ledgerError: string | null;
227  ledgerSeen: string;
228  startedAt: number | undefined;
229};
230
231// Keyed on the event a dispatch hands every feature, so features of one dispatch share the files'
232// stats and the entry goes with the event.
233const statted = new WeakMap<object, { files: string; changes: ReadonlyMap<string, number | null> }>();
234
235async function changesOf(host: Host, root: string, paths: readonly string[]): Promise<ReadonlyMap<string, number | null>> {
236  const { platform } = await sessionOf(host);
237  const stamps = await Promise.all(
238    paths.map((path) =>
239      host.fs.stat(isAbsolutePath(platform, path) ? path : joinPath(platform, root, path)).then(
240        (stat) => (stat.kind === "file" ? stat.mtimeMs : null),
241        () => null,
242      ),
243    ),
244  );
245  return new Map(paths.map((path, index) => [path, stamps[index] ?? null]));
246}
247
248/** The registry's `started_at` for the plan at `planPath` in milliseconds, undefined when it is unregistered, has none or has one that does not parse. */
249async function startOf(host: Host, root: string, planPath: string): Promise<number | undefined> {
250  const registry = `${root}/${BOULDER}`;
251  if (!(await host.fs.exists(registry))) return undefined;
252  const parsed = parseRegistry(await host.fs.read(registry));
253  if (parsed.kind !== "ok") return undefined;
254  const { platform } = await sessionOf(host);
255  const entry = Object.values(parsed.registry.plans).find(({ active_plan: file }) => file !== undefined && samePath(platform, file, planPath));
256  const startedAt = Date.parse(entry?.started_at ?? "");
257  return Number.isNaN(startedAt) ? undefined : startedAt;
258}
259
260/** `within` is the dispatch's event, so a second call in the same dispatch stats no file again. `planPath` names the plan whose start floors the change times. */
261export async function proofFacts(host: Host, files: readonly string[], planPath: string, within?: object): Promise<ProofFacts> {
262  const root = await host.session.root();
263  const paths = [...new Set(files)];
264  const key = JSON.stringify(paths);
265  const shared = within === undefined ? undefined : statted.get(within);
266  const changes = shared?.files === key ? shared.changes : await changesOf(host, root, paths);
267  if (within !== undefined) statted.set(within, { files: key, changes });
268  const { seen, proving, error } = await ledgerOf(host, root);
269  return { changes, proving, ledgerError: error, ledgerSeen: seen, startedAt: await startOf(host, root, planPath) };
270}
271
272/** A task's proof from the facts: undefined when the ledger is unreadable or none of its files can be stated. */
273export function verdictFor(facts: ProofFacts, files: readonly string[]): Verdict | undefined {
274  if (facts.ledgerError !== null) return undefined;
275  return verdictFrom(
276    files.flatMap((file) => {
277      const at = facts.changes.get(file);
278      return at === undefined || at === null ? [] : [at];
279    }),
280    facts.proving,
281    facts.startedAt,
282  );
283}
284
hooks/metrics.ts 91 lines
1import { isEvidenceLogged, type MetricsRecord, outcomeOf, parseRecord, recordPath } from "../src/core/metrics.ts";
2import { LEDGER } from "../src/core/omca-paths.ts";
3import { estimateCostUsd } from "../src/core/pricing.ts";
4import type { Features } from "./dispatch.ts";
5import { type Host, reason, type State } from "./host.ts";
6
7type Row = State["agents"][string];
8
9const NO_USAGE = { input_tokens: 0, output_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 };
10
11async function locate(host: Host, agentId: string): Promise<{ root: string; sessionId: string; path: string } | undefined> {
12  const [root, sessionId] = await Promise.all([host.session.root(), host.session.id()]);
13  const path = recordPath(root, sessionId, agentId);
14  if (path === undefined) host.log(`metrics: no record for session ${JSON.stringify(sessionId)} agent ${JSON.stringify(agentId)}`);
15  return path === undefined ? undefined : { root, sessionId, path };
16}
17
18const write = (host: Host, path: string, record: MetricsRecord) => host.fs.write(path, `${JSON.stringify(record, null, 2)}\n`);
19
20const running = (sessionId: string, agentId: string, row: Row): MetricsRecord => ({
21  session_id: sessionId,
22  agent_id: agentId,
23  agent_type: row.type,
24  model: row.model,
25  effort: row.effort,
26  started_at: new Date(row.startedAt).toISOString(),
27  ended_at: null,
28  duration_ms: null,
29  input_tokens: 0,
30  output_tokens: 0,
31  estimated_cost_usd: null,
32  outcome: "running",
33  evidence_logged: null,
34});
35
36// null when the ledger exists but cannot be read: unknown, not "no evidence".
37async function evidenceLogged(host: Host, root: string, startMs: number, endMs: number): Promise<boolean | null> {
38  const path = `${root}/${LEDGER}`;
39  try {
40    return (await host.fs.exists(path)) && isEvidenceLogged(await host.fs.read(path), startMs, endMs);
41  } catch (error) {
42    host.log(`metrics: could not read ${LEDGER}: ${reason(error)}`);
43    return null;
44  }
45}
46
47async function agentRow(host: Host, agentId: string): Promise<Row | undefined> {
48  const row = (await host.state.agents.get()).value?.[agentId];
49  if (row === undefined) host.log(`metrics: agent ${agentId} is not tracked`);
50  return row;
51}
52
53export const metrics: Features = {
54  "agent.spawn": {
55    async post(host, e, result) {
56      if (result.deny !== undefined || result.agentId === undefined) return undefined;
57      const [at, row] = await Promise.all([locate(host, result.agentId), agentRow(host, result.agentId)]);
58      if (at === undefined || row === undefined || row.teammate) return undefined;
59      const record = running(at.sessionId, result.agentId, row);
60      await write(host, at.path, e.resume === undefined ? record : { ...record, input_tokens: row.inputTokens, output_tokens: row.outputTokens });
61      return undefined;
62    },
63  },
64  "turn.complete": {
65    async post(host, e) {
66      if (e.agentId === undefined) return undefined;
67      const at = await locate(host, e.agentId);
68      if (at === undefined || !(await host.fs.exists(at.path))) return undefined;
69      if (parseRecord(await host.fs.read(at.path))?.outcome !== "running") return undefined;
70      const row = await agentRow(host, e.agentId);
71      if (row === undefined || row.teammate) return undefined;
72      const endedAt = row.endedAt ?? (await host.clock.now());
73      // A turn without usage counted nothing, by the engine's contract; tokens its steps did
74      // count without one cannot be split into priced kinds, so they stay unpriced.
75      const usage = e.usage ?? (row.inputTokens + row.outputTokens === 0 ? { ...NO_USAGE, model: row.model } : undefined);
76      await write(host, at.path, {
77        ...running(at.sessionId, e.agentId, row),
78        ended_at: new Date(endedAt).toISOString(),
79        duration_ms: endedAt - row.startedAt,
80        input_tokens: row.inputTokens,
81        output_tokens: row.outputTokens,
82        // The lane prices each response on its own, which a model priced by prompt length needs.
83        estimated_cost_usd: usage === undefined ? null : e.usage === undefined ? estimateCostUsd(usage.model, usage) : row.costUsd,
84        outcome: outcomeOf(e),
85        evidence_logged: await evidenceLogged(host, at.root, row.startedAt, endedAt),
86      });
87      return undefined;
88    },
89  },
90};
91
hooks/mod-marker.ts 26 lines
1import { isSafeId } from "../src/core/session-id.ts";
2import type { Features } from "./dispatch.ts";
3import { type Host, pluginVersion } from "./host.ts";
4
5// An unreadable manifest costs the marker its version, not the marker itself.
6async function writeMarker(host: Host): Promise<undefined> {
7  const [root, sessionId, now, version] = await Promise.all([
8    host.session.root(),
9    host.session.id(),
10    host.clock.now(),
11    pluginVersion(host),
12  ]);
13  if (!isSafeId(sessionId)) {
14    host.log(`mod-marker: the session id ${JSON.stringify(sessionId)} cannot name a file`);
15    return undefined;
16  }
17  const marker = { written_at: now, version, options: host.options };
18  await host.fs.write(`${root}/.omca/state/mod/${sessionId}.json`, `${JSON.stringify(marker)}\n`);
19  return undefined;
20}
21
22export const modMarker: Features = {
23  "session.start": { post: writeMarker },
24  "turn.start": { pre: (host, e) => (e.agentId === undefined ? writeMarker(host) : undefined) },
25};
26