paseo-follow-up 1.4.0-beta.25 → 1.4.0-beta.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/README.md +1 -1
- package/client/chat.tsx +5 -3
- package/client/panel.tsx +1 -0
- package/index.server.ts +4 -4
- package/package.json +1 -1
- package/server/agent-actions.ts +1 -1
- package/server/deployments.ts +27 -4
- package/server/discovery.ts +4 -4
- package/server/engine.ts +50 -12
- package/server/exclusions.ts +1 -1
- package/server/mcp-source.ts +1 -1
- package/server/mcp.mjs +2 -2
- package/server/pr-actions.ts +1 -1
- package/server/tasks.ts +4 -3
- package/shared/chat.ts +13 -5
- package/shared/contracts.ts +1 -1
- package/shared/follow-up.ts +22 -3
- package/shared/model.ts +55 -18
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,12 @@
|
|
|
2
2
|
|
|
3
3
|
What changed in each version of Follow-up, newest first. Follow-up shows these in "What's new" after an update, and in full from Home's last line.
|
|
4
4
|
|
|
5
|
+
## 1.4.0-beta.26 (2026-11-10)
|
|
6
|
+
|
|
7
|
+
- A finished workspace no longer stalls short of Done when Follow-up can't check what production serves. Done goes through with a "Deploy not confirmed by Follow-up" note.
|
|
8
|
+
- A deploy Follow-up has seen stays counted until a rollback. If the agent declares Done while a rollout is still going, Follow-up records Done when it lands.
|
|
9
|
+
- The chat shows "Workspace done" only when Follow-up accepted it, and declaring Done twice adds no second card.
|
|
10
|
+
|
|
5
11
|
## 1.4.0-beta.25 (2026-11-10)
|
|
6
12
|
|
|
7
13
|
- A question an agent asks again no longer shows up twice in Needs you. Agents get the open question back, and existing duplicates close on update.
|
package/README.md
CHANGED
|
@@ -221,7 +221,7 @@ This replaces the separate **Wait** plugin (`paseo-wait`). While that plugin is
|
|
|
221
221
|
Install the beta:
|
|
222
222
|
|
|
223
223
|
```sh
|
|
224
|
-
paseo plugin update follow-through --version 1.4.0-beta.
|
|
224
|
+
paseo plugin update follow-through --version 1.4.0-beta.26
|
|
225
225
|
# or, for a fresh install:
|
|
226
226
|
paseo plugin install npm:paseo-follow-up@beta
|
|
227
227
|
```
|
package/client/chat.tsx
CHANGED
|
@@ -30,7 +30,7 @@ function ToolRowView({ item, theme }: PluginTimelineItemProps<ToolRow>) {
|
|
|
30
30
|
const row = item.data;
|
|
31
31
|
const [expanded, setExpanded] = useState(false);
|
|
32
32
|
const [hovered, setHovered] = useState(false);
|
|
33
|
-
if (row.done) return <DoneCard summary={row.done.summary} theme={theme} />;
|
|
33
|
+
if (row.done) return <DoneCard summary={row.done.summary} unconfirmed={row.done.unconfirmed ?? []} theme={theme} />;
|
|
34
34
|
const color = row.tone === "danger" ? c.statusDanger : row.tone === "warning" ? c.statusWarning : row.tone === "success" ? c.statusSuccess : c.foregroundMuted;
|
|
35
35
|
const openable = row.more !== null;
|
|
36
36
|
const active = openable && (hovered || expanded);
|
|
@@ -50,7 +50,7 @@ function ToolRowView({ item, theme }: PluginTimelineItemProps<ToolRow>) {
|
|
|
50
50
|
}
|
|
51
51
|
|
|
52
52
|
/** The agent declared the workspace done: the one row in the chat that is allowed to be a little proud. */
|
|
53
|
-
function DoneCard({ summary, theme }: { summary: string; theme: PluginTimelineItemProps["theme"] }) {
|
|
53
|
+
function DoneCard({ summary, unconfirmed, theme }: { summary: string; unconfirmed: string[]; theme: PluginTimelineItemProps["theme"] }) {
|
|
54
54
|
const c = theme.colors;
|
|
55
55
|
return <Reveal>
|
|
56
56
|
<View accessibilityRole="summary" style={{ flexDirection: "row", gap: 12, padding: 12, borderRadius: 10, backgroundColor: tint(c.statusSuccess, c), borderWidth: 1, borderColor: withAlpha(c.statusSuccess, 0.35), marginVertical: 4 }}>
|
|
@@ -58,7 +58,9 @@ function DoneCard({ summary, theme }: { summary: string; theme: PluginTimelineIt
|
|
|
58
58
|
<View style={{ flex: 1, gap: 3 }}>
|
|
59
59
|
<Text style={{ color: c.foreground, fontSize: 14, lineHeight: 19, fontWeight: "600" }}>Workspace done</Text>
|
|
60
60
|
{!!summary && <Text selectable style={{ color: c.foreground, fontSize: 13, lineHeight: 19 }}>{summary}</Text>}
|
|
61
|
-
<Text style={{ color: c.foregroundMuted, fontSize: 12, lineHeight: 17 }}>
|
|
61
|
+
<Text style={{ color: c.foregroundMuted, fontSize: 12, lineHeight: 17 }}>{unconfirmed.length
|
|
62
|
+
? `Deploy not confirmed by Follow-up for ${unconfirmed.map(k => k.includes("#") ? `#${k.split("#")[1]}` : k).join(", ")}; the summary above is the agent's evidence. Archive the workspace when you're ready.`
|
|
63
|
+
: "Follow-up checked every PR and task. Archive the workspace when you're ready."}</Text>
|
|
62
64
|
</View>
|
|
63
65
|
</View>
|
|
64
66
|
</Reveal>;
|
package/client/panel.tsx
CHANGED
|
@@ -195,6 +195,7 @@ function ShippedCard({ workspace: w, theme, compact, now }: { workspace: Workspa
|
|
|
195
195
|
</View>
|
|
196
196
|
</View>
|
|
197
197
|
<Text selectable style={[t.body, { color: c.foreground }]}>{w.completion.summary}</Text>
|
|
198
|
+
{!!w.completion.unconfirmed?.length && <Text style={t.meta}>{`Deploy not confirmed by Follow-up for ${w.completion.unconfirmed.map(k => shortRefs(k, w)).join(", ")}. The summary above is the agent's evidence.`}</Text>}
|
|
198
199
|
<Text style={t.meta}>Archive the workspace from its menu when you're finished with it.</Text>
|
|
199
200
|
</View>
|
|
200
201
|
</Reveal>;
|
package/index.server.ts
CHANGED
|
@@ -338,7 +338,7 @@ export default function contribute(server: PluginServerContext) {
|
|
|
338
338
|
};
|
|
339
339
|
void loop();
|
|
340
340
|
void (async () => { await ready; if (stopped || loadError) return; await inbox.start().catch(error => { inboxError = error instanceof Error ? error.message : String(error); }); void inboxLoop(); })();
|
|
341
|
-
const changed = (w: Workspace) => { w.completion = null; w.updatedAt = new Date().toISOString(); };
|
|
341
|
+
const changed = (w: Workspace) => { w.completion = null; w.declaration = null; w.updatedAt = new Date().toISOString(); };
|
|
342
342
|
|
|
343
343
|
const callerWorkspaceId = async (agentId: string, paseo: PluginHandlerContext["paseo"], allowHandoff = true) => {
|
|
344
344
|
const agent = (await paseo.agents.ref(agentId).refresh())?.agent;
|
|
@@ -983,7 +983,7 @@ export default function contribute(server: PluginServerContext) {
|
|
|
983
983
|
if (!owned && !waking) return;
|
|
984
984
|
if (owned) gateway.markDirty(event.agent.id);
|
|
985
985
|
await store.mutate(state => {
|
|
986
|
-
const w = owned && state.workspaces.find(w => w.id === owned.id); if (w) w.completion = null;
|
|
986
|
+
const w = owned && state.workspaces.find(w => w.id === owned.id); if (w) { w.completion = null; w.declaration = null; }
|
|
987
987
|
const d = waking && state.workspaces.find(w => w.id === waking.id); if (d) delete d.dormant;
|
|
988
988
|
});
|
|
989
989
|
if (waking) void engine.tick();
|
|
@@ -1054,8 +1054,8 @@ export default function contribute(server: PluginServerContext) {
|
|
|
1054
1054
|
const w = state.workspaces.find(w => w.enable_tracking && (w.mainAgentId === event.agent.id || w.contributorAgentIds?.includes(event.agent.id)));
|
|
1055
1055
|
if (!w || w.mainAgentId !== event.agent.id || !interruption) return;
|
|
1056
1056
|
// The provider lost the conversation: every later send fails the same way, so stop sending instead of holding.
|
|
1057
|
-
if (event.outcome.kind === "failed" && conversationGone(event.outcome.error.message)) { w.goneAgent = { agentId: event.agent.id, at: interruption.at, reason: event.outcome.error.message }; w.completion = null; return; }
|
|
1058
|
-
w.hold = interruptionHold(interruption.kind); w.interruption = { ...interruption, agentId: event.agent.id }; w.completion = null;
|
|
1057
|
+
if (event.outcome.kind === "failed" && conversationGone(event.outcome.error.message)) { w.goneAgent = { agentId: event.agent.id, at: interruption.at, reason: event.outcome.error.message }; w.completion = null; w.declaration = null; return; }
|
|
1058
|
+
w.hold = interruptionHold(interruption.kind); w.interruption = { ...interruption, agentId: event.agent.id }; w.completion = null; w.declaration = null;
|
|
1059
1059
|
});
|
|
1060
1060
|
void engine.tick();
|
|
1061
1061
|
}),
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "paseo-follow-up",
|
|
3
3
|
"private": false,
|
|
4
|
-
"version": "1.4.0-beta.
|
|
4
|
+
"version": "1.4.0-beta.26",
|
|
5
5
|
"description": "Follow every workspace PR stack in Paseo, answer agent questions, batch repairs for the main agent, and see what needs you.",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"files": [
|
package/server/agent-actions.ts
CHANGED
|
@@ -53,7 +53,7 @@ export function controlWorkspace(state: State, input: { workspaceId: string; ena
|
|
|
53
53
|
w.batches.push({ ...b, ...(recoveryBatch(b) ? { enable_manual_recovery: true } : {}), id: randomUUID(), messageId: randomUUID(), state: "pending", attempts: b.attempts + 1, createdAt: new Date(now).toISOString(), sentAt: null, settledAt: null, result: "", activityAt: null, acknowledgmentError: null });
|
|
54
54
|
}
|
|
55
55
|
const at = new Date(now).toISOString();
|
|
56
|
-
if (input.clearHold || input.retryBatchId && !recoveryBatch(w.batches.find(b => b.id === input.retryBatchId)!)) { w.completion = null; w.updatedAt = at; }
|
|
56
|
+
if (input.clearHold || input.retryBatchId && !recoveryBatch(w.batches.find(b => b.id === input.retryBatchId)!)) { w.completion = null; w.declaration = null; w.updatedAt = at; }
|
|
57
57
|
else w.updatedAt = at;
|
|
58
58
|
return w;
|
|
59
59
|
}
|
package/server/deployments.ts
CHANGED
|
@@ -12,8 +12,22 @@ const repository = "herosecurity/hero-poc";
|
|
|
12
12
|
const project = "hero-production-environments";
|
|
13
13
|
const roles = ["backend", "etl", "interpretation", "public-api", "web"];
|
|
14
14
|
|
|
15
|
+
/** Messages this probe throws itself. Anything else (gcloud, gh, fetch) is summarized so no transport detail leaks. */
|
|
16
|
+
const OWN_REASONS = new Set(["Deployment image unavailable", "Deployment image metadata exceeds the read limit", "Serving image must have an immutable production digest", "Serving image config unavailable", "Serving source revision is unknown", "Production service catalog incomplete", "Production traffic is not ready", "Serving revision unavailable", "Serving revision is not ready"]);
|
|
17
|
+
export function probeReason(error: unknown): string {
|
|
18
|
+
const message = error instanceof Error ? error.message : "";
|
|
19
|
+
if (OWN_REASONS.has(message)) return message;
|
|
20
|
+
const command = (error as { cmd?: unknown; path?: unknown } | null)?.cmd ?? (error as { path?: unknown } | null)?.path;
|
|
21
|
+
if (typeof command === "string" && /^(gcloud|gh)\b/.test(command)) return `${command.split(" ")[0]} call failed`;
|
|
22
|
+
if (error instanceof SyntaxError) return "unreadable response";
|
|
23
|
+
if (error instanceof Error && error.name === "AbortError") return "registry timed out";
|
|
24
|
+
return "lookup failed";
|
|
25
|
+
}
|
|
26
|
+
|
|
15
27
|
export class Deployments {
|
|
16
|
-
private fleet: { until: number; value: Promise<Fleet |
|
|
28
|
+
private fleet: { until: number; value: Promise<Fleet | { error: string }> } | null = null;
|
|
29
|
+
/** Why the last fleet read failed, for diagnostics and the PR evidence line; null after a success. */
|
|
30
|
+
lastError: string | null = null;
|
|
17
31
|
private images = new Map<string, Promise<string>>();
|
|
18
32
|
private ancestry = new Map<string, Promise<boolean>>();
|
|
19
33
|
private token: { value: string; until: number } | null = null;
|
|
@@ -85,11 +99,20 @@ export class Deployments {
|
|
|
85
99
|
const merged = [...new Map(prs.filter(p => p.snapshot?.state === "MERGED").map(p => [p.key, p])).values()];
|
|
86
100
|
if (!merged.length) return result;
|
|
87
101
|
if (merged.some(p => p.repo === repository)) {
|
|
88
|
-
if (!this.fleet || this.fleet.until <= this.now())
|
|
102
|
+
if (!this.fleet || this.fleet.until <= this.now()) {
|
|
103
|
+
const entry = { until: this.now() + 60_000, value: this.readFleet().then(fleet => { this.lastError = null; return fleet; }, (error: unknown) => {
|
|
104
|
+
// A failure is retried on the next refresh (15 s), not served from cache for a minute.
|
|
105
|
+
entry.until = this.now() + 15_000; this.lastError = probeReason(error);
|
|
106
|
+
return { error: this.lastError };
|
|
107
|
+
}) };
|
|
108
|
+
this.fleet = entry;
|
|
109
|
+
}
|
|
89
110
|
}
|
|
90
|
-
const
|
|
111
|
+
const read = this.fleet ? await this.fleet.value : null;
|
|
112
|
+
const fleet = read && "commits" in read ? read : null;
|
|
113
|
+
const reason = read && "error" in read ? ` (${read.error})` : "";
|
|
91
114
|
for (let start = 0; start < merged.length; start += 4) await Promise.all(merged.slice(start, start + 4).map(async p => {
|
|
92
|
-
const unknown: Deployment = { state: "unknown", environment: p.repo === repository ? "production" : "", commits: [], evidence: p.repo === repository ?
|
|
115
|
+
const unknown: Deployment = { state: "unknown", environment: p.repo === repository ? "production" : "", commits: [], evidence: p.repo === repository ? `Could not verify serving production revisions${reason}. Check gcloud/gh access and refresh.` : "No deployment source configured for this repository.", observedAt: new Date(this.now()).toISOString() };
|
|
93
116
|
if (p.repo !== repository || !fleet || !sha.test(p.snapshot?.mergeCommit ?? "")) { result.set(p.key, unknown); return; }
|
|
94
117
|
try {
|
|
95
118
|
const included = await Promise.all(fleet.commits.map(commit => this.contains(p.snapshot!.mergeCommit!, commit)));
|
package/server/discovery.ts
CHANGED
|
@@ -43,7 +43,7 @@ export function setMainAgent(w: Workspace, to: string, kind: "handover" | "handB
|
|
|
43
43
|
for (const b of w.batches) if (b.state === "pending" && b.recipientAgentId === from) b.recipientAgentId = null;
|
|
44
44
|
if (kind === "handover") w.handover = { from, at: new Date(now).toISOString(), worked: false }; else delete w.handover;
|
|
45
45
|
const stop = w.interruption;
|
|
46
|
-
if (stop && w.hold === interruptionHold(stop.kind) && (stop.agentId ? stop.agentId !== to : kind === "developer")) { w.hold = null; delete w.interruption; w.completion = null; }
|
|
46
|
+
if (stop && w.hold === interruptionHold(stop.kind) && (stop.agentId ? stop.agentId !== to : kind === "developer")) { w.hold = null; delete w.interruption; w.completion = null; w.declaration = null; }
|
|
47
47
|
w.updatedAt = new Date(now).toISOString();
|
|
48
48
|
}
|
|
49
49
|
|
|
@@ -157,7 +157,7 @@ export function applyDiscovery(state: State, discovered: DiscoveredWorkspace[],
|
|
|
157
157
|
if (!w.enable_tracking && followsByDefault(state, row)) { w.enable_auto_sends = startsWithAutoSend(state, w); w.enable_tracking = true; }
|
|
158
158
|
if (!w.inventory) {
|
|
159
159
|
w.inventory = { revision: 1, syncedRevision: 0, candidates: [], historyComplete: false, historyError: null, scannedMessageAt: null };
|
|
160
|
-
w.completion = null;
|
|
160
|
+
w.completion = null; w.declaration = null;
|
|
161
161
|
}
|
|
162
162
|
if (row.history) {
|
|
163
163
|
if (w.goal === row.title && row.history.goal) w.goal = row.history.goal;
|
|
@@ -171,7 +171,7 @@ export function applyDiscovery(state: State, discovered: DiscoveredWorkspace[],
|
|
|
171
171
|
state.workspaces.some(other => other.id !== w.id && other.enable_tracking && !other.archived && other.prs.some(p => p.key === key))) continue;
|
|
172
172
|
w.prs.push({ key, repo: receipt.repo, number: receipt.number, registeredAgentId: receipt.agentId,
|
|
173
173
|
discoveredFromSubmission: true, stack: receipt.branch ?? `PR #${receipt.number}`, parent: null, disposition: null, snapshot: null, error: null });
|
|
174
|
-
w.completion = null; w.updatedAt = new Date(now).toISOString();
|
|
174
|
+
w.completion = null; w.declaration = null; w.updatedAt = new Date(now).toISOString();
|
|
175
175
|
}
|
|
176
176
|
}
|
|
177
177
|
}
|
|
@@ -183,7 +183,7 @@ export function applyHistory(w: Workspace, history: History, messageAt: string |
|
|
|
183
183
|
const excludedKeys = new Set(w.excludedStacks.flatMap(stack => stack.prs.map(p => p.key)));
|
|
184
184
|
if (added.some(key => !excludedKeys.has(key) && !w.prs.some(pr => pr.key === key))) {
|
|
185
185
|
inventory.revision++;
|
|
186
|
-
w.completion = null;
|
|
186
|
+
w.completion = null; w.declaration = null;
|
|
187
187
|
}
|
|
188
188
|
inventory.candidates = [...new Set([...inventory.candidates, ...added])].sort();
|
|
189
189
|
inventory.historyComplete = history.complete;
|
package/server/engine.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
|
-
import { completionBlockers, type Workspace, type State, type Batch } from "../shared/model";
|
|
2
|
+
import { completionBlockers, completionCheck, completionGate, revokesDone, type CompletionGate, type Workspace, type State, type Batch } from "../shared/model";
|
|
3
3
|
import { Store } from "./store";
|
|
4
4
|
import { Github } from "./github";
|
|
5
5
|
import { batchPrompt, tasksFor, isRecovery, needsPrObservations, type TaskWording } from "./tasks";
|
|
@@ -144,7 +144,12 @@ export class Engine {
|
|
|
144
144
|
unacknowledged.state = "blocked";
|
|
145
145
|
unacknowledged.result = unacknowledged.acknowledgmentError ? `Acknowledgment was refused for agent ${unacknowledged.acknowledgmentError.agentId}: ${unacknowledged.acknowledgmentError.error}` : "No accepted acknowledgment is recorded. Check the assigned agent’s result and any tracker errors before retrying.";
|
|
146
146
|
}
|
|
147
|
-
if (w.completion &&
|
|
147
|
+
if (w.completion && revokesDone(w, this.now())) w.completion = null;
|
|
148
|
+
if (w.declaration && !w.completion) {
|
|
149
|
+
const gate = completionGate(w, this.now());
|
|
150
|
+
if (gate.blockers.some(b => b.owner !== "wait")) w.declaration = null;
|
|
151
|
+
else if (!gate.blockers.length) acceptDeclaration(w, gate, this.now());
|
|
152
|
+
}
|
|
148
153
|
});
|
|
149
154
|
if (pruned.length) await this.archive(original.id, pruned).catch(() => undefined);
|
|
150
155
|
for (const b of (await this.store.snapshot()).workspaces.find(w => w.id === original.id)!.batches.filter(b => isRecovery(b) && b.state === "sent")) {
|
|
@@ -328,6 +333,9 @@ export class Engine {
|
|
|
328
333
|
}
|
|
329
334
|
private reconcile(w: Workspace): void {
|
|
330
335
|
const tasks = tasksFor(w, this.now(), this.wording);
|
|
336
|
+
// Hysteresis: a queued Done check survives the agent's own turns; only a real change (new work, Done) ends it.
|
|
337
|
+
const queuedCheck = w.batches.find(b => b.state === "pending" && completionCheck(b));
|
|
338
|
+
if (queuedCheck && w.runtimeBusy && !tasks.some(t => t.kind === "completion")) tasks.push(...tasksFor({ ...w, runtimeBusy: false }, this.now(), this.wording).filter(t => t.kind === "completion"));
|
|
331
339
|
const delivered = new Set(w.batches.filter(b => ["sending", "sent", "completed", "blocked", "uncertain"].includes(b.state)).flatMap(b => b.tasks.map(t => `${t.key}:${t.fingerprint}`)));
|
|
332
340
|
const fresh = tasks.filter(t => !delivered.has(`${t.key}:${t.fingerprint}`));
|
|
333
341
|
let pending = w.batches.find(b => b.state === "pending" && !isRecovery(b));
|
|
@@ -346,9 +354,15 @@ export class Engine {
|
|
|
346
354
|
if (fresh.some(t => ["conflict", "review", "checks", "restack"].includes(t.kind) && w.batches.filter(b => b.id !== pending!.id && ["completed", "blocked"].includes(b.state)).filter(b => b.tasks.some(old => old.key === t.key)).length >= 3)) {
|
|
347
355
|
pending.state = "blocked"; pending.result = "This PR still needs repairs after three follow-up batches. Review it before retrying.";
|
|
348
356
|
}
|
|
349
|
-
|
|
357
|
+
// New repairs or tasks reopen the work; the Done check itself does not.
|
|
358
|
+
if (fresh.some(t => t.kind !== "completion")) { w.completion = null; w.declaration = null; }
|
|
350
359
|
}
|
|
351
|
-
|
|
360
|
+
/**
|
|
361
|
+
* Accepts Done when nothing the agent or developer must do remains. A deploy Follow-up can't confirm is not a
|
|
362
|
+
* blocker: Done is recorded with a "Deploy not confirmed by Follow-up" note and the agent's summary as evidence.
|
|
363
|
+
* Repeating it is a no-op (alreadyDone), and `next` tells the agent whether anything is its to fix.
|
|
364
|
+
*/
|
|
365
|
+
async declareDone(agentId: string, message: string, workspaceId?: string): Promise<DoneResult> {
|
|
352
366
|
const current = ownedWorkspace(await this.store.snapshot(), agentId, workspaceId);
|
|
353
367
|
// Delivery may wait for this very turn to finish, so declarations observe independently.
|
|
354
368
|
const [runtime, observations] = await Promise.all([
|
|
@@ -366,15 +380,20 @@ export class Engine {
|
|
|
366
380
|
if (observation?.snapshot) recordSnapshot(pr, observation.snapshot, this.now());
|
|
367
381
|
}
|
|
368
382
|
// The declaration is made inside the owner's turn; that foreground turn is allowed.
|
|
369
|
-
const
|
|
370
|
-
|
|
371
|
-
const blockers =
|
|
372
|
-
if (
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
w.
|
|
383
|
+
const gate = completionGate({ ...w, runtimeBusy: false }, this.now());
|
|
384
|
+
if (w.archived) gate.blockers.push({ owner: "developer", text: "Workspace is archived" });
|
|
385
|
+
const blockers = gate.blockers.map(b => b.text);
|
|
386
|
+
if (gate.blockers.length) {
|
|
387
|
+
// Nothing left for the agent or developer: keep the declaration and let Follow-up finish it, so nobody retries.
|
|
388
|
+
const stored = gate.blockers.every(b => b.owner === "wait");
|
|
389
|
+
w.declaration = stored ? { summary: message, at: new Date(this.now()).toISOString() } : null;
|
|
390
|
+
return { workspace: w, blockers, unconfirmed: gate.unconfirmed, alreadyDone: false, next: doneGuidance(gate, false, stored) };
|
|
376
391
|
}
|
|
377
|
-
|
|
392
|
+
w.declaration = null;
|
|
393
|
+
const alreadyDone = !!w.completion;
|
|
394
|
+
for (const b of w.batches.filter(b => b.state === "pending" && completionCheck(b))) { b.state = "cancelled"; b.result = "The main agent declared Done."; }
|
|
395
|
+
if (!alreadyDone) w.completion = { summary: message, declaredAt: new Date(this.now()).toISOString(), ...(gate.unconfirmed.length ? { unconfirmed: gate.unconfirmed } : {}) };
|
|
396
|
+
return { workspace: w, blockers, unconfirmed: gate.unconfirmed, alreadyDone, next: doneGuidance(gate, alreadyDone) };
|
|
378
397
|
});
|
|
379
398
|
}
|
|
380
399
|
async acknowledge(agentId: string, batchId: string, outcome: "completed" | "blocked", result: string, workspaceId?: string): Promise<Workspace> {
|
|
@@ -395,6 +414,25 @@ export class Engine {
|
|
|
395
414
|
async stop(): Promise<void> { this.stopped = true; await this.running; await Promise.allSettled(this.recoveryOperations); }
|
|
396
415
|
}
|
|
397
416
|
|
|
417
|
+
export type DoneResult = { workspace: Workspace; blockers: string[]; unconfirmed: string[]; alreadyDone: boolean; next: string };
|
|
418
|
+
/** The declare_done reply in words: what's missing, who can move it, and whether calling again could help. */
|
|
419
|
+
/** Records a stored declaration as Done; the Done check it answers is no longer needed. */
|
|
420
|
+
function acceptDeclaration(w: Workspace, gate: CompletionGate, now: number): void {
|
|
421
|
+
w.completion = { summary: w.declaration!.summary, declaredAt: new Date(now).toISOString(), ...(gate.unconfirmed.length ? { unconfirmed: gate.unconfirmed } : {}) };
|
|
422
|
+
w.declaration = null;
|
|
423
|
+
for (const b of w.batches.filter(b => b.state === "pending" && completionCheck(b))) { b.state = "cancelled"; b.result = "The main agent declared Done."; }
|
|
424
|
+
}
|
|
425
|
+
export function doneGuidance(gate: CompletionGate, alreadyDone = false, stored = false): string {
|
|
426
|
+
const note = gate.unconfirmed.length ? ` Follow-up couldn't confirm what production serves for ${gate.unconfirmed.join(", ")}, so Done carries "Deploy not confirmed by Follow-up" with your summary as the evidence.` : "";
|
|
427
|
+
if (!gate.blockers.length) return alreadyDone ? `Already Done; nothing changed. Don't call declare_done again.${note}` : `Done accepted.${note} Nothing else to do; the developer archives the workspace.`;
|
|
428
|
+
const yours = gate.blockers.filter(b => b.owner === "agent").map(b => b.text);
|
|
429
|
+
const theirs = gate.blockers.filter(b => b.owner !== "agent").map(b => `${b.text} (${b.owner === "developer" ? "needs the developer" : "Follow-up rechecks on its own"})`);
|
|
430
|
+
const parts = [yours.length ? `Yours to fix, then call declare_done again: ${yours.join("; ")}.` : "", theirs.length ? `Not yours to fix: ${theirs.join("; ")}.` : ""];
|
|
431
|
+
if (stored) parts.push("Follow-up kept your declaration and records Done on its own once these clear. Don't call declare_done again; end the turn.");
|
|
432
|
+
else if (!yours.length) parts.push("Don't call declare_done again until one of these changes; end the turn. If the developer needs to act, say so once.");
|
|
433
|
+
return `Not Done yet. ${parts.filter(Boolean).join(" ")}`;
|
|
434
|
+
}
|
|
435
|
+
|
|
398
436
|
export function findWorkspace(state: State, id: string): Workspace {
|
|
399
437
|
const w = state.workspaces.find(w => w.id === id);
|
|
400
438
|
if (!w) throw new Error("Workspace tracking is initializing; try again shortly.");
|
package/server/exclusions.ts
CHANGED
|
@@ -17,5 +17,5 @@ export function excludeStack(w: Workspace, stack: string, reason: string, obliga
|
|
|
17
17
|
b.tasks = b.tasks.filter(t => !keys.has(t.target) && !ids.has(t.target));
|
|
18
18
|
if (!b.tasks.length) { b.state = "cancelled"; b.result = `Stack excluded from workspace scope: ${reason}`; }
|
|
19
19
|
}
|
|
20
|
-
w.completion = null; w.updatedAt = at;
|
|
20
|
+
w.completion = null; w.declaration = null; w.updatedAt = at;
|
|
21
21
|
}
|
package/server/mcp-source.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// Generated by scripts/build.mjs.
|
|
2
|
-
export const mcpSource = "#!/usr/bin/env node\nimport { createInterface } from \"node:readline\";\nimport { createRequire } from \"node:module\";\nimport { pathToFileURL } from \"node:url\";\nimport { readFile, stat } from \"node:fs/promises\";\nimport { existsSync, realpathSync } from \"node:fs\";\nimport { join, delimiter } from \"node:path\";\nimport { homedir } from \"node:os\";\n\nconst string = { type: \"string\" };\nconst boolean = { type: \"boolean\" };\nconst integer = { type: \"integer\", minimum: 1 };\nconst array = { type: \"array\", items: string };\nconst 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 };\nconst trigger = { type: [\"object\", \"null\"], properties: { event: { type: \"string\", enum: [\"now\", \"merge\", \"deploy\"] }, delayDays: { type: \"integer\", minimum: 0, maximum: 3650 } }, required: [\"event\"], additionalProperties: false };\nconst tools = [\n [\"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-through does not require recovery.\", \"follow.agent-status\", { detail: { type: \"string\", enum: [\"summary\", \"full\"] } }, []],\n [\"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\"]],\n [\"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\"]],\n [\"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.\", \"follow.register-pr\", { repo: string, number: integer, stack: string, parentNumber: { type: [\"integer\", \"null\"], minimum: 1 }, disposition: string }, [\"repo\", \"number\", \"stack\"]],\n [\"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\"]],\n [\"update_obligation\", \"Record concrete follow-through: verification, migrations, decisions or stakeholder replies. Never add approve/merge/deploy checklist tasks. afterPrs uses owner/repo#number keys. Tasks are manual unless explicitly scheduled with trigger={event:\\\"now\\\"|\\\"merge\\\"|\\\"deploy\\\",delayDays:0}. Only set a trigger 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 makes a task manual. 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.\", \"follow.obligation\", { id: string, title: string, status: { type: \"string\", enum: [\"pending\", \"waiting\", \"working\", \"blocked\", \"done\", \"waived\"] }, afterPrs: array, dependencyStage: { type: \"string\", enum: [\"merged\", \"deployed\"] }, evidence: string, enable_follow_up: boolean, communication, trigger }, [\"title\", \"status\"]],\n [\"acknowledge_batch\", \"Record a follow-up result. Complete only after verifying all tasks; blocked surfaces the reason to the developer. Always acknowledge before ending a repair turn. Keep the result within 2000 characters.\", \"follow.acknowledge\", { batchId: string, outcome: { type: \"string\", enum: [\"completed\", \"blocked\"] }, result: { ...string, maxLength: 2000 } }, [\"batchId\", \"outcome\", \"result\"]],\n [\"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. 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.\", \"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\"]],\n [\"record_answer\", \"Record the developer's answer when they answered a question in chat instead of in Follow-up. choice is an option letter, 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\"]],\n [\"withdraw_question\", \"Withdraw a question that no longer matters, with a short reason.\", \"follow.withdraw-question\", { id: string, reason: string }, [\"id\", \"reason\"]],\n [\"set_spec\", \"Register the link to this workspace's spec: the Claude artifact (or doc) you keep summarizing the goal, decisions and status. Call it once after the first publish, with the URL from the publish result, and again only if the link changes. Follow-up shows it in the workspace header.\", \"follow.set-spec\", { url: { ...string, maxLength: 2000 }, title: { ...string, maxLength: 120 } }, [\"url\"]],\n [\"needs_you\", \"Call once at the end of a turn, just before your final reply: what the developer has to do next. ask is one line (≤120). kind: decision (give decisions with 2–5 options, a consequence each and recommend=<option index>; with several decisions the developer answers them together and you get one message with a line per decision, skipped ones marked as skipped; a decision that is already an open question goes in questions=[\\\"Q18\\\"] instead, never restated), action (something only they can do: merge, approve, log in, run or send), review (a PR to review and merge; link it with pr), or done (\\\"Nothing needed. <what you finished>.\\\": nothing for the developer, won't flag you). context ≤400 chars: only what they need to decide. Never blocks and never changes what you should do next.\", \"follow.needs-you\", { ask: { ...string, minLength: 1, maxLength: 120 }, kind: { type: \"string\", enum: [\"decision\", \"action\", \"review\", \"done\"] }, decisions: { type: \"array\", maxItems: 3, items: { type: \"object\", properties: { question: { ...string, minLength: 1, maxLength: 200 }, options: { type: \"array\", minItems: 2, maxItems: 5, items: { type: \"object\", properties: { label: { ...string, minLength: 1, maxLength: 60 }, consequence: { ...string, maxLength: 160 } }, required: [\"label\"], additionalProperties: false } }, recommend: { type: \"integer\", minimum: 0, maximum: 4 } }, required: [\"question\"], additionalProperties: false } }, questions: { type: \"array\", maxItems: 3, items: { type: \"string\", pattern: \"^Q\\\\d+$\" } }, context: { ...string, maxLength: 400 }, links: { type: \"array\", maxItems: 4, items: { type: \"object\", properties: { label: string, url: string, path: string, pr: string }, required: [\"label\"], additionalProperties: false } } }, [\"ask\", \"kind\"]],\n [\"declare_done\", \"Declare that the workspace goal is fulfilled. Live PR status and remaining obligations are checked; returned blockers must be resolved first. Done labels the workspace but never archives it.\", \"follow.done\", { summary: string }, [\"summary\"]],\n];\n\n// Agent parity: every action the developer can click in Follow-up, through the same server path (follow.agent-act).\n// Planned tools return a dry run; confirm=true with its planId runs it. Use them only when the developer asked.\nconst planned = { planId: string, confirm: boolean };\nconst prKey = { ...string, description: \"owner/repo#number, from list_prs\" };\nconst ask = \" Only when the developer asked for it. Returns a dry-run plan first; run it with confirm=true and the planId.\";\nconst read = \" Read-only.\";\nconst actionTools = [\n [\"list_prs\", \"List tracked PRs across all workspaces with state, draft, checks, open threads, requested reviewers and merge blockers. Filters: needs_reviewers, ready_to_merge, workspace (id or title). This is how you act \\\"on all\\\".\", \"follow.agent-act\", { workspace: string, needs_reviewers: boolean, ready_to_merge: boolean, include_closed: boolean }, []],\n [\"add_reviewers\", \"Request reviewers on one or many PRs, the same as the Add reviewers button. Without reviewers, asks the developer's saved reviewers for that repository (each PR row in list_prs shows them as configuredReviewers, with source repo, default or none); otherwise the GitHub logins or org/team slugs you give.\" + ask, \"follow.agent-act\", { prs: { type: \"array\", items: prKey }, reviewers: array, ...planned }, []],\n [\"merge\", \"Merge a PR (and its downstack with scope=downstack) through Graphite, using Follow-up's merge plan and blockers. Can't be undone.\" + ask, \"follow.agent-act\", { pr: prKey, scope: { type: \"string\", enum: [\"target\", \"downstack\"] }, ...planned }, []],\n [\"enable_merge_when_ready\", \"Turn on Graphite merge-when-ready for a PR, as the PR sheet does.\" + ask, \"follow.agent-act\", { pr: prKey, scope: { type: \"string\", enum: [\"target\", \"downstack\"] }, ...planned }, []],\n [\"disable_merge_when_ready\", \"Turn off Graphite merge-when-ready for a PR.\" + ask, \"follow.agent-act\", { pr: prKey, scope: { type: \"string\", enum: [\"target\", \"downstack\"] }, ...planned }, []],\n [\"send_repairs\", \"Send a workspace's waiting repairs (review threads, failed checks) to its main agent, like the Send button. Only when the developer asked. batchId defaults to the waiting batch.\", \"follow.agent-act\", { workspace: string, batchId: string }, [\"workspace\"]],\n [\"set_auto_send\", \"Turn Auto-send on or off for a workspace, like its switch. Only when the developer asked.\", \"follow.agent-act\", { workspace: string, value: boolean }, [\"workspace\", \"value\"]],\n [\"clear_hold\", \"Resume Follow-up on a held workspace, like the Resume button. Only when the developer asked.\", \"follow.agent-act\", { workspace: string }, [\"workspace\"]],\n [\"retry_batch\", \"Queue a blocked or uncertain repair batch again, like the Retry button. Only when the developer asked.\", \"follow.agent-act\", { workspace: string, batchId: string }, [\"workspace\", \"batchId\"]],\n [\"track\", \"Follow a workspace again after the developer opted it out in Settings. Follow-up follows every workspace by default. Only when the developer asked.\", \"follow.agent-act\", { workspace: string }, [\"workspace\"]],\n [\"workspace_about\", \"Read what a workspace is about: a short AI overview (goal, where it stands, what's left), a one-line gist, and its linked Linear issues, PRs, Slack threads and docs. Read-only; writes the overview first when none is cached (up to ~90 s). workspaceId is a workspace id or exact title from list_prs.\", \"follow.agent-act\", { workspaceId: string }, [\"workspaceId\"]],\n [\"agent_settings\", \"Read which agent each of Follow-up's special roles uses (What's this about?, Overseer, Recovery, Priority ranker): provider, model, effort, mode and limits, and whether Wait for background jobs is on. Read-only; Tom changes them in Follow-up settings → Agents.\", \"follow.agent-act\", {}, []],\n [\"inbox_list\", \"Read the developer's Needs-you inbox: each root agent, whether it is flagged and why, snoozes and finish flags. Your own row has self=true.\", \"follow.agent-act\", { flagged_only: boolean }, []],\n [\"sign_off\", \"Sign off other agents' Needs-you flags on the developer's behalf, like Sign off. Never your own.\" + ask, \"follow.agent-act\", { agentIds: array, ...planned }, []],\n [\"snooze\", \"Snooze other agents' flags (until: next-event, 1h, tomorrow or an ISO time), like Later.\" + ask, \"follow.agent-act\", { agentIds: array, until: string, ...planned }, []],\n [\"set_finish_flags\", \"Turn finish flags on or off for other agents, like Don't flag finishes.\" + ask, \"follow.agent-act\", { agentIds: array, value: boolean, ...planned }, []],\n [\"set_priorities\", \"Rank workspaces for Home's Priority sort: per workspace (id or exact title) a score 0-100, a one-line reason the developer sees, and its sources [{kind: linear|slack|planning|github|paseo, label, url}]. replace=true drops workspaces you leave out. Used for 6 hours. Returns a dry run; store it with confirm=true and the planId.\", \"follow.agent-act\", { priorities: { type: \"array\", items: { type: \"object\", properties: { workspace: string, score: { type: \"integer\", minimum: 0, maximum: 100 }, reason: { ...string, maxLength: 140 }, sources: { type: \"array\", items: { type: \"object\", properties: { kind: { type: \"string\", enum: [\"linear\", \"slack\", \"planning\", \"github\", \"paseo\"] }, label: string, url: string }, required: [\"kind\", \"label\"] } } }, required: [\"workspace\", \"score\", \"reason\"] } }, replace: boolean, ...planned }, [\"priorities\"]],\n // Settings, onboarding, Home and the panel, one developer RPC each (server/agent-parity.ts). Writes plan first.\n [\"make_main_agent\", \"Make yourself or another root agent of this workspace its main agent (the one that asks the developer, reports Needs-you and calls Done). requested=developer when the developer asked for it (refused only while the main is mid-turn); requested=self for your own claim, allowed only when the main is archived, gone or closed 30 minutes, or you registered every open PR and the main has been idle 24 hours, and never within 30 minutes of a change or 2 hours after you lost the role. Give a one-line reason the developer sees. Returns a dry run; run it with confirm=true and the planId.\", \"follow.agent-act\", { agentId: string, reason: string, requested: { type: \"string\", enum: [\"developer\", \"self\"] }, ...planned }, []],\n [\"display_settings\", \"Read Settings → Display: the header button, sidebar item, composer pill, Needs-you inbox, closed-PR flags, brief nudge, Overseer, ranker and trust bypass switches.\" + read, \"follow.agent-act\", {}, []],\n [\"set_display\", \"Change Settings → Display switches, e.g. { values: { enable_trust_bypass: false } }. Keys from display_settings.\" + ask, \"follow.agent-act\", { values: { type: \"object\", additionalProperties: boolean }, ...planned }, []],\n [\"follow_settings\", \"Read Settings → Following: follow every workspace, the Auto-send default, the active window, and per-workspace exceptions.\" + read, \"follow.agent-act\", {}, []],\n [\"set_follow_settings\", \"Change Settings → Following: enable_follow_every, enable_auto_sends_default, activeWindowDays (1-60), or one workspace's exception { workspaceId, follow, enable_auto_sends }.\" + ask, \"follow.agent-act\", { enable_follow_every: boolean, enable_auto_sends_default: boolean, activeWindowDays: { type: \"integer\", minimum: 1, maximum: 60 }, workspace: { type: \"object\" }, ...planned }, []],\n [\"project_settings\", \"Read each project and whether Follow-up follows its new workspaces by default.\" + read, \"follow.agent-act\", {}, []],\n [\"set_project_tracking\", \"Follow a project's new workspaces by default, or stop: { projectId, enable_default_tracking }.\" + ask, \"follow.agent-act\", { projectId: string, enable_default_tracking: boolean, ...planned }, []],\n [\"pr_workflow\", \"Read Settings → Following → Shipping PRs: each repository's PR workflow (graphite or github), merge method and review-fix setting, and the default. refresh=true re-detects.\" + read, \"follow.agent-act\", { refresh: boolean }, []],\n [\"set_pr_workflow\", \"Change Shipping PRs: per repository (repo owner/name) its setting, mergeMethod or reviewFix (null clears back to the default), or the default.\" + ask, \"follow.agent-act\", { repo: string, setting: { type: [\"string\", \"null\"] }, default: string, mergeMethod: { type: [\"string\", \"null\"] }, reviewFix: { type: [\"object\", \"null\"] }, ...planned }, []],\n [\"reviewer_settings\", \"Read Settings → Reviewers: the default reviewers and each repository's own list.\" + read, \"follow.agent-act\", {}, []],\n [\"reviewer_suggestions\", \"Suggest reviewers for a repository (owner/name) from its recent history.\" + read, \"follow.agent-act\", { repo: string }, [\"repo\"]],\n [\"save_reviewers\", \"Save the reviewers Add reviewers asks: repo owner/name, or null for the default; reviewers [{ login, name?, kind? }].\" + ask, \"follow.agent-act\", { repo: { type: [\"string\", \"null\"] }, reviewers: { type: \"array\", items: { type: \"object\" } }, ...planned }, []],\n [\"set_agent_setting\", \"Change which agent a special role uses (Settings → Agents): role about|overseer|recovery|ranker, entry { provider, model, ... } or null for the default. agent_settings shows the current ones.\" + ask, \"follow.agent-act\", { role: string, entry: { type: [\"object\", \"null\"] }, ...planned }, []],\n [\"set_wait_for_jobs\", \"Turn Settings → Agents → Wait for background jobs on or off (enable_wait), like its switch. Applies to sessions opened afterwards. agent_settings shows it.\" + ask, \"follow.agent-act\", { enable_wait: boolean, ...planned }, []],\n [\"onboarding_status\", \"Read the setup guide's state: whether it was finished or skipped, and the current step.\" + read, \"follow.agent-act\", {}, []],\n [\"onboarding_checks\", \"Run the setup checks (GitHub login, providers, ...) and return each result with its fix. fresh=true re-runs them.\" + read, \"follow.agent-act\", { fresh: boolean }, []],\n [\"set_onboarding\", \"Move the setup guide: action start|step|finish|skip|restart|dismiss-offer, step for action=step.\" + ask, \"follow.agent-act\", { action: string, step: string, ...planned }, []],\n [\"priorities\", \"Read the stored priorities behind Home's Priority sort.\" + read, \"follow.agent-act\", {}, []],\n [\"rank_status\", \"Read the priority ranker's state: last run, whether it's running, and errors.\" + read, \"follow.agent-act\", {}, []],\n [\"rerank_priorities\", \"Re-rank Home's Priority sort now, like Re-rank. force=true re-runs even when nothing changed.\" + ask, \"follow.agent-act\", { force: boolean, ...planned }, []],\n [\"usage\", \"Read provider usage limits and the VM's memory meter, as Home shows them.\" + read, \"follow.agent-act\", {}, []],\n [\"overseer_status\", \"Read the Overseer's state: running, its agent and model, and what a restart would use.\" + read, \"follow.agent-act\", {}, []],\n [\"overseer_start\", \"Start the Overseer, like Start on Home.\" + ask, \"follow.agent-act\", { ...planned }, []],\n [\"overseer_restart\", \"Restart the Overseer (with the model Settings → Agents names now).\" + ask, \"follow.agent-act\", { ...planned }, []],\n [\"overseer_ask\", \"Send the developer's words to the Overseer, as its box on Home does: { text }.\" + ask, \"follow.agent-act\", { text: string, ...planned }, []],\n [\"inbox_brief\", \"Read another agent's full Needs-you brief (decisions, options, links): { agentId }.\" + read, \"follow.agent-act\", { agentId: string }, [\"agentId\"]],\n [\"brief_action\", \"Answer another agent's brief for the developer, like its card: { agentId, briefId, decisionId + choice, or choices [{ decisionId, choice }], or move: retry }. Never your own brief.\" + ask, \"follow.agent-act\", { agentId: string, briefId: string, decisionId: string, choice: string, move: string, choices: { type: \"array\", items: { type: \"object\" } }, ...planned }, []],\n [\"inbox_act\", \"The inbox's other actions on other agents' rows: action undo|mute_turn|unsorted_flag|unsorted_sign_off|batch_undo, agentIds.\" + ask, \"follow.agent-act\", { action: string, agentIds: array, muteTurn: boolean, ...planned }, []],\n [\"answer_question\", \"Send the developer's answer to another agent's question (Q1…), like its card: { workspaceId, questionId, choice, words }. For a question you asked, use record_answer.\" + ask, \"follow.agent-act\", { workspaceId: string, questionId: string, choice: string, words: string, ...planned }, []],\n [\"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 }, []],\n [\"refresh\", \"Refresh PR status now, like Refresh. Cheap; use when status looks stale.\", \"follow.agent-act\", { workspaceId: string }, []],\n [\"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 }, []],\n [\"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 }, []],\n [\"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\"]],\n [\"browser_status\", \"Read whether Send to Paseo is paired and which repositories it may control.\" + read, \"follow.agent-act\", {}, []],\n [\"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.\" + read, \"follow.agent-act\", {}, []],\n [\"trust_bypass_status\", \"Read how many permission prompts trust bypass approved today, and the latest ones.\" + read, \"follow.agent-act\", {}, []],\n];\n// The Overseer's routing tools (1.4.0-beta.0): only in the session Follow-up started as its Overseer.\nconst overseerTools = [\n [\"workstreams\", \"Every workspace Tom has, as Home groups them (needs, fixing, running, waiting, later, quiet): title, branch, PRs with checks, main agent and status, current ask, last activity, priority and reason, Linear keys. Paged (page, size ≤100); filter by group or query (name, branch, key, #PR).\", \"follow.overseer-act\", { page: integer, size: integer, group: { type: \"string\", enum: [\"needs\", \"fixing\", \"running\", \"waiting\", \"later\", \"quiet\"] }, query: string }, []],\n [\"agent_digest\", \"One agent's last steps (default 10) summarised, its status and its open asks to Tom (flag, decisions, questions). Use before routing when the digest isn't enough.\", \"follow.overseer-act\", { agentId: string, steps: integer }, [\"agentId\"]],\n [\"route_candidates\", \"Score every workspace for Tom's ask by Linear key, PR number, branch, workspace name, open asks and recent activity. Returns the top 3 and whether one is a confident match.\", \"follow.overseer-act\", { ask: string }, [\"ask\"]],\n [\"send_to_agent\", \"Forward Tom's words to the agent that owns the work, prefixed \\\"From Tom via Overseer:\\\". reply_to_ask=true only when Tom is answering that agent's open ask (it then clears its Needs-you flag). Then tell Tom where it went in one line.\", \"follow.overseer-act\", { agentId: string, text: string, reply_to_ask: boolean }, [\"agentId\", \"text\"]],\n [\"start_workspace\", \"Start a new workspace with an agent for a task, branched off main with the default model. Only when Tom asked for a new workspace or picked it. Returns a dry run (title from the task and Linear key, branch, project); run it with confirm=true and the planId.\", \"follow.overseer-act\", { task: string, title: string, project: string, linear_key: string, base: string, planId: string, confirm: boolean }, []],\n [\"rerank\", \"Re-rank Home's Priority sort now from Linear, Slack, GitHub review requests and the weekly plan, when Tom asks for it. Returns the top 10 with their reasons. Skips the model when nothing changed.\", \"follow.overseer-act\", {}, []],\n];\nconst overseerNames = new Set(overseerTools.map(t => t[0]));\nconst overseerInstruction = \"You are Follow-up's Overseer. Route Tom's asks with route_candidates and send_to_agent; ask with needs_you kind=decision when unsure; start_workspace only when Tom asked or approved. Never merge, post to people or archive.\";\nconst actionNames = new Set(actionTools.map(t => t[0]));\nconst readOnlyTools = new Set([\"workspace_status\", \"list_prs\", \"inbox_list\", \"workstreams\", \"agent_digest\", \"route_candidates\", \"workspace_about\", \"agent_settings\", \"display_settings\", \"follow_settings\", \"project_settings\", \"pr_workflow\", \"reviewer_settings\", \"reviewer_suggestions\", \"onboarding_status\", \"onboarding_checks\", \"priorities\", \"rank_status\", \"usage\", \"overseer_status\", \"inbox_brief\", \"pr_controls\", \"browser_status\", \"trust_bypass_status\", \"release_notes\"]);\nconst destructiveTools = new Set([\"merge\"]);\nconst actionInstruction = \"Follow-up's action tools let you do anything the developer can click, across every tracked workspace and every Settings tab. Read freely: list_prs, inbox_list, inbox_brief, workspace_about, agent_settings, display_settings, follow_settings, project_settings, pr_workflow, reviewer_settings, onboarding_status, priorities, rank_status, usage, overseer_status, pr_controls. Hand the main role on, or claim it, with make_main_agent. Act only when the developer asks (\\\"the PRs look good, assign reviewers on all\\\": list_prs needs_reviewers=true, add_reviewers with those keys, then confirm the plan): add_reviewers, merge, enable/disable_merge_when_ready, send_repairs, set_auto_send, clear_hold, retry_batch, track, run_recovery, set_priorities, rerank_priorities; settings with set_display (trust bypass too), set_follow_settings, set_project_tracking, set_pr_workflow, save_reviewers, set_agent_setting, set_wait_for_jobs, set_onboarding; and sign_off/snooze/set_finish_flags/inbox_act/brief_action/answer_question for other agents. Planned tools return a dry run showing what changes; run it with confirm=true and its planId. Never sign yourself off or answer your own brief.\";\n\n// Wait (folded in from paseo-wait): its three tools are served natively (server/wait.ts), never by this bridge.\n// Native tools carry no MCP instructions, so the agent hook adds this at SessionStart when FOLLOW_THROUGH_WAIT=1.\nconst 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.\";\n\n// The brief's tool: every root agent while the Needs-you inbox is on; never contributors, recovery or subagents.\n// Kept identical to NEEDS_YOU_INSTRUCTION in shared/brief.ts (a test checks it).\nconst needsYouInstruction = \"When you end a turn, call `needs_you` once, just before your final reply, with what the developer has to do next: a decision (give 2–3 options, what each means for them, and the one you recommend), an action only they can take (merge, approve, log in, run or send something), or kind=done (\\\"Nothing needed\\\" plus what you finished, in one line), which means there is nothing for the developer and won't flag you in their inbox. A decision that is already an open question (you asked it with ask_question, or it is still open from an earlier turn) is never restated: point at it with questions=[\\\"Q18\\\"], or say \\\"Still open: Q18 …\\\" in ask. Keep `ask` to one line and `context` to what they need to decide. Don't repeat your report there; still write your normal reply. Don't call it while a permission prompt is waiting or while you're still working.\";\nfunction toolList(recovery = process.env.FOLLOW_THROUGH_RECOVERY === \"1\", contributor = false, brief = false, briefOnly = false, actions = false) {\n // Action tools: root agents (tracked main or untracked) while Follow-up runs; never recovery or contributors.\n // Contributors get make_main_agent only (its claim rules apply); recovery sessions get none.\n const acting = !actions || recovery ? [] : contributor ? actionTools.filter(t => t[0] === \"make_main_agent\") : actionTools;\n if (briefOnly) return [...(brief ? tools.filter(t => t[0] === \"needs_you\") : []), ...acting];\n return [...tools.filter(t => t[0] === \"needs_you\" ? brief && !recovery && !contributor : contributor ? [\"workspace_status\", \"register_pr\", \"sync_workspace\"].includes(t[0]) : !recovery || ![\"declare_done\", \"sync_workspace\", \"ask_question\", \"record_answer\", \"withdraw_question\", \"set_spec\"].includes(t[0])), ...acting];\n}\n/** Whether this session may call needs_you: launched as a root agent (FOLLOW_THROUGH_BRIEF) and the inbox is on. */\nasync function briefEnabled() {\n if (!process.env.FOLLOW_THROUGH_BRIEF || process.env.FOLLOW_THROUGH_RECOVERY === \"1\") return false;\n try {\n const directory = join(process.env.PASEO_HOME ?? join(homedir(), \".paseo\"), \"plugin-data/follow-through\");\n const lease = JSON.parse(await readFile(join(directory, \"hooks-enabled.json\"), \"utf8\"));\n if (!(lease.expiresAt > Date.now())) return false;\n const brief = JSON.parse(await readFile(join(directory, \"brief.json\"), \"utf8\"));\n return brief?.enable_inbox === true;\n } catch { return false; }\n}\n/**\n * Merge and merge-when-ready say how they run. \"github\": every known repository ships plain GitHub, so Graphite is\n * never named; \"mixed\": either, per list_prs prWorkflow; anything else keeps the Graphite wording it always had.\n */\nfunction describeAction(name, description, workflows) {\n if (workflows !== \"github\" && workflows !== \"mixed\") return description;\n const how = workflows === \"github\"\n ? { merge: \"through GitHub (gh pr merge, with the repository's merge method)\", on: \"Turn on GitHub auto-merge\", off: \"Turn off GitHub auto-merge\" }\n : { merge: \"the way its repository ships (Graphite, or GitHub's gh pr merge; list_prs shows prWorkflow)\", on: \"Turn on merge-when-ready (Graphite) or auto-merge (GitHub)\", off: \"Turn off merge-when-ready (Graphite) or auto-merge (GitHub)\" };\n if (name === \"merge\") return description.replace(\"through Graphite\", how.merge);\n if (name === \"enable_merge_when_ready\") return description.replace(\"Turn on Graphite merge-when-ready\", how.on);\n if (name === \"disable_merge_when_ready\") return description.replace(\"Turn off Graphite merge-when-ready\", how.off);\n return description;\n}\nconst schemas = (list, workflows = null) => list.map(([name, description, , properties, required]) => ({ name, description: describeAction(name, description, workflows), inputSchema: { type: \"object\", properties, required, additionalProperties: false }, annotations: { readOnlyHint: readOnlyTools.has(name), destructiveHint: destructiveTools.has(name) } }));\n/** Action tools: a session Paseo launched as a root agent (FOLLOW_THROUGH_ROOT) while Follow-up runs (fresh hook lease). */\nasync function actionsEnabled() {\n if (!process.env.PASEO_AGENT_ID || process.env.FOLLOW_THROUGH_ROOT !== \"1\" || process.env.FOLLOW_THROUGH_RECOVERY === \"1\") return false;\n try {\n const lease = JSON.parse(await readFile(join(process.env.PASEO_HOME ?? join(homedir(), \".paseo\"), \"plugin-data/follow-through/hooks-enabled.json\"), \"utf8\"));\n return lease.expiresAt > Date.now();\n } catch { return false; }\n}\n/** The bridge input for a tool: action tools travel as { tool, args } through follow.agent-act. */\nconst callInput = (tool, input) => actionNames.has(tool[0]) || overseerNames.has(tool[0]) ? { tool: tool[0], args: input } : input;\n/** The Overseer's routing tools: the session Follow-up launched as its Overseer, while Follow-up runs. */\nasync function overseerEnabled() {\n if (process.env.FOLLOW_THROUGH_OVERSEER !== \"1\" || !process.env.PASEO_AGENT_ID) return false;\n try {\n const lease = JSON.parse(await readFile(join(process.env.PASEO_HOME ?? join(homedir(), \".paseo\"), \"plugin-data/follow-through/hooks-enabled.json\"), \"utf8\"));\n return lease.expiresAt > Date.now();\n } catch { return false; }\n}\nlet scopeCache = null;\nasync function scopeOf(directory, agentId) {\n try {\n const path = join(directory, \"scopes.json\");\n const { mtimeMs } = await stat(path);\n if (scopeCache?.mtimeMs !== mtimeMs) { const file = JSON.parse(await readFile(path, \"utf8\")); scopeCache = { mtimeMs, agents: file.agents ?? {}, workflows: file.workflows ?? null }; }\n return scopeCache.agents[agentId]?.role ?? null;\n } catch (error) {\n if (error?.code !== \"ENOENT\") throw error;\n const state = JSON.parse(await readFile(join(directory, \"state.json\"), \"utf8\"));\n for (const w of state.workspaces) {\n if (!w.enable_tracking || w.archived) continue;\n if (w.mainAgentId === agentId) return \"main\";\n if (w.batches.some(b => b.recipientAgentId === agentId && !b.settledAt && [\"sending\", \"sent\", \"blocked\", \"uncertain\"].includes(b.state) && b.tasks.every(t => t.kind === \"inventory\"))) return \"recovery\";\n if (w.contributorAgentIds?.includes(agentId)) return \"contributor\";\n }\n return null;\n }\n}\n/** This agent's PR workflow from scopes.json (undefined: an older worker, which meant Graphite with /fix-pr). */\nconst workflowOf = agentId => scopeCache ? scopeCache.agents[agentId]?.workflow : undefined;\n/** Whether the repositories Follow-up knows ship through Graphite, GitHub or both (\"mixed\"); null: unknown, as before. */\nconst workflowsOf = () => scopeCache?.workflows ?? null;\nasync function scope(resolveRecovery = false) {\n const agentId = process.env.PASEO_AGENT_ID;\n if (!agentId) return null;\n try {\n const home = process.env.PASEO_HOME ?? join(homedir(), \".paseo\");\n const directory = join(home, \"plugin-data/follow-through\");\n const lease = JSON.parse(await readFile(join(directory, \"hooks-enabled.json\"), \"utf8\"));\n if (!(lease.expiresAt > Date.now())) return null;\n // scopes.json (a few KB, rewritten only when a role changes) instead of the whole state.json; re-read only\n // when its mtime changes. Older workers don't write it, so fall back to state.json.\n const known = await scopeOf(directory, agentId);\n if (known === \"main\") return process.env.FOLLOW_THROUGH_RECOVERY === \"1\" ? \"recovery\" : \"main\";\n if (known) return known;\n if (resolveRecovery && process.env.FOLLOW_THROUGH_RECOVERY === \"1\") {\n const w = await call(\"follow.agent-status\", {});\n if (w.enable_tracking && !w.archived && w.mainAgentId !== agentId && w.batches.some(b => b.recipientAgentId === agentId && !b.settledAt && [\"sending\", \"sent\", \"blocked\", \"uncertain\"].includes(b.state) && b.tasks.every(t => t.kind === \"inventory\"))) return \"recovery\";\n }\n } catch {}\n return null;\n}\nfunction validate(value, schema, path = \"arguments\") {\n const types = Array.isArray(schema.type) ? schema.type : [schema.type];\n const type = value === null ? \"null\" : Array.isArray(value) ? \"array\" : typeof value;\n if (!types.includes(type) && !(type === \"number\" && types.includes(\"integer\") && Number.isInteger(value))) throw new Error(`${path}: expected ${types.join(\" or \")}.`);\n if (schema.enum && !schema.enum.includes(value)) throw new Error(`${path}: choose ${schema.enum.join(\", \")}.`);\n if (type === \"object\") {\n const extra = Object.keys(value).filter(k => !Object.hasOwn(schema.properties ?? {}, k));\n if (extra.length && schema.additionalProperties === false) throw new Error(`Unknown argument ${path}.${extra.join(\", \")}. ${extra.includes(\"dependsOnPrs\") ? \"Use afterPrs with owner/repo#number keys.\" : \"Check this tool's input schema with list.\"}`);\n for (const key of schema.required ?? []) if (!(key in value)) throw new Error(`${path}.${key} is required. Check this tool's input schema with list.`);\n for (const [key, nested] of Object.entries(value)) if (schema.properties?.[key]) validate(nested, schema.properties[key], `${path}.${key}`);\n }\n if (type === \"array\") for (let i = 0; i < value.length; i++) validate(value[i], schema.items, `${path}[${i}]`);\n if (type === \"number\" && (schema.minimum !== undefined && value < schema.minimum || schema.maximum !== undefined && value > schema.maximum)) throw new Error(`${path}: outside the allowed range.`);\n if (type === \"string\" && (schema.minLength !== undefined && value.length < schema.minLength || schema.maxLength !== undefined && value.length > schema.maxLength)) throw new Error(`${path}: outside the allowed length.`);\n}\nfunction currentWork(w) {\n return { id: w.id, title: w.title, goal: w.goal, mainAgentId: w.mainAgentId, enable_tracking: w.enable_tracking, enable_auto_sends: w.enable_auto_sends, hold: w.hold, archived: w.archived, runtimeBusy: w.runtimeBusy, runtimeReason: w.runtimeReason, backgroundBusy: w.backgroundBusy, completion: w.completion,\n prs: w.prs.map(p => ({ key: p.key, stack: p.stack, parent: p.parent, disposition: p.disposition, error: p.error, ...(p.snapshot ? { title: p.snapshot.title, state: p.snapshot.state, head: p.snapshot.head, draft: p.snapshot.draft, reviewDecision: p.snapshot.reviewDecision, conflict: p.snapshot.conflict, openThreads: p.snapshot.threads.length, failedChecks: p.snapshot.failedChecks, otherFailedChecks: p.snapshot.otherFailedChecks ?? [], deployment: p.snapshot.deployment } : {}) })),\n obligations: w.obligations.filter(o => ![\"done\", \"waived\"].includes(o.status)), completedObligations: w.obligations.filter(o => [\"done\", \"waived\"].includes(o.status)).length,\n openQuestions: (w.questions ?? []).filter(q => !q.answer && !q.closed).map(q => ({ id: q.id, title: q.title, question: q.question, options: q.options, recommend: q.recommend, big: q.big, mode: q.mode, askedBy: q.askedBy, taskId: q.taskId })),\n spec: w.spec?.url ? { url: w.spec.url, title: w.spec.title, source: w.spec.source } : null,\n recentAnswers: (w.questions ?? []).filter(q => q.answer).slice(-5).map(q => ({ id: q.id, title: q.title, choice: q.answer.choice, words: q.answer.words, delivery: q.answer.delivery.state })),\n batches: w.batches.filter(b => ![\"completed\", \"cancelled\"].includes(b.state)).map(b => ({ id: b.id, state: b.state, tasks: b.tasks, result: b.result, recipientAgentId: b.recipientAgentId, contextPath: b.contextPath })),\n excludedStacks: w.excludedStacks.map(s => ({ name: s.name, reason: s.reason, prs: s.prs.map(p => p.key) })), ...(w.prWorkflow ? { prWorkflow: w.prWorkflow } : {}), detail: \"summary\" };\n}\nfunction compact(tool, input, result) {\n if (actionNames.has(tool)) return result;\n if (tool === \"workspace_status\") return currentWork(result);\n if (tool === \"needs_you\") return { ok: result.ok, briefId: result.briefId };\n if (tool === \"declare_done\") return { workspaceId: result.workspace.id, completion: result.workspace.completion, blockers: result.blockers };\n if (tool === \"ask_question\") return { workspaceId: result.workspaceId, question: { id: result.question.id, title: result.question.title, recommend: result.question.recommend, big: result.question.big }, mode: result.mode, instruction: result.instruction, ...(result.outcome && result.outcome !== \"asked\" ? { outcome: result.outcome, of: result.of } : {}) };\n if (tool === \"record_answer\" || tool === \"withdraw_question\") return { workspaceId: result.workspaceId, question: { id: result.question.id, answer: result.question.answer, closed: result.question.closed } };\n if (tool === \"set_spec\") return { workspaceId: result.workspaceId, spec: result.spec && { url: result.spec.url, title: result.spec.title, source: result.spec.source }, applied: result.applied, message: result.message };\n if (!result?.prs) return result;\n const workspaceId = result.id;\n if (tool === \"enroll_workspace\") return { workspaceId, goal: result.goal };\n if (tool === \"register_pr\") { const p = result.prs.find(p => p.key === `${input.repo}#${input.number}`); return { workspaceId, pr: { key: p.key, stack: p.stack, parent: p.parent, disposition: p.disposition } }; }\n if (tool === \"update_obligation\") return { workspaceId, obligation: result.obligations.find(o => o.id === result.updatedObligationId) };\n if (tool === \"acknowledge_batch\") { const b = result.batches.find(b => b.id === input.batchId); return { workspaceId, batch: { id: b.id, state: b.state, result: b.result } }; }\n if (tool === \"exclude_stack\") { const s = result.excludedStacks.find(s => s.name === input.stack); return { workspaceId, excludedStack: { name: s.name, reason: s.reason, prs: s.prs.map(p => p.key) } }; }\n return result;\n}\nasync function loadClient() {\n const candidates = [];\n if (process.env.FOLLOW_THROUGH_CLIENT_ENTRY) candidates.push(() => pathToFileURL(process.env.FOLLOW_THROUGH_CLIENT_ENTRY).href);\n const specifier = \"@getpaseo/client/internal/daemon-client\";\n if (process.resourcesPath) candidates.push(() => pathToFileURL(createRequire(join(process.resourcesPath, \"app.asar/node_modules/@getpaseo/cli/dist/index.js\")).resolve(specifier)).href);\n for (const directory of (process.env.PATH ?? \"\").split(delimiter)) {\n const cli = join(directory, process.platform === \"win32\" ? \"paseo.cmd\" : \"paseo\");\n if (existsSync(cli)) candidates.push(() => pathToFileURL(createRequire(realpathSync(cli)).resolve(specifier)).href);\n }\n candidates.push(() => pathToFileURL(createRequire(import.meta.url).resolve(specifier)).href);\n for (const resolve of candidates) try { return await import(resolve()); } catch {}\n throw new Error(\"Cannot load the installed Paseo client. Reload Follow-through to refresh its runtime connection.\");\n}\nconst batchInstructionsMain = \"Follow-through batches contain a header with the batchId and ordered tasks. Read workspace_status and refresh live conditions; skip resolved tasks. Process PRs bottom to top, one fully before the next, using the repository's /fix-pr and safe reparent workflow. Validate feedback, verify changes, submit with Graphite --publish, reply/resolve addressed threads and preserve uncommitted work. Post-deploy tasks require verified serving revisions and existing production permissions. Stakeholder update requests are follow-through tasks: retain the original thread, recipient and developer authorization in communication. Use current evidence, distinguish fixed/deployed/verified, and read existing replies before posting. Record the sent replyUrl; a draft or uncertain send stays blocked and must be checked before retrying. Auto authorizes agent delivery only. Acknowledge the header's batchId with acknowledge_batch before finishing (completed with the result, or blocked with the reason), before declare_done for completion batches. Declare Done only after the whole goal and post-merge work are verified. Leave merging and archiving to the developer.\";\n/**\n * The batch rules for this workspace's PR workflow. Graphite with /fix-pr (and any agent from before workflows\n * existed) gets the original text unchanged; plain GitHub never mentions Graphite, gt or a review command it doesn't have.\n */\nfunction batchInstructions(workflow) {\n const mode = workflow?.mode ?? \"graphite\";\n const fix = workflow === undefined || workflow === null ? \"/fix-pr\" : workflow.reviewFix ?? null;\n if (mode === \"graphite\" && fix === \"/fix-pr\") return batchInstructionsMain;\n const fixing = fix ? `using the repository's ${fix} workflow for review comments` : \"reading each PR's unresolved review threads with gh\";\n const restack = mode === \"graphite\" ? \"the repository's safe reparent workflow\" : \"base branches kept in a chain (restack with git rebase --update-refs, push with --force-with-lease, and after a parent merges retarget its child with gh pr edit --base if GitHub didn't)\";\n const submit = mode === \"graphite\" ? \"submit with Graphite --publish\" : \"push the branch (gh pr create for a new PR, gh pr ready when it leaves draft)\";\n const reply = fix ? \"reply/resolve addressed threads\" : \"reply to each addressed thread and resolve it\";\n return batchInstructionsMain\n .replace(\"using the repository's /fix-pr and safe reparent workflow.\", `${fixing}, with ${restack}.`)\n .replace(\"submit with Graphite --publish, reply/resolve addressed threads\", `${submit}, ${reply}`);\n}\n\nasync function call(method, input) {\n const agentId = process.env.PASEO_AGENT_ID;\n if (!agentId) throw new Error(\"This bridge must run inside a Paseo agent (PASEO_AGENT_ID is missing).\");\n const { DaemonClient } = await loadClient();\n const home = process.env.PASEO_HOME ?? join(homedir(), \".paseo\");\n const config = JSON.parse(await readFile(join(home, \"config.json\"), \"utf8\"));\n let password = process.env.PASEO_PASSWORD;\n if (!password && process.env.PASEO_PASSWORD_FILE) password = (await readFile(process.env.PASEO_PASSWORD_FILE, \"utf8\")).trim();\n if (!password && home === join(homedir(), \".paseo\")) password = await readFile(join(homedir(), \"paseo-hub/secrets/daemon-password\"), \"utf8\").then(s => s.trim()).catch(() => undefined);\n const client = new DaemonClient({ url: process.env.PASEO_DAEMON_URL ?? `ws://${config.daemon?.listen ?? \"127.0.0.1:6767\"}/ws`, clientId: \"follow-through-mcp\", clientType: \"cli\", reconnect: { enabled: false }, connectTimeoutMs: 10000, suppressSendErrors: true, ...(password ? { password } : {}) });\n try { await client.connect(); return await client.invokePluginRpc(\"follow-through\", method, { ...input, agentId }); }\n finally { await client.close().catch(() => undefined); }\n}\n\n\n// The worker imports this file for the same tool tables, validation and receipts (1.4.0-beta.2: Follow-up's tools\n// served natively through Paseo's own MCP). Only a direct run is the CLI / stdio bridge.\nexport { tools, actionTools, overseerTools, toolList, schemas, validate, compact, callInput, needsYouInstruction, actionInstruction, overseerInstruction, waitInstruction, batchInstructions, describeAction };\nfunction isMain() {\n try { return !!process.argv[1] && !!import.meta.url && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href; } catch { return false; }\n}\nif (isMain()) runMain().catch(error => { console.error(error?.message ?? String(error)); process.exitCode = 1; });\nasync function runMain() {\nconst command = process.argv[2];\nif (command === \"list\" || command === \"--help\" || command === \"help\") {\n process.stdout.write(command === \"list\" ? JSON.stringify({ tools: schemas([...toolList(undefined, false, true, false, true), ...overseerTools]) }, null, 2) + \"\\n\" : \"Usage: node mcp.mjs list | call <tool> '<json>' [--compact]\\nNative MCP returns compact receipts; workspace_status({detail:full}) requests complete history. CLI calls retain full replies unless --compact is supplied.\\n\");\n} else if (command === \"call\") {\n try {\n const tool = [...toolList(undefined, false, await briefEnabled(), false, await actionsEnabled()), ...(await overseerEnabled() ? overseerTools : [])].find(t => t[0] === process.argv[3]);\n if (!tool) throw new Error(\"Unknown tool. Run list for names and input schemas.\");\n const input = JSON.parse(process.argv[4] ?? \"{}\");\n validate(input, schemas([tool])[0].inputSchema);\n if (process.argv.slice(5).some(arg => arg !== \"--compact\")) throw new Error(\"Unknown CLI option. Use --compact or omit it for a full reply.\");\n const result = await call(tool[2], callInput(tool, input));\n process.stdout.write(JSON.stringify(process.argv.includes(\"--compact\") && input.detail !== \"full\" ? compact(tool[0], input, result) : result, null, 2) + \"\\n\");\n } catch (error) { console.error(error.message); process.exitCode = 1; }\n} else if (command) {\n console.error(\"Unknown command. Use list, --help, or call <tool> '<json>'.\"); process.exitCode = 1;\n} else {\n const lines = createInterface({ input: process.stdin });\n let tail = Promise.resolve(), initialized = false, lastScope = null;\n const timer = process.env.PASEO_AGENT_ID ? setInterval(() => {\n void (async () => { const current = `${await scope()}:${await briefEnabled()}:${await actionsEnabled()}:${await overseerEnabled()}`; if (initialized && current !== lastScope) process.stdout.write(JSON.stringify({ jsonrpc: \"2.0\", method: \"notifications/tools/list_changed\" }) + \"\\n\"); lastScope = current; })().catch(() => {});\n }, 2000) : null;\n timer?.unref(); lines.on(\"close\", () => { if (timer) clearInterval(timer); });\n lines.on(\"line\", line => {\n tail = tail.then(async () => {\n let request;\n try { request = JSON.parse(line); } catch { return; }\n if (request.id === undefined) return;\n try {\n let result;\n const role = await scope(request.method === \"initialize\" || request.method === \"tools/list\");\n const brief = await briefEnabled();\n const acting = await actionsEnabled();\n const overseeing = await overseerEnabled();\n const workflow = workflowOf(process.env.PASEO_AGENT_ID);\n const available = [...(role ? toolList(role === \"recovery\", role === \"contributor\", brief, false, acting) : toolList(false, false, brief, true, acting)), ...(overseeing ? overseerTools : [])];\n if (request.method === \"initialize\") {\n initialized = true; lastScope = `${role}:${brief}:${acting}:${overseeing}`;\n result = { protocolVersion: request.params?.protocolVersion ?? \"2024-11-05\", capabilities: { tools: { listChanged: true } }, serverInfo: { name: \"paseo-follow-through\", version: \"0.3.5\" }, instructions: (role ? (role === \"contributor\" ? \"Register PRs this session submits, including from secondary git worktrees. Read workspace_status and call sync_workspace before finishing. Goal, task, scope and completion changes remain with the designated main agent.\" : role === \"recovery\" ? \"Recover tracking metadata from evidence, acknowledge your assigned batch, and leave completion to the main agent.\" : \"Keep workspace follow-through updated after PR submission and scope changes. Read workspace_status after compaction. Track all post-merge work. When a decision needs the developer, ask it with ask_question (lettered options and a recommendation) and follow the question mode in its reply. If you keep a spec artifact for this workspace, register its link once with set_spec. \" + batchInstructions(workflow)) + \" Perform bookkeeping silently: no sidebar-update announcements, plugin-status commentary or final sidebar recap. Put receipts and summaries in tools. Report actual work outcomes or decisions/blockers; discuss sidebar status only when explicitly asked.\" : brief ? \"\" : \"Follow-through tools are available to tracked workspace root agents and active recovery agents; contributor sessions receive PR registration and status tools.\") + (brief && role !== \"contributor\" && role !== \"recovery\" ? (role ? \" \" : \"\") + needsYouInstruction : \"\") + (acting && role !== \"contributor\" && role !== \"recovery\" ? \" \" + actionInstruction : \"\") + (overseeing ? \" \" + overseerInstruction : \"\") };\n } else if (request.method === \"ping\") result = {};\n else if (request.method === \"tools/list\") result = { tools: schemas(available, workflowsOf()) };\n else if (request.method === \"tools/call\") {\n const tool = available.find(t => t[0] === request.params?.name);\n try {\n if (!tool) throw new Error(\"This tool is unavailable for the current agent. Tracking must be active; recovery authority ends after acknowledgment.\");\n const input = request.params.arguments ?? {}; validate(input, schemas([tool])[0].inputSchema);\n const value = await call(tool[2], callInput(tool, input));\n result = { content: [{ type: \"text\", text: JSON.stringify(input.detail === \"full\" ? value : compact(tool[0], input, value)) }] };\n } catch (error) { result = { isError: true, content: [{ type: \"text\", text: error.message }] }; }\n } else { process.stdout.write(JSON.stringify({ jsonrpc: \"2.0\", id: request.id, error: { code: -32601, message: \"Method not found\" } }) + \"\\n\"); return; }\n process.stdout.write(JSON.stringify({ jsonrpc: \"2.0\", id: request.id, result }) + \"\\n\");\n } catch (error) { process.stdout.write(JSON.stringify({ jsonrpc: \"2.0\", id: request.id, error: { code: -32603, message: error.message } }) + \"\\n\"); }\n });\n });\n}\n}\n";
|
|
2
|
+
export const mcpSource = "#!/usr/bin/env node\nimport { createInterface } from \"node:readline\";\nimport { createRequire } from \"node:module\";\nimport { pathToFileURL } from \"node:url\";\nimport { readFile, stat } from \"node:fs/promises\";\nimport { existsSync, realpathSync } from \"node:fs\";\nimport { join, delimiter } from \"node:path\";\nimport { homedir } from \"node:os\";\n\nconst string = { type: \"string\" };\nconst boolean = { type: \"boolean\" };\nconst integer = { type: \"integer\", minimum: 1 };\nconst array = { type: \"array\", items: string };\nconst 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 };\nconst trigger = { type: [\"object\", \"null\"], properties: { event: { type: \"string\", enum: [\"now\", \"merge\", \"deploy\"] }, delayDays: { type: \"integer\", minimum: 0, maximum: 3650 } }, required: [\"event\"], additionalProperties: false };\nconst tools = [\n [\"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-through does not require recovery.\", \"follow.agent-status\", { detail: { type: \"string\", enum: [\"summary\", \"full\"] } }, []],\n [\"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\"]],\n [\"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\"]],\n [\"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.\", \"follow.register-pr\", { repo: string, number: integer, stack: string, parentNumber: { type: [\"integer\", \"null\"], minimum: 1 }, disposition: string }, [\"repo\", \"number\", \"stack\"]],\n [\"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\"]],\n [\"update_obligation\", \"Record concrete follow-through: verification, migrations, decisions or stakeholder replies. Never add approve/merge/deploy checklist tasks. afterPrs uses owner/repo#number keys. Tasks are manual unless explicitly scheduled with trigger={event:\\\"now\\\"|\\\"merge\\\"|\\\"deploy\\\",delayDays:0}. Only set a trigger 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 makes a task manual. 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.\", \"follow.obligation\", { id: string, title: string, status: { type: \"string\", enum: [\"pending\", \"waiting\", \"working\", \"blocked\", \"done\", \"waived\"] }, afterPrs: array, dependencyStage: { type: \"string\", enum: [\"merged\", \"deployed\"] }, evidence: string, enable_follow_up: boolean, communication, trigger }, [\"title\", \"status\"]],\n [\"acknowledge_batch\", \"Record a follow-up result. Complete only after verifying all tasks; blocked surfaces the reason to the developer. Always acknowledge before ending a repair turn. Keep the result within 2000 characters.\", \"follow.acknowledge\", { batchId: string, outcome: { type: \"string\", enum: [\"completed\", \"blocked\"] }, result: { ...string, maxLength: 2000 } }, [\"batchId\", \"outcome\", \"result\"]],\n [\"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. 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.\", \"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\"]],\n [\"record_answer\", \"Record the developer's answer when they answered a question in chat instead of in Follow-up. choice is an option letter, 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\"]],\n [\"withdraw_question\", \"Withdraw a question that no longer matters, with a short reason.\", \"follow.withdraw-question\", { id: string, reason: string }, [\"id\", \"reason\"]],\n [\"set_spec\", \"Register the link to this workspace's spec: the Claude artifact (or doc) you keep summarizing the goal, decisions and status. Call it once after the first publish, with the URL from the publish result, and again only if the link changes. Follow-up shows it in the workspace header.\", \"follow.set-spec\", { url: { ...string, maxLength: 2000 }, title: { ...string, maxLength: 120 } }, [\"url\"]],\n [\"needs_you\", \"Call once at the end of a turn, just before your final reply: what the developer has to do next. ask is one line (≤120). kind: decision (give decisions with 2–5 options, a consequence each and recommend=<option index>; with several decisions the developer answers them together and you get one message with a line per decision, skipped ones marked as skipped; a decision that is already an open question goes in questions=[\\\"Q18\\\"] instead, never restated), action (something only they can do: merge, approve, log in, run or send), review (a PR to review and merge; link it with pr), or done (\\\"Nothing needed. <what you finished>.\\\": nothing for the developer, won't flag you). context ≤400 chars: only what they need to decide. Never blocks and never changes what you should do next.\", \"follow.needs-you\", { ask: { ...string, minLength: 1, maxLength: 120 }, kind: { type: \"string\", enum: [\"decision\", \"action\", \"review\", \"done\"] }, decisions: { type: \"array\", maxItems: 3, items: { type: \"object\", properties: { question: { ...string, minLength: 1, maxLength: 200 }, options: { type: \"array\", minItems: 2, maxItems: 5, items: { type: \"object\", properties: { label: { ...string, minLength: 1, maxLength: 60 }, consequence: { ...string, maxLength: 160 } }, required: [\"label\"], additionalProperties: false } }, recommend: { type: \"integer\", minimum: 0, maximum: 4 } }, required: [\"question\"], additionalProperties: false } }, questions: { type: \"array\", maxItems: 3, items: { type: \"string\", pattern: \"^Q\\\\d+$\" } }, context: { ...string, maxLength: 400 }, links: { type: \"array\", maxItems: 4, items: { type: \"object\", properties: { label: string, url: string, path: string, pr: string }, required: [\"label\"], additionalProperties: false } } }, [\"ask\", \"kind\"]],\n [\"declare_done\", \"Declare that the workspace goal is fulfilled. Live PR status and remaining obligations are checked. The reply's `next` says what is missing and whether it is yours to fix; follow it and do not repeat the call when nothing is yours to fix. A deploy Follow-up cannot confirm does not block Done; it is noted. Calling again after Done changes nothing. Done labels the workspace but never archives it.\", \"follow.done\", { summary: string }, [\"summary\"]],\n];\n\n// Agent parity: every action the developer can click in Follow-up, through the same server path (follow.agent-act).\n// Planned tools return a dry run; confirm=true with its planId runs it. Use them only when the developer asked.\nconst planned = { planId: string, confirm: boolean };\nconst prKey = { ...string, description: \"owner/repo#number, from list_prs\" };\nconst ask = \" Only when the developer asked for it. Returns a dry-run plan first; run it with confirm=true and the planId.\";\nconst read = \" Read-only.\";\nconst actionTools = [\n [\"list_prs\", \"List tracked PRs across all workspaces with state, draft, checks, open threads, requested reviewers and merge blockers. Filters: needs_reviewers, ready_to_merge, workspace (id or title). This is how you act \\\"on all\\\".\", \"follow.agent-act\", { workspace: string, needs_reviewers: boolean, ready_to_merge: boolean, include_closed: boolean }, []],\n [\"add_reviewers\", \"Request reviewers on one or many PRs, the same as the Add reviewers button. Without reviewers, asks the developer's saved reviewers for that repository (each PR row in list_prs shows them as configuredReviewers, with source repo, default or none); otherwise the GitHub logins or org/team slugs you give.\" + ask, \"follow.agent-act\", { prs: { type: \"array\", items: prKey }, reviewers: array, ...planned }, []],\n [\"merge\", \"Merge a PR (and its downstack with scope=downstack) through Graphite, using Follow-up's merge plan and blockers. Can't be undone.\" + ask, \"follow.agent-act\", { pr: prKey, scope: { type: \"string\", enum: [\"target\", \"downstack\"] }, ...planned }, []],\n [\"enable_merge_when_ready\", \"Turn on Graphite merge-when-ready for a PR, as the PR sheet does.\" + ask, \"follow.agent-act\", { pr: prKey, scope: { type: \"string\", enum: [\"target\", \"downstack\"] }, ...planned }, []],\n [\"disable_merge_when_ready\", \"Turn off Graphite merge-when-ready for a PR.\" + ask, \"follow.agent-act\", { pr: prKey, scope: { type: \"string\", enum: [\"target\", \"downstack\"] }, ...planned }, []],\n [\"send_repairs\", \"Send a workspace's waiting repairs (review threads, failed checks) to its main agent, like the Send button. Only when the developer asked. batchId defaults to the waiting batch.\", \"follow.agent-act\", { workspace: string, batchId: string }, [\"workspace\"]],\n [\"set_auto_send\", \"Turn Auto-send on or off for a workspace, like its switch. Only when the developer asked.\", \"follow.agent-act\", { workspace: string, value: boolean }, [\"workspace\", \"value\"]],\n [\"clear_hold\", \"Resume Follow-up on a held workspace, like the Resume button. Only when the developer asked.\", \"follow.agent-act\", { workspace: string }, [\"workspace\"]],\n [\"retry_batch\", \"Queue a blocked or uncertain repair batch again, like the Retry button. Only when the developer asked.\", \"follow.agent-act\", { workspace: string, batchId: string }, [\"workspace\", \"batchId\"]],\n [\"track\", \"Follow a workspace again after the developer opted it out in Settings. Follow-up follows every workspace by default. Only when the developer asked.\", \"follow.agent-act\", { workspace: string }, [\"workspace\"]],\n [\"workspace_about\", \"Read what a workspace is about: a short AI overview (goal, where it stands, what's left), a one-line gist, and its linked Linear issues, PRs, Slack threads and docs. Read-only; writes the overview first when none is cached (up to ~90 s). workspaceId is a workspace id or exact title from list_prs.\", \"follow.agent-act\", { workspaceId: string }, [\"workspaceId\"]],\n [\"agent_settings\", \"Read which agent each of Follow-up's special roles uses (What's this about?, Overseer, Recovery, Priority ranker): provider, model, effort, mode and limits, and whether Wait for background jobs is on. Read-only; Tom changes them in Follow-up settings → Agents.\", \"follow.agent-act\", {}, []],\n [\"inbox_list\", \"Read the developer's Needs-you inbox: each root agent, whether it is flagged and why, snoozes and finish flags. Your own row has self=true.\", \"follow.agent-act\", { flagged_only: boolean }, []],\n [\"sign_off\", \"Sign off other agents' Needs-you flags on the developer's behalf, like Sign off. Never your own.\" + ask, \"follow.agent-act\", { agentIds: array, ...planned }, []],\n [\"snooze\", \"Snooze other agents' flags (until: next-event, 1h, tomorrow or an ISO time), like Later.\" + ask, \"follow.agent-act\", { agentIds: array, until: string, ...planned }, []],\n [\"set_finish_flags\", \"Turn finish flags on or off for other agents, like Don't flag finishes.\" + ask, \"follow.agent-act\", { agentIds: array, value: boolean, ...planned }, []],\n [\"set_priorities\", \"Rank workspaces for Home's Priority sort: per workspace (id or exact title) a score 0-100, a one-line reason the developer sees, and its sources [{kind: linear|slack|planning|github|paseo, label, url}]. replace=true drops workspaces you leave out. Used for 6 hours. Returns a dry run; store it with confirm=true and the planId.\", \"follow.agent-act\", { priorities: { type: \"array\", items: { type: \"object\", properties: { workspace: string, score: { type: \"integer\", minimum: 0, maximum: 100 }, reason: { ...string, maxLength: 140 }, sources: { type: \"array\", items: { type: \"object\", properties: { kind: { type: \"string\", enum: [\"linear\", \"slack\", \"planning\", \"github\", \"paseo\"] }, label: string, url: string }, required: [\"kind\", \"label\"] } } }, required: [\"workspace\", \"score\", \"reason\"] } }, replace: boolean, ...planned }, [\"priorities\"]],\n // Settings, onboarding, Home and the panel, one developer RPC each (server/agent-parity.ts). Writes plan first.\n [\"make_main_agent\", \"Make yourself or another root agent of this workspace its main agent (the one that asks the developer, reports Needs-you and calls Done). requested=developer when the developer asked for it (refused only while the main is mid-turn); requested=self for your own claim, allowed only when the main is archived, gone or closed 30 minutes, or you registered every open PR and the main has been idle 24 hours, and never within 30 minutes of a change or 2 hours after you lost the role. Give a one-line reason the developer sees. Returns a dry run; run it with confirm=true and the planId.\", \"follow.agent-act\", { agentId: string, reason: string, requested: { type: \"string\", enum: [\"developer\", \"self\"] }, ...planned }, []],\n [\"display_settings\", \"Read Settings → Display: the header button, sidebar item, composer pill, Needs-you inbox, closed-PR flags, brief nudge, Overseer, ranker and trust bypass switches.\" + read, \"follow.agent-act\", {}, []],\n [\"set_display\", \"Change Settings → Display switches, e.g. { values: { enable_trust_bypass: false } }. Keys from display_settings.\" + ask, \"follow.agent-act\", { values: { type: \"object\", additionalProperties: boolean }, ...planned }, []],\n [\"follow_settings\", \"Read Settings → Following: follow every workspace, the Auto-send default, the active window, and per-workspace exceptions.\" + read, \"follow.agent-act\", {}, []],\n [\"set_follow_settings\", \"Change Settings → Following: enable_follow_every, enable_auto_sends_default, activeWindowDays (1-60), or one workspace's exception { workspaceId, follow, enable_auto_sends }.\" + ask, \"follow.agent-act\", { enable_follow_every: boolean, enable_auto_sends_default: boolean, activeWindowDays: { type: \"integer\", minimum: 1, maximum: 60 }, workspace: { type: \"object\" }, ...planned }, []],\n [\"project_settings\", \"Read each project and whether Follow-up follows its new workspaces by default.\" + read, \"follow.agent-act\", {}, []],\n [\"set_project_tracking\", \"Follow a project's new workspaces by default, or stop: { projectId, enable_default_tracking }.\" + ask, \"follow.agent-act\", { projectId: string, enable_default_tracking: boolean, ...planned }, []],\n [\"pr_workflow\", \"Read Settings → Following → Shipping PRs: each repository's PR workflow (graphite or github), merge method and review-fix setting, and the default. refresh=true re-detects.\" + read, \"follow.agent-act\", { refresh: boolean }, []],\n [\"set_pr_workflow\", \"Change Shipping PRs: per repository (repo owner/name) its setting, mergeMethod or reviewFix (null clears back to the default), or the default.\" + ask, \"follow.agent-act\", { repo: string, setting: { type: [\"string\", \"null\"] }, default: string, mergeMethod: { type: [\"string\", \"null\"] }, reviewFix: { type: [\"object\", \"null\"] }, ...planned }, []],\n [\"reviewer_settings\", \"Read Settings → Reviewers: the default reviewers and each repository's own list.\" + read, \"follow.agent-act\", {}, []],\n [\"reviewer_suggestions\", \"Suggest reviewers for a repository (owner/name) from its recent history.\" + read, \"follow.agent-act\", { repo: string }, [\"repo\"]],\n [\"save_reviewers\", \"Save the reviewers Add reviewers asks: repo owner/name, or null for the default; reviewers [{ login, name?, kind? }].\" + ask, \"follow.agent-act\", { repo: { type: [\"string\", \"null\"] }, reviewers: { type: \"array\", items: { type: \"object\" } }, ...planned }, []],\n [\"set_agent_setting\", \"Change which agent a special role uses (Settings → Agents): role about|overseer|recovery|ranker, entry { provider, model, ... } or null for the default. agent_settings shows the current ones.\" + ask, \"follow.agent-act\", { role: string, entry: { type: [\"object\", \"null\"] }, ...planned }, []],\n [\"set_wait_for_jobs\", \"Turn Settings → Agents → Wait for background jobs on or off (enable_wait), like its switch. Applies to sessions opened afterwards. agent_settings shows it.\" + ask, \"follow.agent-act\", { enable_wait: boolean, ...planned }, []],\n [\"onboarding_status\", \"Read the setup guide's state: whether it was finished or skipped, and the current step.\" + read, \"follow.agent-act\", {}, []],\n [\"onboarding_checks\", \"Run the setup checks (GitHub login, providers, ...) and return each result with its fix. fresh=true re-runs them.\" + read, \"follow.agent-act\", { fresh: boolean }, []],\n [\"set_onboarding\", \"Move the setup guide: action start|step|finish|skip|restart|dismiss-offer, step for action=step.\" + ask, \"follow.agent-act\", { action: string, step: string, ...planned }, []],\n [\"priorities\", \"Read the stored priorities behind Home's Priority sort.\" + read, \"follow.agent-act\", {}, []],\n [\"rank_status\", \"Read the priority ranker's state: last run, whether it's running, and errors.\" + read, \"follow.agent-act\", {}, []],\n [\"rerank_priorities\", \"Re-rank Home's Priority sort now, like Re-rank. force=true re-runs even when nothing changed.\" + ask, \"follow.agent-act\", { force: boolean, ...planned }, []],\n [\"usage\", \"Read provider usage limits and the VM's memory meter, as Home shows them.\" + read, \"follow.agent-act\", {}, []],\n [\"overseer_status\", \"Read the Overseer's state: running, its agent and model, and what a restart would use.\" + read, \"follow.agent-act\", {}, []],\n [\"overseer_start\", \"Start the Overseer, like Start on Home.\" + ask, \"follow.agent-act\", { ...planned }, []],\n [\"overseer_restart\", \"Restart the Overseer (with the model Settings → Agents names now).\" + ask, \"follow.agent-act\", { ...planned }, []],\n [\"overseer_ask\", \"Send the developer's words to the Overseer, as its box on Home does: { text }.\" + ask, \"follow.agent-act\", { text: string, ...planned }, []],\n [\"inbox_brief\", \"Read another agent's full Needs-you brief (decisions, options, links): { agentId }.\" + read, \"follow.agent-act\", { agentId: string }, [\"agentId\"]],\n [\"brief_action\", \"Answer another agent's brief for the developer, like its card: { agentId, briefId, decisionId + choice, or choices [{ decisionId, choice }], or move: retry }. Never your own brief.\" + ask, \"follow.agent-act\", { agentId: string, briefId: string, decisionId: string, choice: string, move: string, choices: { type: \"array\", items: { type: \"object\" } }, ...planned }, []],\n [\"inbox_act\", \"The inbox's other actions on other agents' rows: action undo|mute_turn|unsorted_flag|unsorted_sign_off|batch_undo, agentIds.\" + ask, \"follow.agent-act\", { action: string, agentIds: array, muteTurn: boolean, ...planned }, []],\n [\"answer_question\", \"Send the developer's answer to another agent's question (Q1…), like its card: { workspaceId, questionId, choice, words }. For a question you asked, use record_answer.\" + ask, \"follow.agent-act\", { workspaceId: string, questionId: string, choice: string, words: string, ...planned }, []],\n [\"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 }, []],\n [\"refresh\", \"Refresh PR status now, like Refresh. Cheap; use when status looks stale.\", \"follow.agent-act\", { workspaceId: string }, []],\n [\"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 }, []],\n [\"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 }, []],\n [\"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\"]],\n [\"browser_status\", \"Read whether Send to Paseo is paired and which repositories it may control.\" + read, \"follow.agent-act\", {}, []],\n [\"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.\" + read, \"follow.agent-act\", {}, []],\n [\"trust_bypass_status\", \"Read how many permission prompts trust bypass approved today, and the latest ones.\" + read, \"follow.agent-act\", {}, []],\n];\n// The Overseer's routing tools (1.4.0-beta.0): only in the session Follow-up started as its Overseer.\nconst overseerTools = [\n [\"workstreams\", \"Every workspace Tom has, as Home groups them (needs, fixing, running, waiting, later, quiet): title, branch, PRs with checks, main agent and status, current ask, last activity, priority and reason, Linear keys. Paged (page, size ≤100); filter by group or query (name, branch, key, #PR).\", \"follow.overseer-act\", { page: integer, size: integer, group: { type: \"string\", enum: [\"needs\", \"fixing\", \"running\", \"waiting\", \"later\", \"quiet\"] }, query: string }, []],\n [\"agent_digest\", \"One agent's last steps (default 10) summarised, its status and its open asks to Tom (flag, decisions, questions). Use before routing when the digest isn't enough.\", \"follow.overseer-act\", { agentId: string, steps: integer }, [\"agentId\"]],\n [\"route_candidates\", \"Score every workspace for Tom's ask by Linear key, PR number, branch, workspace name, open asks and recent activity. Returns the top 3 and whether one is a confident match.\", \"follow.overseer-act\", { ask: string }, [\"ask\"]],\n [\"send_to_agent\", \"Forward Tom's words to the agent that owns the work, prefixed \\\"From Tom via Overseer:\\\". reply_to_ask=true only when Tom is answering that agent's open ask (it then clears its Needs-you flag). Then tell Tom where it went in one line.\", \"follow.overseer-act\", { agentId: string, text: string, reply_to_ask: boolean }, [\"agentId\", \"text\"]],\n [\"start_workspace\", \"Start a new workspace with an agent for a task, branched off main with the default model. Only when Tom asked for a new workspace or picked it. Returns a dry run (title from the task and Linear key, branch, project); run it with confirm=true and the planId.\", \"follow.overseer-act\", { task: string, title: string, project: string, linear_key: string, base: string, planId: string, confirm: boolean }, []],\n [\"rerank\", \"Re-rank Home's Priority sort now from Linear, Slack, GitHub review requests and the weekly plan, when Tom asks for it. Returns the top 10 with their reasons. Skips the model when nothing changed.\", \"follow.overseer-act\", {}, []],\n];\nconst overseerNames = new Set(overseerTools.map(t => t[0]));\nconst overseerInstruction = \"You are Follow-up's Overseer. Route Tom's asks with route_candidates and send_to_agent; ask with needs_you kind=decision when unsure; start_workspace only when Tom asked or approved. Never merge, post to people or archive.\";\nconst actionNames = new Set(actionTools.map(t => t[0]));\nconst readOnlyTools = new Set([\"workspace_status\", \"list_prs\", \"inbox_list\", \"workstreams\", \"agent_digest\", \"route_candidates\", \"workspace_about\", \"agent_settings\", \"display_settings\", \"follow_settings\", \"project_settings\", \"pr_workflow\", \"reviewer_settings\", \"reviewer_suggestions\", \"onboarding_status\", \"onboarding_checks\", \"priorities\", \"rank_status\", \"usage\", \"overseer_status\", \"inbox_brief\", \"pr_controls\", \"browser_status\", \"trust_bypass_status\", \"release_notes\"]);\nconst destructiveTools = new Set([\"merge\"]);\nconst actionInstruction = \"Follow-up's action tools let you do anything the developer can click, across every tracked workspace and every Settings tab. Read freely: list_prs, inbox_list, inbox_brief, workspace_about, agent_settings, display_settings, follow_settings, project_settings, pr_workflow, reviewer_settings, onboarding_status, priorities, rank_status, usage, overseer_status, pr_controls. Hand the main role on, or claim it, with make_main_agent. Act only when the developer asks (\\\"the PRs look good, assign reviewers on all\\\": list_prs needs_reviewers=true, add_reviewers with those keys, then confirm the plan): add_reviewers, merge, enable/disable_merge_when_ready, send_repairs, set_auto_send, clear_hold, retry_batch, track, run_recovery, set_priorities, rerank_priorities; settings with set_display (trust bypass too), set_follow_settings, set_project_tracking, set_pr_workflow, save_reviewers, set_agent_setting, set_wait_for_jobs, set_onboarding; and sign_off/snooze/set_finish_flags/inbox_act/brief_action/answer_question for other agents. Planned tools return a dry run showing what changes; run it with confirm=true and its planId. Never sign yourself off or answer your own brief.\";\n\n// Wait (folded in from paseo-wait): its three tools are served natively (server/wait.ts), never by this bridge.\n// Native tools carry no MCP instructions, so the agent hook adds this at SessionStart when FOLLOW_THROUGH_WAIT=1.\nconst 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.\";\n\n// The brief's tool: every root agent while the Needs-you inbox is on; never contributors, recovery or subagents.\n// Kept identical to NEEDS_YOU_INSTRUCTION in shared/brief.ts (a test checks it).\nconst needsYouInstruction = \"When you end a turn, call `needs_you` once, just before your final reply, with what the developer has to do next: a decision (give 2–3 options, what each means for them, and the one you recommend), an action only they can take (merge, approve, log in, run or send something), or kind=done (\\\"Nothing needed\\\" plus what you finished, in one line), which means there is nothing for the developer and won't flag you in their inbox. A decision that is already an open question (you asked it with ask_question, or it is still open from an earlier turn) is never restated: point at it with questions=[\\\"Q18\\\"], or say \\\"Still open: Q18 …\\\" in ask. Keep `ask` to one line and `context` to what they need to decide. Don't repeat your report there; still write your normal reply. Don't call it while a permission prompt is waiting or while you're still working.\";\nfunction toolList(recovery = process.env.FOLLOW_THROUGH_RECOVERY === \"1\", contributor = false, brief = false, briefOnly = false, actions = false) {\n // Action tools: root agents (tracked main or untracked) while Follow-up runs; never recovery or contributors.\n // Contributors get make_main_agent only (its claim rules apply); recovery sessions get none.\n const acting = !actions || recovery ? [] : contributor ? actionTools.filter(t => t[0] === \"make_main_agent\") : actionTools;\n if (briefOnly) return [...(brief ? tools.filter(t => t[0] === \"needs_you\") : []), ...acting];\n return [...tools.filter(t => t[0] === \"needs_you\" ? brief && !recovery && !contributor : contributor ? [\"workspace_status\", \"register_pr\", \"sync_workspace\"].includes(t[0]) : !recovery || ![\"declare_done\", \"sync_workspace\", \"ask_question\", \"record_answer\", \"withdraw_question\", \"set_spec\"].includes(t[0])), ...acting];\n}\n/** Whether this session may call needs_you: launched as a root agent (FOLLOW_THROUGH_BRIEF) and the inbox is on. */\nasync function briefEnabled() {\n if (!process.env.FOLLOW_THROUGH_BRIEF || process.env.FOLLOW_THROUGH_RECOVERY === \"1\") return false;\n try {\n const directory = join(process.env.PASEO_HOME ?? join(homedir(), \".paseo\"), \"plugin-data/follow-through\");\n const lease = JSON.parse(await readFile(join(directory, \"hooks-enabled.json\"), \"utf8\"));\n if (!(lease.expiresAt > Date.now())) return false;\n const brief = JSON.parse(await readFile(join(directory, \"brief.json\"), \"utf8\"));\n return brief?.enable_inbox === true;\n } catch { return false; }\n}\n/**\n * Merge and merge-when-ready say how they run. \"github\": every known repository ships plain GitHub, so Graphite is\n * never named; \"mixed\": either, per list_prs prWorkflow; anything else keeps the Graphite wording it always had.\n */\nfunction describeAction(name, description, workflows) {\n if (workflows !== \"github\" && workflows !== \"mixed\") return description;\n const how = workflows === \"github\"\n ? { merge: \"through GitHub (gh pr merge, with the repository's merge method)\", on: \"Turn on GitHub auto-merge\", off: \"Turn off GitHub auto-merge\" }\n : { merge: \"the way its repository ships (Graphite, or GitHub's gh pr merge; list_prs shows prWorkflow)\", on: \"Turn on merge-when-ready (Graphite) or auto-merge (GitHub)\", off: \"Turn off merge-when-ready (Graphite) or auto-merge (GitHub)\" };\n if (name === \"merge\") return description.replace(\"through Graphite\", how.merge);\n if (name === \"enable_merge_when_ready\") return description.replace(\"Turn on Graphite merge-when-ready\", how.on);\n if (name === \"disable_merge_when_ready\") return description.replace(\"Turn off Graphite merge-when-ready\", how.off);\n return description;\n}\nconst schemas = (list, workflows = null) => list.map(([name, description, , properties, required]) => ({ name, description: describeAction(name, description, workflows), inputSchema: { type: \"object\", properties, required, additionalProperties: false }, annotations: { readOnlyHint: readOnlyTools.has(name), destructiveHint: destructiveTools.has(name) } }));\n/** Action tools: a session Paseo launched as a root agent (FOLLOW_THROUGH_ROOT) while Follow-up runs (fresh hook lease). */\nasync function actionsEnabled() {\n if (!process.env.PASEO_AGENT_ID || process.env.FOLLOW_THROUGH_ROOT !== \"1\" || process.env.FOLLOW_THROUGH_RECOVERY === \"1\") return false;\n try {\n const lease = JSON.parse(await readFile(join(process.env.PASEO_HOME ?? join(homedir(), \".paseo\"), \"plugin-data/follow-through/hooks-enabled.json\"), \"utf8\"));\n return lease.expiresAt > Date.now();\n } catch { return false; }\n}\n/** The bridge input for a tool: action tools travel as { tool, args } through follow.agent-act. */\nconst callInput = (tool, input) => actionNames.has(tool[0]) || overseerNames.has(tool[0]) ? { tool: tool[0], args: input } : input;\n/** The Overseer's routing tools: the session Follow-up launched as its Overseer, while Follow-up runs. */\nasync function overseerEnabled() {\n if (process.env.FOLLOW_THROUGH_OVERSEER !== \"1\" || !process.env.PASEO_AGENT_ID) return false;\n try {\n const lease = JSON.parse(await readFile(join(process.env.PASEO_HOME ?? join(homedir(), \".paseo\"), \"plugin-data/follow-through/hooks-enabled.json\"), \"utf8\"));\n return lease.expiresAt > Date.now();\n } catch { return false; }\n}\nlet scopeCache = null;\nasync function scopeOf(directory, agentId) {\n try {\n const path = join(directory, \"scopes.json\");\n const { mtimeMs } = await stat(path);\n if (scopeCache?.mtimeMs !== mtimeMs) { const file = JSON.parse(await readFile(path, \"utf8\")); scopeCache = { mtimeMs, agents: file.agents ?? {}, workflows: file.workflows ?? null }; }\n return scopeCache.agents[agentId]?.role ?? null;\n } catch (error) {\n if (error?.code !== \"ENOENT\") throw error;\n const state = JSON.parse(await readFile(join(directory, \"state.json\"), \"utf8\"));\n for (const w of state.workspaces) {\n if (!w.enable_tracking || w.archived) continue;\n if (w.mainAgentId === agentId) return \"main\";\n if (w.batches.some(b => b.recipientAgentId === agentId && !b.settledAt && [\"sending\", \"sent\", \"blocked\", \"uncertain\"].includes(b.state) && b.tasks.every(t => t.kind === \"inventory\"))) return \"recovery\";\n if (w.contributorAgentIds?.includes(agentId)) return \"contributor\";\n }\n return null;\n }\n}\n/** This agent's PR workflow from scopes.json (undefined: an older worker, which meant Graphite with /fix-pr). */\nconst workflowOf = agentId => scopeCache ? scopeCache.agents[agentId]?.workflow : undefined;\n/** Whether the repositories Follow-up knows ship through Graphite, GitHub or both (\"mixed\"); null: unknown, as before. */\nconst workflowsOf = () => scopeCache?.workflows ?? null;\nasync function scope(resolveRecovery = false) {\n const agentId = process.env.PASEO_AGENT_ID;\n if (!agentId) return null;\n try {\n const home = process.env.PASEO_HOME ?? join(homedir(), \".paseo\");\n const directory = join(home, \"plugin-data/follow-through\");\n const lease = JSON.parse(await readFile(join(directory, \"hooks-enabled.json\"), \"utf8\"));\n if (!(lease.expiresAt > Date.now())) return null;\n // scopes.json (a few KB, rewritten only when a role changes) instead of the whole state.json; re-read only\n // when its mtime changes. Older workers don't write it, so fall back to state.json.\n const known = await scopeOf(directory, agentId);\n if (known === \"main\") return process.env.FOLLOW_THROUGH_RECOVERY === \"1\" ? \"recovery\" : \"main\";\n if (known) return known;\n if (resolveRecovery && process.env.FOLLOW_THROUGH_RECOVERY === \"1\") {\n const w = await call(\"follow.agent-status\", {});\n if (w.enable_tracking && !w.archived && w.mainAgentId !== agentId && w.batches.some(b => b.recipientAgentId === agentId && !b.settledAt && [\"sending\", \"sent\", \"blocked\", \"uncertain\"].includes(b.state) && b.tasks.every(t => t.kind === \"inventory\"))) return \"recovery\";\n }\n } catch {}\n return null;\n}\nfunction validate(value, schema, path = \"arguments\") {\n const types = Array.isArray(schema.type) ? schema.type : [schema.type];\n const type = value === null ? \"null\" : Array.isArray(value) ? \"array\" : typeof value;\n if (!types.includes(type) && !(type === \"number\" && types.includes(\"integer\") && Number.isInteger(value))) throw new Error(`${path}: expected ${types.join(\" or \")}.`);\n if (schema.enum && !schema.enum.includes(value)) throw new Error(`${path}: choose ${schema.enum.join(\", \")}.`);\n if (type === \"object\") {\n const extra = Object.keys(value).filter(k => !Object.hasOwn(schema.properties ?? {}, k));\n if (extra.length && schema.additionalProperties === false) throw new Error(`Unknown argument ${path}.${extra.join(\", \")}. ${extra.includes(\"dependsOnPrs\") ? \"Use afterPrs with owner/repo#number keys.\" : \"Check this tool's input schema with list.\"}`);\n for (const key of schema.required ?? []) if (!(key in value)) throw new Error(`${path}.${key} is required. Check this tool's input schema with list.`);\n for (const [key, nested] of Object.entries(value)) if (schema.properties?.[key]) validate(nested, schema.properties[key], `${path}.${key}`);\n }\n if (type === \"array\") for (let i = 0; i < value.length; i++) validate(value[i], schema.items, `${path}[${i}]`);\n if (type === \"number\" && (schema.minimum !== undefined && value < schema.minimum || schema.maximum !== undefined && value > schema.maximum)) throw new Error(`${path}: outside the allowed range.`);\n if (type === \"string\" && (schema.minLength !== undefined && value.length < schema.minLength || schema.maxLength !== undefined && value.length > schema.maxLength)) throw new Error(`${path}: outside the allowed length.`);\n}\nfunction currentWork(w) {\n return { id: w.id, title: w.title, goal: w.goal, mainAgentId: w.mainAgentId, enable_tracking: w.enable_tracking, enable_auto_sends: w.enable_auto_sends, hold: w.hold, archived: w.archived, runtimeBusy: w.runtimeBusy, runtimeReason: w.runtimeReason, backgroundBusy: w.backgroundBusy, completion: w.completion,\n prs: w.prs.map(p => ({ key: p.key, stack: p.stack, parent: p.parent, disposition: p.disposition, error: p.error, ...(p.snapshot ? { title: p.snapshot.title, state: p.snapshot.state, head: p.snapshot.head, draft: p.snapshot.draft, reviewDecision: p.snapshot.reviewDecision, conflict: p.snapshot.conflict, openThreads: p.snapshot.threads.length, failedChecks: p.snapshot.failedChecks, otherFailedChecks: p.snapshot.otherFailedChecks ?? [], deployment: p.snapshot.deployment } : {}) })),\n obligations: w.obligations.filter(o => ![\"done\", \"waived\"].includes(o.status)), completedObligations: w.obligations.filter(o => [\"done\", \"waived\"].includes(o.status)).length,\n openQuestions: (w.questions ?? []).filter(q => !q.answer && !q.closed).map(q => ({ id: q.id, title: q.title, question: q.question, options: q.options, recommend: q.recommend, big: q.big, mode: q.mode, askedBy: q.askedBy, taskId: q.taskId })),\n spec: w.spec?.url ? { url: w.spec.url, title: w.spec.title, source: w.spec.source } : null,\n recentAnswers: (w.questions ?? []).filter(q => q.answer).slice(-5).map(q => ({ id: q.id, title: q.title, choice: q.answer.choice, words: q.answer.words, delivery: q.answer.delivery.state })),\n batches: w.batches.filter(b => ![\"completed\", \"cancelled\"].includes(b.state)).map(b => ({ id: b.id, state: b.state, tasks: b.tasks, result: b.result, recipientAgentId: b.recipientAgentId, contextPath: b.contextPath })),\n excludedStacks: w.excludedStacks.map(s => ({ name: s.name, reason: s.reason, prs: s.prs.map(p => p.key) })), ...(w.prWorkflow ? { prWorkflow: w.prWorkflow } : {}), detail: \"summary\" };\n}\nfunction compact(tool, input, result) {\n if (actionNames.has(tool)) return result;\n if (tool === \"workspace_status\") return currentWork(result);\n if (tool === \"needs_you\") return { ok: result.ok, briefId: result.briefId };\n if (tool === \"declare_done\") return { workspaceId: result.workspace.id, done: !result.blockers.length, alreadyDone: !!result.alreadyDone, completion: result.workspace.completion, blockers: result.blockers, ...(result.unconfirmed?.length ? { deployNotConfirmed: result.unconfirmed } : {}), next: result.next };\n if (tool === \"ask_question\") return { workspaceId: result.workspaceId, question: { id: result.question.id, title: result.question.title, recommend: result.question.recommend, big: result.question.big }, mode: result.mode, instruction: result.instruction, ...(result.outcome && result.outcome !== \"asked\" ? { outcome: result.outcome, of: result.of } : {}) };\n if (tool === \"record_answer\" || tool === \"withdraw_question\") return { workspaceId: result.workspaceId, question: { id: result.question.id, answer: result.question.answer, closed: result.question.closed } };\n if (tool === \"set_spec\") return { workspaceId: result.workspaceId, spec: result.spec && { url: result.spec.url, title: result.spec.title, source: result.spec.source }, applied: result.applied, message: result.message };\n if (!result?.prs) return result;\n const workspaceId = result.id;\n if (tool === \"enroll_workspace\") return { workspaceId, goal: result.goal };\n if (tool === \"register_pr\") { const p = result.prs.find(p => p.key === `${input.repo}#${input.number}`); return { workspaceId, pr: { key: p.key, stack: p.stack, parent: p.parent, disposition: p.disposition } }; }\n if (tool === \"update_obligation\") return { workspaceId, obligation: result.obligations.find(o => o.id === result.updatedObligationId) };\n if (tool === \"acknowledge_batch\") { const b = result.batches.find(b => b.id === input.batchId); return { workspaceId, batch: { id: b.id, state: b.state, result: b.result } }; }\n if (tool === \"exclude_stack\") { const s = result.excludedStacks.find(s => s.name === input.stack); return { workspaceId, excludedStack: { name: s.name, reason: s.reason, prs: s.prs.map(p => p.key) } }; }\n return result;\n}\nasync function loadClient() {\n const candidates = [];\n if (process.env.FOLLOW_THROUGH_CLIENT_ENTRY) candidates.push(() => pathToFileURL(process.env.FOLLOW_THROUGH_CLIENT_ENTRY).href);\n const specifier = \"@getpaseo/client/internal/daemon-client\";\n if (process.resourcesPath) candidates.push(() => pathToFileURL(createRequire(join(process.resourcesPath, \"app.asar/node_modules/@getpaseo/cli/dist/index.js\")).resolve(specifier)).href);\n for (const directory of (process.env.PATH ?? \"\").split(delimiter)) {\n const cli = join(directory, process.platform === \"win32\" ? \"paseo.cmd\" : \"paseo\");\n if (existsSync(cli)) candidates.push(() => pathToFileURL(createRequire(realpathSync(cli)).resolve(specifier)).href);\n }\n candidates.push(() => pathToFileURL(createRequire(import.meta.url).resolve(specifier)).href);\n for (const resolve of candidates) try { return await import(resolve()); } catch {}\n throw new Error(\"Cannot load the installed Paseo client. Reload Follow-through to refresh its runtime connection.\");\n}\nconst batchInstructionsMain = \"Follow-through batches contain a header with the batchId and ordered tasks. Read workspace_status and refresh live conditions; skip resolved tasks. Process PRs bottom to top, one fully before the next, using the repository's /fix-pr and safe reparent workflow. Validate feedback, verify changes, submit with Graphite --publish, reply/resolve addressed threads and preserve uncommitted work. Post-deploy tasks require verified serving revisions and existing production permissions. Stakeholder update requests are follow-through tasks: retain the original thread, recipient and developer authorization in communication. Use current evidence, distinguish fixed/deployed/verified, and read existing replies before posting. Record the sent replyUrl; a draft or uncertain send stays blocked and must be checked before retrying. Auto authorizes agent delivery only. Acknowledge the header's batchId with acknowledge_batch before finishing (completed with the result, or blocked with the reason), before declare_done for completion batches. Declare Done only after the whole goal and post-merge work are verified. Leave merging and archiving to the developer.\";\n/**\n * The batch rules for this workspace's PR workflow. Graphite with /fix-pr (and any agent from before workflows\n * existed) gets the original text unchanged; plain GitHub never mentions Graphite, gt or a review command it doesn't have.\n */\nfunction batchInstructions(workflow) {\n const mode = workflow?.mode ?? \"graphite\";\n const fix = workflow === undefined || workflow === null ? \"/fix-pr\" : workflow.reviewFix ?? null;\n if (mode === \"graphite\" && fix === \"/fix-pr\") return batchInstructionsMain;\n const fixing = fix ? `using the repository's ${fix} workflow for review comments` : \"reading each PR's unresolved review threads with gh\";\n const restack = mode === \"graphite\" ? \"the repository's safe reparent workflow\" : \"base branches kept in a chain (restack with git rebase --update-refs, push with --force-with-lease, and after a parent merges retarget its child with gh pr edit --base if GitHub didn't)\";\n const submit = mode === \"graphite\" ? \"submit with Graphite --publish\" : \"push the branch (gh pr create for a new PR, gh pr ready when it leaves draft)\";\n const reply = fix ? \"reply/resolve addressed threads\" : \"reply to each addressed thread and resolve it\";\n return batchInstructionsMain\n .replace(\"using the repository's /fix-pr and safe reparent workflow.\", `${fixing}, with ${restack}.`)\n .replace(\"submit with Graphite --publish, reply/resolve addressed threads\", `${submit}, ${reply}`);\n}\n\nasync function call(method, input) {\n const agentId = process.env.PASEO_AGENT_ID;\n if (!agentId) throw new Error(\"This bridge must run inside a Paseo agent (PASEO_AGENT_ID is missing).\");\n const { DaemonClient } = await loadClient();\n const home = process.env.PASEO_HOME ?? join(homedir(), \".paseo\");\n const config = JSON.parse(await readFile(join(home, \"config.json\"), \"utf8\"));\n let password = process.env.PASEO_PASSWORD;\n if (!password && process.env.PASEO_PASSWORD_FILE) password = (await readFile(process.env.PASEO_PASSWORD_FILE, \"utf8\")).trim();\n if (!password && home === join(homedir(), \".paseo\")) password = await readFile(join(homedir(), \"paseo-hub/secrets/daemon-password\"), \"utf8\").then(s => s.trim()).catch(() => undefined);\n const client = new DaemonClient({ url: process.env.PASEO_DAEMON_URL ?? `ws://${config.daemon?.listen ?? \"127.0.0.1:6767\"}/ws`, clientId: \"follow-through-mcp\", clientType: \"cli\", reconnect: { enabled: false }, connectTimeoutMs: 10000, suppressSendErrors: true, ...(password ? { password } : {}) });\n try { await client.connect(); return await client.invokePluginRpc(\"follow-through\", method, { ...input, agentId }); }\n finally { await client.close().catch(() => undefined); }\n}\n\n\n// The worker imports this file for the same tool tables, validation and receipts (1.4.0-beta.2: Follow-up's tools\n// served natively through Paseo's own MCP). Only a direct run is the CLI / stdio bridge.\nexport { tools, actionTools, overseerTools, toolList, schemas, validate, compact, callInput, needsYouInstruction, actionInstruction, overseerInstruction, waitInstruction, batchInstructions, describeAction };\nfunction isMain() {\n try { return !!process.argv[1] && !!import.meta.url && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href; } catch { return false; }\n}\nif (isMain()) runMain().catch(error => { console.error(error?.message ?? String(error)); process.exitCode = 1; });\nasync function runMain() {\nconst command = process.argv[2];\nif (command === \"list\" || command === \"--help\" || command === \"help\") {\n process.stdout.write(command === \"list\" ? JSON.stringify({ tools: schemas([...toolList(undefined, false, true, false, true), ...overseerTools]) }, null, 2) + \"\\n\" : \"Usage: node mcp.mjs list | call <tool> '<json>' [--compact]\\nNative MCP returns compact receipts; workspace_status({detail:full}) requests complete history. CLI calls retain full replies unless --compact is supplied.\\n\");\n} else if (command === \"call\") {\n try {\n const tool = [...toolList(undefined, false, await briefEnabled(), false, await actionsEnabled()), ...(await overseerEnabled() ? overseerTools : [])].find(t => t[0] === process.argv[3]);\n if (!tool) throw new Error(\"Unknown tool. Run list for names and input schemas.\");\n const input = JSON.parse(process.argv[4] ?? \"{}\");\n validate(input, schemas([tool])[0].inputSchema);\n if (process.argv.slice(5).some(arg => arg !== \"--compact\")) throw new Error(\"Unknown CLI option. Use --compact or omit it for a full reply.\");\n const result = await call(tool[2], callInput(tool, input));\n process.stdout.write(JSON.stringify(process.argv.includes(\"--compact\") && input.detail !== \"full\" ? compact(tool[0], input, result) : result, null, 2) + \"\\n\");\n } catch (error) { console.error(error.message); process.exitCode = 1; }\n} else if (command) {\n console.error(\"Unknown command. Use list, --help, or call <tool> '<json>'.\"); process.exitCode = 1;\n} else {\n const lines = createInterface({ input: process.stdin });\n let tail = Promise.resolve(), initialized = false, lastScope = null;\n const timer = process.env.PASEO_AGENT_ID ? setInterval(() => {\n void (async () => { const current = `${await scope()}:${await briefEnabled()}:${await actionsEnabled()}:${await overseerEnabled()}`; if (initialized && current !== lastScope) process.stdout.write(JSON.stringify({ jsonrpc: \"2.0\", method: \"notifications/tools/list_changed\" }) + \"\\n\"); lastScope = current; })().catch(() => {});\n }, 2000) : null;\n timer?.unref(); lines.on(\"close\", () => { if (timer) clearInterval(timer); });\n lines.on(\"line\", line => {\n tail = tail.then(async () => {\n let request;\n try { request = JSON.parse(line); } catch { return; }\n if (request.id === undefined) return;\n try {\n let result;\n const role = await scope(request.method === \"initialize\" || request.method === \"tools/list\");\n const brief = await briefEnabled();\n const acting = await actionsEnabled();\n const overseeing = await overseerEnabled();\n const workflow = workflowOf(process.env.PASEO_AGENT_ID);\n const available = [...(role ? toolList(role === \"recovery\", role === \"contributor\", brief, false, acting) : toolList(false, false, brief, true, acting)), ...(overseeing ? overseerTools : [])];\n if (request.method === \"initialize\") {\n initialized = true; lastScope = `${role}:${brief}:${acting}:${overseeing}`;\n result = { protocolVersion: request.params?.protocolVersion ?? \"2024-11-05\", capabilities: { tools: { listChanged: true } }, serverInfo: { name: \"paseo-follow-through\", version: \"0.3.5\" }, instructions: (role ? (role === \"contributor\" ? \"Register PRs this session submits, including from secondary git worktrees. Read workspace_status and call sync_workspace before finishing. Goal, task, scope and completion changes remain with the designated main agent.\" : role === \"recovery\" ? \"Recover tracking metadata from evidence, acknowledge your assigned batch, and leave completion to the main agent.\" : \"Keep workspace follow-through updated after PR submission and scope changes. Read workspace_status after compaction. Track all post-merge work. When a decision needs the developer, ask it with ask_question (lettered options and a recommendation) and follow the question mode in its reply. If you keep a spec artifact for this workspace, register its link once with set_spec. \" + batchInstructions(workflow)) + \" Perform bookkeeping silently: no sidebar-update announcements, plugin-status commentary or final sidebar recap. Put receipts and summaries in tools. Report actual work outcomes or decisions/blockers; discuss sidebar status only when explicitly asked.\" : brief ? \"\" : \"Follow-through tools are available to tracked workspace root agents and active recovery agents; contributor sessions receive PR registration and status tools.\") + (brief && role !== \"contributor\" && role !== \"recovery\" ? (role ? \" \" : \"\") + needsYouInstruction : \"\") + (acting && role !== \"contributor\" && role !== \"recovery\" ? \" \" + actionInstruction : \"\") + (overseeing ? \" \" + overseerInstruction : \"\") };\n } else if (request.method === \"ping\") result = {};\n else if (request.method === \"tools/list\") result = { tools: schemas(available, workflowsOf()) };\n else if (request.method === \"tools/call\") {\n const tool = available.find(t => t[0] === request.params?.name);\n try {\n if (!tool) throw new Error(\"This tool is unavailable for the current agent. Tracking must be active; recovery authority ends after acknowledgment.\");\n const input = request.params.arguments ?? {}; validate(input, schemas([tool])[0].inputSchema);\n const value = await call(tool[2], callInput(tool, input));\n result = { content: [{ type: \"text\", text: JSON.stringify(input.detail === \"full\" ? value : compact(tool[0], input, value)) }] };\n } catch (error) { result = { isError: true, content: [{ type: \"text\", text: error.message }] }; }\n } else { process.stdout.write(JSON.stringify({ jsonrpc: \"2.0\", id: request.id, error: { code: -32601, message: \"Method not found\" } }) + \"\\n\"); return; }\n process.stdout.write(JSON.stringify({ jsonrpc: \"2.0\", id: request.id, result }) + \"\\n\");\n } catch (error) { process.stdout.write(JSON.stringify({ jsonrpc: \"2.0\", id: request.id, error: { code: -32603, message: error.message } }) + \"\\n\"); }\n });\n });\n}\n}\n";
|
package/server/mcp.mjs
CHANGED
|
@@ -26,7 +26,7 @@ const tools = [
|
|
|
26
26
|
["withdraw_question", "Withdraw a question that no longer matters, with a short reason.", "follow.withdraw-question", { id: string, reason: string }, ["id", "reason"]],
|
|
27
27
|
["set_spec", "Register the link to this workspace's spec: the Claude artifact (or doc) you keep summarizing the goal, decisions and status. Call it once after the first publish, with the URL from the publish result, and again only if the link changes. Follow-up shows it in the workspace header.", "follow.set-spec", { url: { ...string, maxLength: 2000 }, title: { ...string, maxLength: 120 } }, ["url"]],
|
|
28
28
|
["needs_you", "Call once at the end of a turn, just before your final reply: what the developer has to do next. ask is one line (≤120). kind: decision (give decisions with 2–5 options, a consequence each and recommend=<option index>; with several decisions the developer answers them together and you get one message with a line per decision, skipped ones marked as skipped; a decision that is already an open question goes in questions=[\"Q18\"] instead, never restated), action (something only they can do: merge, approve, log in, run or send), review (a PR to review and merge; link it with pr), or done (\"Nothing needed. <what you finished>.\": nothing for the developer, won't flag you). context ≤400 chars: only what they need to decide. Never blocks and never changes what you should do next.", "follow.needs-you", { ask: { ...string, minLength: 1, maxLength: 120 }, kind: { type: "string", enum: ["decision", "action", "review", "done"] }, decisions: { type: "array", maxItems: 3, items: { type: "object", properties: { question: { ...string, minLength: 1, maxLength: 200 }, options: { type: "array", minItems: 2, maxItems: 5, items: { type: "object", properties: { label: { ...string, minLength: 1, maxLength: 60 }, consequence: { ...string, maxLength: 160 } }, required: ["label"], additionalProperties: false } }, recommend: { type: "integer", minimum: 0, maximum: 4 } }, required: ["question"], additionalProperties: false } }, questions: { type: "array", maxItems: 3, items: { type: "string", pattern: "^Q\\d+$" } }, context: { ...string, maxLength: 400 }, links: { type: "array", maxItems: 4, items: { type: "object", properties: { label: string, url: string, path: string, pr: string }, required: ["label"], additionalProperties: false } } }, ["ask", "kind"]],
|
|
29
|
-
["declare_done", "Declare that the workspace goal is fulfilled. Live PR status and remaining obligations are checked;
|
|
29
|
+
["declare_done", "Declare that the workspace goal is fulfilled. Live PR status and remaining obligations are checked. The reply's `next` says what is missing and whether it is yours to fix; follow it and do not repeat the call when nothing is yours to fix. A deploy Follow-up cannot confirm does not block Done; it is noted. Calling again after Done changes nothing. Done labels the workspace but never archives it.", "follow.done", { summary: string }, ["summary"]],
|
|
30
30
|
];
|
|
31
31
|
|
|
32
32
|
// Agent parity: every action the developer can click in Follow-up, through the same server path (follow.agent-act).
|
|
@@ -238,7 +238,7 @@ function compact(tool, input, result) {
|
|
|
238
238
|
if (actionNames.has(tool)) return result;
|
|
239
239
|
if (tool === "workspace_status") return currentWork(result);
|
|
240
240
|
if (tool === "needs_you") return { ok: result.ok, briefId: result.briefId };
|
|
241
|
-
if (tool === "declare_done") return { workspaceId: result.workspace.id, completion: result.workspace.completion, blockers: result.blockers };
|
|
241
|
+
if (tool === "declare_done") return { workspaceId: result.workspace.id, done: !result.blockers.length, alreadyDone: !!result.alreadyDone, completion: result.workspace.completion, blockers: result.blockers, ...(result.unconfirmed?.length ? { deployNotConfirmed: result.unconfirmed } : {}), next: result.next };
|
|
242
242
|
if (tool === "ask_question") return { workspaceId: result.workspaceId, question: { id: result.question.id, title: result.question.title, recommend: result.question.recommend, big: result.question.big }, mode: result.mode, instruction: result.instruction, ...(result.outcome && result.outcome !== "asked" ? { outcome: result.outcome, of: result.of } : {}) };
|
|
243
243
|
if (tool === "record_answer" || tool === "withdraw_question") return { workspaceId: result.workspaceId, question: { id: result.question.id, answer: result.question.answer, closed: result.question.closed } };
|
|
244
244
|
if (tool === "set_spec") return { workspaceId: result.workspaceId, spec: result.spec && { url: result.spec.url, title: result.spec.title, source: result.spec.source }, applied: result.applied, message: result.message };
|
package/server/pr-actions.ts
CHANGED
|
@@ -184,7 +184,7 @@ export class PrActions {
|
|
|
184
184
|
if (plan.kind === "merge" && current.prActions.some(a => a.kind === "merge" && a.state === "submitted" && prs.some(p => a.heads[p.key] === p.snapshot?.head) && this.now() - Date.parse(a.createdAt) < 30_000)) throw new Error(`A merge was just submitted for this revision. Wait for ${via(prs)}'s result.`);
|
|
185
185
|
if (identity(downstack(current.prs, plan.target)) !== saved.identity) throw new Error("The stack changed before submission.");
|
|
186
186
|
current.prActions.push({ id, kind: plan.kind, prs: prs.map(p => p.key), heads: Object.fromEntries(prs.map(p => [p.key, p.snapshot!.head])), createdAt: new Date(this.now()).toISOString(), state: "sending", result: isGithubFlow(prs[0].snapshot) ? "Waiting for GitHub to confirm." : plan.kind === "merge" ? "Waiting for Graphite to confirm." : "Confirm this PR setting change in the Send to Paseo extension in Chrome." });
|
|
187
|
-
current.completion = null;
|
|
187
|
+
current.completion = null; current.declaration = null;
|
|
188
188
|
});
|
|
189
189
|
let state: "submitted" | "failed" | "uncertain" = "submitted";
|
|
190
190
|
let result: string;
|
package/server/tasks.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import type { Task, Workspace, Batch } from "../shared/model";
|
|
3
3
|
import { settled } from "../shared/model";
|
|
4
|
-
import {
|
|
4
|
+
import { deployState, followUpObligations, recoveryBatch } from "../shared/follow-up";
|
|
5
5
|
import { clientEntry, paseoHome } from "./daemon";
|
|
6
6
|
import { join } from "node:path";
|
|
7
7
|
import { communicationReady } from "../shared/communication";
|
|
@@ -33,8 +33,9 @@ export function tasksFor(w: Workspace, now = Date.now(), wording: TaskWording =
|
|
|
33
33
|
if (!o.enable_follow_up || !["pending", "waiting"].includes(o.status) || !communicationReady(o.communication)) continue;
|
|
34
34
|
if (taskSchedule(o, w, now).ready) add("obligation", o.id, o.title, [o.id, o.revision]);
|
|
35
35
|
}
|
|
36
|
-
if ((w.prs.length || followUpObligations(w).length || w.inventory && w.inventory.syncedRevision >= w.inventory.revision) && !w.completion && !w.runtimeBusy &&
|
|
37
|
-
|
|
36
|
+
if ((w.prs.length || followUpObligations(w).length || w.inventory && w.inventory.syncedRevision >= w.inventory.revision) && !w.completion && !w.declaration && !w.runtimeBusy &&
|
|
37
|
+
// Merged is permanent and a deploy is latched, so a status or probe hiccup never flips this (no create/cancel churn).
|
|
38
|
+
w.prs.every(pr => pr.snapshot?.complete && settled(pr) && deployState(pr, now) !== "not-deployed") &&
|
|
38
39
|
followUpObligations(w).every(o => ["done", "waived"].includes(o.status)))
|
|
39
40
|
add("completion", w.id, "Verify the workspace is finished and declare Done", [w.prs.map(pr => [pr.key, pr.snapshot?.head, pr.disposition]), w.obligations.map(o => [o.id, o.revision, o.status])]);
|
|
40
41
|
return tasks;
|
package/shared/chat.ts
CHANGED
|
@@ -42,7 +42,7 @@ export const toolRowSchema = z.object({
|
|
|
42
42
|
line: z.string(),
|
|
43
43
|
tone: z.enum(["muted", "warning", "danger", "success"]),
|
|
44
44
|
more: z.string().nullable(),
|
|
45
|
-
done: z.object({ summary: z.string() }).nullable(),
|
|
45
|
+
done: z.object({ summary: z.string(), /** PRs whose deploy Follow-up could not confirm. */ unconfirmed: z.array(z.string()).optional() }).nullable(),
|
|
46
46
|
});
|
|
47
47
|
export type ToolRow = z.infer<typeof toolRowSchema>;
|
|
48
48
|
|
|
@@ -63,7 +63,9 @@ export function readText(value: unknown): string | undefined {
|
|
|
63
63
|
}
|
|
64
64
|
function json(text: string | undefined): Record<string, unknown> | null {
|
|
65
65
|
if (!text) return null;
|
|
66
|
-
try { const value = JSON.parse(
|
|
66
|
+
const parse = (body: string) => { try { const value = JSON.parse(body); return record(value) ? value : null; } catch { return null; } };
|
|
67
|
+
// Some providers wrap the reply in extra text; the receipt is the outermost JSON object.
|
|
68
|
+
return parse(text) ?? (text.indexOf("{") >= 0 ? parse(text.slice(text.indexOf("{"), text.lastIndexOf("}") + 1)) : null);
|
|
67
69
|
}
|
|
68
70
|
const str = (value: unknown) => typeof value === "string" ? value : typeof value === "number" ? String(value) : "";
|
|
69
71
|
const firstLine = (text: string) => text.split("\n").map(l => l.trim()).find(Boolean) ?? "";
|
|
@@ -121,10 +123,16 @@ export function toolRow(tool: FollowTool, status: "running" | "completed" | "fai
|
|
|
121
123
|
return { ...base, state: "done", line: kept ? "Spec link kept · the developer chose it" : `Spec link: ${firstLine(str(input.title)) || specHost(str(input.url))}`, more: str(result?.message) || more };
|
|
122
124
|
}
|
|
123
125
|
case "declare_done": {
|
|
126
|
+
// Only a reply Follow-up wrote can show Done: never the agent's own summary when the result is missing or unreadable.
|
|
124
127
|
const blockers = Array.isArray(result?.blockers) ? result!.blockers.map(str).filter(Boolean) : [];
|
|
125
|
-
const
|
|
126
|
-
|
|
127
|
-
|
|
128
|
+
const workspace = record(result?.workspace) ? result!.workspace as Record<string, unknown> : null;
|
|
129
|
+
const completionRecord = record(result?.completion) ? result!.completion : record(workspace?.completion) ? workspace!.completion as Record<string, unknown> : null;
|
|
130
|
+
const next = str(result?.next);
|
|
131
|
+
if (blockers.length) return { ...base, state: "done", tone: "warning", line: `Not done yet · ${blockers.length} blocker${blockers.length === 1 ? "" : "s"}`, more: [blockers.map(b => `• ${b}`).join("\n"), next].filter(Boolean).join("\n\n") };
|
|
132
|
+
if (!completionRecord) return { ...base, state: "done", line: "Done check", more };
|
|
133
|
+
if (result?.alreadyDone === true) return { ...base, state: "done", line: "Already done · nothing changed", more: next || more };
|
|
134
|
+
const unconfirmed = Array.isArray(completionRecord.unconfirmed) ? completionRecord.unconfirmed.map(str).filter(Boolean) : [];
|
|
135
|
+
return { ...base, state: "done", tone: "success", line: "Declared done", more, done: { summary: str(completionRecord.summary) || str(input.summary), ...(unconfirmed.length ? { unconfirmed } : {}) } };
|
|
128
136
|
}
|
|
129
137
|
}
|
|
130
138
|
}
|
package/shared/contracts.ts
CHANGED
|
@@ -36,7 +36,7 @@ export const syncWorkspaceRpc = defineRpc({ name: "follow.sync", input: z.strict
|
|
|
36
36
|
export const enrollRpc = defineRpc({ name: "follow.enroll", input: z.strictObject({ workspaceId: idSchema.optional(), agentId: idSchema, goal: textSchema }), output: workspaceSchema });
|
|
37
37
|
export const registerPrRpc = defineRpc({ name: "follow.register-pr", input: z.strictObject({ agentId: idSchema, repo: z.string().regex(/^[\w.-]+\/[\w.-]+$/), number: z.number().int().positive(), stack: textSchema, parentNumber: z.number().int().positive().nullable().optional(), disposition: z.string().max(2000).optional() }), output: workspaceSchema });
|
|
38
38
|
export const obligationRpc = defineRpc({ name: "follow.obligation", input: z.strictObject({ agentId: idSchema, id: idSchema.optional(), title: textSchema, status: z.enum(["pending", "waiting", "working", "blocked", "done", "waived"]), afterPrs: z.array(idSchema).optional(), dependencyStage: z.enum(["merged", "deployed"]).optional(), evidence: z.string().max(4000).optional(), enable_follow_up: z.boolean().optional(), communication: agentCommunicationSchema.optional(), trigger: taskTriggerSchema.strict().nullable().optional() }), output: workspaceSchema.extend({ updatedObligationId: idSchema }) });
|
|
39
|
-
export const declareDoneRpc = defineRpc({ name: "follow.done", input: z.strictObject({ agentId: idSchema, summary: textSchema }), output: z.object({ workspace: workspaceSchema, blockers: z.array(z.string()) }) });
|
|
39
|
+
export const declareDoneRpc = defineRpc({ name: "follow.done", input: z.strictObject({ agentId: idSchema, summary: textSchema }), output: z.object({ workspace: workspaceSchema, blockers: z.array(z.string()), unconfirmed: z.array(z.string()).default([]), alreadyDone: z.boolean().default(false), next: z.string().default("") }) });
|
|
40
40
|
export const acknowledgeRpc = defineRpc({ name: "follow.acknowledge", input: z.strictObject({ agentId: idSchema, batchId: idSchema, outcome: z.enum(["completed", "blocked"]), result: textSchema }), output: workspaceSchema });
|
|
41
41
|
export const controlRpc = defineRpc({ name: "follow.control", input: z.object({ workspaceId: idSchema, enable_auto_sends: z.boolean().optional(), clearHold: z.boolean().optional(), retryBatchId: idSchema.optional(), /** The developer's "Make main agent": one of the workspace's other root agents. */ mainAgentId: idSchema.optional() }), output: workspaceSchema });
|
|
42
42
|
export const refreshRpc = defineRpc({ name: "follow.refresh", input: z.object({ workspaceId: idSchema.optional() }), output: z.object({ ok: z.boolean() }) });
|
package/shared/follow-up.ts
CHANGED
|
@@ -8,8 +8,27 @@ export function lifecycleOnly(o: Pick<Obligation, "title" | "afterPrs" | "catego
|
|
|
8
8
|
return /^(merge|approve|publish|land|deploy)\b/i.test(o.title) || /^#\d+.*\bneeds?\b.*\b(approval|merge)\b/i.test(o.title);
|
|
9
9
|
}
|
|
10
10
|
export const followUpObligations = (w: Workspace): Obligation[] => w.obligations.filter(o => !lifecycleOnly(o));
|
|
11
|
+
/**
|
|
12
|
+
* Where a merged PR stands against its deploy target.
|
|
13
|
+
* - deployed: Follow-up saw its merge commit serving. Latched by deploymentAnchor: a probe error or an old
|
|
14
|
+
* observation never turns it back; only positive contrary evidence (pending/partial, i.e. a rollback) does.
|
|
15
|
+
* - not-deployed: a fresh probe saw the serving revision without the commit.
|
|
16
|
+
* - unconfirmed: a deploy target exists but Follow-up never confirmed it (probe error, stale, no access).
|
|
17
|
+
* - none: not merged, or no deploy target for this repository.
|
|
18
|
+
*/
|
|
19
|
+
export type DeployState = "none" | "deployed" | "not-deployed" | "unconfirmed";
|
|
20
|
+
export const DEPLOY_FRESH_MS = 120_000;
|
|
21
|
+
export function deployState(pr: Pr, now = Date.now()): DeployState {
|
|
22
|
+
const s = pr.snapshot;
|
|
23
|
+
if (s?.state !== "MERGED") return "none";
|
|
24
|
+
const d = s.deployment;
|
|
25
|
+
const age = d ? now - Date.parse(d.observedAt) : NaN;
|
|
26
|
+
const fresh = age >= 0 && age <= DEPLOY_FRESH_MS;
|
|
27
|
+
if (d && fresh && (d.state === "pending" || d.state === "partial")) return "not-deployed";
|
|
28
|
+
if (s.mergeCommit && pr.deploymentAnchor?.mergeCommit === s.mergeCommit) return "deployed";
|
|
29
|
+
if (!pr.error && s.complete && d?.state === "deployed" && fresh) return "deployed";
|
|
30
|
+
return d?.environment ? "unconfirmed" : "none";
|
|
31
|
+
}
|
|
11
32
|
export function deployed(pr: Pr, now = Date.now()): boolean {
|
|
12
|
-
|
|
13
|
-
return !pr.error && pr.snapshot?.state === "MERGED" && !!pr.snapshot.complete && !!d &&
|
|
14
|
-
d.state === "deployed" && now - Date.parse(d.observedAt) >= 0 && now - Date.parse(d.observedAt) <= 120_000;
|
|
33
|
+
return deployState(pr, now) === "deployed";
|
|
15
34
|
}
|
package/shared/model.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
import { followUpObligations,
|
|
2
|
+
import { followUpObligations, deployState, recoveryBatch } from "./follow-up";
|
|
3
3
|
import { communicationSchema, replyRecorded } from "./communication";
|
|
4
4
|
import { taskTriggerSchema } from "./task-trigger";
|
|
5
5
|
import { isOpen as questionOpen, questionSchema } from "./questions";
|
|
@@ -79,7 +79,11 @@ export const workspaceSchema = z.object({
|
|
|
79
79
|
prs: z.array(prSchema), obligations: z.array(obligationSchema), batches: z.array(batchSchema),
|
|
80
80
|
excludedStacks: z.array(z.object({ name: textSchema, reason: textSchema, excludedAt: z.string(), prs: z.array(prSchema), obligations: z.array(obligationSchema) })).default([]),
|
|
81
81
|
prActions: z.array(z.object({ id: idSchema, kind: z.enum(["merge", "enable_mwr", "disable_mwr", "request_reviewers"]), reviewers: z.array(z.string()).optional(), prs: z.array(idSchema), heads: z.record(z.string(), z.string()), createdAt: z.string(), state: z.enum(["sending", "submitted", "failed", "uncertain"]), result: z.string() })).default([]),
|
|
82
|
-
completion: z.object({ summary: textSchema, declaredAt: z.string()
|
|
82
|
+
completion: z.object({ summary: textSchema, declaredAt: z.string(),
|
|
83
|
+
/** PRs whose deploy Follow-up could not confirm when Done was accepted ("Deploy not confirmed by Follow-up"). */
|
|
84
|
+
unconfirmed: z.array(z.string()).optional() }).nullable(),
|
|
85
|
+
/** The main agent declared Done while only Follow-up's own waits remained (a rollout, a refresh); recorded as Done once they clear. */
|
|
86
|
+
declaration: z.object({ summary: textSchema, at: z.string() }).nullable().optional(),
|
|
83
87
|
updatedAt: z.string(), managedDoneLabel: z.boolean(),
|
|
84
88
|
runtimeReason: z.string().nullable(), runtimeBusy: z.boolean(), backgroundBusy: z.boolean().default(false),
|
|
85
89
|
interruption: z.object({ turnId: z.string().nullable(), at: z.string(), kind: z.enum(["canceled", "failed"]), guardPauseId: z.string().optional(), /** The agent whose turn stopped (since 1.4.0-beta.16). */ agentId: idSchema.optional() }).optional(),
|
|
@@ -127,23 +131,56 @@ export type State = z.infer<typeof stateSchema>;
|
|
|
127
131
|
export function settled(pr: Pr): boolean {
|
|
128
132
|
return pr.snapshot?.state === "MERGED" || (pr.snapshot?.state === "CLOSED" && !!pr.disposition);
|
|
129
133
|
}
|
|
134
|
+
/**
|
|
135
|
+
* What stands between a workspace and Done, and who can move it:
|
|
136
|
+
* - agent: the main agent can resolve it with its tools (record a task, acknowledge a batch, withdraw a question);
|
|
137
|
+
* - developer: needs Tom (merge, answer, resume, check a PR action);
|
|
138
|
+
* - wait: time or Follow-up's own observation (agent busy, deploy rollout, status refresh). Never revokes a Done.
|
|
139
|
+
* `unconfirmed` is not a blocker: PRs whose deploy Follow-up could not confirm. Done is accepted with a note.
|
|
140
|
+
*/
|
|
141
|
+
export type BlockerOwner = "agent" | "developer" | "wait";
|
|
142
|
+
/** `contrary`: positive evidence that shipped work regressed (a rollback). It takes back a Done even though nobody acts. */
|
|
143
|
+
export type Blocker = { text: string; owner: BlockerOwner; contrary?: true };
|
|
144
|
+
export type CompletionGate = { blockers: Blocker[]; unconfirmed: string[] };
|
|
145
|
+
/** A completion check is the nudge to declare Done; it never blocks Done itself. */
|
|
146
|
+
export const completionCheck = (b: Pick<Batch, "tasks">): boolean => b.tasks.length > 0 && b.tasks.every(t => t.kind === "completion");
|
|
147
|
+
export function completionGate(w: Workspace, now = Date.now()): CompletionGate {
|
|
148
|
+
const blockers: Blocker[] = [];
|
|
149
|
+
const unconfirmed: string[] = [];
|
|
150
|
+
const add = (owner: BlockerOwner, text: string, contrary?: true) => blockers.push(contrary ? { owner, text, contrary } : { owner, text });
|
|
151
|
+
for (const pr of w.prs) {
|
|
152
|
+
const ref = `${pr.repo}#${pr.number}`;
|
|
153
|
+
// Merged (or closed with a disposition) is permanent: a later observation failure can't undo it.
|
|
154
|
+
if (pr.snapshot?.complete && settled(pr)) {
|
|
155
|
+
const deploy = deployState(pr, now);
|
|
156
|
+
if (deploy === "not-deployed") add("wait", `Wait for ${ref} to reach ${pr.snapshot.deployment?.environment || "production"}`, true);
|
|
157
|
+
else if (deploy === "unconfirmed") unconfirmed.push(ref);
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
if (pr.error || !pr.snapshot?.complete || now - Date.parse(pr.snapshot.observedAt) > 120_000) { add("wait", `Refresh status for ${ref}`); continue; }
|
|
161
|
+
if (pr.snapshot.state === "CLOSED") add("agent", `Settle ${ref} with a disposition`);
|
|
162
|
+
else add("developer", `Settle ${ref}`);
|
|
163
|
+
}
|
|
164
|
+
for (const o of followUpObligations(w).filter(o => !["done", "waived"].includes(o.status))) add(o.status === "blocked" ? "developer" : "agent", o.title);
|
|
165
|
+
for (const o of followUpObligations(w).filter(o => o.status === "done" && o.communication && !replyRecorded(o.communication))) add("agent", `Record the sent reply for ${o.title}`);
|
|
166
|
+
const open = w.batches.filter(b => !recoveryBatch(b) && !completionCheck(b));
|
|
167
|
+
if (open.some(b => ["sending", "sent"].includes(b.state))) add("agent", "Acknowledge the open follow-up batch");
|
|
168
|
+
if (open.some(b => ["blocked", "uncertain"].includes(b.state))) add("developer", "Retry or dismiss the stuck follow-up batch");
|
|
169
|
+
if (open.some(b => b.state === "pending")) add("developer", "Send or dismiss the queued repairs");
|
|
170
|
+
if (w.prActions.some(a => ["sending", "uncertain"].includes(a.state))) add("developer", "Check the outstanding PR action");
|
|
171
|
+
for (const q of (w.questions ?? []).filter(questionOpen)) add("developer", `Answer or withdraw ${q.id} (${q.title})`);
|
|
172
|
+
if (w.hold) add("developer", w.hold);
|
|
173
|
+
if (w.runtimeBusy) add("wait", "Wait for active agent work to finish");
|
|
174
|
+
if (w.backgroundBusy) add("wait", "Wait for active background agents to finish");
|
|
175
|
+
if (w.runtimeReason) add("wait", w.runtimeReason);
|
|
176
|
+
return { blockers, unconfirmed };
|
|
177
|
+
}
|
|
130
178
|
export function completionBlockers(w: Workspace, now = Date.now()): string[] {
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
});
|
|
137
|
-
blockers.push(...followUpObligations(w).filter(o => !["done", "waived"].includes(o.status)).map(o => o.title));
|
|
138
|
-
blockers.push(...followUpObligations(w).filter(o => o.status === "done" && o.communication && !replyRecorded(o.communication)).map(o => `Record the sent reply for ${o.title}`));
|
|
139
|
-
if (w.batches.some(b => !recoveryBatch(b) && ["pending", "sending", "sent", "blocked", "uncertain"].includes(b.state))) blockers.push("Finish outstanding follow-up batches");
|
|
140
|
-
if (w.prActions.some(a => ["sending", "uncertain"].includes(a.state))) blockers.push("Check the outstanding PR action");
|
|
141
|
-
blockers.push(...(w.questions ?? []).filter(questionOpen).map(q => `Answer or withdraw ${q.id} (${q.title})`));
|
|
142
|
-
if (w.hold) blockers.push(w.hold);
|
|
143
|
-
if (w.runtimeBusy) blockers.push("Wait for active agent work to finish");
|
|
144
|
-
if (w.backgroundBusy) blockers.push("Wait for active background agents to finish");
|
|
145
|
-
if (w.runtimeReason) blockers.push(w.runtimeReason);
|
|
146
|
-
return blockers;
|
|
179
|
+
return completionGate(w, now).blockers.map(b => b.text);
|
|
180
|
+
}
|
|
181
|
+
/** Only new work or contrary evidence takes a Done back; waiting and observation gaps never do. */
|
|
182
|
+
export function revokesDone(w: Workspace, now = Date.now()): boolean {
|
|
183
|
+
return completionGate(w, now).blockers.some(b => b.owner !== "wait" || b.contrary);
|
|
147
184
|
}
|
|
148
185
|
export type Status = "active" | "handling" | "waiting" | "needs-you" | "done";
|
|
149
186
|
export function summary(w: Workspace, now = Date.now()): { status: Status; label: string; reason: string } {
|