paseo-follow-up 2.4.2 → 2.6.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/OVERVIEW.md +1 -1
  3. package/README.md +0 -1
  4. package/client/home.tsx +16 -8
  5. package/client/live.tsx +4 -3
  6. package/client/new-settings.tsx +1 -1
  7. package/client/onboarding.tsx +50 -118
  8. package/client/panel.tsx +2 -1
  9. package/client/release-notes.tsx +98 -123
  10. package/client/setup-dialog.tsx +168 -0
  11. package/client/setup-gate.tsx +69 -0
  12. package/client/setup-ui.ts +27 -0
  13. package/client/tasks.tsx +38 -8
  14. package/client/updates.tsx +6 -6
  15. package/index.client.tsx +1 -1
  16. package/index.server.ts +46 -4
  17. package/package.json +1 -1
  18. package/server/agent-hook.mjs +6 -4
  19. package/server/agent-parity.ts +2 -2
  20. package/server/ai-jobs.ts +26 -5
  21. package/server/engine.ts +6 -2
  22. package/server/hook-source.ts +6 -4
  23. package/server/job-agent.ts +13 -2
  24. package/server/mcp-source.ts +4 -4
  25. package/server/mcp.mjs +4 -4
  26. package/server/obligations.ts +7 -5
  27. package/server/release-notes.ts +5 -5
  28. package/server/scheduled-tasks.ts +92 -0
  29. package/server/session-prompt.ts +30 -3
  30. package/server/turn-end.ts +130 -0
  31. package/server/wait-jobs.ts +18 -2
  32. package/server/wait.ts +17 -12
  33. package/shared/agent-settings.ts +9 -8
  34. package/shared/attention.ts +4 -0
  35. package/shared/changelog.ts +33 -0
  36. package/shared/compass.ts +5 -4
  37. package/shared/contracts.ts +4 -4
  38. package/shared/job-rows.ts +2 -2
  39. package/shared/message-sender.ts +2 -0
  40. package/shared/new-name.ts +4 -1
  41. package/shared/onboarding.ts +17 -13
  42. package/shared/provider-support.ts +83 -34
  43. package/shared/queue.ts +1 -1
  44. package/shared/recommend.ts +1 -1
  45. package/shared/settings-nav.ts +3 -1
  46. package/shared/setup-popup.ts +28 -0
  47. package/shared/task-due.ts +3 -1
  48. package/shared/task-trigger.ts +125 -1
  49. package/shared/wait.ts +2 -2
  50. package/skills/follow-up/SKILL.md +1 -1
@@ -19,14 +19,14 @@ export const mcpSource: string = [
19
19
  "const integer = { type: \"integer\", minimum: 1 };",
20
20
  "const array = { type: \"array\", items: string };",
21
21
  "const communication = { type: \"object\", properties: { threadUrl: string, recipient: string, purpose: { type: \"string\", enum: [\"progress\", \"verified\"] }, authorization: string, replyUrl: { type: [\"string\", \"null\"] } }, required: [\"threadUrl\", \"recipient\"], additionalProperties: false };",
22
- "const trigger = { type: [\"object\", \"null\"], properties: { event: { type: \"string\", enum: [\"now\", \"merge\", \"deploy\"] }, delayDays: { type: \"integer\", minimum: 0, maximum: 3650 } }, required: [\"event\"], additionalProperties: false };",
22
+ "const trigger = { type: [\"object\", \"null\"], properties: { event: { type: \"string\", enum: [\"now\", \"merge\", \"deploy\", \"at\"] }, delayDays: { type: \"integer\", minimum: 0, maximum: 3650 }, at: { type: \"string\", description: \"event at: an ISO time with its offset, like 2026-11-26T12:15:00+02:00\" }, inMinutes: { type: \"integer\", minimum: 1, maximum: 43200, description: \"event at: this many minutes from now, instead of at\" } }, required: [\"event\"], additionalProperties: false };",
23
23
  "const tools = [",
24
24
  " [\"workspace_status\", \"Read the tracked workspace's durable goal, PRs, tasks, work queue and optional recovery history. Read after compaction. Returns current work by default; detail=full includes complete evidence/history. Normal follow-up does not require recovery.\", \"follow.agent-status\", { detail: { type: \"string\", enum: [\"summary\", \"full\"] } }, []],",
25
25
  " [\"sync_workspace\", \"Silently confirm the sidebar matches your work before finishing, after registering owned PRs and substantive tasks. Call even when no changes are needed. Keep the summary in this tool; never announce sync or recap sidebar/plugin status to the developer. Does not declare Done, run recovery, or start repairs. Tracked root agents only.\", \"follow.sync\", { summary: { ...string, minLength: 1, maxLength: 1000 } }, [\"summary\"]],",
26
26
  " [\"enroll_workspace\", \"Refine this developer-activated workspace's goal. Ownership is initialized by Track this workspace or the project’s default-tracking setting. This tool cannot activate another workspace. Never ask the developer to enter this. Keep the goal concise; new scope reopens completion.\", \"follow.enroll\", { goal: string }, [\"goal\"]],",
27
27
  " [\"register_pr\", \"Register a PR produced by this workspace. Call after every submission. Register parents first; repeat to update its stack or parent after restacking. Supply a disposition for a deliberately closed PR. Set agentMerges: true when you merge this PR yourself (no human review): Follow-up then never asks the developer to add reviewers or merge it, and the workspace reads as waiting on you; set it false to hand the merge back. In a repository set to No review (set_pr_workflow review \\\"none\\\") every PR counts as agentMerges unless you set it false.\", \"follow.register-pr\", { repo: string, number: integer, stack: string, parentNumber: { type: [\"integer\", \"null\"], minimum: 1 }, disposition: string, agentMerges: boolean }, [\"repo\", \"number\", \"stack\"]],",
28
28
  " [\"exclude_stack\", \"Correct an unrelated stack registration. Preserve its PRs and requirements in an exclusion audit; future registration is blocked. reason must cite the scope/ownership evidence. obligationIds may include related tasks without PR dependencies. Keep external dependencies separate from owned work.\", \"follow.exclude-stack\", { stack: string, reason: string, obligationIds: array }, [\"stack\", \"reason\"]],",
29
- " [\"update_obligation\", \"Record concrete follow-up: verification, migrations, decisions or stakeholder replies. Never add approve/merge/deploy checklist tasks. afterPrs uses owner/repo#number keys. A task comes due by itself when its afterPrs reach dependencyStage, or on recheck (\\\"YYYY-MM-DD\\\"; a task with no PRs defaults to 3 days after your last update); at your turn's end Follow-up names due tasks: do them and close with evidence, or keep them with a new recheck and why. trigger={event:\\\"now\\\"|\\\"merge\\\"|\\\"deploy\\\",delayDays:0} also sends the task to you as a message; set it only from the developer’s 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 removes it. Auto controls delivery, not timing or production permissions. For Slack replies, communication records the original threadUrl, recipient, purpose (progress or verified), explicit developer authorization and sent replyUrl. Empty authorization never queues a reply; Auto does not authorize external posts. Use a verify-and-reply task after deployment for the final update. Read the thread first; mark blocked when posting is unavailable or uncertain, never treat a draft as sent. Done requires replyUrl and evidence; preserve fields when updating. status=working records you as the agent doing it; pass workingAgentId when another agent (your subagent) is.\", \"follow.obligation\", { id: string, workingAgentId: string, title: string, status: { type: \"string\", enum: [\"pending\", \"waiting\", \"working\", \"blocked\", \"done\", \"waived\"] }, afterPrs: array, dependencyStage: { type: \"string\", enum: [\"merged\", \"deployed\"] }, evidence: string, ask: { ...string, description: \"With blocked, only for a decision you haven't asked: the question the developer must answer (waiting on a PR or agent is status=waiting). Asked already with ask_question? Pass question instead.\" }, question: { type: \"string\", pattern: \"^Q\\\\d+$\", description: \"With blocked: the question (Q<n>) this task waits on, asked with ask_question (task set to this task). No second card is made.\" }, need: { type: \"string\", enum: [\"decision\", \"action\"], description: \"With blocked and ask: decision (they choose; the card takes their answer) or action (they do something and report back, e.g. share a page, approve, log in; the card has Done). Left out: read from the ask.\" }, enable_follow_up: boolean, communication, trigger, recheck: { type: \"string\", description: \"When to look at this task again: \\\"YYYY-MM-DD\\\". Set it when you keep a due task open, with why in evidence.\" }, new: { type: \"boolean\", description: \"Add a separate task even though a similar open one exists.\" } }, [\"title\", \"status\"]],",
29
+ " [\"update_obligation\", \"Record concrete follow-up: verification, migrations, decisions or stakeholder replies. Never add approve/merge/deploy checklist tasks. afterPrs uses owner/repo#number keys. A task comes due by itself when its afterPrs reach dependencyStage, or on recheck (\\\"YYYY-MM-DD\\\"; a task with no PRs defaults to 3 days after your last update); at your turn's end Follow-up names due tasks: do them and close with evidence, or keep them with a new recheck and why. trigger={event:\\\"now\\\"|\\\"merge\\\"|\\\"deploy\\\",delayDays:0} also sends the task to you as a message; set it only from the developer’s requested timing; never infer timing from a title or enable_follow_up alone. trigger={event:\\\"at\\\",at:\\\"<ISO time with offset>\\\"} or {event:\\\"at\\\",inMinutes:30} sends it to you once at that time, Auto-send on or off: set it from a time the developer named, or yourself on a waiting task to check back on something Follow-up can't see (a registry, a release window, a reply); never a sleep loop or a timer of your own (CI: wait_for_checks). 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 removes it. Auto controls delivery, not timing or production permissions. For Slack replies, communication records the original threadUrl, recipient, purpose (progress or verified), explicit developer authorization and sent replyUrl. Empty authorization never queues a reply; Auto does not authorize external posts. Use a verify-and-reply task after deployment for the final update. Read the thread first; mark blocked when posting is unavailable or uncertain, never treat a draft as sent. Done requires replyUrl and evidence; preserve fields when updating. status=working records you as the agent doing it; pass workingAgentId when another agent (your subagent) is.\", \"follow.obligation\", { id: string, workingAgentId: string, title: string, status: { type: \"string\", enum: [\"pending\", \"waiting\", \"working\", \"blocked\", \"done\", \"waived\"] }, afterPrs: array, dependencyStage: { type: \"string\", enum: [\"merged\", \"deployed\"] }, evidence: string, ask: { ...string, description: \"With blocked, only for a decision you haven't asked: the question the developer must answer (waiting on a PR or agent is status=waiting). Asked already with ask_question? Pass question instead.\" }, question: { type: \"string\", pattern: \"^Q\\\\d+$\", description: \"With blocked: the question (Q<n>) this task waits on, asked with ask_question (task set to this task). No second card is made.\" }, need: { type: \"string\", enum: [\"decision\", \"action\"], description: \"With blocked and ask: decision (they choose; the card takes their answer) or action (they do something and report back, e.g. share a page, approve, log in; the card has Done). Left out: read from the ask.\" }, enable_follow_up: boolean, communication, trigger, recheck: { type: \"string\", description: \"When to look at this task again: \\\"YYYY-MM-DD\\\". Set it when you keep a due task open, with why in evidence.\" }, new: { type: \"boolean\", description: \"Add a separate task even though a similar open one exists.\" } }, [\"title\", \"status\"]],",
30
30
  " [\"acknowledge_batch\", \"Record a follow-up result. Complete only after verifying all tasks; blocked surfaces the reason to the developer. in_progress when you or your own subagent are already working on these tasks (say where it stands): not a failure, and Follow-up won't send the same tasks again until that work ends or they change on GitHub. Blocked with humanOnly=true when nothing is left for an agent and only a person can move it (a reviewer must re-review or dismiss a stale review, access must be granted): the developer gets a PR item, not an agent failure. When only part of it waits on a person (one thread needs the reviewer's call), name that part in waitingOn with any outcome and carry on with the rest: the developer gets it as a person item, and later messages tell you to leave it. Always acknowledge before ending a repair turn. Keep the result within 2000 characters.\", \"follow.acknowledge\", { batchId: string, outcome: { type: \"string\", enum: [\"completed\", \"blocked\", \"in_progress\"] }, result: { ...string, maxLength: 2000 }, humanOnly: { type: \"boolean\" }, waitingOn: { ...string, maxLength: 500 } }, [\"batchId\", \"outcome\", \"result\"]],",
31
31
  " [\"ask_question\", \"Ask the developer a decision you can't make yourself. Give a short title, the question, lettered options A, B, C… with what each means for them, and recommend the option you'd pick. Set big only when building ahead would send something off this computer, set something people or programs outside the repo rely on, or most remaining work would build on it. Link a PR (owner/repo#number) or task id when it is about one. When a task waits on this decision, set task, then mark it blocked with update_obligation question=\\\"Q<n>\\\" (not ask): one decision, one card. The reply says the question mode and exactly what to do until the answer arrives. Asking something already open returns the open question (\\\"Already open as Q18\\\") instead of a second one; to change an open question's options, ask again with supersedes=\\\"Q18\\\". At the end of the turn point at it with needs_you questions=[\\\"Q18\\\"], don't restate it. URLs and owner/repo#123 in the question, background and options are clickable for the developer. Every card already ends with a built-in \\\"Something else\\\" choice where the developer writes their own answer; don't add an \\\"Other\\\" option yourself.\", \"follow.ask-question\", { title: { ...string, maxLength: 120 }, question: { ...string, maxLength: 2000 }, options: { type: \"array\", maxItems: 26, items: { type: \"object\", properties: { letter: { type: \"string\", pattern: \"^[A-Z]$\" }, label: { ...string, maxLength: 200 }, consequence: { ...string, maxLength: 600 } }, required: [\"letter\", \"label\"], additionalProperties: false } }, recommend: string, big: string, background: string, links: { type: \"array\", maxItems: 10, items: { type: \"object\", properties: { url: string, path: string, label: string }, additionalProperties: false } }, pr: string, task: string, supersedes: { type: \"string\", pattern: \"^Q\\\\d+$\" } }, [\"title\", \"question\"]],",
32
32
  " [\"record_answer\", \"Record the developer's answer when they answered a question in chat instead of in Follow-up. choice is an option letter, \\\"other\\\" when they chose none of your options (words is then required: their answer), or their short answer when there were no options; words is what they said.\", \"follow.record-answer\", { id: string, choice: string, words: string }, [\"id\", \"choice\"]],",
@@ -140,7 +140,7 @@ export const mcpSource: string = [
140
140
  " [\"run_recovery\", \"Run recovery on a workspace, like Run recovery: a separate agent reads its history for missed PRs and tasks. { workspaceId }.\" + ask, \"follow.agent-act\", { workspaceId: string, ...planned }, []],",
141
141
  " [\"refresh\", \"Refresh PR status now, like Refresh. Cheap; use when status looks stale.\", \"follow.agent-act\", { workspaceId: string }, []],",
142
142
  " [\"set_workspace_spec\", \"Set, remove or reset any workspace's spec link: { workspaceId, action set|remove|reset, url, title }.\" + ask, \"follow.agent-act\", { workspaceId: string, action: string, url: string, title: { type: [\"string\", \"null\"] }, ...planned }, []],",
143
- " [\"set_task_trigger\", \"Schedule a task to run now, on merge or on deploy (trigger { event, delayDays } or null), with afterPrs: { workspaceId, obligationId, expectedRevision, trigger, afterPrs }.\" + ask, \"follow.agent-act\", { workspaceId: string, obligationId: string, expectedRevision: { type: \"integer\", minimum: 0 }, trigger, afterPrs: array, ...planned }, []],",
143
+ " [\"set_task_trigger\", \"Schedule a task to run now, on merge, on deploy or at a time (trigger { event, delayDays } or { event: \\\"at\\\", at | inMinutes } or null), with afterPrs: { workspaceId, obligationId, expectedRevision, trigger, afterPrs }.\" + ask, \"follow.agent-act\", { workspaceId: string, obligationId: string, expectedRevision: { type: \"integer\", minimum: 0 }, trigger, afterPrs: array, ...planned }, []],",
144
144
  " [\"pr_controls\", \"Read a PR's merge controls as the PR sheet shows them (Send to Paseo pairing, Graphite in Chrome): { workspaceId, prKey }.\" + read, \"follow.agent-act\", { workspaceId: string, prKey }, [\"workspaceId\", \"prKey\"]],",
145
145
  " [\"browser_status\", \"Read whether Send to Paseo is paired and which repositories it may control.\" + read, \"follow.agent-act\", {}, []],",
146
146
  " [\"release_notes\", \"Read Follow-up's release notes: the installed version, the version it updated from (previous) and when (updatedAt, ms), and every shipped version's notes, newest first. What's new shows the notes after previous, once per device, unless enable_whats_new is off (set_updates).\" + read, \"follow.agent-act\", {}, []],",
@@ -178,7 +178,7 @@ export const mcpSource: string = [
178
178
  "// Paseo 0.16+ (features.agentBackgroundWork) tracks background shell jobs and wakes the agent when one finishes, so",
179
179
  "// Wait's tools aren't attached there; the agent hook adds this instead when FOLLOW_UP_BACKGROUND_WORK=1.",
180
180
  "const backgroundWorkInstruction = \"When a finite shell command may take a while (tests, builds, installs, deploy checks), run it with native Bash run_in_background=true. Continue useful independent work first if available. When only waiting remains, end your turn and say what you're waiting for: Paseo keeps the job running, shows it with Stop, and wakes you when it finishes. Don't sleep or poll in a loop to keep the turn open. When you're woken, confirm the actual exit code before reporting completion.\";",
181
- "const waitInstruction = \"When a finite shell command may take a while and you need its result to finish the user's task, use Wait: wait_prepare_job({description, command}), run the returned exact bashCommand through native Bash with run_in_background=true, then call wait_for_job({jobId}). Continue useful independent work first if available. When only waiting remains, keep waiting through wait_for_job instead of ending your turn with \\\"waiting for a notification\\\". Each call wakes you after at most 60 seconds (default 30): on still_pending, inspect wait_get_job and the native Bash output, then wait again if appropriate. Confirm the actual exit code before reporting completion. New messages and Stop release observation without killing the job. Already-started ordinary background tasks cannot be adopted: do not rerun a command just to wrap it.\";",
181
+ "const waitInstruction = \"When a finite shell command may take a while and you need its result to finish the user's task, use Wait: wait_prepare_job({description, command}), run the returned exact bashCommand the way the reply's instruction says (on Claude Code through native Bash with run_in_background=true; elsewhere it starts itself in the background), then call wait_for_job({jobId}). Continue useful independent work first if available. When only waiting remains, keep waiting through wait_for_job instead of ending your turn with \\\"waiting for a notification\\\". Each call wakes you after at most 60 seconds (default 30): on still_pending, inspect wait_get_job and the job's output (the native Bash output, or outputPath), then wait again if appropriate. Confirm the actual exit code before reporting completion. New messages and Stop release observation without killing the job. Already-started ordinary background tasks cannot be adopted: do not rerun a command just to wrap it.\";",
182
182
  "",
183
183
  "// The brief's tool: every root agent while the Needs-you inbox is on; never contributors, recovery or subagents.",
184
184
  "// Kept identical to NEEDS_YOU_INSTRUCTION in shared/brief.ts (a test checks it).",
package/server/mcp.mjs CHANGED
@@ -17,14 +17,14 @@ const boolean = { type: "boolean" };
17
17
  const integer = { type: "integer", minimum: 1 };
18
18
  const array = { type: "array", items: string };
19
19
  const communication = { type: "object", properties: { threadUrl: string, recipient: string, purpose: { type: "string", enum: ["progress", "verified"] }, authorization: string, replyUrl: { type: ["string", "null"] } }, required: ["threadUrl", "recipient"], additionalProperties: false };
20
- const trigger = { type: ["object", "null"], properties: { event: { type: "string", enum: ["now", "merge", "deploy"] }, delayDays: { type: "integer", minimum: 0, maximum: 3650 } }, required: ["event"], additionalProperties: false };
20
+ const trigger = { type: ["object", "null"], properties: { event: { type: "string", enum: ["now", "merge", "deploy", "at"] }, delayDays: { type: "integer", minimum: 0, maximum: 3650 }, at: { type: "string", description: "event at: an ISO time with its offset, like 2026-11-26T12:15:00+02:00" }, inMinutes: { type: "integer", minimum: 1, maximum: 43200, description: "event at: this many minutes from now, instead of at" } }, required: ["event"], additionalProperties: false };
21
21
  const tools = [
22
22
  ["workspace_status", "Read the tracked workspace's durable goal, PRs, tasks, work queue and optional recovery history. Read after compaction. Returns current work by default; detail=full includes complete evidence/history. Normal follow-up does not require recovery.", "follow.agent-status", { detail: { type: "string", enum: ["summary", "full"] } }, []],
23
23
  ["sync_workspace", "Silently confirm the sidebar matches your work before finishing, after registering owned PRs and substantive tasks. Call even when no changes are needed. Keep the summary in this tool; never announce sync or recap sidebar/plugin status to the developer. Does not declare Done, run recovery, or start repairs. Tracked root agents only.", "follow.sync", { summary: { ...string, minLength: 1, maxLength: 1000 } }, ["summary"]],
24
24
  ["enroll_workspace", "Refine this developer-activated workspace's goal. Ownership is initialized by Track this workspace or the project’s default-tracking setting. This tool cannot activate another workspace. Never ask the developer to enter this. Keep the goal concise; new scope reopens completion.", "follow.enroll", { goal: string }, ["goal"]],
25
25
  ["register_pr", "Register a PR produced by this workspace. Call after every submission. Register parents first; repeat to update its stack or parent after restacking. Supply a disposition for a deliberately closed PR. Set agentMerges: true when you merge this PR yourself (no human review): Follow-up then never asks the developer to add reviewers or merge it, and the workspace reads as waiting on you; set it false to hand the merge back. In a repository set to No review (set_pr_workflow review \"none\") every PR counts as agentMerges unless you set it false.", "follow.register-pr", { repo: string, number: integer, stack: string, parentNumber: { type: ["integer", "null"], minimum: 1 }, disposition: string, agentMerges: boolean }, ["repo", "number", "stack"]],
26
26
  ["exclude_stack", "Correct an unrelated stack registration. Preserve its PRs and requirements in an exclusion audit; future registration is blocked. reason must cite the scope/ownership evidence. obligationIds may include related tasks without PR dependencies. Keep external dependencies separate from owned work.", "follow.exclude-stack", { stack: string, reason: string, obligationIds: array }, ["stack", "reason"]],
27
- ["update_obligation", "Record concrete follow-up: verification, migrations, decisions or stakeholder replies. Never add approve/merge/deploy checklist tasks. afterPrs uses owner/repo#number keys. A task comes due by itself when its afterPrs reach dependencyStage, or on recheck (\"YYYY-MM-DD\"; a task with no PRs defaults to 3 days after your last update); at your turn's end Follow-up names due tasks: do them and close with evidence, or keep them with a new recheck and why. trigger={event:\"now\"|\"merge\"|\"deploy\",delayDays:0} also sends the task to you as a message; set it only from the developer’s 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 removes it. Auto controls delivery, not timing or production permissions. For Slack replies, communication records the original threadUrl, recipient, purpose (progress or verified), explicit developer authorization and sent replyUrl. Empty authorization never queues a reply; Auto does not authorize external posts. Use a verify-and-reply task after deployment for the final update. Read the thread first; mark blocked when posting is unavailable or uncertain, never treat a draft as sent. Done requires replyUrl and evidence; preserve fields when updating. status=working records you as the agent doing it; pass workingAgentId when another agent (your subagent) is.", "follow.obligation", { id: string, workingAgentId: string, title: string, status: { type: "string", enum: ["pending", "waiting", "working", "blocked", "done", "waived"] }, afterPrs: array, dependencyStage: { type: "string", enum: ["merged", "deployed"] }, evidence: string, ask: { ...string, description: "With blocked, only for a decision you haven't asked: the question the developer must answer (waiting on a PR or agent is status=waiting). Asked already with ask_question? Pass question instead." }, question: { type: "string", pattern: "^Q\\d+$", description: "With blocked: the question (Q<n>) this task waits on, asked with ask_question (task set to this task). No second card is made." }, need: { type: "string", enum: ["decision", "action"], description: "With blocked and ask: decision (they choose; the card takes their answer) or action (they do something and report back, e.g. share a page, approve, log in; the card has Done). Left out: read from the ask." }, enable_follow_up: boolean, communication, trigger, recheck: { type: "string", description: "When to look at this task again: \"YYYY-MM-DD\". Set it when you keep a due task open, with why in evidence." }, new: { type: "boolean", description: "Add a separate task even though a similar open one exists." } }, ["title", "status"]],
27
+ ["update_obligation", "Record concrete follow-up: verification, migrations, decisions or stakeholder replies. Never add approve/merge/deploy checklist tasks. afterPrs uses owner/repo#number keys. A task comes due by itself when its afterPrs reach dependencyStage, or on recheck (\"YYYY-MM-DD\"; a task with no PRs defaults to 3 days after your last update); at your turn's end Follow-up names due tasks: do them and close with evidence, or keep them with a new recheck and why. trigger={event:\"now\"|\"merge\"|\"deploy\",delayDays:0} also sends the task to you as a message; set it only from the developer’s requested timing; never infer timing from a title or enable_follow_up alone. trigger={event:\"at\",at:\"<ISO time with offset>\"} or {event:\"at\",inMinutes:30} sends it to you once at that time, Auto-send on or off: set it from a time the developer named, or yourself on a waiting task to check back on something Follow-up can't see (a registry, a release window, a reply); never a sleep loop or a timer of your own (CI: wait_for_checks). 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 removes it. Auto controls delivery, not timing or production permissions. For Slack replies, communication records the original threadUrl, recipient, purpose (progress or verified), explicit developer authorization and sent replyUrl. Empty authorization never queues a reply; Auto does not authorize external posts. Use a verify-and-reply task after deployment for the final update. Read the thread first; mark blocked when posting is unavailable or uncertain, never treat a draft as sent. Done requires replyUrl and evidence; preserve fields when updating. status=working records you as the agent doing it; pass workingAgentId when another agent (your subagent) is.", "follow.obligation", { id: string, workingAgentId: string, title: string, status: { type: "string", enum: ["pending", "waiting", "working", "blocked", "done", "waived"] }, afterPrs: array, dependencyStage: { type: "string", enum: ["merged", "deployed"] }, evidence: string, ask: { ...string, description: "With blocked, only for a decision you haven't asked: the question the developer must answer (waiting on a PR or agent is status=waiting). Asked already with ask_question? Pass question instead." }, question: { type: "string", pattern: "^Q\\d+$", description: "With blocked: the question (Q<n>) this task waits on, asked with ask_question (task set to this task). No second card is made." }, need: { type: "string", enum: ["decision", "action"], description: "With blocked and ask: decision (they choose; the card takes their answer) or action (they do something and report back, e.g. share a page, approve, log in; the card has Done). Left out: read from the ask." }, enable_follow_up: boolean, communication, trigger, recheck: { type: "string", description: "When to look at this task again: \"YYYY-MM-DD\". Set it when you keep a due task open, with why in evidence." }, new: { type: "boolean", description: "Add a separate task even though a similar open one exists." } }, ["title", "status"]],
28
28
  ["acknowledge_batch", "Record a follow-up result. Complete only after verifying all tasks; blocked surfaces the reason to the developer. in_progress when you or your own subagent are already working on these tasks (say where it stands): not a failure, and Follow-up won't send the same tasks again until that work ends or they change on GitHub. Blocked with humanOnly=true when nothing is left for an agent and only a person can move it (a reviewer must re-review or dismiss a stale review, access must be granted): the developer gets a PR item, not an agent failure. When only part of it waits on a person (one thread needs the reviewer's call), name that part in waitingOn with any outcome and carry on with the rest: the developer gets it as a person item, and later messages tell you to leave it. Always acknowledge before ending a repair turn. Keep the result within 2000 characters.", "follow.acknowledge", { batchId: string, outcome: { type: "string", enum: ["completed", "blocked", "in_progress"] }, result: { ...string, maxLength: 2000 }, humanOnly: { type: "boolean" }, waitingOn: { ...string, maxLength: 500 } }, ["batchId", "outcome", "result"]],
29
29
  ["ask_question", "Ask the developer a decision you can't make yourself. Give a short title, the question, lettered options A, B, C… with what each means for them, and recommend the option you'd pick. Set big only when building ahead would send something off this computer, set something people or programs outside the repo rely on, or most remaining work would build on it. Link a PR (owner/repo#number) or task id when it is about one. When a task waits on this decision, set task, then mark it blocked with update_obligation question=\"Q<n>\" (not ask): one decision, one card. The reply says the question mode and exactly what to do until the answer arrives. Asking something already open returns the open question (\"Already open as Q18\") instead of a second one; to change an open question's options, ask again with supersedes=\"Q18\". At the end of the turn point at it with needs_you questions=[\"Q18\"], don't restate it. URLs and owner/repo#123 in the question, background and options are clickable for the developer. Every card already ends with a built-in \"Something else\" choice where the developer writes their own answer; don't add an \"Other\" option yourself.", "follow.ask-question", { title: { ...string, maxLength: 120 }, question: { ...string, maxLength: 2000 }, options: { type: "array", maxItems: 26, items: { type: "object", properties: { letter: { type: "string", pattern: "^[A-Z]$" }, label: { ...string, maxLength: 200 }, consequence: { ...string, maxLength: 600 } }, required: ["letter", "label"], additionalProperties: false } }, recommend: string, big: string, background: string, links: { type: "array", maxItems: 10, items: { type: "object", properties: { url: string, path: string, label: string }, additionalProperties: false } }, pr: string, task: string, supersedes: { type: "string", pattern: "^Q\\d+$" } }, ["title", "question"]],
30
30
  ["record_answer", "Record the developer's answer when they answered a question in chat instead of in Follow-up. choice is an option letter, \"other\" when they chose none of your options (words is then required: their answer), or their short answer when there were no options; words is what they said.", "follow.record-answer", { id: string, choice: string, words: string }, ["id", "choice"]],
@@ -138,7 +138,7 @@ const actionTools = [
138
138
  ["run_recovery", "Run recovery on a workspace, like Run recovery: a separate agent reads its history for missed PRs and tasks. { workspaceId }." + ask, "follow.agent-act", { workspaceId: string, ...planned }, []],
139
139
  ["refresh", "Refresh PR status now, like Refresh. Cheap; use when status looks stale.", "follow.agent-act", { workspaceId: string }, []],
140
140
  ["set_workspace_spec", "Set, remove or reset any workspace's spec link: { workspaceId, action set|remove|reset, url, title }." + ask, "follow.agent-act", { workspaceId: string, action: string, url: string, title: { type: ["string", "null"] }, ...planned }, []],
141
- ["set_task_trigger", "Schedule a task to run now, on merge or on deploy (trigger { event, delayDays } or null), with afterPrs: { workspaceId, obligationId, expectedRevision, trigger, afterPrs }." + ask, "follow.agent-act", { workspaceId: string, obligationId: string, expectedRevision: { type: "integer", minimum: 0 }, trigger, afterPrs: array, ...planned }, []],
141
+ ["set_task_trigger", "Schedule a task to run now, on merge, on deploy or at a time (trigger { event, delayDays } or { event: \"at\", at | inMinutes } or null), with afterPrs: { workspaceId, obligationId, expectedRevision, trigger, afterPrs }." + ask, "follow.agent-act", { workspaceId: string, obligationId: string, expectedRevision: { type: "integer", minimum: 0 }, trigger, afterPrs: array, ...planned }, []],
142
142
  ["pr_controls", "Read a PR's merge controls as the PR sheet shows them (Send to Paseo pairing, Graphite in Chrome): { workspaceId, prKey }." + read, "follow.agent-act", { workspaceId: string, prKey }, ["workspaceId", "prKey"]],
143
143
  ["browser_status", "Read whether Send to Paseo is paired and which repositories it may control." + read, "follow.agent-act", {}, []],
144
144
  ["release_notes", "Read Follow-up's release notes: the installed version, the version it updated from (previous) and when (updatedAt, ms), and every shipped version's notes, newest first. What's new shows the notes after previous, once per device, unless enable_whats_new is off (set_updates)." + read, "follow.agent-act", {}, []],
@@ -176,7 +176,7 @@ const actionInstruction = "Follow-up's action tools let you do anything the deve
176
176
  // Paseo 0.16+ (features.agentBackgroundWork) tracks background shell jobs and wakes the agent when one finishes, so
177
177
  // Wait's tools aren't attached there; the agent hook adds this instead when FOLLOW_UP_BACKGROUND_WORK=1.
178
178
  const backgroundWorkInstruction = "When a finite shell command may take a while (tests, builds, installs, deploy checks), run it with native Bash run_in_background=true. Continue useful independent work first if available. When only waiting remains, end your turn and say what you're waiting for: Paseo keeps the job running, shows it with Stop, and wakes you when it finishes. Don't sleep or poll in a loop to keep the turn open. When you're woken, confirm the actual exit code before reporting completion.";
179
- const waitInstruction = "When a finite shell command may take a while and you need its result to finish the user's task, use Wait: wait_prepare_job({description, command}), run the returned exact bashCommand through native Bash with run_in_background=true, then call wait_for_job({jobId}). Continue useful independent work first if available. When only waiting remains, keep waiting through wait_for_job instead of ending your turn with \"waiting for a notification\". Each call wakes you after at most 60 seconds (default 30): on still_pending, inspect wait_get_job and the native Bash output, then wait again if appropriate. Confirm the actual exit code before reporting completion. New messages and Stop release observation without killing the job. Already-started ordinary background tasks cannot be adopted: do not rerun a command just to wrap it.";
179
+ const waitInstruction = "When a finite shell command may take a while and you need its result to finish the user's task, use Wait: wait_prepare_job({description, command}), run the returned exact bashCommand the way the reply's instruction says (on Claude Code through native Bash with run_in_background=true; elsewhere it starts itself in the background), then call wait_for_job({jobId}). Continue useful independent work first if available. When only waiting remains, keep waiting through wait_for_job instead of ending your turn with \"waiting for a notification\". Each call wakes you after at most 60 seconds (default 30): on still_pending, inspect wait_get_job and the job's output (the native Bash output, or outputPath), then wait again if appropriate. Confirm the actual exit code before reporting completion. New messages and Stop release observation without killing the job. Already-started ordinary background tasks cannot be adopted: do not rerun a command just to wrap it.";
180
180
 
181
181
  // The brief's tool: every root agent while the Needs-you inbox is on; never contributors, recovery or subagents.
182
182
  // Kept identical to NEEDS_YOU_INSTRUCTION in shared/brief.ts (a test checks it).
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import type { Obligation, Workspace } from "../shared/model";
3
3
  import { lifecycleOnly } from "../shared/follow-up";
4
4
  import { communicationKey, communicationSchema, replyRecorded, type Communication } from "../shared/communication";
5
- import type { TaskTrigger } from "../shared/task-trigger";
5
+ import { storedTrigger, type TaskTrigger, type TaskTriggerInput } from "../shared/task-trigger";
6
6
  import { currentQuestion } from "../shared/questions";
7
7
  import { RECHECK_DAYS } from "../shared/task-due";
8
8
  import { sameTask, similarLines, similarOpen } from "../shared/task-dup";
@@ -16,7 +16,7 @@ type Update = {
16
16
  /** While blocked: what the ask wants of the developer, a decision or an action they take and report back. */
17
17
  need?: "decision" | "action";
18
18
  dependencyStage?: "merged" | "deployed"; enable_follow_up?: boolean; communication?: Pick<Communication, "threadUrl" | "recipient"> & Partial<Communication>;
19
- trigger?: TaskTrigger | null;
19
+ trigger?: TaskTriggerInput | TaskTrigger | null;
20
20
  /** due-by-fact: when to look at it again, "YYYY-MM-DD" or an ISO time. An open task with no PRs gets RECHECK_DAYS out by default. */
21
21
  recheck?: string;
22
22
  /** The clock (tests); defaults to Date.now(). */
@@ -68,14 +68,16 @@ export function updateObligation(w: Workspace, input: Update): Obligation {
68
68
  const destination = communication ? communicationSchema.parse({ ...existing?.communication, ...communication }) : existing?.communication;
69
69
  if (destination?.replyUrl && !replyRecorded(destination)) throw new Error("The reply receipt must be a different message in the original Slack workspace/channel/thread.");
70
70
  if (destination && status === "done" && !replyRecorded(destination)) throw new Error("A draft is not a sent reply. Record communication.replyUrl before completing this task; use blocked when posting is unavailable or uncertain.");
71
- const trigger = input.trigger === undefined ? existing?.trigger : input.trigger;
71
+ const now = input.now ?? Date.now();
72
+ // An at trigger's time is resolved and checked here (inMinutes from now, an ISO time with its offset); the same time
73
+ // again keeps whether it already went out (a-scheduled-task-arrives-once-at-its-time).
74
+ const trigger = input.trigger === undefined ? existing?.trigger : storedTrigger(input.trigger, existing?.trigger, now);
72
75
  if (trigger?.event === "now" && (afterPrs.length || trigger.delayDays)) throw new Error("Now requires no PR dependencies or delay. Choose a merge/deploy trigger for delayed work.");
73
- if (trigger && trigger.event !== "now" && !afterPrs.length) throw new Error("Select at least one owned PR for a merge/deploy trigger.");
76
+ if (trigger && (trigger.event === "merge" || trigger.event === "deploy") && !afterPrs.length) throw new Error("Select at least one owned PR for a merge/deploy trigger.");
74
77
  const stage = trigger?.event === "merge" ? "merged" : trigger?.event === "deploy" ? "deployed" : dependencyStage ?? existing?.dependencyStage ?? "deployed";
75
78
  const followUp = enable_follow_up ?? (input.trigger !== undefined ? !!trigger : existing?.enable_follow_up ?? false);
76
79
  // due-by-fact: every open task knows what moves it. With no PRs that is a re-check date: the agent's, else
77
80
  // RECHECK_DAYS from this update (an update is the agent looking at it). A finished task records when.
78
- const now = input.now ?? Date.now();
79
81
  const recheck = input.recheck === undefined ? undefined : /^\d{4}-\d{2}-\d{2}$/.test(input.recheck) ? Date.parse(`${input.recheck}T00:00:00Z`) : Date.parse(input.recheck);
80
82
  if (recheck !== undefined && !Number.isFinite(recheck)) throw new Error("recheck is a date: \"YYYY-MM-DD\" or an ISO time.");
81
83
  const finished = ["done", "waived"].includes(status);
@@ -3,7 +3,7 @@ import type { ZodType } from "zod";
3
3
  import { readFile, writeFile, rename, mkdir } from "node:fs/promises";
4
4
  import { join } from "node:path";
5
5
  import { compareVersions } from "../shared/version";
6
- import { parseChangelog, LEGACY_BASELINE, type InstallKind, type ReleaseNote } from "../shared/changelog";
6
+ import { parseChangelog, releasesUrl, LEGACY_BASELINE, type InstallKind, type ReleaseNote } from "../shared/changelog";
7
7
 
8
8
  /**
9
9
  * Follow-up's own install, as Paseo describes it: where it lives, which version, and from what source. Read from the
@@ -24,12 +24,12 @@ export function describeSelf(rows: readonly PluginRow[]): Omit<SelfInstall, "ver
24
24
  return { id: row.id, path: row.path, version: row.installation?.currentRevision ?? null, installKind, status: row.status ?? null, error: row.error ?? null, registry };
25
25
  }
26
26
 
27
- /** The installed package's version, its display name (the manifest's `name`) and CHANGELOG.md, read from the plugin's own folder. */
28
- export async function readPackage(path: string): Promise<{ version: string | null; name: string | null; notes: ReleaseNote[] }> {
29
- const pkg = await readFile(join(path, "package.json"), "utf8").then(t => JSON.parse(t) as { version?: string }, () => null);
27
+ /** The installed package's version, its display name (the manifest's `name`), CHANGELOG.md and release pages, read from the plugin's own folder. */
28
+ export async function readPackage(path: string): Promise<{ version: string | null; name: string | null; notes: ReleaseNote[]; releases: string | null }> {
29
+ const pkg = await readFile(join(path, "package.json"), "utf8").then(t => JSON.parse(t) as { version?: string; repository?: unknown }, () => null);
30
30
  const manifest = await readFile(join(path, "paseo-plugin.json"), "utf8").then(t => JSON.parse(t) as { name?: unknown }, () => null);
31
31
  const notes = await readFile(join(path, "CHANGELOG.md"), "utf8").then(parseChangelog, () => []);
32
- return { version: pkg?.version ?? null, name: typeof manifest?.name === "string" && manifest.name.trim() ? manifest.name.trim() : null, notes };
32
+ return { version: pkg?.version ?? null, name: typeof manifest?.name === "string" && manifest.name.trim() ? manifest.name.trim() : null, notes, releases: releasesUrl(pkg?.repository) };
33
33
  }
34
34
 
35
35
  /** versions.json: which version this host runs, the one before it, and the host-wide What's new record. */
@@ -0,0 +1,92 @@
1
+ import type { MessageQueue, Resolution } from "./message-queue";
2
+ import type { QueueItem } from "../shared/queue";
3
+ import type { State, Workspace } from "../shared/model";
4
+ import { followUpObligations } from "../shared/follow-up";
5
+ import { pendingAt, scheduledText } from "../shared/task-trigger";
6
+
7
+ /** What the channel needs to know about the agent when the message goes: nothing here loads it. */
8
+ export type ScheduledAgent = { status: string; archived: boolean; workspaceId: string | null } | null;
9
+ export const scheduledItemId = (workspaceId: string, obligationId: string, at: string) => `scheduled:${workspaceId}:${obligationId}:${at}`;
10
+ /** Why a time trigger didn't go out, as the task row says it ("Not sent · the agent was archived"). */
11
+ export const NOT_SENT = { archived: "the agent was archived", closed: "the agent was closed", workspace: "the workspace was archived", none: "the workspace has no main agent" } as const;
12
+
13
+ /**
14
+ * Scheduled tasks (a-scheduled-task-arrives-once-at-its-time): a task whose trigger is a time goes to its main agent
15
+ * once, at that time, whether Auto-send is on or not: someone named the time (the developer in the sheet, or the agent
16
+ * for its own check-back). `evaluate` runs after each engine pass, whose untouched-pass skip already ends at the
17
+ * earliest due time (engine nextDue), so it fires within a tick and never before. A due trigger is saved as one
18
+ * `scheduled` queue message first (a-message-is-saved-before-sent-and-arrives-once) and then marked `queuedAt` on the
19
+ * task, so a crash between the two re-enqueues the same id, which the queue returns as it is. A closed or archived
20
+ * agent gets nothing, and the task row says why (`notSent`); a worker down at the time fires once, late, on its first
21
+ * pass. The channel resolves the agent when it goes, waits for a running turn to end, and sends to an idle one even
22
+ * when Paseo unloaded it: it asked for this message, as with wait_for_checks (the one exception to invariant 1).
23
+ */
24
+ export class ScheduledTasks {
25
+ private queue: MessageQueue | null = null;
26
+ /** Fired triggers (tests). */
27
+ readonly fired: { workspaceId: string; obligationId: string; at: string; sent: boolean; why: string }[] = [];
28
+ constructor(private deps: {
29
+ snapshot: () => Promise<State>;
30
+ mutateWorkspace: (id: string, work: (w: Workspace) => void) => Promise<unknown>;
31
+ agent: (agentId: string) => Promise<ScheduledAgent>;
32
+ now?: () => number;
33
+ }) {}
34
+ private now(): number { return (this.deps.now ?? Date.now)(); }
35
+
36
+ /** After an engine pass: every due time trigger in those workspaces (all when `ids` is absent). */
37
+ async evaluate(ids?: ReadonlySet<string>): Promise<void> {
38
+ const state = await this.deps.snapshot();
39
+ const now = this.now();
40
+ for (const w of state.workspaces) {
41
+ if (ids && !ids.has(w.id) || !w.enable_tracking) continue;
42
+ const due = followUpObligations(w).filter(o => o.enable_follow_up && !["done", "waived"].includes(o.status) && pendingAt(o.trigger) && Date.parse(o.trigger!.at!) <= now);
43
+ for (const o of due) await this.fire(w, o.id, o.trigger!.at!, now);
44
+ }
45
+ }
46
+
47
+ private async fire(w: Workspace, obligationId: string, at: string, now: number): Promise<void> {
48
+ const o = w.obligations.find(x => x.id === obligationId)!;
49
+ const agent = w.archived ? null : await this.deps.agent(w.mainAgentId).catch(() => undefined);
50
+ // Unknown (Paseo unreachable): try on the next pass; never a guess either way.
51
+ if (agent === undefined) return;
52
+ const why = w.archived ? NOT_SENT.workspace : !w.mainAgentId ? NOT_SENT.none : !agent || agent.archived ? NOT_SENT.archived : agent.status === "closed" ? NOT_SENT.closed : null;
53
+ if (!why && this.queue) {
54
+ this.queue.enqueue({ id: scheduledItemId(w.id, o.id, at), kind: "scheduled", key: w.id, ref: { workspaceId: w.id, obligationId: o.id, agentId: w.mainAgentId, at },
55
+ messageId: `scheduled-${o.id}-${Date.parse(at).toString(36)}`, text: scheduledText(o, at, now), priority: "now", state: "queued" });
56
+ }
57
+ if (!why && !this.queue) return;
58
+ await this.mark(w.id, o.id, at, t => { if (why) t.notSent = why; else t.queuedAt = new Date(now).toISOString(); });
59
+ this.fired.push({ workspaceId: w.id, obligationId: o.id, at, sent: !why, why: why ?? "queued" });
60
+ }
61
+
62
+ /** Writes onto the task's trigger only while it is still the same time (an edit since wins). */
63
+ private async mark(workspaceId: string, obligationId: string, at: string, edit: (t: NonNullable<Workspace["obligations"][number]["trigger"]>) => void): Promise<void> {
64
+ await this.deps.mutateWorkspace(workspaceId, w => {
65
+ const o = w.obligations.find(x => x.id === obligationId);
66
+ if (o?.trigger?.event === "at" && o.trigger.at === at) edit(o.trigger);
67
+ }).catch(error => console.warn(`[follow-up] couldn't record a scheduled task: ${error instanceof Error ? error.message : String(error)}`));
68
+ }
69
+
70
+ /** The queue's `scheduled` channel: the main agent, resolved when it goes; never woken from closed or archived. */
71
+ attachQueue(queue: MessageQueue): void {
72
+ this.queue = queue;
73
+ queue.register("scheduled", {
74
+ resolve: async (item): Promise<Resolution> => {
75
+ let agent: ScheduledAgent;
76
+ try { agent = await this.deps.agent(item.ref.agentId!); }
77
+ catch { return { defer: "Paseo unreachable" }; }
78
+ if (!agent || agent.archived) return { cancel: NOT_SENT.archived };
79
+ if (agent.status === "closed") return { cancel: NOT_SENT.closed };
80
+ if (item.state === "queued" && ["running", "initializing"].includes(agent.status)) return { defer: "waits for the agent's turn to end" };
81
+ return { target: { workspaceId: agent.workspaceId, recipients: [item.ref.agentId!] } };
82
+ },
83
+ // The task row mirrors the message: Sent once it left, Not sent (and why) if it was cancelled.
84
+ project: async (item: QueueItem) => {
85
+ const { workspaceId, obligationId, at } = item.ref;
86
+ if (!workspaceId || !obligationId || !at) return;
87
+ if (item.state === "sent") await this.mark(workspaceId, obligationId, at, t => { t.sentAt = item.envelope?.at ?? new Date(this.now()).toISOString(); });
88
+ else if (item.state === "cancelled") await this.mark(workspaceId, obligationId, at, t => { t.notSent = (item.reason ?? "it was cancelled").slice(0, 200); });
89
+ },
90
+ });
91
+ }
92
+ }
@@ -1,4 +1,6 @@
1
1
  import { execFile } from "node:child_process";
2
+ import { z } from "zod";
3
+ import type { AgentToolDefinition } from "@getpaseo/plugin/server";
2
4
  import { hookSource } from "./hook-source";
3
5
  import { hasHooks, isAcp } from "../shared/provider-support";
4
6
 
@@ -75,7 +77,23 @@ export function hooklessParts(env: Readonly<Record<string, string | undefined>>,
75
77
  return env.FOLLOW_UP_ROOT === "1" || tracked ? [...parts, "checks"] : parts;
76
78
  }
77
79
 
78
- type OpenRequest = { agentId?: string; provider: string; purpose: string; env: Record<string, string>; appendSystemPrompt?: string[] };
80
+ type OpenRequest = { agentId?: string; provider: string; purpose: string; env: Record<string, string>; appendSystemPrompt?: string[]; tools?: AgentToolDefinition[] };
81
+
82
+ /** The tool an ACP agent reads Follow-up's instructions through (Paseo doesn't pass a plugin's system prompt to ACP). */
83
+ export const INSTRUCTIONS_TOOL = "follow_session_instructions";
84
+ /**
85
+ * Follow-up's instructions as a tool: its description is in the agent's context on every turn (tool lists reach ACP
86
+ * agents through Paseo's MCP), and it tells the agent to read them first. The text is what the system prompt would
87
+ * have carried, fixed at session open like a system prompt.
88
+ */
89
+ export function instructionsTool(text: string): AgentToolDefinition {
90
+ return {
91
+ name: INSTRUCTIONS_TOOL,
92
+ description: "Follow-up's instructions for this session. Call this once at the start of the session and again after compaction, before any other follow_ tool, and follow what it returns.",
93
+ input: z.object({}).strict(),
94
+ execute: () => ({ text }),
95
+ };
96
+ }
79
97
  export type PromptDeps = {
80
98
  /** The host takes `appendSystemPrompt` from a session-open hook (Paseo 0.17+). */
81
99
  hostSupports(): Promise<boolean>;
@@ -102,12 +120,21 @@ export async function withSystemPrompt<R extends OpenRequest>(request: R, deps:
102
120
  if (request.purpose !== "interactive") return request;
103
121
  const native = request.env.FOLLOW_UP_TOOLS === "native";
104
122
  const hooked = hasHooks(request.provider);
105
- // An ACP agent never receives appendSystemPrompt (Paseo 0.17.4), so nothing is claimed as sent: no text, no env.
106
- if (!hooked && await (deps.acp?.(request.provider) ?? Promise.resolve(isAcp(request.provider))).catch(() => isAcp(request.provider))) return request;
123
+ // An ACP agent never receives appendSystemPrompt (Paseo 0.17.4): the same text goes in a tool it is told to read
124
+ // first (instructionsTool), and no env claims a system prompt it never got.
125
+ const acp = !hooked && await (deps.acp?.(request.provider) ?? Promise.resolve(isAcp(request.provider))).catch(() => isAcp(request.provider));
107
126
  // Without a hook, the system prompt is the only way Follow-up's text reaches the agent (an-agent-on-any-provider-gets-follow-up).
108
127
  const workspace = hooked || request.env.FOLLOW_UP_RECOVERY === "1" || !request.agentId || !deps.workspace ? null : await deps.workspace(request.agentId, native).catch(() => null);
109
128
  const wanted = hooked ? promptParts(request.env) : hooklessParts(request.env, !!workspace);
110
129
  if (!wanted.length && !workspace) return request;
130
+ if (acp) {
131
+ if (!Array.isArray(request.tools) || request.tools.some(t => t.name === INSTRUCTIONS_TOOL)) return request;
132
+ const bridge = await deps.bridge().catch(() => null);
133
+ if (!bridge) return request;
134
+ const { parts, text } = promptText(wanted, bridge, native);
135
+ if (!parts.length && !workspace) return request;
136
+ return { ...request, tools: [...request.tools, instructionsTool([...(workspace ? [workspace] : []), ...text].join("\n\n"))] };
137
+ }
111
138
  if (!(await deps.hostSupports().catch(() => false))) return request;
112
139
  if (hooked && !(await deps.providerSupports(request.provider).catch(() => false))) return request;
113
140
  const bridge = await deps.bridge().catch(() => null);
@@ -0,0 +1,130 @@
1
+ import { hookSource } from "./hook-source";
2
+ import { pickNudges, type DueEntry, type NudgeReceipt } from "../shared/task-due";
3
+ import { providerCaps } from "../shared/provider-support";
4
+ import { messageSender } from "../shared/message-sender";
5
+ import { startsTurn } from "./turn-timeline";
6
+
7
+ /**
8
+ * Turn-end checks for a provider without Follow-up's hook (an-agent-on-any-provider-gets-follow-up). Claude Code and
9
+ * Codex get them from the Stop hook (server/agent-hook.mjs); every other provider gets the same checks from Paseo's
10
+ * turn-end event, with the hook's own words: the sync reminder after a turn that changed something and didn't sync,
11
+ * the needs_you nudge, and the due tasks.
12
+ *
13
+ * The Stop hook blocks the stop; an event can't, so the checks go as one queued message (invariant 36) after the turn,
14
+ * and only when something is due: a quiet turn sends nothing. It never loops: the turn that message starts is never
15
+ * checked (one reply, like the hook's stop_hook_active), told from the turn's own prompt, so a worker restart between
16
+ * the message and its reply can't start a loop. The needs_you nudge, which a hook gives in-turn for free but costs a
17
+ * whole turn here, follows only a turn the developer started (their message, or their answer from a card); never a
18
+ * repair, a recovery, another agent's message, or a turn whose prompt the read didn't reach. It never wakes a dormant agent: it runs only on a turn that
19
+ * just ended, and the queue sends only to that loaded agent. Due tasks share the hook's receipt (at most 3 a turn end,
20
+ * each at most twice and once a day).
21
+ */
22
+
23
+ const literal = (name: string): string => {
24
+ const m = hookSource.match(new RegExp(`export const ${name} = (.+?);\\n`));
25
+ if (!m) throw new Error(`turn-end: the hook no longer exports ${name}`);
26
+ return JSON.parse(m[1]!) as string;
27
+ };
28
+ export const STOP_REASON = literal("stopReason");
29
+ export const NUDGE_REASON = literal("nudgeReason");
30
+ export const DUE_HEADER = literal("dueHeader");
31
+ const TOOL_NAMES = (() => { const m = hookSource.match(/export const TOOL_NAMES = (\[.+?\]);\n/); return m ? JSON.parse(m[1]!) as string[] : []; })();
32
+ const toolPattern = new RegExp(`(?<![\\w])(${TOOL_NAMES.join("|")})(?![\\w])`, "g");
33
+ /** Follow-up's tools under the names a native session has them (the hook's `named`). */
34
+ const named = (text: string) => text.replace(toolPattern, "follow_$1");
35
+ /** The first line of every turn-end message: how the agent, the inbox and the tests tell it apart. */
36
+ export const TURN_END_PREFIX = literal("turnEndPrefix");
37
+
38
+ export type TurnEndEntry = { role: "main" | "contributor" | "recovery"; workspaceId: string; due?: DueEntry[] };
39
+ export type TurnEndInput = {
40
+ provider: string;
41
+ /** scopes.json's entry for this agent, null when it isn't tracked. */
42
+ entry: TurnEndEntry | null;
43
+ /** The ended turn's timeline items (the read the worker already made), null when there was none. */
44
+ items: readonly unknown[] | null;
45
+ /** When this turn started, as the worker saw it; null when it didn't (a worker that started mid-turn). */
46
+ startedAt: number | null;
47
+ /** The workspace's last confirmed sync for this agent (sync_workspace), if any. */
48
+ syncedAt: number | null;
49
+ /** The agent's last needs_you, if any. */
50
+ needsYouAt: number | null;
51
+ /** The inbox and its nudge are on, and this agent has no permission prompt showing. */
52
+ nudge: boolean;
53
+ receipt: NudgeReceipt;
54
+ now: number;
55
+ };
56
+
57
+ /** A tool call that isn't Follow-up's own (a shell, an edit, a write…): the turn changed something worth syncing. */
58
+ function changedSomething(items: readonly unknown[] | null): boolean {
59
+ return (items ?? []).some(i => {
60
+ const item = i as { type?: string; name?: unknown };
61
+ if (item?.type !== "tool_call" || typeof item.name !== "string") return false;
62
+ return !/(^|[._/])follow_[a-z_]+$|^wait_|^(?:mcp__)?follow-up(?:__|[.:/])/.test(item.name);
63
+ });
64
+ }
65
+
66
+ /** Who started the turn, from its prompt (the first item that starts a turn in the read); null when it isn't there. */
67
+ export function turnPrompt(items: readonly unknown[] | null): "developer" | "turn-end" | "other" | null {
68
+ const first = (items ?? []).find(startsTurn) as { type?: string; text?: unknown } | undefined;
69
+ if (!first) return null;
70
+ if (first.type !== "user_message" || typeof first.text !== "string") return "other";
71
+ if (first.text.startsWith(TURN_END_PREFIX)) return "turn-end";
72
+ const sender = messageSender(first.text);
73
+ return sender.kind === "developer" || sender.kind === "follow-up" && sender.what === "answer" ? "developer" : "other";
74
+ }
75
+
76
+ /** What the turn end says, or null for nothing (the common case), and the due-task receipt to keep. Pure. */
77
+ export function turnEndCheck(i: TurnEndInput): { text: string | null; receipt: NudgeReceipt | null } {
78
+ if (providerCaps(i.provider).turnEnd !== "event" || !i.entry || i.entry.role === "recovery") return { text: null, receipt: null };
79
+ const prompt = turnPrompt(i.items);
80
+ // The reply to our own message is never checked (the loop guard that survives a restart).
81
+ if (prompt === "turn-end") return { text: null, receipt: null };
82
+ const since = i.startedAt ?? i.now;
83
+ const sync = changedSomething(i.items) && !(i.syncedAt !== null && i.syncedAt >= since);
84
+ const nudge = i.entry.role === "main" && i.nudge && prompt === "developer" && !(i.needsYouAt !== null && i.needsYouAt >= since);
85
+ const picked = i.entry.due?.length ? pickNudges(i.entry.due, i.receipt, i.now) : { lines: [], receipt: i.receipt };
86
+ if (!sync && !nudge && !picked.lines.length) return { text: null, receipt: null };
87
+ const parts = [
88
+ picked.lines.length ? named(DUE_HEADER) + "\n" + picked.lines.map(l => `- ${l}`).join("\n") : null,
89
+ sync ? `${STOP_REASON} This is metadata bookkeeping only; do not start queued repairs or recovery. Call ${named("sync_workspace")} with a short summary.` : null,
90
+ nudge ? named(NUDGE_REASON) : null,
91
+ ].filter(Boolean);
92
+ return { text: `${TURN_END_PREFIX} your turn ended with this still open. Handle it, then stop without repeating your reply.\n\n${parts.join("\n\n")}`, receipt: picked.lines.length ? picked.receipt : null };
93
+ }
94
+
95
+ export type TurnEndDeps = {
96
+ input(agentId: string, provider: string, items: readonly unknown[] | null, startedAt: number | null): Promise<Omit<TurnEndInput, "provider" | "items" | "startedAt" | "now"> | null>;
97
+ saveReceipt(workspaceId: string, receipt: NudgeReceipt): Promise<void>;
98
+ /** Queues the message for this agent (message-queue.ts); returns once it is saved. */
99
+ send(agentId: string, workspaceId: string, text: string, turnId: string | null): Promise<void>;
100
+ now?: () => number;
101
+ };
102
+
103
+ /** The worker's side: when turns start, which turn a check's own message started, and the send. */
104
+ export class TurnEnd {
105
+ private started = new Map<string, number>();
106
+ /** Agents whose next turn was started by a turn-end message: that turn is never checked. */
107
+ private answering = new Set<string>();
108
+ constructor(private d: TurnEndDeps) {}
109
+
110
+ turnStarted(agentId: string): void { this.started.set(agentId, (this.d.now ?? Date.now)()); }
111
+
112
+ async turnEnded(agent: { id: string; provider: string; parentAgentId: string | null }, outcome: { kind: string }, turnId: string | null, items: readonly unknown[] | null): Promise<string | null> {
113
+ const startedAt = this.started.get(agent.id) ?? null;
114
+ this.started.delete(agent.id);
115
+ if (providerCaps(agent.provider).turnEnd !== "event" || agent.parentAgentId) return null;
116
+ // The reply to our own message: never checked, so a check can't start a loop.
117
+ if (this.answering.delete(agent.id)) return null;
118
+ if (outcome.kind !== "completed") return null;
119
+ const base = await this.d.input(agent.id, agent.provider, items, startedAt);
120
+ if (!base?.entry) return null;
121
+ const now = (this.d.now ?? Date.now)();
122
+ const { text, receipt } = turnEndCheck({ ...base, provider: agent.provider, items, startedAt, now });
123
+ if (!text) return null;
124
+ if (receipt) await this.d.saveReceipt(base.entry.workspaceId, receipt).catch(() => undefined);
125
+ this.answering.add(agent.id);
126
+ try { await this.d.send(agent.id, base.entry.workspaceId, text, turnId); }
127
+ catch { this.answering.delete(agent.id); return null; }
128
+ return text;
129
+ }
130
+ }
@@ -34,6 +34,12 @@ const metadataSchema = z.object({ version: z.literal(1), id: z.string().uuid(),
34
34
  const resultSchema = z.object({ exitCode: z.number().int().min(0).max(255), timedOut: z.literal(true).optional() }).strict();
35
35
 
36
36
  export interface Owner { id: string; cwd: string }
37
+ /**
38
+ * How the agent's shell runs the job (shared/provider-support.ts providerCaps `wait`): Claude Code backgrounds it
39
+ * itself (native Bash run_in_background); any other provider runs a command that detaches itself and returns at once,
40
+ * its output in the job's `output.log`.
41
+ */
42
+ export type WaitShell = "background-bash" | "detached";
37
43
  /** `timedOut`: the runner stopped the command at its time limit (exit 124). */
38
44
  export interface JobStatus { jobId: string; status: "prepared" | "running" | "completed" | "failed"; description: string; createdAt: string; exitCode?: number; timedOut?: true }
39
45
  export type WaitResult = JobStatus & { outcome: "completed" | "failed" | "still_pending" | "new_message"; waitedSeconds: number; instruction: string };
@@ -68,7 +74,7 @@ export class WaitJobs {
68
74
  }
69
75
 
70
76
  /** Writes the job record and returns the exact command to run. Runs nothing. */
71
- async prepare(owner: Owner, raw: z.input<typeof prepareInput>) {
77
+ async prepare(owner: Owner, raw: z.input<typeof prepareInput>, shell: WaitShell = "background-bash") {
72
78
  const input = prepareInput.parse(raw);
73
79
  if (this.closed) throw new Error("Wait tools are stopping");
74
80
  const id = randomUUID();
@@ -82,9 +88,19 @@ export class WaitJobs {
82
88
  await writeFile(join(path, "job.json"), JSON.stringify(record), { mode: 0o600, flag: "wx" });
83
89
  const limit = input.timeoutSeconds ?? DEFAULT_JOB_TIMEOUT_SECONDS;
84
90
  await writeFile(join(path, "timeout"), String(limit), { mode: 0o600, flag: "wx" });
91
+ const run = ["sh", runner, path, owner.cwd, input.command].map(quote).join(" ");
92
+ if (shell === "detached") {
93
+ const output = join(path, "output.log");
94
+ return {
95
+ jobId: id,
96
+ bashCommand: `nohup ${run} > ${quote(output)} 2>&1 < /dev/null &`,
97
+ outputPath: output,
98
+ instruction: "Run bashCommand with your shell tool exactly as given: it starts the job in the background and returns at once. Then call wait_for_job. Its output is in outputPath. Preparing this job has not executed the command.",
99
+ };
100
+ }
85
101
  return {
86
102
  jobId: id,
87
- bashCommand: ["sh", runner, path, owner.cwd, input.command].map(quote).join(" "),
103
+ bashCommand: run,
88
104
  instruction: "Run bashCommand using native Bash with run_in_background=true. Then call wait_for_job. Preparing this job has not executed the command.",
89
105
  };
90
106
  }