paseo-follow-up 2.5.0 → 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.
@@ -0,0 +1,69 @@
1
+ import { useEffect, useState } from "react";
2
+ import { View } from "react-native";
3
+ import { Icon } from "@getpaseo/plugin/client/ui";
4
+ import { Pressable, Text } from "./text";
5
+ import { Button, text, type Theme } from "./kit";
6
+ import { finishSetupLine, setupOwner, setupPopup } from "../shared/setup-popup";
7
+ import { Setup, TITLES, useOnboarding, type SetupDeps } from "./onboarding";
8
+ import { ReleaseNotesSheet, useReleaseNotes } from "./release-notes";
9
+ import { reopenSetup, resetSetupSession, setupClosed, setupSession, useSetupSession } from "./setup-ui";
10
+ import { useViewVersion } from "./view-store";
11
+
12
+ export { resetSetupSession };
13
+
14
+ /**
15
+ * Setup's popup (setup-is-one-popup) on whichever Follow-up surface mounts first: Home, the workspace panel or the
16
+ * sidebar item, like What's new. It opens by itself while setup is under way (a first install, or Set up again) and
17
+ * Close hasn't put it away on this device; the done page stays up after Finish. The rules are shared/setup-popup.ts;
18
+ * the steps and their moves are client/onboarding.tsx `Setup`, the same set-onboarding calls agents' tools make.
19
+ */
20
+ export function SetupGate({ surface, theme, compact, deps = {} }: { surface: string; theme: Theme; compact: boolean; deps?: Partial<SetupDeps> }) {
21
+ const onboarding = useOnboarding();
22
+ const session = useSetupSession();
23
+ useViewVersion();
24
+ const closed = setupClosed();
25
+ const view = onboarding.data;
26
+ const decision = setupPopup({ view, closed, done: session.done });
27
+ const notes = useReleaseNotes().data;
28
+ const [notesOpen, setNotesOpen] = useState(false);
29
+ // Setup over (finished, skipped, or by an agent): forget Close, so the next Set up again opens the popup by itself.
30
+ useEffect(() => { if (view && !view.show && !session.done) reopenSetup(); }, [view, session.done]);
31
+ useEffect(() => {
32
+ if (decision === "open" && session.owner == null) setupSession.set({ owner: setupOwner(session.owner, surface) });
33
+ }, [decision, session.owner, surface]);
34
+ useEffect(() => () => { if (setupSession.get().owner === surface) setupSession.set({ owner: null }); }, [surface]);
35
+ if (decision !== "open" || session.owner !== surface || !view) return null;
36
+ const full: SetupDeps = {
37
+ openSettings: deps.openSettings ?? (() => undefined), openHome: deps.openHome, name: notes?.name,
38
+ whatsNew: notes ? { version: notes.version, open: () => setNotesOpen(true) } : null,
39
+ };
40
+ return <>
41
+ <Setup theme={theme} compact={compact} view={view} deps={full} />
42
+ {notesOpen && <ReleaseNotesSheet theme={theme} compact={compact} onClose={() => setNotesOpen(false)} />}
43
+ </>;
44
+ }
45
+
46
+ /** Home's one line while Close has put setup away: it names the step setup stopped on and opens the popup there. */
47
+ export function FinishSetupLine({ theme, compact }: { theme: Theme; compact: boolean }) {
48
+ const c = theme.colors; const t = text(c, compact);
49
+ const view = useOnboarding().data;
50
+ useViewVersion();
51
+ const line = finishSetupLine(view, setupClosed());
52
+ if (!line) return null;
53
+ // Where setup stopped, by the step's own title, so the line says what is left.
54
+ const meta = line.step === "intro" ? "Setup hasn't started yet." : `Next: ${TITLES[line.step]}`;
55
+ if (compact) return <Pressable accessibilityRole="button" accessibilityLabel={line.label} accessibilityHint={meta} onPress={reopenSetup}
56
+ style={state => ({ flexDirection: "row", alignItems: "center", gap: 10, minHeight: 56, marginHorizontal: 16, paddingHorizontal: 14, paddingVertical: 10, borderRadius: 10, borderWidth: 1, borderColor: c.border, backgroundColor: state.pressed ? c.surface2 : c.surface1 })}>
57
+ <Icon name="ListChecks" size={16} color={c.foregroundMuted} />
58
+ <View style={{ flex: 1, minWidth: 0, gap: 1 }}>
59
+ <Text numberOfLines={1} style={t.label}>{line.label}</Text>
60
+ <Text numberOfLines={1} style={t.meta}>{meta}</Text>
61
+ </View>
62
+ <Icon name="ChevronRight" size={16} color={c.foregroundMuted} />
63
+ </Pressable>;
64
+ return <View style={{ flexDirection: "row", alignItems: "center", gap: 10, marginHorizontal: 16, paddingLeft: 12, paddingRight: 4, paddingVertical: 4, borderRadius: 8, backgroundColor: c.surface1 }}>
65
+ <Icon name="ListChecks" size={14} color={c.foregroundMuted} />
66
+ <Text style={[t.meta, { flex: 1 }]}>{meta}</Text>
67
+ <Button theme={theme} kind="ghost" title={line.label} onPress={reopenSetup} />
68
+ </View>;
69
+ }
@@ -0,0 +1,27 @@
1
+ import { useSyncExternalStore } from "react";
2
+ import { deviceStorage } from "../shared/settings-nav";
3
+ import { SETUP_CLOSED_KEY } from "../shared/setup-popup";
4
+
5
+ /**
6
+ * Setup's popup in this app session (setup-is-one-popup, client/setup-gate.tsx): which Follow-up surface draws it
7
+ * (`owner`, the first to want it) and whether the done page is up (`done`: after Finish the server already says setup
8
+ * is over). Close is the device's, not the session's: SETUP_CLOSED_KEY in the device's view state, so a put-away popup
9
+ * stays away after a reload until Home's Finish setup line opens it.
10
+ */
11
+ type Session = { owner: string | null; done: boolean };
12
+ let state: Session = { owner: null, done: false };
13
+ const listeners = new Set<() => void>();
14
+ export const setupSession = {
15
+ get: () => state,
16
+ set(next: Partial<Session>) { state = { ...state, ...next }; listeners.forEach(l => l()); },
17
+ subscribe(l: () => void) { listeners.add(l); return () => { listeners.delete(l); }; },
18
+ };
19
+ export const useSetupSession = () => useSyncExternalStore(setupSession.subscribe, setupSession.get, setupSession.get);
20
+ /** Tests and a fresh app session: nobody draws the popup, no done page. */
21
+ export const resetSetupSession = () => setupSession.set({ owner: null, done: false });
22
+
23
+ export const setupClosed = () => deviceStorage.get(SETUP_CLOSED_KEY) === "1";
24
+ /** Close (X): put the popup away on this device. The server hears nothing; setup stays on its step. */
25
+ export const closeSetup = () => deviceStorage.set(SETUP_CLOSED_KEY, "1");
26
+ /** Finish setup, Set up again, or setup ending: the next time setup is under way, the popup opens by itself. */
27
+ export const reopenSetup = () => { if (deviceStorage.get(SETUP_CLOSED_KEY) === "1") deviceStorage.set(SETUP_CLOSED_KEY, ""); };
package/index.client.tsx CHANGED
@@ -114,7 +114,7 @@ export default function contribute(host: PluginClientContext) {
114
114
  let nextToken = 0;
115
115
  const openNext = (from: string | null) => client.openScreen({ screenId: OVERVIEW, params: { next: String(++nextToken), ...(from ? { from } : {}) } });
116
116
 
117
- const removeDisplay = contributeDisplay(client, { id: "follow-up-overview", title: "Follow-up", Component: sidebarItem(sources, OVERVIEW) });
117
+ const removeDisplay = contributeDisplay(client, { id: "follow-up-overview", title: "Follow-up", Component: sidebarItem(sources, OVERVIEW, { openSettings: category => openSettings(category as SettingsCategory) }) });
118
118
  const briefDeps: BriefDeps = {
119
119
  signOff: agentId => void inbox.signOff([agentId]), openNext,
120
120
  openAgent: agentId => client.openScreen({ screenId: OVERVIEW, params: { next: String(++nextToken), open: agentId } }),
package/index.server.ts CHANGED
@@ -70,6 +70,7 @@ import { Wait, waitStatus, type WaitPaseoConfig } from "./server/wait";
70
70
  import { removeGlobalRegistrations } from "./server/mcp-registrations";
71
71
  import { TrustBypass } from "./server/trust-bypass";
72
72
  import { scopes } from "./server/scopes";
73
+ import { TurnEnd } from "./server/turn-end";
73
74
  import { updateObligation } from "./server/obligations";
74
75
  import { Inbox, INBOX_WRITE_MS, type GuardPause } from "./server/inbox";
75
76
  import { daemonDirectory, guardPath } from "./server/inbox-directory";
@@ -428,6 +429,31 @@ export default function contribute(server: PluginServerContext) {
428
429
  queue.enqueue({ id: `message:${agentId}:${messageId}`, kind: "message", key, ref: { agentId }, messageId, text, ...(by ? { by } : {}), ...(images.length ? { images } : {}), priority: "now", state: "queued" });
429
430
  };
430
431
  onDaemonReconnect(() => queue.reconnected());
432
+ // Turn-end checks for a provider without Follow-up's hook (server/turn-end.ts): the hook's checks, as one queued message.
433
+ const turnEnd = new TurnEnd({
434
+ input: async (agentId, _provider, _items, _startedAt) => {
435
+ const w = agentTrackedWorkspace(await store.snapshot(), agentId);
436
+ if (!w) return null;
437
+ // Only this workspace's scopes (a-nudge-costs-its-workspace), never the whole state's.
438
+ const entry = scopes({ workspaces: [w] } as unknown as Parameters<typeof scopes>[0])[agentId] ?? null;
439
+ const json = (name: string) => readFile(join(directory, "hook-state", name), "utf8").then(t => JSON.parse(t) as Record<string, unknown>, () => null);
440
+ const synced = await json(`sync-${agentId}.json`);
441
+ const called = await json(`needs-you-${agentId}.json`) as NeedsYouRecord | null;
442
+ const receipt = /^[\w-]+$/.test(w.id) ? await json(`task-nudges-${w.id}.json`) : null;
443
+ const settings = await inboxSettings();
444
+ return {
445
+ entry, receipt: (receipt ?? {}) as never,
446
+ syncedAt: synced && synced.workspaceId === w.id && typeof synced.at === "number" ? synced.at : null,
447
+ needsYouAt: typeof called?.at === "number" ? called.at : null,
448
+ nudge: settings.enable_inbox === true && settings.enable_brief_nudge === true && !inbox.pendingPermissions().includes(agentId),
449
+ };
450
+ },
451
+ saveReceipt: async (workspaceId, receipt) => { if (/^[\w-]+$/.test(workspaceId)) await writeFile(join(directory, "hook-state", `task-nudges-${workspaceId}.json`), JSON.stringify(receipt), { mode: 0o600 }); },
452
+ send: async (agentId, workspaceId, text, turnId) => {
453
+ const messageId = randomUUID();
454
+ queue.enqueue({ id: `turn-end:${agentId}:${turnId ?? messageId}`, kind: "message", key: workspaceId, ref: { agentId }, messageId, text, priority: "now", state: "queued" });
455
+ },
456
+ });
431
457
  /**
432
458
  * Stores a field's pasted images, runs the action with their refs, and removes any the action didn't queue (a
433
459
  * repeated answer, an ask already open, a refusal): only a queue item keeps an image file.
@@ -2113,6 +2139,7 @@ export default function contribute(server: PluginServerContext) {
2113
2139
  // The shared directory learns from events instead of polling Paseo (see DaemonDirectory). Registered first so the
2114
2140
  // handlers below read the patched rows.
2115
2141
  server.on("agent.turn_started", async event => gateway.directory.turnStarted(event.agent, event.turnId)),
2142
+ server.on("agent.turn_started", async event => turnEnd.turnStarted(event.agent.id)),
2116
2143
  server.on("agent.turn_ended", async event => gateway.directory.turnEnded(event.agent, event.outcome)),
2117
2144
  server.on("agent.turn_ended", async event => contextRequests.turnEnded(event.agent.id)),
2118
2145
  server.on("agent.permission_requested", async event => gateway.directory.permissionRequested(event.agent.id, event.request as { id?: string })),
@@ -2219,6 +2246,8 @@ export default function contribute(server: PluginServerContext) {
2219
2246
  const compaction = event.outcome.kind === "canceled" && await compactionJustDelivered(event.agent.id, Date.parse(interruption!.at)).catch(() => false);
2220
2247
  const nudged = await turnEnded(store, event.agent.id, event.outcome, event.turnId ?? null, items, { interruption, guarded, newerTurn, compaction });
2221
2248
  if (nudged) void engine.nudge(nudged);
2249
+ // A provider without the hook: the Stop hook's checks, from this same read (an-agent-on-any-provider-gets-follow-up).
2250
+ await turnEnd.turnEnded(event.agent, event.outcome, event.turnId ?? null, items).catch(() => undefined);
2222
2251
  }),
2223
2252
  server.on("workspace.archived", async event => { await ready; if (!loadError && !stopped) await store.mutate(state => { const w = state.workspaces.find(w => w.id === event.workspace.id); if (w) w.archived = true; }); }),
2224
2253
  ];
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "paseo-follow-up",
3
3
  "private": false,
4
- "version": "2.5.0",
4
+ "version": "2.6.0-beta.1",
5
5
  "description": "Every agent, one inbox. Follow-up brings what all your coding agents need from you into one ranked list, and follows their work through merge, deploy and after.",
6
6
  "type": "module",
7
7
  "files": [
@@ -35,16 +35,18 @@ export function toolsDetached(isNative, current, mine) { return isNative && !!cu
35
35
  export const detachedNotice = "Follow-up was updated while this session was open, so its follow_* tools are detached and fail with \"Tool not found\" until this session reopens (Paseo reopens it before your next prompt). Until then use the bridge, which runs the same tools with their unprefixed names: node \"$FOLLOW_UP_CLI\" call <tool> '<json>' --compact (for example sync_workspace or needs_you). Do not mention this to the developer.";
36
36
  const quietRevision = 1;
37
37
  const quietInstruction = "Do routine bookkeeping silently. Do not announce tracker calls, say you updated/synced the sidebar, recap panel state, or add plugin-status commentary/final paragraphs. Put receipts and evidence in the tools. User-facing messages should cover the actual work outcome, or a decision/blocker requiring the developer; answer sidebar status only when explicitly asked. If this continuation is bookkeeping only, use the tools and finish without another recap or repeating your previous answer.";
38
- const stopReason = "Silently complete this workspace's sidebar bookkeeping before finishing.";
38
+ export const stopReason = "Silently complete this workspace's sidebar bookkeeping before finishing.";
39
39
  // Kept identical to NEEDS_YOU_NUDGE in shared/brief.ts (a test checks it).
40
- const 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.";
40
+ export const 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.";
41
41
 
42
42
  /**
43
43
  * R2: whether to nudge a Claude Code root agent that ended its turn without needs_you. Pure, so every skip is testable.
44
44
  * At most once per turn: Claude's stop_hook_active and our own per-turn `stopped` marker both end it.
45
45
  */
46
46
  /** due-by-fact: the line above the due tasks a turn end names. */
47
- const dueHeader = "Follow-up: these tasks are due. For each, do it and close it with update_obligation (status=done with evidence), or keep it with recheck=\"YYYY-MM-DD\" and why in evidence.";
47
+ /** The first line of the turn-end message a provider without this hook gets instead (server/turn-end.ts). */
48
+ export const turnEndPrefix = "Follow-up turn-end check:";
49
+ export const dueHeader = "Follow-up: these tasks are due. For each, do it and close it with update_obligation (status=done with evidence), or keep it with recheck=\"YYYY-MM-DD\" and why in evidence.";
48
50
  /**
49
51
  * The due tasks to name at this turn end: due entries (from scopes.json) whose time passed, not yet named twice for
50
52
  * this fact and revision and not within a day, oldest first, at most 3; and the receipt counting them. A copy of
package/server/ai-jobs.ts CHANGED
@@ -5,6 +5,7 @@ import { basename, dirname, join } from "node:path";
5
5
  import type { z } from "zod";
6
6
  import { guardFor, refusedCalls, type ToolGrant } from "./job-guard";
7
7
  import { guardedProvider } from "../shared/agent-settings";
8
+ import { GUARDED_PHRASE } from "../shared/provider-support";
8
9
 
9
10
  /**
10
11
  * Small bounded model jobs: a prompt in, validated JSON out. Shared by Summaries and the Overseer ranker.
@@ -25,7 +26,7 @@ export type JobSpec<T> = {
25
26
  prompt: string;
26
27
  schema: z.ZodType<T>;
27
28
  system?: string;
28
- /** Any Paseo provider id; "claude" (default) and "codex" run through their headless CLI, the rest as a hidden agent. */
29
+ /** Any Paseo provider id; "claude" (default), "codex" and "pi" run through their headless CLI, the rest as a hidden agent. */
29
30
  provider?: string;
30
31
  /** The provider's model: "haiku" (Claude's default here), "sonnet", "gpt-6-luna"… */
31
32
  model?: string;
@@ -40,7 +41,7 @@ export type JobSpec<T> = {
40
41
  runner?: Runner;
41
42
  /**
42
43
  * The prompt carries words someone else wrote (an issue, a thread, a chat, a plan, mail). Such a job runs only on a
43
- * provider Follow-up can take every tool away from (`guardedProvider`); on any other it is refused before it starts
44
+ * provider Follow-up can take every tool away from (`guardedProvider`, shared/provider-support.ts); on any other it is refused before it starts
44
45
  * (a-job-that-reads-outside-content-can-only-read).
45
46
  */
46
47
  outside?: boolean;
@@ -87,7 +88,7 @@ export class AiJobs {
87
88
  if (this.stopped) return done({ ok: false, reason: "stopped", error: "Follow-up is stopping.", costUsd: null, durationMs: 0 });
88
89
  const provider = spec.provider ?? "claude";
89
90
  // Someone else's words never reach a model that has tools: refused before any runner, the tests' included.
90
- if (spec.outside && !guardedProvider(provider)) return done({ ok: false, reason: "unguarded", error: `This job reads words other people wrote, and Follow-up can't take ${provider}'s tools away. Pick Claude or Codex in Settings → Agents.`, costUsd: null, durationMs: 0 });
91
+ if (spec.outside && !guardedProvider(provider)) return done({ ok: false, reason: "unguarded", error: `This job reads words other people wrote, and Follow-up can't take ${provider}'s tools away. Pick ${GUARDED_PHRASE} in Settings → Agents.`, costUsd: null, durationMs: 0 });
91
92
  // An injected runner (tests) always wins, so a job can never reach the real CLI from a test; then the job's own.
92
93
  const runner = this.opts.runner ?? spec.runner ?? this.opts.runners?.[provider] ?? defaultRunner(provider) ?? this.opts.generic;
93
94
  if (!runner) return done({ ok: false, reason: "failed", error: `${provider} can't run one-shot jobs here; pick another provider in Settings → Agents.`, costUsd: null, durationMs: 0 });
@@ -185,10 +186,30 @@ export function parseCodexEvents(stdout: string): RunOutput {
185
186
  }
186
187
  const codexError = (raw: string) => { try { const j = JSON.parse(raw); return String(j?.error?.message ?? raw).slice(0, 200); } catch { return raw.slice(0, 200); } };
187
188
 
188
- /** Claude's own default for jobs; Codex uses its CLI default when no model is set. */
189
+ /**
190
+ * `pi -p` with no tools at all and nothing loaded from the developer's setup: no extensions, skills, prompt templates
191
+ * or context files, no saved session (flags from Pi's README). The prompt goes on stdin, which print mode merges into
192
+ * the message; the reply is the printed text. Pi reports no cost.
193
+ */
194
+ export function piArgs(input: Pick<RunInput, "model" | "system"> & { thinking?: string | null }): string[] {
195
+ return ["-p", "--no-tools", "--no-extensions", "--no-skills", "--no-prompt-templates", "--no-context-files", "--no-session",
196
+ ...(input.model ? ["--model", input.model] : []), ...(input.thinking ? ["--thinking", input.thinking] : []), "--system-prompt", input.system,
197
+ "Answer the material below as the system prompt says."];
198
+ }
199
+ export function parsePiOutput(stdout: string): RunOutput {
200
+ if (!stdout.trim()) throw new Error("Pi returned no reply.");
201
+ return { text: stdout, costUsd: null, inputTokens: null, outputTokens: null };
202
+ }
203
+ /** Spawns `pi` the same way as the other CLIs: an argument array, the prompt on stdin, from the temp dir. */
204
+ export function piRunner(command = "pi"): Runner {
205
+ return input => spawnJob(command, piArgs(input), input.prompt, parsePiOutput, input, childEnv({}, {}));
206
+ }
207
+
208
+ /** Claude's own default for jobs; Codex and Pi use their CLI default when no model is set. */
189
209
  export const DEFAULT_MODEL: Record<string, string> = { claude: "haiku" };
210
+ /** The providers whose own CLI runs a job with no tools (shared/provider-support.ts CLI_GUARD_PROVIDERS). */
190
211
  export function defaultRunner(provider: string): Runner | null {
191
- return provider === "claude" ? claudeRunner() : provider === "codex" ? codexRunner() : null;
212
+ return provider === "claude" ? claudeRunner() : provider === "codex" ? codexRunner() : provider === "pi" ? piRunner() : null;
192
213
  }
193
214
 
194
215
  /** The envelope of a one-turn reply is a few KB; anything near this is runaway output. */
@@ -37,16 +37,18 @@ export const hookSource: string = [
37
37
  "export const detachedNotice = \"Follow-up was updated while this session was open, so its follow_* tools are detached and fail with \\\"Tool not found\\\" until this session reopens (Paseo reopens it before your next prompt). Until then use the bridge, which runs the same tools with their unprefixed names: node \\\"$FOLLOW_UP_CLI\\\" call <tool> '<json>' --compact (for example sync_workspace or needs_you). Do not mention this to the developer.\";",
38
38
  "const quietRevision = 1;",
39
39
  "const quietInstruction = \"Do routine bookkeeping silently. Do not announce tracker calls, say you updated/synced the sidebar, recap panel state, or add plugin-status commentary/final paragraphs. Put receipts and evidence in the tools. User-facing messages should cover the actual work outcome, or a decision/blocker requiring the developer; answer sidebar status only when explicitly asked. If this continuation is bookkeeping only, use the tools and finish without another recap or repeating your previous answer.\";",
40
- "const stopReason = \"Silently complete this workspace's sidebar bookkeeping before finishing.\";",
40
+ "export const stopReason = \"Silently complete this workspace's sidebar bookkeeping before finishing.\";",
41
41
  "// Kept identical to NEEDS_YOU_NUDGE in shared/brief.ts (a test checks it).",
42
- "const 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.\";",
42
+ "export const 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.\";",
43
43
  "",
44
44
  "/**",
45
45
  " * R2: whether to nudge a Claude Code root agent that ended its turn without needs_you. Pure, so every skip is testable.",
46
46
  " * At most once per turn: Claude's stop_hook_active and our own per-turn `stopped` marker both end it.",
47
47
  " */",
48
48
  "/** due-by-fact: the line above the due tasks a turn end names. */",
49
- "const dueHeader = \"Follow-up: these tasks are due. For each, do it and close it with update_obligation (status=done with evidence), or keep it with recheck=\\\"YYYY-MM-DD\\\" and why in evidence.\";",
49
+ "/** The first line of the turn-end message a provider without this hook gets instead (server/turn-end.ts). */",
50
+ "export const turnEndPrefix = \"Follow-up turn-end check:\";",
51
+ "export const dueHeader = \"Follow-up: these tasks are due. For each, do it and close it with update_obligation (status=done with evidence), or keep it with recheck=\\\"YYYY-MM-DD\\\" and why in evidence.\";",
50
52
  "/**",
51
53
  " * The due tasks to name at this turn end: due entries (from scopes.json) whose time passed, not yet named twice for",
52
54
  " * this fact and revision and not within a day, oldest first, at most 3; and the receipt counting them. A copy of",
@@ -4,7 +4,7 @@ import type { Runner, RunInput } from "./ai-jobs";
4
4
 
5
5
  /**
6
6
  * One-shot jobs on any Paseo provider: the job runs as a short-lived agent in a background workspace, so it never shows
7
- * in the developer's workspace or agent lists, and is archived as soon as it answers. Claude and Codex keep their
7
+ * in the developer's workspace or agent lists, and is archived as soon as it answers. Claude, Codex and Pi keep their
8
8
  * headless CLI fast path (ai-jobs.ts); this is for every other provider.
9
9
  *
10
10
  * Paseo 0.15.2 refuses `internal` agents from clients ("create a background workspace instead"), so a background
@@ -33,6 +33,17 @@ export type JobAgentOptions = {
33
33
  directory: string;
34
34
  };
35
35
 
36
+ /**
37
+ * A job agent gets no tools wherever its provider can be told so (shared/provider-support.ts SESSION_GUARD_PROVIDERS):
38
+ * OpenCode takes a session permission rule, and Paseo turns `permission: "deny"` into `*` denied for every tool, its
39
+ * own MCP tools included, before any prompt; Auto Accept stays off (Paseo turns it on for an unattended agent
40
+ * otherwise). A job never needs a tool, so every job there is locked, not only one that reads other people's words.
41
+ * Belt and braces: a job that still asks for a permission fails and is archived (status "permission").
42
+ */
43
+ export function lockedConfig(provider: string): Record<string, unknown> {
44
+ return provider === "opencode" ? { providerOptions: { permission: "deny", auto_accept: false } } : {};
45
+ }
46
+
36
47
  /** The provider string Paseo's agent config takes: "opencode/qwen3-coder", or the provider alone for its default model. */
37
48
  export const providerModel = (provider: string, model: string) => model ? `${provider}/${model}` : provider;
38
49
 
@@ -54,7 +65,7 @@ export function jobAgentRunner(opts: JobAgentOptions): Runner {
54
65
  };
55
66
  const create = async (paseo: JobPaseo, input: RunInput) => {
56
67
  const options = {
57
- config: { provider: providerModel(input.provider, input.model), systemPrompt: input.system, ...(input.thinking ? { thinkingOptionId: input.thinking } : {}) },
68
+ config: { provider: providerModel(input.provider, input.model), systemPrompt: input.system, ...(input.thinking ? { thinkingOptionId: input.thinking } : {}), ...lockedConfig(input.provider) },
58
69
  title: `${JOBS_TITLE}: one-shot`, labels: { [JOB_LABEL]: "1" }, prompt: input.prompt, autoArchive: true,
59
70
  };
60
71
  // A saved workspace can be archived or gone (a fresh Paseo home): make a new one once, then give up.
@@ -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
@@ -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).
@@ -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
  }