paseo-follow-up 1.4.0-beta.4 → 1.4.0-beta.5
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 +1 -1
- package/index.server.ts +14 -0
- package/package.json +1 -1
- package/server/agent-hook.mjs +31 -7
- package/server/hook-source.ts +1 -1
package/README.md
CHANGED
|
@@ -170,7 +170,7 @@ The choices live in `agents.json` in Follow-up's data folder. Anything missing o
|
|
|
170
170
|
Install the beta:
|
|
171
171
|
|
|
172
172
|
```sh
|
|
173
|
-
paseo plugin update follow-through --version 1.4.0-beta.
|
|
173
|
+
paseo plugin update follow-through --version 1.4.0-beta.5
|
|
174
174
|
# or, for a fresh install:
|
|
175
175
|
paseo plugin install npm:paseo-follow-up@beta
|
|
176
176
|
```
|
package/index.server.ts
CHANGED
|
@@ -4,6 +4,7 @@ import { askQuestion, recordAnswer, syncTaskQuestions, withdrawQuestion } from "
|
|
|
4
4
|
import { agentSetSpec, developerSetSpec } from "./server/spec";
|
|
5
5
|
import type { PluginServerContext, PluginHandlerContext } from "@getpaseo/plugin/server";
|
|
6
6
|
import { mkdir, writeFile } from "node:fs/promises";
|
|
7
|
+
import { mkdirSync, renameSync, writeFileSync } from "node:fs";
|
|
7
8
|
import { join } from "node:path";
|
|
8
9
|
import { randomUUID } from "node:crypto";
|
|
9
10
|
import * as rpc from "./shared/contracts";
|
|
@@ -64,6 +65,18 @@ export default function contribute(server: PluginServerContext) {
|
|
|
64
65
|
const questionMode = async (): Promise<QuestionMode> => { try { const state = await questionSettings.read(); return state.status === "ready" ? state.values.mode : DEFAULT_QUESTION_MODE; } catch { return DEFAULT_QUESTION_MODE; } };
|
|
65
66
|
const directory = join(paseoHome, "plugin-data", "follow-through");
|
|
66
67
|
const bridge = join(directory, "mcp.mjs");
|
|
68
|
+
/**
|
|
69
|
+
* Native tools live in this process: a reload or update drops them from every open session (Paseo 0.15.2 re-attaches
|
|
70
|
+
* only when a session reopens, which it does before that agent's next prompt). Each worker gets an instance id and each
|
|
71
|
+
* native session records the instance that attached its tools, so the agent hook can tell an agent mid-turn that its
|
|
72
|
+
* follow_ tools are gone and the bridge still works. Written synchronously, before any session can open.
|
|
73
|
+
*/
|
|
74
|
+
const toolsInstance = randomUUID();
|
|
75
|
+
try {
|
|
76
|
+
mkdirSync(join(directory, "hook-state"), { recursive: true, mode: 0o700 });
|
|
77
|
+
writeFileSync(join(directory, `tools-instance.json.${toolsInstance}`), JSON.stringify({ instance: toolsInstance }), { mode: 0o600 });
|
|
78
|
+
renameSync(join(directory, `tools-instance.json.${toolsInstance}`), join(directory, "tools-instance.json"));
|
|
79
|
+
} catch { /* Without it the hook assumes the tools are attached, as before. */ }
|
|
67
80
|
// Every RPC handler, also callable in-process: native agent tools run the same handlers the stdio bridge reaches.
|
|
68
81
|
const handlers = new Map<string, { input: { parseAsync(value: unknown): Promise<unknown> }; run: (input: any, context: PluginHandlerContext) => unknown }>();
|
|
69
82
|
const handle: PluginServerContext["handle"] = (contract, handler) => { handlers.set(contract.name, { input: contract.input, run: handler as never }); server.handle(contract, handler); };
|
|
@@ -237,6 +250,7 @@ export default function contribute(server: PluginServerContext) {
|
|
|
237
250
|
if (process.env.FOLLOW_THROUGH_FORCE_STDIO !== "1" && nativeToolsAvailable(request, await paseoConfig())) {
|
|
238
251
|
const flags = { recovery, brief: !!brief && !recovery, root: root && !recovery, overseer: overseer && !recovery };
|
|
239
252
|
const env = { ...request.env, FOLLOW_THROUGH_TOOLS: "native", FOLLOW_THROUGH_PROVIDER: request.provider, ...(flags.root ? { FOLLOW_THROUGH_ROOT: "1" } : {}), ...(flags.overseer ? { FOLLOW_THROUGH_OVERSEER: "1" } : {}) };
|
|
253
|
+
if (/^[\w-]+$/.test(request.agentId)) await writeFile(join(directory, "hook-state", `native-${request.agentId}.json`), JSON.stringify({ instance: toolsInstance }), { mode: 0o600 }).catch(() => undefined);
|
|
240
254
|
return { ...request, env, tools: [...request.tools, ...nativeTools(flags, live, invoke)] };
|
|
241
255
|
}
|
|
242
256
|
return withSessionMcp({ ...request, env: { ...request.env, FOLLOW_THROUGH_TOOLS: "stdio", FOLLOW_THROUGH_PROVIDER: request.provider } }, directory, clientEntry(), paseoHome, recovery, process.env, brief, root, overseer, providers) as R;
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "paseo-follow-up",
|
|
3
3
|
"private": false,
|
|
4
|
-
"version": "1.4.0-beta.
|
|
4
|
+
"version": "1.4.0-beta.5",
|
|
5
5
|
"description": "Follow every workspace PR stack in Paseo, answer agent questions, batch repairs for the main agent, and see what needs you.",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"files": [
|
package/server/agent-hook.mjs
CHANGED
|
@@ -6,7 +6,7 @@ import { createHash, randomUUID } from "node:crypto";
|
|
|
6
6
|
|
|
7
7
|
const directory = dirname(fileURLToPath(import.meta.url));
|
|
8
8
|
/** 1.4.0-beta.2: launched with Follow-up's tools served by Paseo's MCP (follow_<name>), or the follow-through bridge (<name>). Agents opened before the upgrade carry no flag and keep the bridge names. */
|
|
9
|
-
|
|
9
|
+
let native = process.env.FOLLOW_THROUGH_TOOLS === "native";
|
|
10
10
|
// Tool names that read unambiguously in prose; kept identical to server/mcp.mjs's underscore names (a test checks it).
|
|
11
11
|
export const TOOL_NAMES = ["workspace_status", "sync_workspace", "enroll_workspace", "register_pr", "exclude_stack", "update_obligation", "acknowledge_batch", "ask_question", "record_answer", "withdraw_question", "set_spec", "workspace_about", "agent_settings", "needs_you", "declare_done", "list_prs", "add_reviewers", "enable_merge_when_ready", "disable_merge_when_ready", "send_repairs", "set_auto_send", "clear_hold", "retry_batch", "inbox_list", "sign_off", "set_finish_flags", "set_priorities", "agent_digest", "route_candidates", "send_to_agent", "start_workspace"];
|
|
12
12
|
const toolPattern = new RegExp(`(?<![\\w])(${TOOL_NAMES.join("|")})(?![\\w])`, "g");
|
|
@@ -14,6 +14,15 @@ const toolPattern = new RegExp(`(?<![\\w])(${TOOL_NAMES.join("|")})(?![\\w])`, "
|
|
|
14
14
|
export function named(text, isNative = native) { return isNative ? text.replace(toolPattern, "follow_$1") : text; }
|
|
15
15
|
/** Whether a tool call is Follow-up's own, under either name set (mcp__follow-through__x, follow-through.x, mcp__paseo__follow_x, paseo.follow_x). */
|
|
16
16
|
export function isFollowTool(tool) { return /follow[\s_-]*through/i.test(tool) || /^(?:mcp__paseo__|paseo[.:/])follow_[a-z_]+$/.test(tool); }
|
|
17
|
+
/** Whether a shell call runs the bridge, however it names it ($FOLLOW_THROUGH_CLI, as the skill says, or the path). */
|
|
18
|
+
export function isBridgeCall(args, bridgePath) { return args.includes(bridgePath) || /\$\{?FOLLOW_THROUGH_CLI\b/.test(args) || /mcp\.mjs["']?\s+call\b/.test(args); }
|
|
19
|
+
/**
|
|
20
|
+
* Native tools are attached by one worker; a plugin reload or update drops them from open sessions until each reopens
|
|
21
|
+
* (Paseo 0.15.2 reopens a session before that agent's next prompt). The worker records its instance and the instance
|
|
22
|
+
* that attached each session's tools; a mismatch means this session's follow_ tools are gone. Pure, so it's testable.
|
|
23
|
+
*/
|
|
24
|
+
export function toolsDetached(isNative, current, mine) { return isNative && !!current?.instance && mine?.instance !== current.instance; }
|
|
25
|
+
export const detachedNotice = "Follow-up was updated while this session was open, so its follow_* tools are detached and fail with \"Tool not found\" until this session reopens (Paseo reopens it before your next prompt). Until then use the bridge, which runs the same tools with their unprefixed names: node \"$FOLLOW_THROUGH_CLI\" call <tool> '<json>' --compact (for example sync_workspace or needs_you). Do not mention this to the developer.";
|
|
17
26
|
const quietRevision = 1;
|
|
18
27
|
const quietInstruction = "Do routine bookkeeping silently. Do not announce tracker calls, say you updated/synced the sidebar, recap panel state, or add plugin-status commentary/final paragraphs. Put receipts and evidence in the tools. User-facing messages should cover the actual work outcome, or a decision/blocker requiring the developer; answer sidebar status only when explicitly asked. If this continuation is bookkeeping only, use the tools and finish without another recap or repeating your previous answer.";
|
|
19
28
|
const stopReason = "Silently complete this workspace's sidebar bookkeeping before finishing.";
|
|
@@ -126,6 +135,10 @@ async function main() {
|
|
|
126
135
|
if (event.agent_id || event.hook_event_name === "SubagentStop") return;
|
|
127
136
|
const lease = await json(join(directory, "hooks-enabled.json"));
|
|
128
137
|
if (lease.expiresAt < Date.now() || !lease.clientEntry) return;
|
|
138
|
+
const instance = native ? await json(join(directory, "tools-instance.json")).catch(() => null) : null;
|
|
139
|
+
const detached = toolsDetached(native, instance, native ? await json(join(directory, "hook-state", `native-${agentId}.json`)).catch(() => null) : null);
|
|
140
|
+
// Detached: name the bridge's tools everywhere below, and include the bridge paragraph.
|
|
141
|
+
if (detached) native = false;
|
|
129
142
|
// The Overseer: a fresh digest at the start of every turn; no sidebar bookkeeping and no Stop-hook nudge.
|
|
130
143
|
if (process.env.FOLLOW_THROUGH_OVERSEER === "1") {
|
|
131
144
|
if (event.hook_event_name === "SessionStart") {
|
|
@@ -171,19 +184,30 @@ async function main() {
|
|
|
171
184
|
if (name === "UserPromptSubmit") {
|
|
172
185
|
if (turn?.stopped && String(event.prompt ?? "").startsWith(stopReason)) return;
|
|
173
186
|
const text = await sessionText(); const hash = text ? digest(text) : null;
|
|
174
|
-
await save(path, { startedAt: Date.now(), dirtyAt: null, stopped: false, quietRevision, contextHash: hash });
|
|
187
|
+
await save(path, { startedAt: Date.now(), dirtyAt: null, lastToolAt: null, stopped: false, quietRevision, contextHash: hash, ...(turn?.detachedNotice ? { detachedNotice: turn.detachedNotice } : {}) });
|
|
175
188
|
if (text && shouldRepeat(process.env.FOLLOW_THROUGH_PROVIDER, turn, hash)) emit(text);
|
|
176
189
|
return;
|
|
177
190
|
}
|
|
178
191
|
if (name === "PostToolUse") {
|
|
179
|
-
|
|
192
|
+
// Said once per session per worker: the tools stay detached until the session reopens.
|
|
193
|
+
const notice = detached && turn?.detachedNotice !== instance.instance;
|
|
194
|
+
if (!workspace) {
|
|
195
|
+
if (notice) { await save(path, { ...turn, detachedNotice: instance.instance }); emit(detachedNotice); }
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
180
198
|
const tool = String(event.tool_name ?? "");
|
|
181
199
|
const args = JSON.stringify(event.tool_input ?? {});
|
|
182
|
-
const trackedTool = isFollowTool(tool) || args
|
|
200
|
+
const trackedTool = isFollowTool(tool) || isBridgeCall(args, join(directory, "mcp.mjs"));
|
|
183
201
|
const dirty = !trackedTool && /(bash|shell|exec_command|write_stdin|edit|write|apply_patch|notebook)/i.test(tool);
|
|
184
202
|
const upgrade = turn?.quietRevision !== quietRevision;
|
|
185
|
-
|
|
186
|
-
|
|
203
|
+
// A dirty call is dated from when it could have started (the previous tool's end), not when it ended: a call that
|
|
204
|
+
// itself confirms sync, through any bridge spelling, then still satisfies the Stop check, which reads the
|
|
205
|
+
// sync record the RPC handler wrote rather than tool names.
|
|
206
|
+
const now = Date.now();
|
|
207
|
+
const callStart = turn?.lastToolAt || turn?.startedAt || now;
|
|
208
|
+
await save(path, { ...turn, startedAt: turn?.startedAt ?? (dirty ? callStart : 0), stopped: turn?.stopped ?? false, ...(dirty ? { dirtyAt: callStart } : {}), quietRevision, lastToolAt: now, ...(notice ? { detachedNotice: instance.instance } : {}) });
|
|
209
|
+
const text = [upgrade ? quietInstruction : null, notice ? detachedNotice : null].filter(Boolean).join("\n\n");
|
|
210
|
+
if (text) emit(text);
|
|
187
211
|
return;
|
|
188
212
|
}
|
|
189
213
|
if (event.stop_hook_active || turn?.stopped || event.background_tasks?.length) return;
|
|
@@ -196,7 +220,7 @@ async function main() {
|
|
|
196
220
|
const nudge = shouldNudge({ provider, brief, agentId, contributor, recovery: false, subagent: false, stopHookActive: !!event.stop_hook_active, turn, called });
|
|
197
221
|
if (!sync && !nudge) return;
|
|
198
222
|
await save(path, { ...turn, startedAt: turn?.startedAt ?? Date.now(), stopped: true, ...(nudge ? { nudgedAt: Date.now() } : {}) });
|
|
199
|
-
const reasons = [sync ? stopReason + " This is metadata bookkeeping only; do not start queued repairs or recovery.\n\n" + context() : null, nudge ? named(nudgeReason) : null].filter(Boolean);
|
|
223
|
+
const reasons = [detached ? detachedNotice : null, sync ? stopReason + " This is metadata bookkeeping only; do not start queued repairs or recovery.\n\n" + context() : null, nudge ? named(nudgeReason) : null].filter(Boolean);
|
|
200
224
|
process.stdout.write(JSON.stringify({ decision: "block", reason: reasons.join("\n\n") }) + "\n");
|
|
201
225
|
}
|
|
202
226
|
// Tests import shouldNudge without running the hook.
|
package/server/hook-source.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// Generated by scripts/build.mjs.
|
|
2
|
-
export const hookSource = "#!/usr/bin/env node\nimport { readFile, writeFile, mkdir, rename } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { createHash, randomUUID } from \"node:crypto\";\n\nconst directory = dirname(fileURLToPath(import.meta.url));\n/** 1.4.0-beta.2: launched with Follow-up's tools served by Paseo's MCP (follow_<name>), or the follow-through bridge (<name>). Agents opened before the upgrade carry no flag and keep the bridge names. */\nconst native = process.env.FOLLOW_THROUGH_TOOLS === \"native\";\n// Tool names that read unambiguously in prose; kept identical to server/mcp.mjs's underscore names (a test checks it).\nexport const TOOL_NAMES = [\"workspace_status\", \"sync_workspace\", \"enroll_workspace\", \"register_pr\", \"exclude_stack\", \"update_obligation\", \"acknowledge_batch\", \"ask_question\", \"record_answer\", \"withdraw_question\", \"set_spec\", \"workspace_about\", \"agent_settings\", \"needs_you\", \"declare_done\", \"list_prs\", \"add_reviewers\", \"enable_merge_when_ready\", \"disable_merge_when_ready\", \"send_repairs\", \"set_auto_send\", \"clear_hold\", \"retry_batch\", \"inbox_list\", \"sign_off\", \"set_finish_flags\", \"set_priorities\", \"agent_digest\", \"route_candidates\", \"send_to_agent\", \"start_workspace\"];\nconst toolPattern = new RegExp(`(?<![\\\\w])(${TOOL_NAMES.join(\"|\")})(?![\\\\w])`, \"g\");\n/** Names Follow-up's tools the way this agent has them. */\nexport function named(text, isNative = native) { return isNative ? text.replace(toolPattern, \"follow_$1\") : text; }\n/** Whether a tool call is Follow-up's own, under either name set (mcp__follow-through__x, follow-through.x, mcp__paseo__follow_x, paseo.follow_x). */\nexport function isFollowTool(tool) { return /follow[\\s_-]*through/i.test(tool) || /^(?:mcp__paseo__|paseo[.:/])follow_[a-z_]+$/.test(tool); }\nconst quietRevision = 1;\nconst quietInstruction = \"Do routine bookkeeping silently. Do not announce tracker calls, say you updated/synced the sidebar, recap panel state, or add plugin-status commentary/final paragraphs. Put receipts and evidence in the tools. User-facing messages should cover the actual work outcome, or a decision/blocker requiring the developer; answer sidebar status only when explicitly asked. If this continuation is bookkeeping only, use the tools and finish without another recap or repeating your previous answer.\";\nconst stopReason = \"Silently complete this workspace's sidebar bookkeeping before finishing.\";\n// Kept identical to NEEDS_YOU_NUDGE in shared/brief.ts (a test checks it).\nconst nudgeReason = \"Before you stop, call needs_you once with what the developer has to do next: a decision with options, an action only they can take, or kind=done (\\\"Nothing needed\\\" plus what you finished), which means nothing for the developer and won't flag you. Then stop; don't repeat your reply.\";\n\n/**\n * R2: whether to nudge a Claude Code root agent that ended its turn without needs_you. Pure, so every skip is testable.\n * At most once per turn: Claude's stop_hook_active and our own per-turn `stopped` marker both end it.\n */\nexport function shouldNudge({ provider, brief, agentId, contributor, recovery, subagent, stopHookActive, turn, called }) {\n if (provider !== \"claude\" || recovery || subagent || contributor || stopHookActive) return false;\n if (!brief || brief.enable_inbox !== true || brief.enable_brief_nudge !== true) return false;\n if (Array.isArray(brief.pending) && brief.pending.includes(agentId)) return false;\n if (!turn || turn.stopped || !turn.startedAt) return false;\n return !(called && called.at >= turn.startedAt);\n}\n/**\n * The Overseer's per-turn digest (1.4.0-beta.0). The daemon rewrites overseer-digest.json only when it changes (one line and a hash\n * per workspace); this diffs it against what the Overseer saw last turn. Pure, so size and paging are testable.\n * Kept to about 3k tokens: at most 20 needs lines and 30 changes, then a pointer to the workstreams tool.\n */\nexport function overseerDigest(file, seen, now = Date.now(), { needsMax = 20, changedMax = 30, restingMax = 40, chars = 12_000 } = {}) {\n const all = Array.isArray(file?.rows) ? file.rows : [];\n const rows = all.filter(r => !r.resting);\n const resting = all.filter(r => r.resting);\n const prior = seen && typeof seen.rows === \"object\" && seen.rows ? seen.rows : null;\n const age = Math.max(0, Math.round((now - Date.parse(file?.at ?? \"\")) / 1000));\n const lines = [`Follow-up digest (last change ${Number.isFinite(age) ? `${age}s` : \"?\"} ago): ${file?.total ?? all.length} workspaces, ${file?.needs ?? 0} need Tom. Paging: workstreams(page, group, query).`];\n const needs = rows.filter(r => r.group === \"needs\");\n if (needs.length) {\n lines.push(`Needs Tom (${needs.length}):`);\n for (const r of needs.slice(0, needsMax)) lines.push(`- ${r.line}`);\n if (needs.length > needsMax) lines.push(`- …${needs.length - needsMax} more: workstreams(group=\"needs\")`);\n } else lines.push(\"Nothing needs Tom right now.\");\n if (!prior) {\n const active = rows.filter(r => r.group === \"running\" || r.group === \"fixing\");\n lines.push(`First turn. Running now (${active.length}):`);\n for (const r of active.slice(0, changedMax)) lines.push(`- ${r.line}`);\n if (active.length > changedMax) lines.push(`- …${active.length - changedMax} more: workstreams(group=\"running\")`);\n } else {\n const current = new Set(all.map(r => r.id));\n const changed = rows.filter(r => prior[r.id] !== r.hash && r.group !== \"needs\");\n const gone = Object.keys(prior).filter(id => !current.has(id));\n lines.push(changed.length || gone.length ? `Changed since your last turn (${changed.length + gone.length}):` : \"No other changes since your last turn.\");\n for (const r of changed.slice(0, changedMax)) lines.push(`- [${r.group}] ${r.line}`);\n if (changed.length > changedMax) lines.push(`- …${changed.length - changedMax} more changed: workstreams()`);\n if (gone.length) lines.push(`- ${gone.length} workspace${gone.length === 1 ? \"\" : \"s\"} archived or removed: ${gone.slice(0, 5).join(\", \")}`);\n }\n if (resting.length) lines.push(`Resting (${resting.length}; agents likely unloaded, sending wakes them): ${resting.slice(0, restingMax).map(r => r.line).join(\"; \")}${resting.length > restingMax ? `; …${resting.length - restingMax} more: workstreams()` : \"\"}`);\n let text = \"\";\n for (const l of lines) { if (text.length + l.length + 1 > chars) { text += \"- …truncated: use workstreams()\\n\"; break; } text += l + \"\\n\"; }\n return { text: text.trimEnd(), seen: { at: now, rows: Object.fromEntries(all.map(r => [r.id, r.hash])) } };\n}\nconst quote = value => \"'\" + value.replaceAll(\"'\", \"'\\\\''\") + \"'\";\nasync function json(path) { return JSON.parse(await readFile(path, \"utf8\")); }\nasync function save(path, value) {\n await mkdir(dirname(path), { recursive: true, mode: 0o700 });\n const temporary = path + \".\" + randomUUID();\n await writeFile(temporary, JSON.stringify(value), { mode: 0o600 });\n await rename(temporary, path);\n}\nfunction instructions(lease, contributor = false) {\n return named(paragraphs(lease, contributor).filter(p => !(native && /^Prefer (?:the )?native/i.test(p))).join(\"\\n\\n\"));\n}\nfunction paragraphs(lease, contributor) {\n if (contributor) return [\n \"Maintain PR tracking for this session in its tracked workspace. Read workspace_status now and after compaction. Register every PR you submit, including from secondary git worktrees, with register_pr; register parents before children. References and external dependencies are not owned PRs. Call sync_workspace before finishing. The designated main agent retains goal, task, scope and completion authority.\",\n quietInstruction,\n `Prefer native Follow-through tools. CLI fallback: FOLLOW_THROUGH_CLIENT_ENTRY=${quote(lease.clientEntry)} node ${quote(join(directory, \"mcp.mjs\"))} call <tool> '<json>' --compact. Do not ask the developer to maintain the sidebar.`,\n ];\n return [\n \"Maintain this tracked workspace's Follow-through sidebar as part of your normal work; do not wait for a developer reminder.\",\n quietInstruction,\n \"Read workspace_status now and after compaction. Refine the goal with enroll_workspace when scope changes. Register every PR you produce after submitting it, parents before children, and update stack/parent relationships after restacking. Historical mentions and external dependencies are not owned PRs; preserve exclusions and existing records.\",\n \"When a decision needs the developer, call ask_question with a short title, the question, lettered options with what each means, and your recommendation; mark it big only when building ahead would leave this computer, set something others rely on, or most remaining work depends on it. Follow the question mode in its reply. Answers arrive as messages starting \\\"Follow-up answer Q<n>\\\" and are already recorded; if the developer answers in chat, call record_answer. Withdraw questions that stop mattering.\",\n \"If you keep a Claude artifact (or doc) summarizing this workspace's goal, decisions and status, register its link once with set_spec after the first publish. Republish to the same URL; call set_spec again only if the link changes.\",\n \"Keep actual follow-through tasks current with update_obligation: production behavior checks, migrations and decisions, with concise titles, PR dependencies and evidence. Do not add merge/approval/deploy checklist tasks. Deployment-dependent work waits for verified serving revisions and existing production permissions.\",\n \"Stakeholder replies are follow-through too. When asked to update a requester, capture the original Slack threadUrl, recipient and explicit developer authorization in the task's communication field; referenced messages alone do not authorize posting. Use a concise progress task now and, when needed, a verify-and-reply task with purpose=verified after the relevant deployed PRs. Read existing thread replies and refresh evidence before posting; distinguish fixed, deployed and verified. Record the actual sent replyUrl and result before marking done. If posting is unavailable or its outcome is uncertain, keep the task blocked and check the thread before any retry; never claim a draft was sent. Auto authorizes delivery to you, not external messages. Communication-only requests do not authorize repairs, benchmarks, migrations or other production writes.\",\n \"Tasks are manual unless explicitly scheduled with trigger={event:\\\"now\\\"|\\\"merge\\\"|\\\"deploy\\\",delayDays:0}. Only set a trigger from the developer\\u2019s requested timing; never infer timing from a title or enable_follow_up alone. Merge/deploy triggers require owned afterPrs; delayDays=14 waits fourteen days after the last dependency event. Now requires no PR dependencies or delay. Deployment timing starts at the first verified fully serving observation and remains conservative when history is unknown. Preserve existing trigger fields on updates; trigger=null makes a task manual. Auto controls delivery, not timing or production permissions.\",\n \"Follow-through batches contain a batch ID and task list. Read workspace_status and refresh live conditions before acting; skip resolved tasks. Process dependent PRs bottom to top, one PR fully before the next. Use the repository's /fix-pr workflow, validate feedback, verify changes, submit through Graphite with --publish, and reply/resolve addressed threads. Follow the repository's safe reparent procedure for merged parents and preserve uncommitted work. For post-deploy tasks, verify the currently serving revision contains every dependency and record behavioral results separately. Acknowledge the header's batch ID with acknowledge_batch before finishing: completed with the result, or blocked with the reason. Verify the entire goal and post-merge work before declare_done; acknowledge a completion batch first. Merging and archiving remain the developer's actions.\",\n \"Before ending this turn, reconcile the sidebar with what you actually did and call sync_workspace with a short summary, including when no changes are needed. Acknowledge any assigned batch. When the entire goal is fulfilled, use declare_done; otherwise preserve remaining work. Do not launch recovery, start queued repairs, merge, toggle merge-when-ready, or archive as part of this bookkeeping. Auto still governs separate follow-up sends. Subagents report to the main agent instead of claiming workspace ownership.\",\n `Prefer the native follow-through MCP tools. For a full historical record, use workspace_status with detail=full. CLI compatibility fallback: FOLLOW_THROUGH_CLIENT_ENTRY=${quote(lease.clientEntry)} node ${quote(join(directory, \"mcp.mjs\"))} call <tool> '<json>' --compact. Omit --compact only when an existing script needs the full response. Never ask the developer to maintain the sidebar or run this bridge.`,\n ];\n}\n/** With native tools there's no MCP initialize reply, so the role text it carried comes from the hook instead. */\nasync function nativeExtras(brief) {\n if (!native) return [];\n const bridge = await import(pathToFileURL(join(directory, \"mcp.mjs\")).href).catch(() => null);\n if (!bridge) return [];\n return [\n brief?.enable_inbox && process.env.FOLLOW_THROUGH_BRIEF ? bridge.needsYouInstruction : null,\n process.env.FOLLOW_THROUGH_ROOT === \"1\" ? bridge.actionInstruction : null,\n process.env.FOLLOW_THROUGH_OVERSEER === \"1\" ? bridge.overseerInstruction : null,\n ].filter(Boolean).map(text => named(text));\n}\n/**\n * Claude Code keeps hook context for the whole session and re-runs SessionStart after compaction, so the same text\n * on every prompt only costs tokens (~1.3k per turn for a tracked main agent): send it once per session and again\n * only when it changes. Other providers keep the per-prompt text.\n */\nexport function shouldRepeat(provider, turn, hash) { return provider !== \"claude\" || turn?.contextHash !== hash; }\nconst digest = text => createHash(\"sha256\").update(text).digest(\"hex\").slice(0, 16);\nasync function main() {\n const agentId = process.env.PASEO_AGENT_ID;\n if (!agentId || !/^[\\w-]+$/.test(agentId) || process.env.FOLLOW_THROUGH_RECOVERY === \"1\") return;\n let input = \"\";\n for await (const chunk of process.stdin) { input += chunk; if (input.length > 2_000_000) return; }\n const event = JSON.parse(input);\n if (event.agent_id || event.hook_event_name === \"SubagentStop\") return;\n const lease = await json(join(directory, \"hooks-enabled.json\"));\n if (lease.expiresAt < Date.now() || !lease.clientEntry) return;\n // The Overseer: a fresh digest at the start of every turn; no sidebar bookkeeping and no Stop-hook nudge.\n if (process.env.FOLLOW_THROUGH_OVERSEER === \"1\") {\n if (event.hook_event_name === \"SessionStart\") {\n const extras = await nativeExtras(await json(join(directory, \"brief.json\")).catch(() => null));\n if (extras.length) process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: \"SessionStart\", additionalContext: extras.join(\"\\n\\n\") } }) + \"\\n\");\n return;\n }\n if (event.hook_event_name !== \"UserPromptSubmit\") return;\n const file = await json(join(directory, \"overseer-digest.json\")).catch(() => null);\n if (!file || file.agentId !== agentId) return;\n const seenPath = join(directory, \"hook-state\", `overseer-seen-${agentId}.json`);\n const digest = overseerDigest(file, await json(seenPath).catch(() => null));\n await save(seenPath, digest.seen);\n process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: \"UserPromptSubmit\", additionalContext: digest.text } }) + \"\\n\");\n return;\n }\n // scopes.json is a few KB; this hook runs on every tool call. Older workers don't write it: read state.json.\n const scopes = await json(join(directory, \"scopes.json\")).catch(() => null);\n let workspace = null; let contributor = false;\n if (scopes?.agents) { const entry = scopes.agents[agentId]; if (entry && entry.role !== \"recovery\") { workspace = { id: entry.workspaceId }; contributor = entry.role === \"contributor\"; } }\n else {\n const state = await json(join(directory, \"state.json\")).catch(() => ({ workspaces: [] }));\n workspace = state.workspaces.find(w => (w.mainAgentId === agentId || w.contributorAgentIds?.includes(agentId)) && w.enable_tracking && !w.archived) ?? null;\n contributor = !!workspace && workspace.mainAgentId !== agentId;\n }\n // The brief nudge applies to root agents launched with FOLLOW_THROUGH_BRIEF, tracked or not.\n const provider = process.env.FOLLOW_THROUGH_BRIEF || null;\n const brief = provider ? await json(join(directory, \"brief.json\")).catch(() => null) : null;\n if (!workspace && !(brief?.enable_inbox && brief?.enable_brief_nudge) && !(native && process.env.FOLLOW_THROUGH_ROOT === \"1\")) return;\n const context = () => instructions(lease, contributor);\n const sessionText = async () => [workspace ? context() : null, ...await nativeExtras(brief)].filter(Boolean).join(\"\\n\\n\");\n const name = event.hook_event_name;\n if (![\"SessionStart\", \"UserPromptSubmit\", \"PostToolUse\", \"Stop\"].includes(name)) return;\n const session = createHash(\"sha256\").update(String(event.session_id ?? agentId)).digest(\"hex\").slice(0, 24);\n const path = join(directory, \"hook-state\", `${agentId}-${session}.json`);\n const turn = await json(path).catch(() => null);\n const emit = text => process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: name, additionalContext: text } }) + \"\\n\");\n if (name === \"SessionStart\") {\n const text = await sessionText();\n if (text) { emit(text); await save(path, { ...turn, contextHash: digest(text) }); }\n return;\n }\n if (name === \"UserPromptSubmit\") {\n if (turn?.stopped && String(event.prompt ?? \"\").startsWith(stopReason)) return;\n const text = await sessionText(); const hash = text ? digest(text) : null;\n await save(path, { startedAt: Date.now(), dirtyAt: null, stopped: false, quietRevision, contextHash: hash });\n if (text && shouldRepeat(process.env.FOLLOW_THROUGH_PROVIDER, turn, hash)) emit(text);\n return;\n }\n if (name === \"PostToolUse\") {\n if (!workspace) return;\n const tool = String(event.tool_name ?? \"\");\n const args = JSON.stringify(event.tool_input ?? {});\n const trackedTool = isFollowTool(tool) || args.includes(join(directory, \"mcp.mjs\"));\n const dirty = !trackedTool && /(bash|shell|exec_command|write_stdin|edit|write|apply_patch|notebook)/i.test(tool);\n const upgrade = turn?.quietRevision !== quietRevision;\n if (dirty || upgrade) await save(path, { ...turn, startedAt: turn?.startedAt ?? (dirty ? Date.now() : 0), stopped: turn?.stopped ?? false, ...(dirty ? { dirtyAt: Date.now() } : {}), quietRevision });\n if (upgrade) emit(quietInstruction);\n return;\n }\n if (event.stop_hook_active || turn?.stopped || event.background_tasks?.length) return;\n let sync = false;\n if (workspace) {\n const confirmed = await json(join(directory, \"hook-state\", `sync-${agentId}.json`)).catch(() => null);\n sync = !(turn && confirmed?.workspaceId === workspace.id && confirmed.at >= Math.max(turn.startedAt, turn.dirtyAt ?? 0));\n }\n const called = await json(join(directory, \"hook-state\", `needs-you-${agentId}.json`)).catch(() => null);\n const nudge = shouldNudge({ provider, brief, agentId, contributor, recovery: false, subagent: false, stopHookActive: !!event.stop_hook_active, turn, called });\n if (!sync && !nudge) return;\n await save(path, { ...turn, startedAt: turn?.startedAt ?? Date.now(), stopped: true, ...(nudge ? { nudgedAt: Date.now() } : {}) });\n const reasons = [sync ? stopReason + \" This is metadata bookkeeping only; do not start queued repairs or recovery.\\n\\n\" + context() : null, nudge ? named(nudgeReason) : null].filter(Boolean);\n process.stdout.write(JSON.stringify({ decision: \"block\", reason: reasons.join(\"\\n\\n\") }) + \"\\n\");\n}\n// Tests import shouldNudge without running the hook.\nif (process.env.FOLLOW_THROUGH_HOOK_IMPORT !== \"1\") main().catch(() => {});\n";
|
|
2
|
+
export const hookSource = "#!/usr/bin/env node\nimport { readFile, writeFile, mkdir, rename } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { createHash, randomUUID } from \"node:crypto\";\n\nconst directory = dirname(fileURLToPath(import.meta.url));\n/** 1.4.0-beta.2: launched with Follow-up's tools served by Paseo's MCP (follow_<name>), or the follow-through bridge (<name>). Agents opened before the upgrade carry no flag and keep the bridge names. */\nlet native = process.env.FOLLOW_THROUGH_TOOLS === \"native\";\n// Tool names that read unambiguously in prose; kept identical to server/mcp.mjs's underscore names (a test checks it).\nexport const TOOL_NAMES = [\"workspace_status\", \"sync_workspace\", \"enroll_workspace\", \"register_pr\", \"exclude_stack\", \"update_obligation\", \"acknowledge_batch\", \"ask_question\", \"record_answer\", \"withdraw_question\", \"set_spec\", \"workspace_about\", \"agent_settings\", \"needs_you\", \"declare_done\", \"list_prs\", \"add_reviewers\", \"enable_merge_when_ready\", \"disable_merge_when_ready\", \"send_repairs\", \"set_auto_send\", \"clear_hold\", \"retry_batch\", \"inbox_list\", \"sign_off\", \"set_finish_flags\", \"set_priorities\", \"agent_digest\", \"route_candidates\", \"send_to_agent\", \"start_workspace\"];\nconst toolPattern = new RegExp(`(?<![\\\\w])(${TOOL_NAMES.join(\"|\")})(?![\\\\w])`, \"g\");\n/** Names Follow-up's tools the way this agent has them. */\nexport function named(text, isNative = native) { return isNative ? text.replace(toolPattern, \"follow_$1\") : text; }\n/** Whether a tool call is Follow-up's own, under either name set (mcp__follow-through__x, follow-through.x, mcp__paseo__follow_x, paseo.follow_x). */\nexport function isFollowTool(tool) { return /follow[\\s_-]*through/i.test(tool) || /^(?:mcp__paseo__|paseo[.:/])follow_[a-z_]+$/.test(tool); }\n/** Whether a shell call runs the bridge, however it names it ($FOLLOW_THROUGH_CLI, as the skill says, or the path). */\nexport function isBridgeCall(args, bridgePath) { return args.includes(bridgePath) || /\\$\\{?FOLLOW_THROUGH_CLI\\b/.test(args) || /mcp\\.mjs[\"']?\\s+call\\b/.test(args); }\n/**\n * Native tools are attached by one worker; a plugin reload or update drops them from open sessions until each reopens\n * (Paseo 0.15.2 reopens a session before that agent's next prompt). The worker records its instance and the instance\n * that attached each session's tools; a mismatch means this session's follow_ tools are gone. Pure, so it's testable.\n */\nexport function toolsDetached(isNative, current, mine) { return isNative && !!current?.instance && mine?.instance !== current.instance; }\nexport const detachedNotice = \"Follow-up was updated while this session was open, so its follow_* tools are detached and fail with \\\"Tool not found\\\" until this session reopens (Paseo reopens it before your next prompt). Until then use the bridge, which runs the same tools with their unprefixed names: node \\\"$FOLLOW_THROUGH_CLI\\\" call <tool> '<json>' --compact (for example sync_workspace or needs_you). Do not mention this to the developer.\";\nconst quietRevision = 1;\nconst quietInstruction = \"Do routine bookkeeping silently. Do not announce tracker calls, say you updated/synced the sidebar, recap panel state, or add plugin-status commentary/final paragraphs. Put receipts and evidence in the tools. User-facing messages should cover the actual work outcome, or a decision/blocker requiring the developer; answer sidebar status only when explicitly asked. If this continuation is bookkeeping only, use the tools and finish without another recap or repeating your previous answer.\";\nconst stopReason = \"Silently complete this workspace's sidebar bookkeeping before finishing.\";\n// Kept identical to NEEDS_YOU_NUDGE in shared/brief.ts (a test checks it).\nconst nudgeReason = \"Before you stop, call needs_you once with what the developer has to do next: a decision with options, an action only they can take, or kind=done (\\\"Nothing needed\\\" plus what you finished), which means nothing for the developer and won't flag you. Then stop; don't repeat your reply.\";\n\n/**\n * R2: whether to nudge a Claude Code root agent that ended its turn without needs_you. Pure, so every skip is testable.\n * At most once per turn: Claude's stop_hook_active and our own per-turn `stopped` marker both end it.\n */\nexport function shouldNudge({ provider, brief, agentId, contributor, recovery, subagent, stopHookActive, turn, called }) {\n if (provider !== \"claude\" || recovery || subagent || contributor || stopHookActive) return false;\n if (!brief || brief.enable_inbox !== true || brief.enable_brief_nudge !== true) return false;\n if (Array.isArray(brief.pending) && brief.pending.includes(agentId)) return false;\n if (!turn || turn.stopped || !turn.startedAt) return false;\n return !(called && called.at >= turn.startedAt);\n}\n/**\n * The Overseer's per-turn digest (1.4.0-beta.0). The daemon rewrites overseer-digest.json only when it changes (one line and a hash\n * per workspace); this diffs it against what the Overseer saw last turn. Pure, so size and paging are testable.\n * Kept to about 3k tokens: at most 20 needs lines and 30 changes, then a pointer to the workstreams tool.\n */\nexport function overseerDigest(file, seen, now = Date.now(), { needsMax = 20, changedMax = 30, restingMax = 40, chars = 12_000 } = {}) {\n const all = Array.isArray(file?.rows) ? file.rows : [];\n const rows = all.filter(r => !r.resting);\n const resting = all.filter(r => r.resting);\n const prior = seen && typeof seen.rows === \"object\" && seen.rows ? seen.rows : null;\n const age = Math.max(0, Math.round((now - Date.parse(file?.at ?? \"\")) / 1000));\n const lines = [`Follow-up digest (last change ${Number.isFinite(age) ? `${age}s` : \"?\"} ago): ${file?.total ?? all.length} workspaces, ${file?.needs ?? 0} need Tom. Paging: workstreams(page, group, query).`];\n const needs = rows.filter(r => r.group === \"needs\");\n if (needs.length) {\n lines.push(`Needs Tom (${needs.length}):`);\n for (const r of needs.slice(0, needsMax)) lines.push(`- ${r.line}`);\n if (needs.length > needsMax) lines.push(`- …${needs.length - needsMax} more: workstreams(group=\"needs\")`);\n } else lines.push(\"Nothing needs Tom right now.\");\n if (!prior) {\n const active = rows.filter(r => r.group === \"running\" || r.group === \"fixing\");\n lines.push(`First turn. Running now (${active.length}):`);\n for (const r of active.slice(0, changedMax)) lines.push(`- ${r.line}`);\n if (active.length > changedMax) lines.push(`- …${active.length - changedMax} more: workstreams(group=\"running\")`);\n } else {\n const current = new Set(all.map(r => r.id));\n const changed = rows.filter(r => prior[r.id] !== r.hash && r.group !== \"needs\");\n const gone = Object.keys(prior).filter(id => !current.has(id));\n lines.push(changed.length || gone.length ? `Changed since your last turn (${changed.length + gone.length}):` : \"No other changes since your last turn.\");\n for (const r of changed.slice(0, changedMax)) lines.push(`- [${r.group}] ${r.line}`);\n if (changed.length > changedMax) lines.push(`- …${changed.length - changedMax} more changed: workstreams()`);\n if (gone.length) lines.push(`- ${gone.length} workspace${gone.length === 1 ? \"\" : \"s\"} archived or removed: ${gone.slice(0, 5).join(\", \")}`);\n }\n if (resting.length) lines.push(`Resting (${resting.length}; agents likely unloaded, sending wakes them): ${resting.slice(0, restingMax).map(r => r.line).join(\"; \")}${resting.length > restingMax ? `; …${resting.length - restingMax} more: workstreams()` : \"\"}`);\n let text = \"\";\n for (const l of lines) { if (text.length + l.length + 1 > chars) { text += \"- …truncated: use workstreams()\\n\"; break; } text += l + \"\\n\"; }\n return { text: text.trimEnd(), seen: { at: now, rows: Object.fromEntries(all.map(r => [r.id, r.hash])) } };\n}\nconst quote = value => \"'\" + value.replaceAll(\"'\", \"'\\\\''\") + \"'\";\nasync function json(path) { return JSON.parse(await readFile(path, \"utf8\")); }\nasync function save(path, value) {\n await mkdir(dirname(path), { recursive: true, mode: 0o700 });\n const temporary = path + \".\" + randomUUID();\n await writeFile(temporary, JSON.stringify(value), { mode: 0o600 });\n await rename(temporary, path);\n}\nfunction instructions(lease, contributor = false) {\n return named(paragraphs(lease, contributor).filter(p => !(native && /^Prefer (?:the )?native/i.test(p))).join(\"\\n\\n\"));\n}\nfunction paragraphs(lease, contributor) {\n if (contributor) return [\n \"Maintain PR tracking for this session in its tracked workspace. Read workspace_status now and after compaction. Register every PR you submit, including from secondary git worktrees, with register_pr; register parents before children. References and external dependencies are not owned PRs. Call sync_workspace before finishing. The designated main agent retains goal, task, scope and completion authority.\",\n quietInstruction,\n `Prefer native Follow-through tools. CLI fallback: FOLLOW_THROUGH_CLIENT_ENTRY=${quote(lease.clientEntry)} node ${quote(join(directory, \"mcp.mjs\"))} call <tool> '<json>' --compact. Do not ask the developer to maintain the sidebar.`,\n ];\n return [\n \"Maintain this tracked workspace's Follow-through sidebar as part of your normal work; do not wait for a developer reminder.\",\n quietInstruction,\n \"Read workspace_status now and after compaction. Refine the goal with enroll_workspace when scope changes. Register every PR you produce after submitting it, parents before children, and update stack/parent relationships after restacking. Historical mentions and external dependencies are not owned PRs; preserve exclusions and existing records.\",\n \"When a decision needs the developer, call ask_question with a short title, the question, lettered options with what each means, and your recommendation; mark it big only when building ahead would leave this computer, set something others rely on, or most remaining work depends on it. Follow the question mode in its reply. Answers arrive as messages starting \\\"Follow-up answer Q<n>\\\" and are already recorded; if the developer answers in chat, call record_answer. Withdraw questions that stop mattering.\",\n \"If you keep a Claude artifact (or doc) summarizing this workspace's goal, decisions and status, register its link once with set_spec after the first publish. Republish to the same URL; call set_spec again only if the link changes.\",\n \"Keep actual follow-through tasks current with update_obligation: production behavior checks, migrations and decisions, with concise titles, PR dependencies and evidence. Do not add merge/approval/deploy checklist tasks. Deployment-dependent work waits for verified serving revisions and existing production permissions.\",\n \"Stakeholder replies are follow-through too. When asked to update a requester, capture the original Slack threadUrl, recipient and explicit developer authorization in the task's communication field; referenced messages alone do not authorize posting. Use a concise progress task now and, when needed, a verify-and-reply task with purpose=verified after the relevant deployed PRs. Read existing thread replies and refresh evidence before posting; distinguish fixed, deployed and verified. Record the actual sent replyUrl and result before marking done. If posting is unavailable or its outcome is uncertain, keep the task blocked and check the thread before any retry; never claim a draft was sent. Auto authorizes delivery to you, not external messages. Communication-only requests do not authorize repairs, benchmarks, migrations or other production writes.\",\n \"Tasks are manual unless explicitly scheduled with trigger={event:\\\"now\\\"|\\\"merge\\\"|\\\"deploy\\\",delayDays:0}. Only set a trigger from the developer\\u2019s requested timing; never infer timing from a title or enable_follow_up alone. Merge/deploy triggers require owned afterPrs; delayDays=14 waits fourteen days after the last dependency event. Now requires no PR dependencies or delay. Deployment timing starts at the first verified fully serving observation and remains conservative when history is unknown. Preserve existing trigger fields on updates; trigger=null makes a task manual. Auto controls delivery, not timing or production permissions.\",\n \"Follow-through batches contain a batch ID and task list. Read workspace_status and refresh live conditions before acting; skip resolved tasks. Process dependent PRs bottom to top, one PR fully before the next. Use the repository's /fix-pr workflow, validate feedback, verify changes, submit through Graphite with --publish, and reply/resolve addressed threads. Follow the repository's safe reparent procedure for merged parents and preserve uncommitted work. For post-deploy tasks, verify the currently serving revision contains every dependency and record behavioral results separately. Acknowledge the header's batch ID with acknowledge_batch before finishing: completed with the result, or blocked with the reason. Verify the entire goal and post-merge work before declare_done; acknowledge a completion batch first. Merging and archiving remain the developer's actions.\",\n \"Before ending this turn, reconcile the sidebar with what you actually did and call sync_workspace with a short summary, including when no changes are needed. Acknowledge any assigned batch. When the entire goal is fulfilled, use declare_done; otherwise preserve remaining work. Do not launch recovery, start queued repairs, merge, toggle merge-when-ready, or archive as part of this bookkeeping. Auto still governs separate follow-up sends. Subagents report to the main agent instead of claiming workspace ownership.\",\n `Prefer the native follow-through MCP tools. For a full historical record, use workspace_status with detail=full. CLI compatibility fallback: FOLLOW_THROUGH_CLIENT_ENTRY=${quote(lease.clientEntry)} node ${quote(join(directory, \"mcp.mjs\"))} call <tool> '<json>' --compact. Omit --compact only when an existing script needs the full response. Never ask the developer to maintain the sidebar or run this bridge.`,\n ];\n}\n/** With native tools there's no MCP initialize reply, so the role text it carried comes from the hook instead. */\nasync function nativeExtras(brief) {\n if (!native) return [];\n const bridge = await import(pathToFileURL(join(directory, \"mcp.mjs\")).href).catch(() => null);\n if (!bridge) return [];\n return [\n brief?.enable_inbox && process.env.FOLLOW_THROUGH_BRIEF ? bridge.needsYouInstruction : null,\n process.env.FOLLOW_THROUGH_ROOT === \"1\" ? bridge.actionInstruction : null,\n process.env.FOLLOW_THROUGH_OVERSEER === \"1\" ? bridge.overseerInstruction : null,\n ].filter(Boolean).map(text => named(text));\n}\n/**\n * Claude Code keeps hook context for the whole session and re-runs SessionStart after compaction, so the same text\n * on every prompt only costs tokens (~1.3k per turn for a tracked main agent): send it once per session and again\n * only when it changes. Other providers keep the per-prompt text.\n */\nexport function shouldRepeat(provider, turn, hash) { return provider !== \"claude\" || turn?.contextHash !== hash; }\nconst digest = text => createHash(\"sha256\").update(text).digest(\"hex\").slice(0, 16);\nasync function main() {\n const agentId = process.env.PASEO_AGENT_ID;\n if (!agentId || !/^[\\w-]+$/.test(agentId) || process.env.FOLLOW_THROUGH_RECOVERY === \"1\") return;\n let input = \"\";\n for await (const chunk of process.stdin) { input += chunk; if (input.length > 2_000_000) return; }\n const event = JSON.parse(input);\n if (event.agent_id || event.hook_event_name === \"SubagentStop\") return;\n const lease = await json(join(directory, \"hooks-enabled.json\"));\n if (lease.expiresAt < Date.now() || !lease.clientEntry) return;\n const instance = native ? await json(join(directory, \"tools-instance.json\")).catch(() => null) : null;\n const detached = toolsDetached(native, instance, native ? await json(join(directory, \"hook-state\", `native-${agentId}.json`)).catch(() => null) : null);\n // Detached: name the bridge's tools everywhere below, and include the bridge paragraph.\n if (detached) native = false;\n // The Overseer: a fresh digest at the start of every turn; no sidebar bookkeeping and no Stop-hook nudge.\n if (process.env.FOLLOW_THROUGH_OVERSEER === \"1\") {\n if (event.hook_event_name === \"SessionStart\") {\n const extras = await nativeExtras(await json(join(directory, \"brief.json\")).catch(() => null));\n if (extras.length) process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: \"SessionStart\", additionalContext: extras.join(\"\\n\\n\") } }) + \"\\n\");\n return;\n }\n if (event.hook_event_name !== \"UserPromptSubmit\") return;\n const file = await json(join(directory, \"overseer-digest.json\")).catch(() => null);\n if (!file || file.agentId !== agentId) return;\n const seenPath = join(directory, \"hook-state\", `overseer-seen-${agentId}.json`);\n const digest = overseerDigest(file, await json(seenPath).catch(() => null));\n await save(seenPath, digest.seen);\n process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: \"UserPromptSubmit\", additionalContext: digest.text } }) + \"\\n\");\n return;\n }\n // scopes.json is a few KB; this hook runs on every tool call. Older workers don't write it: read state.json.\n const scopes = await json(join(directory, \"scopes.json\")).catch(() => null);\n let workspace = null; let contributor = false;\n if (scopes?.agents) { const entry = scopes.agents[agentId]; if (entry && entry.role !== \"recovery\") { workspace = { id: entry.workspaceId }; contributor = entry.role === \"contributor\"; } }\n else {\n const state = await json(join(directory, \"state.json\")).catch(() => ({ workspaces: [] }));\n workspace = state.workspaces.find(w => (w.mainAgentId === agentId || w.contributorAgentIds?.includes(agentId)) && w.enable_tracking && !w.archived) ?? null;\n contributor = !!workspace && workspace.mainAgentId !== agentId;\n }\n // The brief nudge applies to root agents launched with FOLLOW_THROUGH_BRIEF, tracked or not.\n const provider = process.env.FOLLOW_THROUGH_BRIEF || null;\n const brief = provider ? await json(join(directory, \"brief.json\")).catch(() => null) : null;\n if (!workspace && !(brief?.enable_inbox && brief?.enable_brief_nudge) && !(native && process.env.FOLLOW_THROUGH_ROOT === \"1\")) return;\n const context = () => instructions(lease, contributor);\n const sessionText = async () => [workspace ? context() : null, ...await nativeExtras(brief)].filter(Boolean).join(\"\\n\\n\");\n const name = event.hook_event_name;\n if (![\"SessionStart\", \"UserPromptSubmit\", \"PostToolUse\", \"Stop\"].includes(name)) return;\n const session = createHash(\"sha256\").update(String(event.session_id ?? agentId)).digest(\"hex\").slice(0, 24);\n const path = join(directory, \"hook-state\", `${agentId}-${session}.json`);\n const turn = await json(path).catch(() => null);\n const emit = text => process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: name, additionalContext: text } }) + \"\\n\");\n if (name === \"SessionStart\") {\n const text = await sessionText();\n if (text) { emit(text); await save(path, { ...turn, contextHash: digest(text) }); }\n return;\n }\n if (name === \"UserPromptSubmit\") {\n if (turn?.stopped && String(event.prompt ?? \"\").startsWith(stopReason)) return;\n const text = await sessionText(); const hash = text ? digest(text) : null;\n await save(path, { startedAt: Date.now(), dirtyAt: null, lastToolAt: null, stopped: false, quietRevision, contextHash: hash, ...(turn?.detachedNotice ? { detachedNotice: turn.detachedNotice } : {}) });\n if (text && shouldRepeat(process.env.FOLLOW_THROUGH_PROVIDER, turn, hash)) emit(text);\n return;\n }\n if (name === \"PostToolUse\") {\n // Said once per session per worker: the tools stay detached until the session reopens.\n const notice = detached && turn?.detachedNotice !== instance.instance;\n if (!workspace) {\n if (notice) { await save(path, { ...turn, detachedNotice: instance.instance }); emit(detachedNotice); }\n return;\n }\n const tool = String(event.tool_name ?? \"\");\n const args = JSON.stringify(event.tool_input ?? {});\n const trackedTool = isFollowTool(tool) || isBridgeCall(args, join(directory, \"mcp.mjs\"));\n const dirty = !trackedTool && /(bash|shell|exec_command|write_stdin|edit|write|apply_patch|notebook)/i.test(tool);\n const upgrade = turn?.quietRevision !== quietRevision;\n // A dirty call is dated from when it could have started (the previous tool's end), not when it ended: a call that\n // itself confirms sync, through any bridge spelling, then still satisfies the Stop check, which reads the\n // sync record the RPC handler wrote rather than tool names.\n const now = Date.now();\n const callStart = turn?.lastToolAt || turn?.startedAt || now;\n await save(path, { ...turn, startedAt: turn?.startedAt ?? (dirty ? callStart : 0), stopped: turn?.stopped ?? false, ...(dirty ? { dirtyAt: callStart } : {}), quietRevision, lastToolAt: now, ...(notice ? { detachedNotice: instance.instance } : {}) });\n const text = [upgrade ? quietInstruction : null, notice ? detachedNotice : null].filter(Boolean).join(\"\\n\\n\");\n if (text) emit(text);\n return;\n }\n if (event.stop_hook_active || turn?.stopped || event.background_tasks?.length) return;\n let sync = false;\n if (workspace) {\n const confirmed = await json(join(directory, \"hook-state\", `sync-${agentId}.json`)).catch(() => null);\n sync = !(turn && confirmed?.workspaceId === workspace.id && confirmed.at >= Math.max(turn.startedAt, turn.dirtyAt ?? 0));\n }\n const called = await json(join(directory, \"hook-state\", `needs-you-${agentId}.json`)).catch(() => null);\n const nudge = shouldNudge({ provider, brief, agentId, contributor, recovery: false, subagent: false, stopHookActive: !!event.stop_hook_active, turn, called });\n if (!sync && !nudge) return;\n await save(path, { ...turn, startedAt: turn?.startedAt ?? Date.now(), stopped: true, ...(nudge ? { nudgedAt: Date.now() } : {}) });\n const reasons = [detached ? detachedNotice : null, sync ? stopReason + \" This is metadata bookkeeping only; do not start queued repairs or recovery.\\n\\n\" + context() : null, nudge ? named(nudgeReason) : null].filter(Boolean);\n process.stdout.write(JSON.stringify({ decision: \"block\", reason: reasons.join(\"\\n\\n\") }) + \"\\n\");\n}\n// Tests import shouldNudge without running the hook.\nif (process.env.FOLLOW_THROUGH_HOOK_IMPORT !== \"1\") main().catch(() => {});\n";
|