@meshpoint/cli 0.0.0-stage → 1.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,118 @@
1
- # Temporary Holding Version
1
+ # meshpoint clients
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The `meshpoint` CLI and harness adapters for Meshpoint 1.0. Adapters: Claude Code, Codex, Cursor, Antigravity, pi, opencode, OpenClaw. Claude Code, Codex, pi, opencode and OpenClaw are verified live against staging; Cursor and Antigravity are ported from their published hook docs and need a live check.
4
+
5
+ ## Install
6
+
7
+ ```
8
+ npm i -g @meshpoint/cli@next # 1.0.0-rc prereleases, until 1.0
9
+ npm i -g @meshpoint/cli # at 1.0
10
+ ```
11
+
12
+ ```
13
+ meshpoint login # browser login when one can open; otherwise a device code to approve in the console
14
+ meshpoint login --device # force the device code (cloud agents, SSH); --browser forces the browser
15
+ meshpoint login --base-url https://meshpoint-platform-staging.cmptr.workers.dev # staging
16
+ meshpoint login --base-url <url> --token <agent token> # pasted dev token instead
17
+ meshpoint whoami # account, org, role
18
+ meshpoint doctor # login, repo, connected harnesses, last capture, spool; exit 1 when something is wrong
19
+ meshpoint org | org invite <email> [--owner] | org invites | org remove <user> | org sessions | org revoke <id> | org rotate-key | org projects
20
+ meshpoint logout
21
+ meshpoint connect # which harnesses this machine has and whether each is connected (--json for agents)
22
+ meshpoint connect claude-code # hooks + skill in ~/.claude/, covers every repo
23
+ meshpoint connect codex # ~/.codex/{hooks.json,rules/meshpoint.rules} + ~/.agents/skills/meshpoint
24
+ meshpoint connect cursor # ~/.cursor/hooks.json + skill
25
+ meshpoint connect antigravity # ~/.gemini/config/hooks.json + skill
26
+ meshpoint connect pi [--pi-dir /abs/dir] # extension stub + skill (default ~/.pi/agent)
27
+ meshpoint connect openclaw # hook pack via `openclaw plugins install`
28
+ meshpoint connect opencode [--config-dir /abs/dir] # plugin link + skill (default ~/.config/opencode)
29
+ meshpoint connect <harness> --project /abs/path/to/repo # per-repo files instead (<repo>/.claude, .codex, .cursor, .agents)
30
+ meshpoint connect <harness> --remove [--project <dir>]
31
+ meshpoint status # config + project id for the current repo
32
+ meshpoint items put --item gotcha 'title' 'body' # write items for the current repo and branch
33
+ meshpoint items put < items.json # same, as a JSON array of {kind, title, body}
34
+ meshpoint items retract 3f9c1a2b # retract by id or unique id prefix
35
+ ```
36
+
37
+ `connect <harness>` without `--project` writes to your user config, so every repo you open is on the mesh. `--project <dir>` writes into one repo instead; the files then travel with the repo in git. The meshpoint testbed on the maintainers' machines uses `--project` only.
38
+
39
+ ## Login
40
+
41
+ `meshpoint login` listens on a random `127.0.0.1` port, opens `<base>/v1/auth/start?port&nonce&agent` in the browser, and the platform sends the browser back to that port with a one-time grant code after WorkOS AuthKit. The CLI exchanges the code for a 7-day agent token plus a 90-day refresh secret, stored in `~/.config/meshpoint/config.json` (mode 600). Every command refreshes the token when it has under a day left; the hook keeps the stored token if a refresh fails. The agent name defaults to `cli-<hostname>`.
42
+
43
+ Without a browser (no `DISPLAY` or `WAYLAND_DISPLAY` on Linux, or an SSH or CI shell) the CLI uses the device code instead: `POST /v1/auth/device` returns a code and the CLI prints
44
+
45
+ ```
46
+ Open https://app.meshpoint.dev/device?code=ABCD-EFGH
47
+ or go to https://app.meshpoint.dev/device and enter ABCD-EFGH
48
+ Waiting for approval (expires in 15 min)…
49
+ ```
50
+
51
+ then polls `POST /v1/auth/device/token` every few seconds (backing off on 429 and network errors) until the user approves the code in the console, which returns the same grant as the browser flow. `--device` and `--browser` force one flow. Denial and expiry end the command with exit 1.
52
+
53
+ `meshpoint doctor` checks the login file, that the token is accepted (`GET /v1/me`), that the current directory is a repo with an origin remote, that every harness found on the machine is connected (user scope or this repo), the project's last capture, and that the spool directory is writable. `·` lines are informational (no capture yet); only `✗` lines fail the command. `--json` returns `{ok, checks:[{id, status, detail}]}`.
54
+
55
+ ## How the Claude Code adapter works
56
+
57
+ Every hook runs `meshpoint tap claude-code` with the event payload on stdin.
58
+
59
+ | hook | what happens |
60
+ |---|---|
61
+ | SessionStart (startup, resume, clear, compact) | `recall` for the repo's origin remote and branch, teammates fetched in the background (waits up to 1.5s), both rendered into `additionalContext`. |
62
+ | UserPromptSubmit | prompt spooled as a `[user]` turn. |
63
+ | Stop | the assistant reply since the last prompt spooled as an `[assistant]` turn, with the files it touched through tools as presence paths. When a checkpoint is due, the hook blocks the stop once and asks the agent to run the `meshpoint` skill. |
64
+ | PreCompact | spool sent now. |
65
+ | SessionEnd | spool sent now. |
66
+
67
+ Credentials in a prompt or reply (API keys with known prefixes, private key blocks, passwords in URLs, bearer headers, values assigned to names like `token` or `password`) are replaced with `[REDACTED:<kind>]` before the turn is written to the spool, so neither the disk nor the platform holds them; the SDK applies the same masking to items. Turns are spooled to `~/.local/state/meshpoint/spool/<session>.jsonl` and sent once the oldest spooled turn is 60s old, so a session costs about one request per minute. A failed send keeps the spool for the next hook. Any failure degrades to an empty hook answer; the mesh never breaks the harness.
68
+
69
+ ## Codex
70
+
71
+ Codex speaks the same hook protocol (event names, payload fields, `hookSpecificOutput.additionalContext`, Stop `decision: block`), so `meshpoint tap codex` is the same tap with a reader for Codex rollouts (`response_item` messages, `apply_patch` paths). `connect codex` writes three things: `.codex/hooks.json` (with `additionalContextLimit` raised from Codex's 2500-char default), `.codex/rules/meshpoint.rules` (prefix rules allowing `meshpoint items put` and `meshpoint items retract`; Codex has no per-skill `allowed-tools`, and "allow" also runs the command outside the sandbox so it can reach the platform), and `.agents/skills/meshpoint/SKILL.md`. Project `.codex/` files load only once the project is trusted in `~/.codex/config.toml` (`[projects."<dir>"] trust_level = "trusted"`); a `-c projects.<dir>.trust_level` command-line override does not load them. Codex asks to review new hooks with `/hooks` before running them; `codex exec` runs hooks too, and `--dangerously-bypass-hook-trust` skips the review for automation. The Codex account's model list may lack the slug pinned in `config.toml` (every turn then fails with `model_not_found`); check `~/.codex/models_cache.json`.
72
+
73
+ ## One core, many harnesses
74
+
75
+ `src/tap.ts` holds one harness session's side of the mesh (`Tap`): recall and presence rendered for injection at start, turns spooled and sent in 60s batches, the checkpoint nudge, one refresh-and-retry after a 401. Hook-style harnesses (Claude Code, Codex, Cursor, Antigravity, OpenClaw) run `meshpoint tap <harness>` once per event with the payload on stdin; in-process harnesses (pi, opencode) call `openTap()` from `src/runtime.ts` and drive the same object directly. Adding a harness means translating its events onto `start / user / assistant / nudge / end`.
76
+
77
+ ## Cursor
78
+
79
+ `connect cursor` writes `.cursor/hooks.json` entries for `sessionStart`, `beforeSubmitPrompt`, `afterAgentResponse`, `stop`, `preCompact` and `sessionEnd` (command `meshpoint tap cursor`; file format `{"version":1,"hooks":{...}}` per cursor.com/docs/hooks) and the checkpoint skill at `.cursor/skills/meshpoint/SKILL.md`. Cursor reloads `hooks.json` on save. Existing hooks are kept; `--remove` deletes only the meshpoint entries and the skill. Recall and presence arrive as `additional_context` at session start; prompts and replies come from the `beforeSubmitPrompt` and `afterAgentResponse` payloads; a due checkpoint is delivered as a `followup_message` from the `stop` hook, which Cursor submits as the next user message (Cursor caps auto follow-ups at 5 per conversation). Cursor must be allowed to run `meshpoint items put` and `meshpoint items retract` in its shell approval settings. Not yet checked live: the transcript file format (touched paths and the nudge counter depend on it), whether `afterAgentResponse` fires once per turn, and whether the agent picks the skill up from the follow-up on its own. Cursor also loads `.claude/settings.json` hooks, so a repo connected for both would run two taps.
80
+
81
+ ## Antigravity
82
+
83
+ `connect antigravity` installs one `meshpoint` group in `hooks.json` (workspace `<repo>/.agents/hooks.json`, global `~/.gemini/config/hooks.json`) with handlers running `meshpoint tap antigravity <Event>` for `SessionStart`, `PreInvocation` and `Stop`, and the skill at `.agents/skills/meshpoint/SKILL.md`. Payloads are camelCase and carry no event name, hence the argument. Recall is injected once per conversation as an `injectSteps` system message, keyed by `conversationId` under `~/.local/state/meshpoint/antigravity/`; `PreInvocation` with `invocationNum` 0 spools `lastUserInput` as the user turn (deduplicated, since every model call repeats it); `Stop` spools the reply with the files its tool calls touched, answers `{"decision":"continue","reason":...}` once when a checkpoint is due, and sends the spool at once when `fullyIdle` is true. There is no session-end or compaction event. Not yet checked live: the `transcript.jsonl` line schema (the reader accepts Gemini-shaped and generic records; without per-line timestamps the nudge never fires) and a community report that Stop hooks did not fire in one IDE build.
84
+
85
+ ## pi
86
+
87
+ `connect pi` writes `<dir>/extensions/meshpoint.js`, a one-line stub importing the built extension by absolute path (pi's loader resolves relative imports from a symlink's own directory, so a symlink does not work), and `<dir>/skills/meshpoint/SKILL.md`. `<dir>` defaults to `$PI_CODING_AGENT_DIR`, then `~/.pi/agent`; pi loads every `.js` in its extensions directory, no settings change needed (`/reload` or restart). Re-run `connect pi` after moving the CLI. Events: `session_start` opens the tap; `before_agent_start` spools the prompt and, once per session, returns a hidden custom message with recall and presence; `turn_end` collects the reply and `tool_call` the `edit`/`write` paths; `agent_before_settle` spools the reply and, when a checkpoint is due, appends the nudge as a custom message with `continue: true` so pi runs one more turn; `session_before_compact` and `session_shutdown` send the spool; `session_compact` re-injects for the next prompt. Verified live: `pi -p` in the testbed against staging captured and showed presence. On this machine `~/.pi/agent/extensions` is a symlink into a dotfiles repo; use `--pi-dir` for tests.
88
+
89
+ ## opencode
90
+
91
+ `connect opencode` links `<dir>/plugins/meshpoint.js` to the CLI's `dist/opencode/plugin.js` (bun follows the link's real path, so `../runtime.js` and the SDK resolve from the CLI install; re-run after moving it) and writes `<dir>/skills/meshpoint/SKILL.md`; `<dir>` defaults to `~/.config/opencode` honouring `XDG_CONFIG_HOME`. Restart opencode. The plugin file has exactly one export because opencode calls every export as a plugin. Per session it fetches recall and presence once and appends them to the system prompt of every model request (`experimental.chat.system.transform`, waiting up to 4s for the fetch on the first request); `chat.message` spools the prompt, `experimental.text.complete` the reply, `tool.execute.after` the `edit`/`write` paths; `session.idle` flushes a due spool and, when a checkpoint is due, sends a follow-up prompt through `client.session.promptAsync` asking for the `meshpoint` skill. Subagent sessions are ignored. `opencode run` exits about 20ms after `session.idle` without awaiting event handlers, so the last turn of a one-shot run stays spooled until that session continues (`opencode run -c`). Verified live: a headless run in the testbed, continued 60s later, flushed three turns to staging and showed presence.
92
+
93
+ ## OpenClaw
94
+
95
+ `connect openclaw` writes a dependency-free hook pack (`package.json` with `openclaw.hooks: ["."]`, `HOOK.md`, `handler.js`) and installs it with `openclaw plugins install <dir> --force`; the handler runs `meshpoint tap openclaw` per event, so the Gateway host needs the CLI on PATH and a login. `agent:bootstrap` adds team knowledge, last checkpoint and active teammates to the bootstrap context (a virtual `MESHPOINT.md`, cached per session for 15 minutes because bootstrap fires every run); `message:received` and `message:sent` capture the turns; `/new`, `/reset` and automatic resets send the spool. A chat agent has no repo: set `MESHPOINT_PROJECT=<id>` (`[A-Za-z0-9._-]{1,128}`) and optionally `MESHPOINT_BRANCH` (default `main`) in the Gateway environment; with neither a git workspace nor that variable the hook does nothing. Recall is branch-scoped, so the branch must match where items were written. `--remove` disables the hook and deletes the pack (OpenClaw's `plugins uninstall` does not handle hook packs); restart the Gateway afterwards. Verified live on a Gateway (OpenClaw 2026.9.6) against staging on 2026-11-10: the bootstrap injection reached the model (it answered from a planted item), `message:sent` captured the reply, `/new` flushed the spool, and the console showed the capture and presence. `message:received` fires only for inbound channel messages, not for `openclaw agent -m` runs, so that path still needs a real chat message; `openclaw agent --deliver --channel <ch> --to <id>` is enough to exercise `message:sent`. Gateway logs live in `/tmp/openclaw/openclaw-<date>.log`, not journald. The nudge asks for the `meshpoint` skill, which this adapter does not install (OpenClaw skills live in the workspace).
96
+
97
+ ## Checkpoints
98
+
99
+ Distillation is agent-side: the platform runs no model. `connect` installs the `meshpoint` skill next to the hooks. The skill has the agent write what the session established as items of the fixed kinds (`decision`, `gotcha`, `convention`, `fact`, `status`, `todo`) through `meshpoint items put`, which records the time of the last checkpoint per project branch in `~/.local/state/meshpoint/checkpoints/`. The skill uses the `--item kind title body` argument form: Claude Code's command guard asks for approval on heredocs or JSON with quotes even when the command is allowlisted, while plain single-quoted arguments pass under the skill's `allowed-tools: Bash(meshpoint items put:*)`.
100
+
101
+ The session-start inject shows each item's id prefix so the skill can retract what the session made obsolete (`meshpoint items retract <prefix>...`, resolved against a fresh recall; ambiguous prefixes are refused).
102
+
103
+ A checkpoint is due after 20 assistant replies or 60k chars of reply text since the later of the last checkpoint and the last nudge (`~/.local/state/meshpoint/nudges/<session>.json`). An ignored nudge is not repeated until the next pile. The benchmark behind this: one-shot items scored 0.67 resume correctness against 0.60 for a freeform summary and 0.32 for a transcript tail (ceiling 0.82).
104
+
105
+ The project id is derived from `git remote get-url origin` (`host--owner--repo`); directories without an origin remote are ignored.
106
+
107
+ ## Develop
108
+
109
+ The package depends on the published `@meshpoint/sdk`. To work against the sibling checkout instead, link it without touching `package.json`:
110
+
111
+ ```
112
+ npm install
113
+ npm install ../meshpoint-sdk --no-save # use the local SDK build (run `npm run build` there first)
114
+ npm run check
115
+ npm run build && node dist/bin.js --help
116
+ ```
117
+
118
+ Publishing (maintainers, after `npm login`): `npm publish` in `../meshpoint-sdk`, then here. `prepublishOnly` runs the checks and the build; `publishConfig` tags prereleases `next`.
@@ -0,0 +1,50 @@
1
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import path from "node:path";
4
+ import { skillMarkdown, SKILL_NAME } from "../claude-code/skill.js";
5
+ export const ANTIGRAVITY_TAP_COMMAND = "meshpoint tap antigravity";
6
+ export const MESHPOINT_GROUP = "meshpoint";
7
+ export const ANTIGRAVITY_EVENTS = ["SessionStart", "PreInvocation", "Stop"];
8
+ const HOOK_TIMEOUT_S = 30;
9
+ export function installAntigravityHooks(file) {
10
+ const group = { enabled: true };
11
+ for (const event of ANTIGRAVITY_EVENTS) {
12
+ group[event] = [{ type: "command", command: `${ANTIGRAVITY_TAP_COMMAND} ${event}`, timeout: HOOK_TIMEOUT_S }];
13
+ }
14
+ return { ...file, [MESHPOINT_GROUP]: group };
15
+ }
16
+ export function removeAntigravityHooks(file) {
17
+ const { [MESHPOINT_GROUP]: _removed, ...rest } = file;
18
+ return rest;
19
+ }
20
+ // Workspace layout: <repo>/.agents/{hooks.json,skills/meshpoint}. Global layout: ~/.gemini/config/
21
+ // {hooks.json,skills/meshpoint} (the hooks and skills references, per-surface file locations).
22
+ export function antigravityPaths(projectDir, home = homedir()) {
23
+ const dir = projectDir ? path.join(projectDir, ".agents") : path.join(home, ".gemini", "config");
24
+ return { hooks: path.join(dir, "hooks.json"), skillDir: path.join(dir, "skills", SKILL_NAME) };
25
+ }
26
+ export function connectAntigravity(opts) {
27
+ const paths = opts.paths ?? antigravityPaths(opts.projectDir);
28
+ let file = {};
29
+ try {
30
+ file = JSON.parse(readFileSync(paths.hooks, "utf8"));
31
+ }
32
+ catch (err) {
33
+ if (err.code !== "ENOENT")
34
+ throw new Error(`could not read ${paths.hooks}: ${err.message}`);
35
+ }
36
+ if (opts.remove) {
37
+ const next = removeAntigravityHooks(file);
38
+ if (Object.keys(next).length > 0)
39
+ writeFileSync(paths.hooks, `${JSON.stringify(next, null, 2)}\n`);
40
+ else
41
+ rmSync(paths.hooks, { force: true });
42
+ rmSync(paths.skillDir, { recursive: true, force: true });
43
+ return `removed the ${MESHPOINT_GROUP} hook group from ${paths.hooks} and ${paths.skillDir}`;
44
+ }
45
+ mkdirSync(path.dirname(paths.hooks), { recursive: true });
46
+ writeFileSync(paths.hooks, `${JSON.stringify(installAntigravityHooks(file), null, 2)}\n`);
47
+ mkdirSync(paths.skillDir, { recursive: true });
48
+ writeFileSync(path.join(paths.skillDir, "SKILL.md"), skillMarkdown({ allowedTools: false }));
49
+ return `installed the ${MESHPOINT_GROUP} hook group in ${paths.hooks} (${ANTIGRAVITY_EVENTS.join(", ")}) and ${paths.skillDir}/SKILL.md. Antigravity loads hooks.json on the next conversation; toggle it under Customizations > Hooks.`;
50
+ }
@@ -0,0 +1,123 @@
1
+ import { createHash } from "node:crypto";
2
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { lastAssistantTurn, lastUserText } from "../claude-code/transcript.js";
5
+ import { Tap } from "../tap.js";
6
+ import { parseAntigravityTranscript } from "./transcript.js";
7
+ // Stop's decision is required; anything but "continue" lets the agent stop.
8
+ const ALLOW_STOP = '{"decision":"stop"}';
9
+ // A conversation outlives executions and hook processes, so what the hook has already done for it
10
+ // is kept on disk, like the nudge records in Checkpoints.
11
+ class Conversations {
12
+ dir;
13
+ constructor(dir) {
14
+ this.dir = dir;
15
+ }
16
+ file(conversation) {
17
+ return path.join(this.dir, "antigravity", `${conversation.replace(/[^A-Za-z0-9._-]/g, "_")}.json`);
18
+ }
19
+ read(conversation) {
20
+ try {
21
+ const parsed = JSON.parse(readFileSync(this.file(conversation), "utf8"));
22
+ return typeof parsed === "object" && parsed !== null ? parsed : {};
23
+ }
24
+ catch {
25
+ return {};
26
+ }
27
+ }
28
+ update(conversation, patch) {
29
+ const file = this.file(conversation);
30
+ mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
31
+ writeFileSync(file, `${JSON.stringify({ ...this.read(conversation), ...patch })}\n`, { mode: 0o600 });
32
+ }
33
+ }
34
+ // The event, from the command argument bin copied in, else from the fields only that event has.
35
+ // PreInvocation and PostInvocation share a payload shape; only PreInvocation is installed.
36
+ function eventName(payload) {
37
+ if (payload.hookEventName)
38
+ return payload.hookEventName;
39
+ if (payload.fullyIdle !== undefined || payload.terminationReason !== undefined)
40
+ return "Stop";
41
+ if (payload.invocationNum !== undefined)
42
+ return "PreInvocation";
43
+ if (payload.conversationId !== undefined)
44
+ return "SessionStart";
45
+ return "";
46
+ }
47
+ // Context goes in as an injectSteps systemMessage (SessionStart example in the hooks reference);
48
+ // ephemeralMessage is transient and the recall must stay in the trajectory.
49
+ function inject(text) {
50
+ return JSON.stringify({ injectSteps: [{ systemMessage: { systemMessage: text } }] });
51
+ }
52
+ // One hook event in, one JSON answer out, the Antigravity way: recall injected once per
53
+ // conversation (SessionStart, or the first PreInvocation when SessionStart did not fire), the
54
+ // prompt spooled at the first invocation of each execution, the reply at Stop, the spool sent at
55
+ // Stop with fullyIdle. The Tap swallows mesh failures; this layer only speaks the hook protocol.
56
+ export async function runAntigravityTap(payload, deps) {
57
+ const event = eventName(payload);
58
+ const empty = event === "Stop" ? ALLOW_STOP : "{}";
59
+ const repo = deps.repo(payload.workspacePaths?.[0] ?? process.cwd());
60
+ if (!repo)
61
+ return empty;
62
+ const conversation = payload.conversationId ?? "unknown";
63
+ const tap = new Tap({
64
+ config: deps.config,
65
+ repo,
66
+ session: conversation,
67
+ spool: deps.spool,
68
+ checkpoints: deps.checkpoints,
69
+ ...(deps.now ? { now: deps.now } : {}),
70
+ ...(deps.fetch ? { fetch: deps.fetch } : {}),
71
+ ...(deps.presenceWaitMs !== undefined ? { presenceWaitMs: deps.presenceWaitMs } : {}),
72
+ ...(deps.refresh ? { refresh: deps.refresh } : {}),
73
+ });
74
+ const conversations = new Conversations(deps.stateDir);
75
+ const transcript = () => {
76
+ if (!payload.transcriptPath)
77
+ return [];
78
+ try {
79
+ return (deps.parseTranscript ?? parseAntigravityTranscript)(deps.readTranscript(payload.transcriptPath));
80
+ }
81
+ catch {
82
+ return [];
83
+ }
84
+ };
85
+ const recall = async () => {
86
+ if (conversations.read(conversation).recalled)
87
+ return "{}";
88
+ const text = await tap.start();
89
+ conversations.update(conversation, { recalled: true });
90
+ return text ? inject(text) : "{}";
91
+ };
92
+ switch (event) {
93
+ case "SessionStart":
94
+ return recall();
95
+ case "PreInvocation": {
96
+ // invocationNum is 0-indexed: 0 is the first model call of an execution (one user prompt).
97
+ if ((payload.invocationNum ?? 0) !== 0)
98
+ return "{}";
99
+ const out = await recall();
100
+ const prompt = (payload.lastUserInput ?? lastUserText(transcript()) ?? "").trim();
101
+ const hash = prompt ? createHash("sha256").update(prompt).digest("hex").slice(0, 16) : "";
102
+ if (prompt && conversations.read(conversation).user !== hash) {
103
+ await tap.user(prompt);
104
+ conversations.update(conversation, { user: hash });
105
+ }
106
+ return out;
107
+ }
108
+ case "Stop": {
109
+ const entries = transcript();
110
+ const turn = lastAssistantTurn(entries);
111
+ await tap.assistant(turn?.text ?? "", turn?.paths ?? []);
112
+ // decision "continue" re-enters the loop with reason as a system message. The nudge record
113
+ // keeps the continuation's own Stop from nudging again.
114
+ const reason = tap.nudge(entries);
115
+ // There is no session-end event; fullyIdle means the agent and its background tasks are done.
116
+ if (payload.fullyIdle === true)
117
+ await tap.end();
118
+ return reason ? JSON.stringify({ decision: "continue", reason }) : ALLOW_STOP;
119
+ }
120
+ default:
121
+ return empty;
122
+ }
123
+ }
@@ -0,0 +1,88 @@
1
+ // Reads user and assistant text, and the files touched through tools, out of an Antigravity
2
+ // transcript.jsonl. The hooks reference (antigravity.google/docs/hooks, "Common input fields")
3
+ // documents only the file's path, not its line schema, so this reader is tolerant: it accepts the
4
+ // Gemini content shape ({role: "user"|"model", parts: [{text}|{functionCall: {name, args}}]}) and
5
+ // the generic shape ({role|type, content: string|[{type: "text", text}]}). Tool arguments use the
6
+ // names from the hooks reference's tool list (TargetFile, AbsolutePath). Needs a live check.
7
+ const PATH_KEYS = ["TargetFile", "AbsolutePath", "file_path", "path"];
8
+ function isRecord(v) {
9
+ return typeof v === "object" && v !== null && !Array.isArray(v);
10
+ }
11
+ function role(record) {
12
+ const raw = record.role ?? record.type ?? record.author;
13
+ if (typeof raw !== "string")
14
+ return null;
15
+ const r = raw.toLowerCase();
16
+ if (r === "user" || r === "human")
17
+ return "user";
18
+ if (r === "assistant" || r === "model" || r === "agent")
19
+ return "assistant";
20
+ return null;
21
+ }
22
+ function timestamp(raw) {
23
+ if (typeof raw === "string")
24
+ return Date.parse(raw) || 0;
25
+ if (typeof raw !== "number" || !Number.isFinite(raw))
26
+ return 0;
27
+ return raw < 1e12 ? raw * 1000 : raw;
28
+ }
29
+ function pathsOf(args, out) {
30
+ if (!isRecord(args))
31
+ return;
32
+ for (const key of PATH_KEYS) {
33
+ const v = args[key];
34
+ if (typeof v === "string" && v)
35
+ out.push(v);
36
+ }
37
+ }
38
+ function collect(block, texts, paths) {
39
+ if (typeof block === "string") {
40
+ texts.push(block);
41
+ return;
42
+ }
43
+ if (!isRecord(block))
44
+ return;
45
+ if (typeof block.text === "string")
46
+ texts.push(block.text);
47
+ if (isRecord(block.functionCall))
48
+ pathsOf(block.functionCall.args, paths);
49
+ pathsOf(block.input, paths);
50
+ if (isRecord(block.toolCall))
51
+ pathsOf(block.toolCall.args, paths);
52
+ }
53
+ export function parseAntigravityTranscript(jsonl) {
54
+ const entries = [];
55
+ for (const line of jsonl.split("\n")) {
56
+ if (!line.trim())
57
+ continue;
58
+ let parsed;
59
+ try {
60
+ parsed = JSON.parse(line);
61
+ }
62
+ catch {
63
+ continue;
64
+ }
65
+ if (!isRecord(parsed))
66
+ continue;
67
+ const message = isRecord(parsed.message) ? parsed.message : parsed;
68
+ const r = role(parsed) ?? role(message);
69
+ if (!r)
70
+ continue;
71
+ const texts = [];
72
+ const paths = [];
73
+ const body = message.parts ?? message.content ?? message.text;
74
+ if (Array.isArray(body))
75
+ for (const block of body)
76
+ collect(block, texts, paths);
77
+ else
78
+ collect(body, texts, paths);
79
+ if (isRecord(parsed.toolCall))
80
+ pathsOf(parsed.toolCall.args, paths);
81
+ const text = texts.join("\n").trim();
82
+ // Tool results come back as user-role records with no prose; skip those so turns stay human.
83
+ if (!text && (r === "user" || paths.length === 0))
84
+ continue;
85
+ entries.push({ role: r, text, paths, at: timestamp(parsed.timestamp ?? parsed.createTime ?? message.timestamp) });
86
+ }
87
+ return entries;
88
+ }