paseo-follow-up 1.4.0-beta.35 → 1.4.0-beta.39

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
@@ -238,7 +238,7 @@ This replaces the separate **Wait** plugin (`paseo-wait`). While that plugin is
238
238
  Install the beta:
239
239
 
240
240
  ```sh
241
- paseo plugin update follow-through --version 1.4.0-beta.35
241
+ paseo plugin update follow-through --version 1.4.0-beta.39
242
242
  # or, for a fresh install:
243
243
  paseo plugin install npm:paseo-follow-up@beta
244
244
  ```
package/index.server.ts CHANGED
@@ -4,13 +4,14 @@ import { askQuestion, needsYouQuestions, recordAnswer, syncTaskQuestions, withdr
4
4
  import { agentSetSpec, developerSetSpec } from "./server/spec";
5
5
  import type { PluginServerContext, PluginHandlerContext, PluginHookContext, PluginSessionOpenRequest } from "@getpaseo/plugin/server";
6
6
  import { mkdir, writeFile } from "node:fs/promises";
7
- import { existsSync, mkdirSync, renameSync, writeFileSync } from "node:fs";
7
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
8
8
  import { join } from "node:path";
9
9
  import { randomUUID } from "node:crypto";
10
10
  import * as rpc from "./shared/contracts";
11
11
  import { browserRepositories, browserWorkspaces, prClaims, prOwner } from "./server/pr-owner";
12
12
  import { type Workspace } from "./shared/model";
13
13
  import { isWorkspaceRoot } from "./server/workspace-agent";
14
+ import { BackgroundAgents, backgroundAgentsFile } from "./server/background-agents";
14
15
  import { Store } from "./server/store";
15
16
  import { PriorityStore } from "./server/priorities";
16
17
  import { UsageReader } from "./server/usage";
@@ -1057,7 +1058,14 @@ export default function contribute(server: PluginServerContext) {
1057
1058
  handle(rpc.onboardingChecksRpc, async ({ fresh }, { paseo }) => { await requireReady(); seen(paseo); return readiness.run(!!fresh); });
1058
1059
 
1059
1060
  type SessionOpen = (input: { request: PluginSessionOpenRequest }, context: PluginHookContext) => Promise<PluginSessionOpenRequest | void>;
1060
- const withWait = (handler: SessionOpen): SessionOpen => async (input, context) => wait.open((await handler(input, context)) ?? input.request);
1061
+ // Paseo 0.16 background agents (another plugin's helpers) get no root treatment: no tools, no Wait, no needs_you or
1062
+ // Stop-hook nudge. The flag is only in the agent snapshot, so session open reads it once per agent.
1063
+ let saveBackground: () => Promise<void> = async () => {};
1064
+ const background = new BackgroundAgents(() => saveBackground());
1065
+ saveBackground = backgroundAgentsFile(directory, () => background.ids);
1066
+ try { background.seed(JSON.parse(readFileSync(join(directory, "background-agents.json"), "utf8"))?.agents); } catch { /* none yet */ }
1067
+ const isBackground = (agentId: string, paseo: PluginHandlerContext["paseo"]) => background.check(agentId, async id => (await paseo.agents.ref(id).refresh())?.agent as { background?: unknown } | undefined);
1068
+ const withWait = (handler: SessionOpen): SessionOpen => async (input, context) => wait.open((await handler(input, context)) ?? input.request, { background: await isBackground(input.request.agentId, context.paseo) });
1061
1069
  const removers = [
1062
1070
  server.on("agent.permission_requested", async (event, { paseo }) => { trustApi = paseo; await trust.handle(event.agent, event.request as never).catch(() => undefined); }),
1063
1071
  displaySettings.subscribe(() => void writeBriefState().catch(() => undefined)),
@@ -1069,7 +1077,8 @@ export default function contribute(server: PluginServerContext) {
1069
1077
  server.on("agent.permission_resolved", async event => gateway.directory.permissionResolved(event.agent.id, event.requestId)),
1070
1078
  server.on("agent.archived", async event => gateway.directory.agentArchived(event.agent.id, event.archivedAt)),
1071
1079
  server.on("agent.closed", async event => gateway.directory.agentClosed(event.agent.id)),
1072
- server.on("agent.created", async event => { await ready; await gateway.directory.agentCreated(event.agent); }),
1080
+ // 0.16: the background flag first shows up here (it isn't in session_open yet), so the hook learns it now.
1081
+ server.on("agent.created", async (event, { paseo }) => { await ready; await isBackground(event.agent.id, paseo); await gateway.directory.agentCreated(event.agent); }),
1073
1082
  server.on("workspace.created", async event => gateway.directory.workspaceCreated(event.workspace)),
1074
1083
  server.on("workspace.archived", async event => gateway.directory.workspaceArchived(event.workspace.id)),
1075
1084
  server.on("agent.turn_started", async () => updater.activity()),
@@ -1103,6 +1112,7 @@ export default function contribute(server: PluginServerContext) {
1103
1112
  server.before("agent.session_open", withWait(async ({ request }, { paseo }) => {
1104
1113
  await ready;
1105
1114
  if (loadError || stopped || request.purpose !== "interactive") return request;
1115
+ if (await isBackground(request.agentId, paseo)) return request;
1106
1116
  // The Overseer: needs_you (no Stop-hook nudge), the action tools and its routing tools. Never tracked.
1107
1117
  if (request.labels[OVERSEER_LABEL] === "1" && ["claude", "codex"].includes(request.provider)) {
1108
1118
  const env = { ...request.env, FOLLOW_THROUGH_OVERSEER: "1", FOLLOW_THROUGH_BRIEF: request.provider };
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.35",
4
+ "version": "1.4.0-beta.39",
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": [
@@ -163,6 +163,10 @@ async function main() {
163
163
  if (event.agent_id || event.hook_event_name === "SubagentStop") return;
164
164
  const lease = await json(join(directory, "hooks-enabled.json"));
165
165
  if (lease.expiresAt < Date.now() || !lease.clientEntry) return;
166
+ // A Paseo 0.16 background agent (another plugin's helper) gets nothing from Follow-up: no context, no Stop-hook
167
+ // nudge. The worker lists them as it learns of them (server/background-agents.ts); Paseo doesn't say so at launch.
168
+ const background = await json(join(directory, "background-agents.json")).catch(() => null);
169
+ if (Array.isArray(background?.agents) && background.agents.includes(agentId)) return;
166
170
  const instance = native ? await json(join(directory, "tools-instance.json")).catch(() => null) : null;
167
171
  const detached = toolsDetached(native, instance, native ? await json(join(directory, "hook-state", `native-${agentId}.json`)).catch(() => null) : null);
168
172
  // Detached: name the bridge's tools everywhere below, and include the bridge paragraph.
@@ -0,0 +1,49 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { rename, writeFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+
5
+ /**
6
+ * Paseo 0.16 background agents (`background: true` at creation): helpers another plugin runs for itself, with no
7
+ * tab, no notifications and no sidebar row. Follow-up gives them no root-agent treatment: no action tools, no Wait,
8
+ * no needs_you or Stop-hook nudge, no inbox rows and no directory row. Paseo sends the flag only in the agent
9
+ * snapshot (fetch_agent / agents.ref(id).refresh()), not in lifecycle events or session_open, so callers read it from
10
+ * a snapshot they already have or from one refresh. On Paseo 0.15 the field is absent and nothing changes.
11
+ */
12
+ export const isBackgroundAgent = (agent: { background?: unknown } | null | undefined): boolean => agent?.background === true;
13
+
14
+ /**
15
+ * Whether an agent is a background agent. Only "yes" is remembered (the flag is fixed when the agent is created):
16
+ * on Paseo 0.16 a brand-new agent's snapshot doesn't exist yet at session_open, so an early "no" must not stick.
17
+ * `onFound` hears each agent the first time it turns out to be a background agent.
18
+ */
19
+ export class BackgroundAgents {
20
+ private known = new Set<string>();
21
+ constructor(private onFound: (agentId: string) => void | Promise<void> = () => {}, private limit = 2000) {}
22
+ async check(agentId: string, refresh: (id: string) => Promise<{ background?: unknown } | null | undefined>): Promise<boolean> {
23
+ if (this.known.has(agentId)) return true;
24
+ let snapshot;
25
+ // Unknown is not background: a failed read keeps today's behaviour and is asked again next time.
26
+ try { snapshot = await refresh(agentId); } catch { return false; }
27
+ if (!isBackgroundAgent(snapshot)) return false;
28
+ if (this.known.size >= this.limit) this.known.delete(this.known.values().next().value!);
29
+ this.known.add(agentId);
30
+ await this.onFound(agentId);
31
+ return true;
32
+ }
33
+ get ids() { return [...this.known]; }
34
+ /** Agents found before a restart (background-agents.json), so the hook keeps skipping them. */
35
+ seed(ids: unknown) { if (Array.isArray(ids)) for (const id of ids.slice(-this.limit)) if (typeof id === "string") this.known.add(id); }
36
+ }
37
+
38
+ /** background-agents.json, which the agent hook reads so a helper's turns get no context and no Stop-hook nudge. */
39
+ export function backgroundAgentsFile(directory: string, agents: () => string[]) {
40
+ let writing = Promise.resolve();
41
+ return () => {
42
+ writing = writing.then(async () => {
43
+ const temporary = join(directory, `background-agents.${randomUUID()}.tmp`);
44
+ await writeFile(temporary, JSON.stringify({ version: 1, agents: agents() }), { mode: 0o600 });
45
+ await rename(temporary, join(directory, "background-agents.json"));
46
+ }).catch(() => undefined);
47
+ return writing;
48
+ };
49
+ }
package/server/daemon.ts CHANGED
@@ -24,7 +24,7 @@ import { DaemonDirectory, type DirectoryRows } from "./directory";
24
24
  type RecoveryAgentOptions = Partial<PluginBeforeRequests["agent.create"]["config"]> & { workspaceId: string; labels: Record<string, string>; idempotencyKey: string; env: Record<string, string> };
25
25
 
26
26
  export const paseoHome = process.env.PASEO_HOME ?? join(homedir(), ".paseo");
27
- export type Agent = { id: string; provider: string; cwd: string; model?: string | null; currentModeId?: string | null; runtimeInfo?: { modeId?: string | null } | null; thinkingOptionId?: string | null; features?: { id: string; value: unknown }[]; persistence?: { sessionId: string; nativeHandle?: string } | null; title?: string | null; createdAt: string; workspaceId?: string; status: string; archivedAt?: string | null; labels: Record<string, string>; lastUserMessageAt: string | null; pendingPermissions: unknown[]; activeTurn?: unknown; lastError?: string | null };
27
+ export type Agent = { id: string; provider: string; cwd: string; model?: string | null; currentModeId?: string | null; runtimeInfo?: { modeId?: string | null } | null; thinkingOptionId?: string | null; features?: { id: string; value: unknown }[]; persistence?: { sessionId: string; nativeHandle?: string } | null; title?: string | null; createdAt: string; workspaceId?: string; status: string; archivedAt?: string | null; labels: Record<string, string>; lastUserMessageAt: string | null; pendingPermissions: unknown[]; activeTurn?: unknown; lastError?: string | null; /** Paseo 0.16 background agent; absent on 0.15. */ background?: boolean };
28
28
  type WorkspaceRow = { id: string; name: string; projectId?: string | null; labels?: string[]; archivingAt?: string | null };
29
29
  export interface Daemon {
30
30
  connect(): Promise<void>; close(): Promise<void>;
@@ -1,5 +1,6 @@
1
1
  import type { Project } from "../shared/settings";
2
2
  import { pages, withDaemon, type Agent, type Daemon } from "./daemon";
3
+ import { isBackgroundAgent } from "./background-agents";
3
4
  import { isLoaded } from "./agent-load";
4
5
 
5
6
  /** A row of Paseo's workspace list. fetch_workspaces carries more (git and GitHub runtime) for the Overseer. */
@@ -104,6 +105,8 @@ export class DaemonDirectory {
104
105
  async live(client: Daemon, id: string): Promise<Agent | null> {
105
106
  this.count("fetch_agent_request");
106
107
  const agent = (await client.fetchAgent(id))?.agent ?? null;
108
+ // Paseo's own lists leave background agents out, so a row for one would only flicker until the next re-read.
109
+ if (agent && isBackgroundAgent(agent)) { if (this.rows) this.rows.agents = this.rows.agents.filter(row => row.agent.id !== id); return agent; }
107
110
  if (agent && this.rows) {
108
111
  const i = this.rows.agents.findIndex(row => row.agent.id === id);
109
112
  if (i >= 0) this.rows.agents[i] = { agent }; else this.rows.agents.push({ agent });
@@ -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. */\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\", \"display_settings\", \"set_display\", \"follow_settings\", \"set_follow_settings\", \"project_settings\", \"set_project_tracking\", \"pr_workflow\", \"set_pr_workflow\", \"reviewer_settings\", \"reviewer_suggestions\", \"save_reviewers\", \"set_agent_setting\", \"set_wait_for_jobs\", \"onboarding_status\", \"onboarding_checks\", \"set_onboarding\", \"rank_status\", \"rerank_priorities\", \"overseer_status\", \"overseer_start\", \"overseer_restart\", \"overseer_ask\", \"inbox_brief\", \"brief_action\", \"inbox_act\", \"answer_question\", \"run_recovery\", \"set_workspace_spec\", \"set_task_trigger\", \"pr_controls\", \"browser_status\", \"trust_bypass_status\", \"release_notes\", \"updates_status\", \"check_updates\", \"set_updates\", \"install_update\", \"make_main_agent\"];\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 (or questions=[\\\"Q18\\\"] for one that is already an open question), 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}\n/**\n * How batches are worked, for this workspace's PR workflow (from scopes.json). Graphite with /fix-pr, and agents of an\n * older worker that wrote no workflow, keep the original text; plain GitHub never mentions Graphite, gt or /fix-pr.\n */\nexport function batchParagraph(workflow) {\n const mode = workflow?.mode ?? \"graphite\";\n const fix = workflow === undefined || workflow === null ? \"/fix-pr\" : workflow.reviewFix ?? null;\n const steps = \"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.\";\n const review = fix ? `Use the repository's ${fix} workflow, validate feedback, verify changes,` : \"For review comments, read the PR's unresolved threads with gh, validate the feedback, fix it and verify the change,\";\n const submit = mode === \"graphite\" ? \"submit through Graphite with --publish\" : \"push the branch (gh pr create for a new PR, gh pr ready when it leaves draft)\";\n const reply = fix ? \"reply/resolve addressed threads\" : \"reply to each addressed thread and resolve it\";\n const restack = mode === \"graphite\" ? \"Follow the repository's safe reparent procedure for merged parents\" : \"Keep stacked PRs as a chain of base branches: restack with git rebase --update-refs and push with --force-with-lease, and when a parent merges retarget its child with gh pr edit --base if GitHub didn't already\";\n return `${steps} ${review} ${submit}, and ${reply}. ${restack} and preserve uncommitted work.`;\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, workflow) {\n return named(paragraphs(lease, contributor, workflow).filter(p => !(native && /^Prefer (?:the )?native/i.test(p))).join(\"\\n\\n\"));\n}\nfunction paragraphs(lease, contributor, workflow) {\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. Ask each decision once: asking it again returns the open question, and at a turn's end you point at it (needs_you questions=[\\\"Q<n>\\\"]) instead of restating it. Answers arrive as messages starting \\\"Follow-up answer Q<n>\\\" and are already recorded; several decisions from one card arrive together in one message, one line per decision, with skipped ones marked \\\"skipped\\\" and still open; 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 batchParagraph(workflow) + \" 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/** The old main's notice, within a day of losing the role: who took over, why, and what to do. Null otherwise. */\nexport function demotedNotice(demoted, now = Date.now()) {\n if (!demoted?.at || now - Date.parse(demoted.at) > 24 * 60 * 60_000) return null;\n const time = new Date(demoted.at).toISOString().slice(11, 16);\n const who = demoted.by === \"developer\" ? \"the developer moved it\" : demoted.by === \"auto\" ? \"Follow-up moved it\" : \"it was claimed\";\n return { at: demoted.at, text: `You're no longer this workspace's main agent: ${demoted.to} took over at ${time} UTC (${who}${demoted.reason ? `: ${demoted.reason}` : \"\"}). Report to it instead of asking the developer or calling Done. If that's wrong, ask the developer to make you main again; you can't take it back on your own for 2 hours.` };\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/** Wait's guidance (server/wait.ts attaches its tools natively, so there is no MCP initialize text to carry it). */\nasync function waitExtras() {\n if (process.env.FOLLOW_THROUGH_WAIT !== \"1\") return [];\n const bridge = await import(pathToFileURL(join(directory, \"mcp.mjs\")).href).catch(() => null);\n return bridge?.waitInstruction ? [bridge.waitInstruction] : [];\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)), ...await waitExtras()];\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; let workflow; let demoted = null;\n if (scopes?.agents) { const entry = scopes.agents[agentId]; if (entry && entry.role !== \"recovery\") { workspace = { id: entry.workspaceId }; contributor = entry.role === \"contributor\"; workflow = entry.workflow; demoted = contributor ? demotedNotice(entry.demoted) : null; } }\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\")) {\n // Every other Claude session with Wait (subagents, untracked agents) still gets Wait's guidance, once per session.\n if (event.hook_event_name === \"SessionStart\") { const extras = await waitExtras(); if (extras.length) process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: \"SessionStart\", additionalContext: extras.join(\"\\n\\n\") } }) + \"\\n\"); }\n return;\n }\n const context = () => instructions(lease, contributor, workflow);\n const sessionText = async () => [workspace ? context() : null, ...await nativeExtras(brief), ...await waitExtras()].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 // Lost the main role (make_main_agent, Make main agent, or a handover): said once, on the next turn.\n const tellDemoted = demoted && turn?.demotedNotice !== demoted.at;\n await save(path, { startedAt: Date.now(), dirtyAt: null, lastToolAt: null, stopped: false, quietRevision, contextHash: hash, ...(turn?.detachedNotice ? { detachedNotice: turn.detachedNotice } : {}), ...(tellDemoted || turn?.demotedNotice ? { demotedNotice: tellDemoted ? demoted.at : turn.demotedNotice } : {}) });\n const out = [text && shouldRepeat(process.env.FOLLOW_THROUGH_PROVIDER, turn, hash) ? text : null, tellDemoted ? demoted.text : null].filter(Boolean);\n if (out.length) emit(out.join(\"\\n\\n\"));\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";
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\", \"display_settings\", \"set_display\", \"follow_settings\", \"set_follow_settings\", \"project_settings\", \"set_project_tracking\", \"pr_workflow\", \"set_pr_workflow\", \"reviewer_settings\", \"reviewer_suggestions\", \"save_reviewers\", \"set_agent_setting\", \"set_wait_for_jobs\", \"onboarding_status\", \"onboarding_checks\", \"set_onboarding\", \"rank_status\", \"rerank_priorities\", \"overseer_status\", \"overseer_start\", \"overseer_restart\", \"overseer_ask\", \"inbox_brief\", \"brief_action\", \"inbox_act\", \"answer_question\", \"run_recovery\", \"set_workspace_spec\", \"set_task_trigger\", \"pr_controls\", \"browser_status\", \"trust_bypass_status\", \"release_notes\", \"updates_status\", \"check_updates\", \"set_updates\", \"install_update\", \"make_main_agent\"];\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 (or questions=[\\\"Q18\\\"] for one that is already an open question), 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}\n/**\n * How batches are worked, for this workspace's PR workflow (from scopes.json). Graphite with /fix-pr, and agents of an\n * older worker that wrote no workflow, keep the original text; plain GitHub never mentions Graphite, gt or /fix-pr.\n */\nexport function batchParagraph(workflow) {\n const mode = workflow?.mode ?? \"graphite\";\n const fix = workflow === undefined || workflow === null ? \"/fix-pr\" : workflow.reviewFix ?? null;\n const steps = \"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.\";\n const review = fix ? `Use the repository's ${fix} workflow, validate feedback, verify changes,` : \"For review comments, read the PR's unresolved threads with gh, validate the feedback, fix it and verify the change,\";\n const submit = mode === \"graphite\" ? \"submit through Graphite with --publish\" : \"push the branch (gh pr create for a new PR, gh pr ready when it leaves draft)\";\n const reply = fix ? \"reply/resolve addressed threads\" : \"reply to each addressed thread and resolve it\";\n const restack = mode === \"graphite\" ? \"Follow the repository's safe reparent procedure for merged parents\" : \"Keep stacked PRs as a chain of base branches: restack with git rebase --update-refs and push with --force-with-lease, and when a parent merges retarget its child with gh pr edit --base if GitHub didn't already\";\n return `${steps} ${review} ${submit}, and ${reply}. ${restack} and preserve uncommitted work.`;\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, workflow) {\n return named(paragraphs(lease, contributor, workflow).filter(p => !(native && /^Prefer (?:the )?native/i.test(p))).join(\"\\n\\n\"));\n}\nfunction paragraphs(lease, contributor, workflow) {\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. Ask each decision once: asking it again returns the open question, and at a turn's end you point at it (needs_you questions=[\\\"Q<n>\\\"]) instead of restating it. Answers arrive as messages starting \\\"Follow-up answer Q<n>\\\" and are already recorded; several decisions from one card arrive together in one message, one line per decision, with skipped ones marked \\\"skipped\\\" and still open; 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 batchParagraph(workflow) + \" 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/** The old main's notice, within a day of losing the role: who took over, why, and what to do. Null otherwise. */\nexport function demotedNotice(demoted, now = Date.now()) {\n if (!demoted?.at || now - Date.parse(demoted.at) > 24 * 60 * 60_000) return null;\n const time = new Date(demoted.at).toISOString().slice(11, 16);\n const who = demoted.by === \"developer\" ? \"the developer moved it\" : demoted.by === \"auto\" ? \"Follow-up moved it\" : \"it was claimed\";\n return { at: demoted.at, text: `You're no longer this workspace's main agent: ${demoted.to} took over at ${time} UTC (${who}${demoted.reason ? `: ${demoted.reason}` : \"\"}). Report to it instead of asking the developer or calling Done. If that's wrong, ask the developer to make you main again; you can't take it back on your own for 2 hours.` };\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/** Wait's guidance (server/wait.ts attaches its tools natively, so there is no MCP initialize text to carry it). */\nasync function waitExtras() {\n if (process.env.FOLLOW_THROUGH_WAIT !== \"1\") return [];\n const bridge = await import(pathToFileURL(join(directory, \"mcp.mjs\")).href).catch(() => null);\n return bridge?.waitInstruction ? [bridge.waitInstruction] : [];\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 // A Paseo 0.16 background agent (another plugin's helper) gets nothing from Follow-up: no context, no Stop-hook\n // nudge. The worker lists them as it learns of them (server/background-agents.ts); Paseo doesn't say so at launch.\n const background = await json(join(directory, \"background-agents.json\")).catch(() => null);\n if (Array.isArray(background?.agents) && background.agents.includes(agentId)) 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)), ...await waitExtras()];\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; let workflow; let demoted = null;\n if (scopes?.agents) { const entry = scopes.agents[agentId]; if (entry && entry.role !== \"recovery\") { workspace = { id: entry.workspaceId }; contributor = entry.role === \"contributor\"; workflow = entry.workflow; demoted = contributor ? demotedNotice(entry.demoted) : null; } }\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\")) {\n // Every other Claude session with Wait (subagents, untracked agents) still gets Wait's guidance, once per session.\n if (event.hook_event_name === \"SessionStart\") { const extras = await waitExtras(); if (extras.length) process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: \"SessionStart\", additionalContext: extras.join(\"\\n\\n\") } }) + \"\\n\"); }\n return;\n }\n const context = () => instructions(lease, contributor, workflow);\n const sessionText = async () => [workspace ? context() : null, ...await nativeExtras(brief), ...await waitExtras()].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 // Lost the main role (make_main_agent, Make main agent, or a handover): said once, on the next turn.\n const tellDemoted = demoted && turn?.demotedNotice !== demoted.at;\n await save(path, { startedAt: Date.now(), dirtyAt: null, lastToolAt: null, stopped: false, quietRevision, contextHash: hash, ...(turn?.detachedNotice ? { detachedNotice: turn.detachedNotice } : {}), ...(tellDemoted || turn?.demotedNotice ? { demotedNotice: tellDemoted ? demoted.at : turn.demotedNotice } : {}) });\n const out = [text && shouldRepeat(process.env.FOLLOW_THROUGH_PROVIDER, turn, hash) ? text : null, tellDemoted ? demoted.text : null].filter(Boolean);\n if (out.length) emit(out.join(\"\\n\\n\"));\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";
@@ -9,7 +9,7 @@ const info = (a: Snapshot): AgentInfo => ({
9
9
  id: a.id, workspaceId: a.workspaceId ?? null, parentAgentId: a.parentAgentId ?? a.labels?.["paseo.parent-agent-id"] ?? null,
10
10
  title: a.title ?? null, status: a.status, archivedAt: a.archivedAt ?? null, updatedAt: a.updatedAt ?? null,
11
11
  lastUserMessageAt: a.lastUserMessageAt ?? null, requiresAttention: !!a.requiresAttention, attentionReason: a.attentionReason ?? null,
12
- attentionTimestamp: a.attentionTimestamp ?? null, createdAt: a.createdAt ?? null,
12
+ attentionTimestamp: a.attentionTimestamp ?? null, createdAt: a.createdAt ?? null, ...(a.background === true ? { background: true } : {}),
13
13
  pendingPermissionIds: Array.isArray(a.pendingPermissions) ? a.pendingPermissions.flatMap(p => typeof (p as { id?: unknown })?.id === "string" ? [(p as { id: string }).id] : []) : null,
14
14
  });
15
15
 
package/server/inbox.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { mkdir, open, readFile, rename, unlink } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import { randomUUID } from "node:crypto";
4
+ import { BackgroundAgents } from "./background-agents";
4
5
  import { emptyInbox, expired, inboxStateSchema, newEntry, reduce, StaleSignOff, type Entry, type InboxEvent, type InboxRow, type InboxState, type Reason } from "../shared/inbox";
5
6
  import type { State as FollowState, Workspace as FollowWorkspace } from "../shared/model";
6
7
  import { prActionBlocks } from "../shared/pr-actions";
@@ -59,6 +60,8 @@ export type AgentInfo = {
59
60
  requiresAttention: boolean; attentionReason: string | null;
60
61
  /** When Paseo marked the agent as needing attention (a turn finished unread). Optional for older hosts and stubs. */
61
62
  attentionTimestamp?: string | null; createdAt?: string | null;
63
+ /** Paseo 0.16 background agent (a plugin's helper): its turns never raise rows. Absent on 0.15. */
64
+ background?: boolean;
62
65
  /** Ids of the permission prompts Paseo shows for this agent right now. Absent or null: unknown, so nothing is cleared. */
63
66
  pendingPermissionIds?: string[] | null;
64
67
  };
@@ -256,9 +259,14 @@ export class Inbox {
256
259
  return { rootId: current.id, subagent, delegated: false };
257
260
  }
258
261
 
262
+ /** Paseo 0.16 background agents are another plugin's helpers: their turns never raise rows (background-agents.ts). */
263
+ private backgroundAgents = new BackgroundAgents();
264
+ private background(id: string) { return this.backgroundAgents.check(id, agentId => this.o.directory.agent(agentId)); }
265
+
259
266
  async turnStarted(agent: { id: string; workspaceId: string | null; parentAgentId?: string | null }, turnId?: string | null): Promise<void> {
267
+ if (!await this.on()) { this.live.add(agent.id); return; }
268
+ if (await this.background(agent.id)) return;
260
269
  this.live.add(agent.id);
261
- if (!await this.on()) return;
262
270
  const root = await this.root(agent);
263
271
  if (root.subagent) return;
264
272
  const at = this.now();
@@ -275,6 +283,7 @@ export class Inbox {
275
283
  async turnEnded(agent: { id: string; workspaceId: string | null; parentAgentId?: string | null }, outcome: { kind: "completed" } | { kind: "failed"; error: { message: string } } | { kind: "canceled"; reason: string }, turnId: string | null): Promise<void> {
276
284
  this.live.delete(agent.id);
277
285
  if (!await this.on()) return;
286
+ if (await this.background(agent.id)) return;
278
287
  const root = await this.root(agent);
279
288
  if (root.subagent) {
280
289
  // Subagent finishes are covered by the parent's own turn end; failures surface on the parent's brief.
@@ -18,15 +18,24 @@ import { runnerSource } from "./wait-runner-source";
18
18
  */
19
19
  export const DEFAULT_WAIT_SECONDS = 30;
20
20
  export const HARD_MAX_WAIT_SECONDS = 60;
21
+ /** A prepared job's time limit: 3 h unless the agent asks for another, at most 12 h. The runner stops it after that. */
22
+ export const DEFAULT_JOB_TIMEOUT_SECONDS = 3 * 3600;
23
+ export const MAX_JOB_TIMEOUT_SECONDS = 12 * 3600;
24
+ export const prepareInput = z.object({
25
+ description: z.string().min(1).max(240),
26
+ command: z.string().min(1).max(32000),
27
+ timeoutSeconds: z.number().int().min(1).max(MAX_JOB_TIMEOUT_SECONDS).optional(),
28
+ }).strict();
21
29
  export const waitInput = z.object({
22
30
  jobId: z.string().uuid(),
23
31
  max_wait_seconds: z.number().int().min(1).max(HARD_MAX_WAIT_SECONDS).default(DEFAULT_WAIT_SECONDS),
24
32
  }).strict();
25
33
  const metadataSchema = z.object({ version: z.literal(1), id: z.string().uuid(), agentId: z.string(), cwd: z.string(), description: z.string(), createdAt: z.string() }).strict();
26
- const resultSchema = z.object({ exitCode: z.number().int().min(0).max(255) }).strict();
34
+ const resultSchema = z.object({ exitCode: z.number().int().min(0).max(255), timedOut: z.literal(true).optional() }).strict();
27
35
 
28
36
  export interface Owner { id: string; cwd: string }
29
- export interface JobStatus { jobId: string; status: "prepared" | "running" | "completed" | "failed"; description: string; createdAt: string; exitCode?: number }
37
+ /** `timedOut`: the runner stopped the command at its time limit (exit 124). */
38
+ export interface JobStatus { jobId: string; status: "prepared" | "running" | "completed" | "failed"; description: string; createdAt: string; exitCode?: number; timedOut?: true }
30
39
  export type WaitResult = JobStatus & { outcome: "completed" | "failed" | "still_pending" | "new_message"; waitedSeconds: number; instruction: string };
31
40
 
32
41
  const quote = (value: string) => "'" + value.replaceAll("'", "'\\''") + "'";
@@ -50,7 +59,8 @@ export class WaitJobs {
50
59
  }
51
60
 
52
61
  /** Writes the job record and returns the exact command to run. Runs nothing. */
53
- async prepare(owner: Owner, input: { description: string; command: string }) {
62
+ async prepare(owner: Owner, raw: z.input<typeof prepareInput>) {
63
+ const input = prepareInput.parse(raw);
54
64
  if (this.closed) throw new Error("Wait tools are stopping");
55
65
  const id = randomUUID();
56
66
  const path = this.path(owner, id);
@@ -61,6 +71,8 @@ export class WaitJobs {
61
71
  await rename(temporary, runner);
62
72
  const record = { version: 1, id, agentId: owner.id, cwd: owner.cwd, description: input.description, createdAt: new Date().toISOString() };
63
73
  await writeFile(join(path, "job.json"), JSON.stringify(record), { mode: 0o600, flag: "wx" });
74
+ const limit = input.timeoutSeconds ?? DEFAULT_JOB_TIMEOUT_SECONDS;
75
+ await writeFile(join(path, "timeout"), String(limit), { mode: 0o600, flag: "wx" });
64
76
  return {
65
77
  jobId: id,
66
78
  bashCommand: ["sh", runner, path, owner.cwd, input.command].map(quote).join(" "),
@@ -76,8 +88,8 @@ export class WaitJobs {
76
88
  if (record.agentId !== owner.id || record.id !== jobId || record.cwd !== owner.cwd) throw new Error("Job ownership does not match this agent and working directory");
77
89
  const base = { jobId, description: record.description, createdAt: record.createdAt };
78
90
  try {
79
- const { exitCode } = resultSchema.parse(await jsonFile(join(path, "result.json")));
80
- return { ...base, status: exitCode === 0 ? "completed" : "failed", exitCode };
91
+ const { exitCode, timedOut } = resultSchema.parse(await jsonFile(join(path, "result.json")));
92
+ return { ...base, status: exitCode === 0 ? "completed" : "failed", exitCode, ...(timedOut ? { timedOut } : {}) };
81
93
  } catch (error) { if (!missing(error)) throw error; }
82
94
  try {
83
95
  const started = await lstat(join(path, "started"));
@@ -119,6 +131,7 @@ export class WaitJobs {
119
131
  ...current, outcome, waitedSeconds: (Date.now() - started) / 1000,
120
132
  instruction: outcome === "still_pending" ? "The wait ceiling was reached. Inspect the job and its output now. If it is healthy and still needed, call wait_for_job again. Do not treat this as completion."
121
133
  : outcome === "new_message" ? "A new message arrived. Handle it before deciding whether to wait again. The underlying job was not stopped."
134
+ : current.timedOut ? "The command hit its time limit and was stopped (exit 124); it did not finish. Inspect its output, then decide whether to run it again with a longer timeoutSeconds or change it."
122
135
  : "The command exited. Inspect its output and exit code before continuing.",
123
136
  });
124
137
  };
@@ -1,2 +1,2 @@
1
1
  // Generated by scripts/build.mjs from server/wait-runner.sh.
2
- export const runnerSource = "#!/bin/sh\n# Wait (folded in from paseo-wait 0.0.1). Invoked by the agent's native Bash tool, never by the plugin worker.\n# It records \"started\" once and writes an atomic exit receipt (result.json), the only proof of completion.\nset -u\numask 077\njob_directory=$1\nworking_directory=$2\njob_command=$3\nif ! mkdir \"$job_directory/started\" 2>/dev/null; then\n echo 'This prepared job has already started; prepare a new job to run it again.' >&2\n exit 125\nfi\nfinish() {\n job_status=$?\n trap - EXIT\n printf '{\"exitCode\":%s}\\n' \"$job_status\" > \"$job_directory/result.tmp\"\n mv \"$job_directory/result.tmp\" \"$job_directory/result.json\"\n exit \"$job_status\"\n}\ntrap finish EXIT\ntrap 'exit 130' INT\ntrap 'exit 143' TERM\ncd \"$working_directory\" || exit 126\nbash -c \"$job_command\"\nexit $?\n";
2
+ export const runnerSource = "#!/bin/sh\n# Wait (folded in from paseo-wait 0.0.1). Invoked by the agent's native Bash tool, never by the plugin worker.\n# It records \"started\" once and writes an atomic exit receipt (result.json), the only proof of completion.\nset -u\numask 077\njob_directory=$1\nworking_directory=$2\njob_command=$3\nif ! mkdir \"$job_directory/started\" 2>/dev/null; then\n echo 'This prepared job has already started; prepare a new job to run it again.' >&2\n exit 125\nfi\nfinish() {\n job_status=$?\n trap - EXIT\n if [ -e \"$job_directory/timed-out\" ]; then\n printf '{\"exitCode\":%s,\"timedOut\":true}\\n' \"$job_status\" > \"$job_directory/result.tmp\"\n else\n printf '{\"exitCode\":%s}\\n' \"$job_status\" > \"$job_directory/result.tmp\"\n fi\n mv \"$job_directory/result.tmp\" \"$job_directory/result.json\"\n exit \"$job_status\"\n}\ntrap finish EXIT\ntrap 'exit 130' INT\ntrap 'exit 143' TERM\ncd \"$working_directory\" || exit 126\n# A time limit (seconds) written at prepare: the command is stopped after it (TERM, then KILL 30 s later), so a\n# job that never finishes (an unbounded poll loop) can't keep the machine busy forever. Exit 124 means it hit the\n# limit; the receipt records that. Without timeout(1) (macOS) the command runs unbounded, as before.\n#\n# GNU timeout puts itself and the command in a new process group, so a TERM sent to this runner's group (Stop,\n# Claude Code killing the background task) wouldn't reach the job, and a foreground child would hold this shell's\n# TERM trap until it exited. So timeout runs in the background and every TERM, INT or HUP is forwarded to it; timeout\n# passes it on to the command's group (and KILLs it 30 s later if it's still there). The job's stdin is /dev/null\n# (an asynchronous command's default), which a Wait job never reads.\njob_limit=$(cat \"$job_directory/timeout\" 2>/dev/null || true)\nif [ -n \"$job_limit\" ] && command -v timeout >/dev/null 2>&1; then\n # The trap is set first, so a signal that lands before timeout has started is passed on once it has.\n job_pid= job_stop=\n trap 'job_stop=1; [ -n \"$job_pid\" ] && kill -TERM \"$job_pid\" 2>/dev/null' TERM INT HUP\n timeout -k 30 \"$job_limit\" bash -c \"$job_command\" &\n job_pid=$!\n if [ -n \"$job_stop\" ]; then kill -TERM \"$job_pid\" 2>/dev/null; fi\n wait \"$job_pid\"\n job_status=$?\n # A forwarded signal interrupts wait; keep waiting until timeout itself has exited, for its real status.\n while kill -0 \"$job_pid\" 2>/dev/null; do wait \"$job_pid\"; job_status=$?; done\n # Some coreutils versions also exit 124 when timeout itself is signalled, so 124 means the limit only when nobody\n # stopped the job; a stopped job reports 143 (TERM), like the unbounded path.\n if [ -n \"$job_stop\" ]; then\n if [ \"$job_status\" -eq 124 ]; then job_status=143; fi\n elif [ \"$job_status\" -eq 124 ]; then\n : > \"$job_directory/timed-out\"\n fi\n exit \"$job_status\"\nfi\nbash -c \"$job_command\"\nexit $?\n";
@@ -13,7 +13,11 @@ fi
13
13
  finish() {
14
14
  job_status=$?
15
15
  trap - EXIT
16
- printf '{"exitCode":%s}\n' "$job_status" > "$job_directory/result.tmp"
16
+ if [ -e "$job_directory/timed-out" ]; then
17
+ printf '{"exitCode":%s,"timedOut":true}\n' "$job_status" > "$job_directory/result.tmp"
18
+ else
19
+ printf '{"exitCode":%s}\n' "$job_status" > "$job_directory/result.tmp"
20
+ fi
17
21
  mv "$job_directory/result.tmp" "$job_directory/result.json"
18
22
  exit "$job_status"
19
23
  }
@@ -21,5 +25,35 @@ trap finish EXIT
21
25
  trap 'exit 130' INT
22
26
  trap 'exit 143' TERM
23
27
  cd "$working_directory" || exit 126
28
+ # A time limit (seconds) written at prepare: the command is stopped after it (TERM, then KILL 30 s later), so a
29
+ # job that never finishes (an unbounded poll loop) can't keep the machine busy forever. Exit 124 means it hit the
30
+ # limit; the receipt records that. Without timeout(1) (macOS) the command runs unbounded, as before.
31
+ #
32
+ # GNU timeout puts itself and the command in a new process group, so a TERM sent to this runner's group (Stop,
33
+ # Claude Code killing the background task) wouldn't reach the job, and a foreground child would hold this shell's
34
+ # TERM trap until it exited. So timeout runs in the background and every TERM, INT or HUP is forwarded to it; timeout
35
+ # passes it on to the command's group (and KILLs it 30 s later if it's still there). The job's stdin is /dev/null
36
+ # (an asynchronous command's default), which a Wait job never reads.
37
+ job_limit=$(cat "$job_directory/timeout" 2>/dev/null || true)
38
+ if [ -n "$job_limit" ] && command -v timeout >/dev/null 2>&1; then
39
+ # The trap is set first, so a signal that lands before timeout has started is passed on once it has.
40
+ job_pid= job_stop=
41
+ trap 'job_stop=1; [ -n "$job_pid" ] && kill -TERM "$job_pid" 2>/dev/null' TERM INT HUP
42
+ timeout -k 30 "$job_limit" bash -c "$job_command" &
43
+ job_pid=$!
44
+ if [ -n "$job_stop" ]; then kill -TERM "$job_pid" 2>/dev/null; fi
45
+ wait "$job_pid"
46
+ job_status=$?
47
+ # A forwarded signal interrupts wait; keep waiting until timeout itself has exited, for its real status.
48
+ while kill -0 "$job_pid" 2>/dev/null; do wait "$job_pid"; job_status=$?; done
49
+ # Some coreutils versions also exit 124 when timeout itself is signalled, so 124 means the limit only when nobody
50
+ # stopped the job; a stopped job reports 143 (TERM), like the unbounded path.
51
+ if [ -n "$job_stop" ]; then
52
+ if [ "$job_status" -eq 124 ]; then job_status=143; fi
53
+ elif [ "$job_status" -eq 124 ]; then
54
+ : > "$job_directory/timed-out"
55
+ fi
56
+ exit "$job_status"
57
+ fi
24
58
  bash -c "$job_command"
25
59
  exit $?
package/server/wait.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import type { AgentToolDefinition, AgentToolContext, PluginSessionOpenRequest } from "@getpaseo/plugin/server";
3
- import { WaitJobs, waitInput } from "./wait-jobs";
3
+ import { WaitJobs, waitInput, prepareInput } from "./wait-jobs";
4
4
  import type { WaitStatus } from "../shared/wait";
5
5
 
6
6
  /**
@@ -61,9 +61,9 @@ export class Wait {
61
61
  this.tools = [
62
62
  {
63
63
  name: "wait_prepare_job",
64
- description: "For a finite shell command that may take a while and whose result you need before finishing (tests, builds, installs, deploy checks): prepare it here instead of running it directly. Returns jobId and bashCommand and runs nothing. Run that exact bashCommand with native Bash run_in_background=true, then call wait_for_job instead of ending your turn.",
65
- input: z.object({ description: z.string().min(1).max(240), command: z.string().min(1).max(32000) }).strict(),
66
- execute: async (input, context) => { guard(context); return json(await this.jobs.prepare(owner(context), input as { description: string; command: string })); },
64
+ description: "For a finite shell command that may take a while and whose result you need before finishing (tests, builds, installs, deploy checks): prepare it here instead of running it directly. Returns jobId and bashCommand and runs nothing. Run that exact bashCommand with native Bash run_in_background=true, then call wait_for_job instead of ending your turn. The command is stopped after timeoutSeconds (default 3 hours, at most 12); a stopped job reports timedOut.",
65
+ input: prepareInput,
66
+ execute: async (input, context) => { guard(context); return json(await this.jobs.prepare(owner(context), input as z.input<typeof prepareInput>)); },
67
67
  },
68
68
  {
69
69
  name: "wait_get_job",
@@ -93,8 +93,9 @@ export class Wait {
93
93
  }
94
94
 
95
95
  /** Adds Wait's tools to an interactive Claude session, unless it's off, opted out, or the standalone plugin has it. */
96
- async open<R extends PluginSessionOpenRequest>(request: R): Promise<R> {
97
- if (request.purpose !== "interactive" || request.provider !== "claude") return request;
96
+ async open<R extends PluginSessionOpenRequest>(request: R, options: { background?: boolean } = {}): Promise<R> {
97
+ // A Paseo 0.16 background agent is another plugin's helper: no Wait (server/background-agents.ts).
98
+ if (options.background || request.purpose !== "interactive" || request.provider !== "claude") return request;
98
99
  if (request.labels["plugin-tools/enabled"] === "false" || request.labels["paseo-wait/enabled"] === "false" || request.labels[WAIT_LABEL] === "false") return request;
99
100
  if (!Array.isArray(request.tools) || request.tools.some(tool => (WAIT_TOOLS as readonly string[]).includes(tool.name))) return request;
100
101
  if (!(await this.deps.enabled())) return request;
@@ -3,6 +3,8 @@ export type WorkspaceAgent = {
3
3
  workspaceId?: string | null;
4
4
  archivedAt?: string | null;
5
5
  labels: Record<string, string>;
6
+ /** Paseo 0.16: a helper another plugin runs for itself. Never a root (server/background-agents.ts). */
7
+ background?: boolean;
6
8
  };
7
9
 
8
10
  /** Parent labels record who launched an agent, including launches into another workspace. */
@@ -10,7 +12,7 @@ export async function isWorkspaceRoot(
10
12
  agent: WorkspaceAgent,
11
13
  findParent: (id: string) => Promise<WorkspaceAgent | null | undefined>,
12
14
  ): Promise<boolean> {
13
- if (!agent.workspaceId || agent.archivedAt) return false;
15
+ if (!agent.workspaceId || agent.archivedAt || agent.background === true) return false;
14
16
  const parentId = agent.labels["paseo.parent-agent-id"];
15
17
  if (!parentId) return true;
16
18
  if (parentId === agent.id) return false;