paseo-follow-up 2.1.0-beta.4 → 2.1.0
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 +87 -0
- package/client/brief.tsx +12 -7
- package/client/chat.tsx +15 -6
- package/client/needs-you.tsx +25 -7
- package/client/questions.tsx +21 -15
- package/client/report-issue.tsx +2 -2
- package/client/spec.tsx +1 -1
- package/index.server.ts +92 -15
- package/package.json +1 -1
- package/server/agent-actions.ts +1 -1
- package/server/agent-hook.mjs +7 -2
- package/server/agent-parity.ts +5 -0
- package/server/daemon.ts +86 -32
- package/server/engine.ts +212 -122
- package/server/hook-source.ts +7 -2
- package/server/inbox.ts +64 -64
- package/server/linked.ts +28 -6
- package/server/local-titles.ts +67 -0
- package/server/mcp-source.ts +4 -2
- package/server/mcp.mjs +4 -2
- package/server/message-queue.ts +384 -0
- package/server/overseer.ts +12 -3
- package/server/questions.ts +4 -2
- package/server/report-send.ts +3 -2
- package/server/spec.ts +18 -29
- package/server/store.ts +9 -2
- package/server/teardown.ts +7 -1
- package/server/transcript-titles.ts +165 -0
- package/shared/about.ts +1 -0
- package/shared/attention.ts +12 -3
- package/shared/brief.ts +2 -3
- package/shared/chat.ts +1 -1
- package/shared/contracts.ts +5 -1
- package/shared/headline.ts +1 -0
- package/shared/linked-display.ts +6 -1
- package/shared/linked.ts +2 -2
- package/shared/local-titles.ts +68 -0
- package/shared/model.ts +6 -0
- package/shared/overseer.ts +3 -0
- package/shared/questions.ts +35 -7
- package/shared/queue.ts +173 -0
- package/shared/spec.ts +1 -0
- package/shared/status-invariants.ts +22 -0
package/index.server.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { TranscriptTitleLookup, TranscriptTitleStore, trackedTitleTranscripts } from "./server/transcript-titles";
|
|
2
|
+
import { fillLinkedTitles, fillWorkspaceTitles, localTitles, workspaceNeedsTitles, type TitleIndex } from "./shared/local-titles";
|
|
1
3
|
import { stopWorker } from "./server/teardown";
|
|
2
4
|
import { WriteHealth } from "./server/write-behind";
|
|
3
5
|
import { actorBy, actorOf, type Actor } from "./shared/actor";
|
|
@@ -60,7 +62,9 @@ import { updateObligation } from "./server/obligations";
|
|
|
60
62
|
import { Inbox, INBOX_WRITE_MS, type GuardPause } from "./server/inbox";
|
|
61
63
|
import { daemonDirectory, guardPath } from "./server/inbox-directory";
|
|
62
64
|
import { fileSources } from "./server/inbox-classifier";
|
|
63
|
-
import { onBeforeSend } from "./server/daemon";
|
|
65
|
+
import { onBeforeSend, onDaemonReconnect } from "./server/daemon";
|
|
66
|
+
import { MessageQueue, undeliveredEntry } from "./server/message-queue";
|
|
67
|
+
import { queueView } from "./shared/queue";
|
|
64
68
|
import { copyFile, readFile, rename, stat } from "node:fs/promises";
|
|
65
69
|
import { HistoryCache } from "./server/history-cache";
|
|
66
70
|
import { Governor } from "./server/governor";
|
|
@@ -214,7 +218,16 @@ export default function contribute(server: PluginServerContext) {
|
|
|
214
218
|
actions.settleTasks = w => engine.settleTasks(w);
|
|
215
219
|
const governor = new Governor();
|
|
216
220
|
const linkedStore = new LinkedStore(directory);
|
|
217
|
-
const linked = new LinkedService({ store: linkedStore, sources: liveLinkedSources(), roomForBackground: async () => governor.allowsBackground()
|
|
221
|
+
const linked = new LinkedService({ store: linkedStore, sources: liveLinkedSources(), roomForBackground: async () => governor.allowsBackground(),
|
|
222
|
+
workspaces: async () => (await store.snapshot()).workspaces,
|
|
223
|
+
titlesChanged: async (titles: TitleIndex) => {
|
|
224
|
+
for (const w of (await store.snapshot()).workspaces) {
|
|
225
|
+
if (!w.enable_tracking) continue;
|
|
226
|
+
if (workspaceNeedsTitles(w, titles)) await store.mutateWorkspace(w.id, current => { fillWorkspaceTitles(current, titles); });
|
|
227
|
+
}
|
|
228
|
+
},
|
|
229
|
+
});
|
|
230
|
+
const transcriptTitles = new TranscriptTitleLookup({ store: new TranscriptTitleStore(directory), paths: (workspaces, priority) => trackedTitleTranscripts(paseoHome, workspaces, undefined, priority) });
|
|
218
231
|
// Extraction rides discovery's own timeline batch (loaded agents only): no extra reads (shared/linked-extract.ts).
|
|
219
232
|
gateway.linkRefs = batch => void linked.note(batch).catch(() => undefined);
|
|
220
233
|
const listCache = new ListCache();
|
|
@@ -234,11 +247,6 @@ export default function contribute(server: PluginServerContext) {
|
|
|
234
247
|
if (!api) { unsent.set(`${agentId}|${brief.id}`, { agentId, brief }); return; }
|
|
235
248
|
await api.agents.ref(agentId).timeline.append({ type: "plugin", id: brief.id, kind: BRIEF_KIND, version: BRIEF_VERSION, data: brief });
|
|
236
249
|
};
|
|
237
|
-
/** A message to one agent: through the plugin session once a handler has seen one, else a daemon connection (worker start). */
|
|
238
|
-
const sendTo = (agentId: string) => async (text: string, messageId: string) => {
|
|
239
|
-
if (api) await api.agents.ref(agentId).send(text, { messageId, activeTurnBehavior: "steer" });
|
|
240
|
-
else await withDaemon(client => client.sendMessage(agentId, text, { messageId, activeTurnBehavior: "steer" }));
|
|
241
|
-
};
|
|
242
250
|
const seen = (paseo: PaseoApi) => {
|
|
243
251
|
api = paseo;
|
|
244
252
|
for (const [key, row] of unsent) { unsent.delete(key); void append(row.agentId, row.brief).catch(() => undefined); }
|
|
@@ -298,7 +306,40 @@ export default function contribute(server: PluginServerContext) {
|
|
|
298
306
|
catch { return null; }
|
|
299
307
|
},
|
|
300
308
|
});
|
|
301
|
-
onBeforeSend((agentId, messageId) => inbox.noteDelivery(agentId, messageId));
|
|
309
|
+
onBeforeSend((agentId, messageId, by) => inbox.noteDelivery(agentId, messageId, by === "developer" || by?.startsWith("agent:") ? by as "developer" | `agent:${string}` : undefined));
|
|
310
|
+
// a-message-is-saved-before-sent-and-arrives-once: every message to an agent goes through one queue (queue.json).
|
|
311
|
+
const queue = new MessageQueue(directory, { deliverTo: (target, text, messageId, by) => gateway.deliverTo(target, text, messageId, by), arrived: (agentId, messageId, since, marker) => gateway.arrivedMessage(agentId, messageId, since, marker), probe: () => gateway.probe() }, { health: writeHealth });
|
|
312
|
+
engine.attachQueue(queue);
|
|
313
|
+
inbox.attachQueue(queue);
|
|
314
|
+
// Overseer forwards and reports handed to an agent: no record of their own, so the queue item is their status
|
|
315
|
+
// (follow_queue_list). Archived agents cancel, with the reason on the item.
|
|
316
|
+
queue.register("message", {
|
|
317
|
+
async resolve(item) {
|
|
318
|
+
const rows = await gateway.directory.read().catch(() => null);
|
|
319
|
+
if (!rows) return { defer: "Paseo unreachable" };
|
|
320
|
+
const agent = rows.agents.find(r => r.agent.id === item.ref.agentId)?.agent;
|
|
321
|
+
if (!agent || agent.archivedAt) return { cancel: "The agent was archived, so the message wasn't sent." };
|
|
322
|
+
return { target: { workspaceId: null, recipients: [item.ref.agentId!] } };
|
|
323
|
+
},
|
|
324
|
+
// No card of its own: one that didn't go out (Failed, or Queued past MESSAGE_STUCK_MS) shows in its workspace's
|
|
325
|
+
// Needs you with Retry and Cancel, and leaves it once sent or cancelled.
|
|
326
|
+
async project(item) {
|
|
327
|
+
const w = (await store.snapshot()).workspaces.find(w => w.id === item.key && w.enable_tracking && !w.archived);
|
|
328
|
+
if (!w) return;
|
|
329
|
+
const has = w.undelivered?.find(m => m.id === item.id);
|
|
330
|
+
const entry = undeliveredEntry(item, Date.now(), gateway.directory.cached(item.ref.agentId!)?.title ?? null, has?.since ?? null, queue.scale);
|
|
331
|
+
if (!entry && !has || entry && has && JSON.stringify(entry) === JSON.stringify(has)) return;
|
|
332
|
+
await store.mutateWorkspace(w.id, x => {
|
|
333
|
+
const rest = (x.undelivered ?? []).filter(m => m.id !== item.id);
|
|
334
|
+
x.undelivered = entry ? [...rest, entry].slice(-20) : rest;
|
|
335
|
+
});
|
|
336
|
+
},
|
|
337
|
+
});
|
|
338
|
+
const enqueueMessage = (agentId: string, text: string, messageId: string, by?: string) => {
|
|
339
|
+
const key = gateway.directory.cached(agentId)?.workspaceId ?? `agent:${agentId}`;
|
|
340
|
+
queue.enqueue({ id: `message:${agentId}:${messageId}`, kind: "message", key, ref: { agentId }, messageId, text, ...(by ? { by } : {}), priority: "now", state: "queued" });
|
|
341
|
+
};
|
|
342
|
+
onDaemonReconnect(() => queue.reconnected());
|
|
302
343
|
/** What the bridge and the Stop hook read: is the inbox on, may agents be nudged, who has a prompt showing. */
|
|
303
344
|
const writeBriefState = async () => {
|
|
304
345
|
const values = await inboxSettings();
|
|
@@ -406,6 +447,7 @@ export default function contribute(server: PluginServerContext) {
|
|
|
406
447
|
// 1.4.0-beta.2: tools are per agent now; drop the old user-scope registrations that spawned mcp.mjs in every session.
|
|
407
448
|
void removeGlobalRegistrations().then(results => { const removed = results.filter(r => r.status === "removed").map(r => r.path); if (removed.length) console.warn(`[follow-up] removed the global follow-up MCP registration from ${removed.length} file(s); backups end in .follow-up-unregister.bak`); });
|
|
408
449
|
governor.start();
|
|
450
|
+
await linked.backfill();
|
|
409
451
|
await engine.recover();
|
|
410
452
|
await migrateTracking();
|
|
411
453
|
await dedupeQuestions();
|
|
@@ -422,8 +464,13 @@ export default function contribute(server: PluginServerContext) {
|
|
|
422
464
|
await agentHooks.start().catch(() => { hookError = "Automatic sidebar instructions could not be registered for every provider. Check Claude/Codex hook settings; following still works."; });
|
|
423
465
|
hookTimer = setInterval(() => void agentHooks.heartbeat().catch(() => {}), 30_000);
|
|
424
466
|
await writeBriefState().catch(() => undefined);
|
|
425
|
-
//
|
|
426
|
-
|
|
467
|
+
// The message queue: answers recorded before a reload (or before the upgrade from 2.0's per-answer senders) join it,
|
|
468
|
+
// a send a reload cut off is read back from the agent's chat before it goes again, and everything due goes now.
|
|
469
|
+
await queue.load();
|
|
470
|
+
await engine.adoptAnswers().catch(error => console.warn(`[follow-up] couldn't move answers onto the queue: ${error instanceof Error ? error.message : String(error)}`));
|
|
471
|
+
await engine.adoptBatches().catch(error => console.warn(`[follow-up] couldn't move batches onto the queue: ${error instanceof Error ? error.message : String(error)}`));
|
|
472
|
+
await inbox.adoptOutbox().catch(error => console.warn(`[follow-up] couldn't move the answer outbox onto the queue: ${error instanceof Error ? error.message : String(error)}`));
|
|
473
|
+
queue.start();
|
|
427
474
|
})().catch(() => { loadError = "Follow-up could not start. Check its saved state and worker lock."; });
|
|
428
475
|
for (const file of [store, reviewerStore.persist, agentSettings.persist, prWorkflow.persist, inbox.store.persist]) file.health = writeHealth;
|
|
429
476
|
const requireReady = async () => { if (waiting) throw new Error(waiting); await ready; if (loadError || stopped) throw new Error(loadError ?? "Follow-up is stopping"); };
|
|
@@ -672,9 +719,11 @@ export default function contribute(server: PluginServerContext) {
|
|
|
672
719
|
handle(rpc.setSpecRpc, async ({ agentId, url, title }, { paseo }) => {
|
|
673
720
|
await requireReady();
|
|
674
721
|
const workspaceId = await callerWorkspaceId(agentId, paseo);
|
|
722
|
+
const links = await linkedStore.read();
|
|
675
723
|
return store.mutate(state => {
|
|
676
724
|
const w = agentWorkspace(state, agentId, "write", workspaceId);
|
|
677
725
|
const { applied, message } = agentSetSpec(w, agentId, url, title, Date.now());
|
|
726
|
+
fillWorkspaceTitles(w, localTitles(state.workspaces, links));
|
|
678
727
|
return { workspaceId: w.id, spec: w.spec, applied, message };
|
|
679
728
|
});
|
|
680
729
|
});
|
|
@@ -721,10 +770,12 @@ export default function contribute(server: PluginServerContext) {
|
|
|
721
770
|
});
|
|
722
771
|
handle(rpc.workspaceSpecRpc, async (input, context) => {
|
|
723
772
|
await requireReady();
|
|
773
|
+
const links = await linkedStore.read();
|
|
724
774
|
return store.mutate(state => {
|
|
725
775
|
const w = findWorkspace(state, input.workspaceId);
|
|
726
776
|
if (!w.enable_tracking || w.archived) throw new Error("Follow-up isn't following this workspace. Turn it back on in Follow-up settings, under Workspace exceptions.");
|
|
727
777
|
developerSetSpec(w, input, Date.now(), actorOf(context));
|
|
778
|
+
fillWorkspaceTitles(w, localTitles(state.workspaces, links));
|
|
728
779
|
return w;
|
|
729
780
|
});
|
|
730
781
|
});
|
|
@@ -851,7 +902,7 @@ export default function contribute(server: PluginServerContext) {
|
|
|
851
902
|
branch: w.gitRuntime?.currentBranch ?? null, pr: w.githubRuntime?.pullRequest?.title ? { number: w.githubRuntime.pullRequest.number ?? null, title: w.githubRuntime.pullRequest.title } : null }));
|
|
852
903
|
};
|
|
853
904
|
const overseerOn = async () => (await inboxSettings()).enable_overseer !== false;
|
|
854
|
-
overseer = new Overseer({ directory, store, inbox, sources: senderSources, priorities: priorityStore, workspaces: paseoWorkspaces, enabled: overseerOn, paseoHome, tight: async () => !governor.allowsBackground(),
|
|
905
|
+
overseer = new Overseer({ directory, store, inbox, enqueue: enqueueMessage, sources: senderSources, priorities: priorityStore, workspaces: paseoWorkspaces, enabled: overseerOn, paseoHome, tight: async () => !governor.allowsBackground(),
|
|
855
906
|
windowMs: async () => activeWindowMs(await store.snapshot()), agent: () => agentSettings.role("overseer"),
|
|
856
907
|
// Harness override only (isolated test daemons): "provider/model" wins over Settings → Agents.
|
|
857
908
|
provider: process.env.FOLLOW_UP_OVERSEER_PROVIDER || undefined,
|
|
@@ -1126,6 +1177,21 @@ export default function contribute(server: PluginServerContext) {
|
|
|
1126
1177
|
if (!stopped) linkedTimer = setTimeout(() => void linkedLoop(), 10 * 60_000);
|
|
1127
1178
|
};
|
|
1128
1179
|
linkedTimer = setTimeout(() => void linkedLoop(), 90_000);
|
|
1180
|
+
// Local title recovery is independent of a panel/RPC response: one shared index, at most 4 MB for an unnamed backlog.
|
|
1181
|
+
let titleTimer: ReturnType<typeof setTimeout> | null = null;
|
|
1182
|
+
const titleLoop = async () => {
|
|
1183
|
+
await ready;
|
|
1184
|
+
if (stopped || loadError) return;
|
|
1185
|
+
if (governor.allowsBackground()) try {
|
|
1186
|
+
const state = await store.snapshot(), file = await linkedStore.read();
|
|
1187
|
+
await transcriptTitles.tick(state.workspaces, file.workspaces, async titles => {
|
|
1188
|
+
await linkedStore.mutate(file => { fillLinkedTitles(file, titles); });
|
|
1189
|
+
for (const w of (await store.snapshot()).workspaces) if (w.enable_tracking && workspaceNeedsTitles(w, titles)) await store.mutateWorkspace(w.id, current => { fillWorkspaceTitles(current, titles); });
|
|
1190
|
+
});
|
|
1191
|
+
} catch { /* a local miss never prevents following work */ }
|
|
1192
|
+
if (!stopped) titleTimer = setTimeout(() => void titleLoop(), 30_000);
|
|
1193
|
+
};
|
|
1194
|
+
titleTimer = setTimeout(() => void titleLoop(), 30_000);
|
|
1129
1195
|
// Developer RPCs as agent tools (server/agent-parity.ts): the same handler the button's RPC runs.
|
|
1130
1196
|
const rpcBridge = {
|
|
1131
1197
|
async validate(method: string, input: unknown) { const h = handlers.get(method); if (!h) throw new Error(`Unknown Follow-up method ${method}.`); return h.input.parseAsync(input); },
|
|
@@ -1173,7 +1239,7 @@ export default function contribute(server: PluginServerContext) {
|
|
|
1173
1239
|
handle(rpc.reportSendRpc, async (input, { paseo }) => {
|
|
1174
1240
|
seen(paseo);
|
|
1175
1241
|
return sendReport({
|
|
1176
|
-
rows: () => gateway.directory.read().catch(() => null), multiplicity: hostMultiplicity, sendTo: (agentId, prompt, messageId) =>
|
|
1242
|
+
rows: () => gateway.directory.read().catch(() => null), multiplicity: hostMultiplicity, sendTo: async (agentId, prompt, messageId) => enqueueMessage(agentId, prompt, messageId, "developer"),
|
|
1177
1243
|
agentTitle: async agentId => (await gateway.directory.read().catch(() => null))?.agents.find(r => r.agent.id === agentId)?.agent.title ?? null,
|
|
1178
1244
|
provider: async () => ({ provider: await providerModel(paseo as unknown as OverseerPaseo, (await agentSettings.role("overseer").catch(() => null))?.provider?.split("/")[0] ?? "claude") }),
|
|
1179
1245
|
paseo: paseo as unknown as ReportSendDeps["paseo"],
|
|
@@ -1200,6 +1266,17 @@ export default function contribute(server: PluginServerContext) {
|
|
|
1200
1266
|
// Home, the sidebar badge and the pills poll this; an unchanged list answers in a few bytes (see inboxAnswer).
|
|
1201
1267
|
handle(rpc.inboxListRpc, async ({ etag }) => { await requireReady(); const handedBack = noReviewRepoList().length ? (await store.snapshot()).workspaces.flatMap(w => w.prs.filter(handsMergeBack).map(p => p.key)) : [];
|
|
1202
1268
|
return inboxAnswer({ ...await inbox.list(), error: inboxError, ...(handedBack.length ? { handedBack } : {}) }, etag); });
|
|
1269
|
+
handle(rpc.queueListRpc, async ({ workspaceId, agentId }) => {
|
|
1270
|
+
await requireReady();
|
|
1271
|
+
const { items, recent } = queue.list({ ...(workspaceId ? { key: workspaceId } : {}), ...(agentId ? { agentId } : {}) });
|
|
1272
|
+
return { items: items.map(queueView), recent: recent.map(queueView) };
|
|
1273
|
+
});
|
|
1274
|
+
// Retry or Cancel one item: the card's buttons, Needs you's message row and follow_queue_action run this.
|
|
1275
|
+
handle(rpc.queueActionRpc, async ({ itemId, action }) => {
|
|
1276
|
+
await requireReady();
|
|
1277
|
+
const item = action === "retry" ? await queue.retry(itemId) : await queue.cancel(itemId, "Cancelled; it won't be sent.");
|
|
1278
|
+
return { item: queueView(item) };
|
|
1279
|
+
});
|
|
1203
1280
|
handle(rpc.inboxBriefRpc, async ({ agentId }) => { await requireReady(); return { brief: await inbox.brief(agentId) }; });
|
|
1204
1281
|
handle(rpc.inboxActRpc, async (input, context) => {
|
|
1205
1282
|
await requireReady();
|
|
@@ -1299,7 +1376,7 @@ export default function contribute(server: PluginServerContext) {
|
|
|
1299
1376
|
handle(rpc.briefActionRpc, async ({ agentId, briefId, decisionId, choice, words, choices, move, answerId }, context) => {
|
|
1300
1377
|
const { paseo } = context;
|
|
1301
1378
|
await requireReady(); seen(paseo);
|
|
1302
|
-
const brief = await inbox.briefAction(agentId, { briefId, decisionId, choice, words, choices, move, answerId },
|
|
1379
|
+
const brief = await inbox.briefAction(agentId, { briefId, decisionId, choice, words, choices, move, answerId }, actorOf(context));
|
|
1303
1380
|
return { brief };
|
|
1304
1381
|
});
|
|
1305
1382
|
|
|
@@ -1489,11 +1566,11 @@ export default function contribute(server: PluginServerContext) {
|
|
|
1489
1566
|
const stop = () => stopping ??= (async () => {
|
|
1490
1567
|
process.off("disconnect", hostGone);
|
|
1491
1568
|
restoreConsole();
|
|
1492
|
-
stopped = true; wait.close(); updater.stop(); pluginMove.stop(); governor.stop(); if (timer) clearTimeout(timer); if (aboutTimer) clearTimeout(aboutTimer); if (linkedTimer) clearTimeout(linkedTimer); aiJobs.stop(); ranker = null; if (inboxTimer) clearTimeout(inboxTimer); inbox.stop(); rpcTiming.stop(); if (hookTimer) clearInterval(hookTimer); memoryWatch?.stop(); displayOff?.(); usageWatch?.close(); removers.forEach(remove => remove());
|
|
1569
|
+
stopped = true; wait.close(); updater.stop(); pluginMove.stop(); governor.stop(); if (timer) clearTimeout(timer); if (aboutTimer) clearTimeout(aboutTimer); if (linkedTimer) clearTimeout(linkedTimer); if (titleTimer) clearTimeout(titleTimer); aiJobs.stop(); ranker = null; if (inboxTimer) clearTimeout(inboxTimer); inbox.stop(); queue.stop(); rpcTiming.stop(); if (hookTimer) clearInterval(hookTimer); memoryWatch?.stop(); displayOff?.(); usageWatch?.close(); removers.forEach(remove => remove());
|
|
1493
1570
|
// One deadline for every wait (worker-stop-never-waits-on-a-stuck-pass, server/teardown.ts): start-up and the work
|
|
1494
1571
|
// in flight may be stuck on a daemon or CLI that never answers. Work that ends inside the deadline is saved; what
|
|
1495
1572
|
// outlives it can't write, because the store closes before the lock is released.
|
|
1496
|
-
await stopWorker({ files: [reviewerStore, agentSettings, prWorkflow], ready, hooks: hooksStarted ? () => agentHooks.stop() : undefined, actions, closeConnections, engine, store, inbox: inbox.store, unlock });
|
|
1573
|
+
await stopWorker({ files: [reviewerStore, agentSettings, prWorkflow, queue], ready, hooks: hooksStarted ? () => agentHooks.stop() : undefined, actions, closeConnections, engine, store, inbox: inbox.store, unlock });
|
|
1497
1574
|
})();
|
|
1498
1575
|
return stop;
|
|
1499
1576
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "paseo-follow-up",
|
|
3
3
|
"private": false,
|
|
4
|
-
"version": "2.1.0
|
|
4
|
+
"version": "2.1.0",
|
|
5
5
|
"description": "A Paseo plugin that follows every workspace until the work is done: one Home for what needs you, questions you answer anywhere, and repairs that send themselves.",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"files": [
|
package/server/agent-actions.ts
CHANGED
|
@@ -47,7 +47,7 @@ export function rowPrs(state: State, r: InboxRow, now: number): PrLink[] {
|
|
|
47
47
|
return [...out.values()];
|
|
48
48
|
}
|
|
49
49
|
|
|
50
|
-
export const AGENT_TOOLS = ["make_main_agent", "list_prs", "add_reviewers", "merge", "enable_merge_when_ready", "disable_merge_when_ready", "send_repairs", "set_auto_send", "clear_hold", "retry_batch", "track", "inbox_list", "sign_off", "snooze", "snooze_workspace", "set_finish_flags", "set_priorities", "workspace_about", "agent_settings", "follow_settings", "set_follow_settings", "project_settings", "set_project_tracking", "pr_workflow", "set_pr_workflow", "reviewer_settings", "reviewer_suggestions", "save_reviewers", "set_agent_setting", "set_wait_for_jobs", "onboarding_status", "onboarding_checks", "set_onboarding", "priorities", "rank_status", "rerank_priorities", "usage", "overseer_status", "overseer_start", "overseer_restart", "overseer_ask", "inbox_brief", "brief_action", "inbox_act", "answer_question", "run_recovery", "refresh", "set_workspace_spec", "set_task_trigger", "pr_controls", "browser_status", "trust_bypass_status", "release_notes", "link_items", "set_linked_items", "updates_status", "check_updates", "set_updates", "install_update", "display_settings", "set_display", "retry_move", "report_issue", "report_send", "ai_rename"] as const;
|
|
50
|
+
export const AGENT_TOOLS = ["make_main_agent", "list_prs", "add_reviewers", "merge", "enable_merge_when_ready", "disable_merge_when_ready", "send_repairs", "set_auto_send", "clear_hold", "retry_batch", "track", "inbox_list", "sign_off", "snooze", "snooze_workspace", "set_finish_flags", "set_priorities", "workspace_about", "agent_settings", "follow_settings", "set_follow_settings", "project_settings", "set_project_tracking", "pr_workflow", "set_pr_workflow", "reviewer_settings", "reviewer_suggestions", "save_reviewers", "set_agent_setting", "set_wait_for_jobs", "onboarding_status", "onboarding_checks", "set_onboarding", "priorities", "rank_status", "rerank_priorities", "usage", "overseer_status", "overseer_start", "overseer_restart", "overseer_ask", "inbox_brief", "brief_action", "queue_list", "queue_action", "inbox_act", "answer_question", "run_recovery", "refresh", "set_workspace_spec", "set_task_trigger", "pr_controls", "browser_status", "trust_bypass_status", "release_notes", "link_items", "set_linked_items", "updates_status", "check_updates", "set_updates", "install_update", "display_settings", "set_display", "retry_move", "report_issue", "report_send", "ai_rename"] as const;
|
|
51
51
|
export type AgentTool = typeof AGENT_TOOLS[number];
|
|
52
52
|
/** Tools that only read. */
|
|
53
53
|
export const READ_ONLY_TOOLS: readonly AgentTool[] = ["list_prs", "inbox_list", "workspace_about", "agent_settings", "display_settings", ...RPC_TOOLS.filter(t => t.kind === "read").map(t => t.name as AgentTool)];
|
package/server/agent-hook.mjs
CHANGED
|
@@ -13,7 +13,7 @@ const directory = dirname(fileURLToPath(import.meta.url));
|
|
|
13
13
|
/** 1.4.0-beta.2: launched with Follow-up's tools served by Paseo's MCP (follow_<name>), or the follow-up bridge (<name>). Agents opened before the upgrade carry no flag and keep the bridge names. */
|
|
14
14
|
let native = env("TOOLS") === "native";
|
|
15
15
|
// Tool names that read unambiguously in prose; kept identical to server/mcp.mjs's underscore names (a test checks it).
|
|
16
|
-
export const TOOL_NAMES = ["workspace_status", "sync_workspace", "enroll_workspace", "register_pr", "exclude_stack", "update_obligation", "acknowledge_batch", "ask_question", "record_answer", "withdraw_question", "set_spec", "link_item", "unlink_item", "link_items", "set_linked_items", "workspace_about", "agent_settings", "needs_you", "declare_done", "list_prs", "add_reviewers", "enable_merge_when_ready", "disable_merge_when_ready", "send_repairs", "set_auto_send", "clear_hold", "retry_batch", "inbox_list", "sign_off", "snooze_workspace", "set_finish_flags", "set_priorities", "agent_digest", "route_candidates", "send_to_agent", "start_workspace", "display_settings", "set_display", "follow_settings", "set_follow_settings", "project_settings", "set_project_tracking", "pr_workflow", "set_pr_workflow", "reviewer_settings", "reviewer_suggestions", "save_reviewers", "set_agent_setting", "set_wait_for_jobs", "onboarding_status", "onboarding_checks", "set_onboarding", "rank_status", "rerank_priorities", "overseer_status", "overseer_start", "overseer_restart", "overseer_ask", "inbox_brief", "brief_action", "inbox_act", "answer_question", "run_recovery", "set_workspace_spec", "set_task_trigger", "pr_controls", "browser_status", "trust_bypass_status", "release_notes", "updates_status", "check_updates", "set_updates", "install_update", "make_main_agent", "retry_move", "report_issue", "report_send", "ai_rename"];
|
|
16
|
+
export const TOOL_NAMES = ["workspace_status", "sync_workspace", "enroll_workspace", "register_pr", "exclude_stack", "update_obligation", "acknowledge_batch", "ask_question", "record_answer", "withdraw_question", "set_spec", "link_item", "unlink_item", "link_items", "set_linked_items", "workspace_about", "agent_settings", "needs_you", "declare_done", "list_prs", "add_reviewers", "enable_merge_when_ready", "disable_merge_when_ready", "send_repairs", "set_auto_send", "clear_hold", "retry_batch", "inbox_list", "sign_off", "snooze_workspace", "set_finish_flags", "set_priorities", "agent_digest", "route_candidates", "send_to_agent", "start_workspace", "display_settings", "set_display", "follow_settings", "set_follow_settings", "project_settings", "set_project_tracking", "pr_workflow", "set_pr_workflow", "reviewer_settings", "reviewer_suggestions", "save_reviewers", "set_agent_setting", "set_wait_for_jobs", "onboarding_status", "onboarding_checks", "set_onboarding", "rank_status", "rerank_priorities", "overseer_status", "overseer_start", "overseer_restart", "overseer_ask", "inbox_brief", "brief_action", "queue_list", "queue_action", "inbox_act", "answer_question", "run_recovery", "set_workspace_spec", "set_task_trigger", "pr_controls", "browser_status", "trust_bypass_status", "release_notes", "updates_status", "check_updates", "set_updates", "install_update", "make_main_agent", "retry_move", "report_issue", "report_send", "ai_rename"];
|
|
17
17
|
const toolPattern = new RegExp(`(?<![\\w])(${TOOL_NAMES.join("|")})(?![\\w])`, "g");
|
|
18
18
|
/** Names Follow-up's tools the way this agent has them. */
|
|
19
19
|
export function named(text, isNative = native) { return isNative ? text.replace(toolPattern, "follow_$1") : text; }
|
|
@@ -105,6 +105,11 @@ export async function freshDigest(read, seen, { now = Date.now, sleep = ms => ne
|
|
|
105
105
|
* How batches are worked, for this workspace's PR workflow (from scopes.json). Graphite with /fix-pr, and agents of an
|
|
106
106
|
* older worker that wrote no workflow, keep the original text; plain GitHub never mentions Graphite, gt or /fix-pr.
|
|
107
107
|
*/
|
|
108
|
+
/**
|
|
109
|
+
* One Follow-up message can carry several parts (shared/queue.ts ENVELOPE_SEPARATOR, PART_HEADERS): an answer and the
|
|
110
|
+
* batch that rode along with it. tests/message-envelope.test.ts holds this text to the envelope format.
|
|
111
|
+
*/
|
|
112
|
+
export const ENVELOPE_GUIDANCE = "One Follow-up message can carry several parts, separated by a line holding only ---; each part starts with its own header (\"Follow-up answer …\" or \"Follow-up batch …\") and follows its own rules: an answer is already recorded, a batch is acknowledged with acknowledge_batch by its batch ID.";
|
|
108
113
|
export function batchParagraph(workflow) {
|
|
109
114
|
const mode = workflow?.mode ?? "graphite";
|
|
110
115
|
const fix = workflow === undefined || workflow === null ? "/fix-pr" : workflow.reviewFix ?? null;
|
|
@@ -143,7 +148,7 @@ function paragraphs(lease, contributor, workflow) {
|
|
|
143
148
|
"Maintain this tracked workspace's Follow-up sidebar as part of your normal work; do not wait for a developer reminder.",
|
|
144
149
|
quietInstruction,
|
|
145
150
|
"Read workspace_status now and after compaction. Refine the goal with enroll_workspace when scope changes. Register every PR you produce after submitting it, parents before children, and update stack/parent relationships after restacking. Historical mentions and external dependencies are not owned PRs; preserve exclusions and existing records.",
|
|
146
|
-
"When a decision needs the developer, call ask_question with a short title, the question, lettered options with what each means, and your recommendation; mark it big only when building ahead would leave this computer, set something others rely on, or most remaining work depends on it. Follow the question mode in its reply. Ask each decision once: asking it again returns the open question, and at a turn's end you point at it (needs_you questions=[\"Q<n>\"]) instead of restating it. Answers arrive as messages starting \"Follow-up answer Q<n>\" and are already recorded; several decisions from one card arrive together in one message, one line per decision, with skipped ones marked \"skipped\" and still open. An answer of Something else — \"…\" means none of your options: the quoted words are the developer's answer. Every card already offers Something else, so don't add an Other option. If the developer answers in chat, call record_answer (choice \"other\" with words when it matches none of your options). Withdraw questions that stop mattering.",
|
|
151
|
+
"When a decision needs the developer, call ask_question with a short title, the question, lettered options with what each means, and your recommendation; mark it big only when building ahead would leave this computer, set something others rely on, or most remaining work depends on it. Follow the question mode in its reply. Ask each decision once: asking it again returns the open question, and at a turn's end you point at it (needs_you questions=[\"Q<n>\"]) instead of restating it. Answers arrive as messages starting \"Follow-up answer Q<n>\" and are already recorded; several decisions from one card arrive together in one message, one line per decision, with skipped ones marked \"skipped\" and still open. An answer of Something else — \"…\" means none of your options: the quoted words are the developer's answer. Every card already offers Something else, so don't add an Other option. If the developer answers in chat, call record_answer (choice \"other\" with words when it matches none of your options). Withdraw questions that stop mattering. " + ENVELOPE_GUIDANCE,
|
|
147
152
|
linkInstruction,
|
|
148
153
|
"If you keep a Claude artifact (or doc) summarizing this workspace's goal, decisions and status, register its link once with set_spec after the first publish. Republish to the same URL; call set_spec again only if the link changes.",
|
|
149
154
|
"Keep actual follow-up tasks current with update_obligation: production behavior checks, migrations and decisions, with concise titles, PR dependencies and evidence. Do not add merge/approval/deploy checklist tasks. Deployment-dependent work waits for verified serving revisions and existing production permissions. A task waiting on a PR or another agent is status=waiting; blocked is only for the developer, with ask set to the question they must answer.",
|
package/server/agent-parity.ts
CHANGED
|
@@ -70,6 +70,10 @@ export const RPC_TOOLS: readonly RpcTool[] = [
|
|
|
70
70
|
{ name: "overseer_restart", rpc: "follow.overseer-restart", kind: "planned", before: { rpc: "follow.overseer-status" }, input: z.strictObject({ ...confirm }) },
|
|
71
71
|
{ name: "overseer_ask", rpc: "follow.overseer-ask", kind: "planned", input: z.strictObject({ text: z.string().trim().min(1).max(2000).optional(), ...confirm }) },
|
|
72
72
|
// Needs-you: the brief card and the inbox's other actions
|
|
73
|
+
// The message queue: what waits to go to agents, and Retry or Cancel on one item (a card's Retry, Needs you's message row).
|
|
74
|
+
{ name: "queue_list", rpc: "follow.queue-list", kind: "read", input: z.strictObject({ workspaceId: id.optional(), agentId: id.optional() }) },
|
|
75
|
+
{ name: "queue_action", rpc: "follow.queue-action", kind: "planned", before: { rpc: "follow.queue-list", input: () => ({}) },
|
|
76
|
+
input: z.strictObject({ itemId: z.string().min(1).max(400).optional(), action: z.enum(["retry", "cancel"]).optional(), ...confirm }) },
|
|
73
77
|
{ name: "inbox_brief", rpc: "follow.inbox-brief", kind: "read", input: z.strictObject({ agentId: id }) },
|
|
74
78
|
{ name: "brief_action", rpc: "follow.brief-action", kind: "planned", before: { rpc: "follow.inbox-brief", input: a => ({ agentId: a.agentId }) },
|
|
75
79
|
input: z.strictObject({ agentId: id.optional(), briefId: z.string().max(300).optional(), decisionId: z.string().max(20).optional(), choice: briefChoiceSchema.optional(), words: z.string().trim().max(2000).optional(), move: z.enum(["retry", "done"]).optional(),
|
|
@@ -168,6 +172,7 @@ export const PARITY: Record<string, { tools: readonly string[]; note?: string }
|
|
|
168
172
|
"follow.overseer-ask": { tools: ["overseer_ask"] },
|
|
169
173
|
"follow.inbox-list": { tools: ["inbox_list"] },
|
|
170
174
|
"follow.inbox-brief": { tools: ["inbox_brief"] },
|
|
175
|
+
"follow.queue-action": { tools: ["queue_action"] },
|
|
171
176
|
"follow.inbox-act": { tools: ["sign_off", "snooze", "set_finish_flags", "inbox_act"] },
|
|
172
177
|
"follow.brief-action": { tools: ["brief_action"] },
|
|
173
178
|
"follow.answer-question": { tools: ["answer_question"], note: "The tool sends (action send). Copy and Put in chat (action copy, chat) only move the developer's own words into their clipboard or their composer for them to send; an agent answers by sending, so it has no Put in chat." },
|
package/server/daemon.ts
CHANGED
|
@@ -14,6 +14,7 @@ import { defaultTracking, followsEvery, optedOut, projectSetting, type Project }
|
|
|
14
14
|
import { recoveryHandoff } from "./recovery-handoff";
|
|
15
15
|
import { applyRecoveryRole, recoveryConfig, type RecoveryRole } from "./recovery-config";
|
|
16
16
|
import { submittedPrs, type Submission } from "./submissions";
|
|
17
|
+
import { receiptTitles } from "./local-titles";
|
|
17
18
|
import { publishedArtifacts } from "./spec";
|
|
18
19
|
import type { Artifact } from "../shared/spec";
|
|
19
20
|
import { extractHistory, inMainCooldown, type History, type DiscoveredWorkspace } from "./discovery";
|
|
@@ -27,9 +28,11 @@ export { ConversationGone } from "./delivery";
|
|
|
27
28
|
import { compactionDelivered, turnIdOf } from "../shared/status";
|
|
28
29
|
import { activeWindowMs, backgroundCount, isLive, isLoaded, recentlyUsed, workspaceActive, conversationGone, DEFAULT_ACTIVE_WINDOW_DAYS, DAY_MS } from "./agent-load";
|
|
29
30
|
import { HistoryCache } from "./history-cache";
|
|
31
|
+
import { agentRecord, headAndTail, transcriptFile } from "./transcript";
|
|
30
32
|
import { DaemonDirectory, type DirectoryRows } from "./directory";
|
|
31
33
|
import { traceDaemon } from "./request-trace";
|
|
32
34
|
import type { TurnTimeline } from "./turn-timeline";
|
|
35
|
+
import { PASEO_UNREACHABLE } from "../shared/queue";
|
|
33
36
|
type RecoveryAgentOptions = Partial<PluginBeforeRequests["agent.create"]["config"]> & { workspaceId: string; labels: Record<string, string>; idempotencyKey: string; env: Record<string, string>; /** Paseo 0.16 (features.backgroundAgents): no tab, no notification, no sidebar row. */ background?: boolean };
|
|
34
37
|
|
|
35
38
|
/**
|
|
@@ -100,7 +103,7 @@ export interface Daemon {
|
|
|
100
103
|
type Module = { DaemonClient: new (input: Record<string, unknown>) => Daemon };
|
|
101
104
|
const clients = new Set<Daemon>();
|
|
102
105
|
/** Called before Follow-up sends a message, so the Needs-you inbox can tell its own sends from the developer's. */
|
|
103
|
-
let beforeSend: (agentId: string, messageId: string) => Promise<void> = async () => {};
|
|
106
|
+
let beforeSend: (agentId: string, messageId: string, by?: string) => Promise<void> = async () => {};
|
|
104
107
|
export function onBeforeSend(note: typeof beforeSend): void { beforeSend = note; }
|
|
105
108
|
let stopped = false;
|
|
106
109
|
export function clientEntry(): string { return createRequire(process.argv[1]).resolve(["@getpaseo", "client", "internal", "daemon-client"].join("/")); }
|
|
@@ -137,11 +140,15 @@ export function withDaemon<T>(work: (client: Daemon) => Promise<T>): Promise<T>
|
|
|
137
140
|
* a 5 s idle close opened one per tick (39 hellos in 12 min).
|
|
138
141
|
*/
|
|
139
142
|
export const SHARED_CLIENT_MAX_MS = 30 * 60_000;
|
|
143
|
+
/** Called when a daemon connection opens after the last one failed or dropped (the message queue retries at once). */
|
|
144
|
+
let reopened: () => void = () => {};
|
|
145
|
+
export function onDaemonReconnect(note: () => void): void { reopened = note; }
|
|
140
146
|
export type SharedConnect = <T>(work: (client: Daemon) => Promise<T>) => Promise<T>;
|
|
141
147
|
type Shared = { client: Promise<Daemon>; opened: number; users: number; retired: boolean };
|
|
142
148
|
export function sharedDaemon(open: () => Promise<Daemon> = openDaemon, o: { maxMs?: number; now?: () => number } = {}): SharedConnect {
|
|
143
149
|
const maxMs = o.maxMs ?? SHARED_CLIENT_MAX_MS, now = o.now ?? Date.now;
|
|
144
150
|
let current: Shared | null = null;
|
|
151
|
+
let lost = false;
|
|
145
152
|
const close = async (entry: Shared) => {
|
|
146
153
|
if (current === entry) current = null;
|
|
147
154
|
const client = await entry.client.catch(() => null);
|
|
@@ -153,10 +160,10 @@ export function sharedDaemon(open: () => Promise<Daemon> = openDaemon, o: { maxM
|
|
|
153
160
|
if (stopped) throw new Error("Follow-up is stopping");
|
|
154
161
|
if (current && now() - current.opened >= maxMs) { current.retired = true; const old = current; current = null; settle(old); }
|
|
155
162
|
if (!current) {
|
|
156
|
-
const client = open().then(c => { if (stopped) { void c.close().catch(() => undefined); throw new Error("Follow-up is stopping"); } clients.add(c); return c; });
|
|
163
|
+
const client = open().then(c => { if (stopped) { void c.close().catch(() => undefined); throw new Error("Follow-up is stopping"); } clients.add(c); if (lost) { lost = false; reopened(); } return c; });
|
|
157
164
|
const entry: Shared = { client, opened: now(), users: 0, retired: false };
|
|
158
165
|
current = entry;
|
|
159
|
-
void client.catch(() => { if (current === entry) current = null; });
|
|
166
|
+
void client.catch(() => { lost = true; if (current === entry) current = null; });
|
|
160
167
|
}
|
|
161
168
|
const entry = current;
|
|
162
169
|
entry.users++;
|
|
@@ -166,7 +173,7 @@ export function sharedDaemon(open: () => Promise<Daemon> = openDaemon, o: { maxM
|
|
|
166
173
|
catch (error) {
|
|
167
174
|
// A dropped connection isn't reused: the next call opens a fresh one.
|
|
168
175
|
const status = (client as unknown as { connectionState?: { status?: string } }).connectionState?.status;
|
|
169
|
-
if (status !== undefined && status !== "connected") { entry.retired = true; if (current === entry) current = null; }
|
|
176
|
+
if (status !== undefined && status !== "connected") { lost = true; entry.retired = true; if (current === entry) current = null; }
|
|
170
177
|
throw error;
|
|
171
178
|
}
|
|
172
179
|
} finally {
|
|
@@ -413,13 +420,14 @@ export class PaseoGateway implements Gateway {
|
|
|
413
420
|
const read = kept ?? (cached?.cursor && cached.history.complete && !cached.history.error ? this.turnTimeline?.since(agent.id, cached.cursor, OVERLAP) ?? await readSince(client!, agent.id, cached.cursor) : null) ?? await readAll(client!, agent.id);
|
|
414
421
|
end = read.end;
|
|
415
422
|
const items = read.entries.map(e => e.item);
|
|
423
|
+
const titles = await receiptTitles(read.entries);
|
|
416
424
|
// Linked items ride this read. Best-effort: a throw here must never mark the history unreadable.
|
|
417
425
|
if (this.linkRefs) try {
|
|
418
426
|
const after = cached?.cursor && read.end && cached.cursor.epoch === read.end.epoch ? cached.cursor.seq : -1;
|
|
419
|
-
const found = timelineRefs(read.entries, after);
|
|
427
|
+
const found = [...timelineRefs(read.entries, after), ...[...titles].map(([raw, evidence]) => ({ raw, strong: true, title: evidence.title, titleRank: evidence.rank }))];
|
|
420
428
|
if (found.length) refs.set(dueRow.id, [...refs.get(dueRow.id) ?? [], ...found]);
|
|
421
429
|
} catch { /* skipped for this batch */ }
|
|
422
|
-
const fresh = { artifacts: publishedArtifacts(read.entries, agent.id), history: extractHistory(items, read.complete, read.complete ? null : "History exceeds the recovery window; inspect older transcripts during inventory"), submissions: submittedPrs(items, agent.id, repo) };
|
|
430
|
+
const fresh = { artifacts: publishedArtifacts(read.entries, agent.id, titles), history: extractHistory(items, read.complete, read.complete ? null : "History exceeds the recovery window; inspect older transcripts during inventory"), submissions: submittedPrs(items, agent.id, repo) };
|
|
423
431
|
if (read.incremental && cached) {
|
|
424
432
|
this.incrementalReads++;
|
|
425
433
|
history = { candidates: [...new Set([...cached.history.candidates, ...fresh.history.candidates])].sort(), goal: cached.history.goal ?? fresh.history.goal, complete: true, error: null };
|
|
@@ -534,18 +542,7 @@ export class PaseoGateway implements Gateway {
|
|
|
534
542
|
const recipient = batch.recipientAgentId ?? w.mainAgentId;
|
|
535
543
|
const a = (await client.fetchAgent(recipient))?.agent;
|
|
536
544
|
if (!a || !isLoaded(a)) return null;
|
|
537
|
-
|
|
538
|
-
let cursor: Cursor | null = null;
|
|
539
|
-
for (let pageIndex = 0; pageIndex < 5; pageIndex++) {
|
|
540
|
-
const page = await client.fetchAgentTimeline(recipient, { direction: cursor ? "before" : "tail", ...(cursor ? { cursor } : {}), limit: 200, projection: "canonical", timeout: 15_000 });
|
|
541
|
-
if (page.error || page.gap || page.staleCursor) return null;
|
|
542
|
-
if (page.entries.some(e => { const item = e.item as { messageId?: unknown; clientMessageId?: unknown } | null; return item?.messageId === batch.messageId || item?.clientMessageId === batch.messageId; })) return true;
|
|
543
|
-
const oldest = page.entries.reduce((min, e) => Math.min(min, e.timestamp ? Date.parse(e.timestamp) : Infinity), Infinity);
|
|
544
|
-
if (!page.hasOlder || oldest < since) return false;
|
|
545
|
-
if (!page.startCursor) return null;
|
|
546
|
-
cursor = page.startCursor;
|
|
547
|
-
}
|
|
548
|
-
return null;
|
|
545
|
+
return timelineHas(client, recipient, batch.messageId, Date.parse(batch.createdAt));
|
|
549
546
|
}).catch(() => null);
|
|
550
547
|
}
|
|
551
548
|
async send(w: Workspace, batch: Batch, text: string): Promise<void> {
|
|
@@ -580,32 +577,62 @@ export class PaseoGateway implements Gateway {
|
|
|
580
577
|
});
|
|
581
578
|
}
|
|
582
579
|
/**
|
|
583
|
-
* A
|
|
584
|
-
* Session Guard pauses and pending permission prompts defer it; an unavailable agent falls back to the
|
|
580
|
+
* A queued message (server/message-queue.ts), sent like the developer typing into the agent's chat (it steers an
|
|
581
|
+
* active turn). Session Guard pauses and pending permission prompts defer it; an unavailable agent falls back to the
|
|
582
|
+
* next. DeliveryDeferred means nothing was sent (safe to retry); any other error came after the message went out.
|
|
585
583
|
*/
|
|
586
|
-
async
|
|
587
|
-
// Anything that fails before the message goes out is safe to retry; only a failed send itself is ambiguous.
|
|
584
|
+
async deliverTo(target: { workspaceId: string | null; recipients: string[] }, text: string, messageId: string, by?: string): Promise<string> {
|
|
588
585
|
let attempted = false;
|
|
589
586
|
return this.connect(async client => {
|
|
590
|
-
for (const id of recipients) {
|
|
587
|
+
for (const id of target.recipients) {
|
|
591
588
|
const a = (await client.fetchAgent(id))?.agent;
|
|
592
|
-
if (!a || a.archivedAt || a.workspaceId !==
|
|
589
|
+
if (!a || a.archivedAt || (target.workspaceId && a.workspaceId !== target.workspaceId)) continue;
|
|
593
590
|
let guarded: boolean;
|
|
594
591
|
try { guarded = !!this.guard.waiting(await this.guard.read(), { agentIds: [id] }); }
|
|
595
|
-
catch { throw new DeliveryDeferred("Session Guard state is
|
|
596
|
-
if (guarded) throw new DeliveryDeferred("
|
|
597
|
-
if (a.pendingPermissions.length) throw new DeliveryDeferred("
|
|
592
|
+
catch { throw new DeliveryDeferred("Session Guard's state is unreadable"); }
|
|
593
|
+
if (guarded) throw new DeliveryDeferred("waiting for Session Guard to resume the agent");
|
|
594
|
+
if (a.pendingPermissions.length) throw new DeliveryDeferred("waiting for the agent's permission prompt");
|
|
595
|
+
if (conversationGone(a.lastError)) throw new ConversationGone(id, a.lastError!);
|
|
598
596
|
attempted = true;
|
|
599
|
-
await beforeSend(id, messageId).catch(() => undefined);
|
|
600
|
-
await client.sendMessage(id, text, { messageId, activeTurnBehavior: "steer" });
|
|
597
|
+
await beforeSend(id, messageId, by).catch(() => undefined);
|
|
598
|
+
try { await client.sendMessage(id, text, { messageId, activeTurnBehavior: "steer" }); }
|
|
599
|
+
catch (error) { if (conversationGone(error)) throw new ConversationGone(id, error instanceof Error ? error.message : String(error)); throw error; }
|
|
601
600
|
return id;
|
|
602
601
|
}
|
|
603
|
-
throw new DeliveryDeferred("
|
|
602
|
+
throw new DeliveryDeferred("no agent in this workspace can take it right now");
|
|
604
603
|
}).catch(error => {
|
|
605
|
-
if (attempted || error instanceof DeliveryDeferred) throw error;
|
|
606
|
-
throw new DeliveryDeferred(
|
|
604
|
+
if (attempted || error instanceof DeliveryDeferred || error instanceof ConversationGone) throw error;
|
|
605
|
+
throw new DeliveryDeferred(PASEO_UNREACHABLE);
|
|
607
606
|
});
|
|
608
607
|
}
|
|
608
|
+
/**
|
|
609
|
+
* The message queue's outage probe (PROBE_MS): opens the worker's one shared connection if it isn't open, and nothing
|
|
610
|
+
* else (no agent read, so no agent wakes). True when it is connected. A connection that went stale is retired, so the
|
|
611
|
+
* next call opens a fresh one.
|
|
612
|
+
*/
|
|
613
|
+
async probe(): Promise<boolean> {
|
|
614
|
+
return this.connect(async client => {
|
|
615
|
+
const status = (client as unknown as { connectionState?: { status?: string } }).connectionState?.status;
|
|
616
|
+
if (status !== undefined && status !== "connected") throw new Error("Paseo connection is down");
|
|
617
|
+
return true;
|
|
618
|
+
}).catch(() => false);
|
|
619
|
+
}
|
|
620
|
+
/**
|
|
621
|
+
* Whether `messageId` reached the agent since `since`. A loaded agent: its timeline, where Paseo records the message
|
|
622
|
+
* with its clientMessageId when it accepts it (before the provider runs). An unloaded one is never read (that would
|
|
623
|
+
* wake it, Invariant 1): its provider transcript on disk is searched for `marker` instead, and only a find counts.
|
|
624
|
+
* Null: unknown.
|
|
625
|
+
*/
|
|
626
|
+
async arrivedMessage(agentId: string, messageId: string, since: string, marker: string): Promise<boolean | null> {
|
|
627
|
+
const loaded = await this.connect(async client => {
|
|
628
|
+
const a = (await client.fetchAgent(agentId))?.agent;
|
|
629
|
+
if (!a) return null;
|
|
630
|
+
if (!isLoaded(a)) return "unloaded" as const;
|
|
631
|
+
return timelineHas(client, agentId, messageId, Date.parse(since) - 60_000);
|
|
632
|
+
}).catch(() => null);
|
|
633
|
+
if (loaded !== "unloaded") return loaded;
|
|
634
|
+
return transcriptHas(paseoHome, agentId, marker);
|
|
635
|
+
}
|
|
609
636
|
async handoff(w: Workspace, callerId: string): Promise<{ batchId: string; fromAgentId: string } | null> {
|
|
610
637
|
return this.connect(async client => {
|
|
611
638
|
const caller = (await client.fetchAgent(callerId))?.agent;
|
|
@@ -713,3 +740,30 @@ export function handBackMainAgent(roots: Agent[], w: { mainAgentId: string; hand
|
|
|
713
740
|
const original = roots.find(a => a.id === w.handover!.from);
|
|
714
741
|
return original && original.status !== "closed" ? original : undefined;
|
|
715
742
|
}
|
|
743
|
+
|
|
744
|
+
/** Whether the agent's chat holds `messageId`, read back from the tail to `sinceMs` (at most 5 pages). Null: unknown. */
|
|
745
|
+
async function timelineHas(client: Daemon, agentId: string, messageId: string, sinceMs: number): Promise<boolean | null> {
|
|
746
|
+
let cursor: Cursor | null = null;
|
|
747
|
+
for (let pageIndex = 0; pageIndex < 5; pageIndex++) {
|
|
748
|
+
const page = await client.fetchAgentTimeline(agentId, { direction: cursor ? "before" : "tail", ...(cursor ? { cursor } : {}), limit: 200, projection: "canonical", timeout: 15_000 });
|
|
749
|
+
if (page.error || page.gap || page.staleCursor) return null;
|
|
750
|
+
if (page.entries.some(e => { const item = e.item as { messageId?: unknown; clientMessageId?: unknown } | null; return item?.messageId === messageId || item?.clientMessageId === messageId; })) return true;
|
|
751
|
+
const oldest = page.entries.reduce((min, e) => Math.min(min, e.timestamp ? Date.parse(e.timestamp) : Infinity), Infinity);
|
|
752
|
+
if (!page.hasOlder || oldest < sinceMs) return false;
|
|
753
|
+
if (!page.startCursor) return null;
|
|
754
|
+
cursor = page.startCursor;
|
|
755
|
+
}
|
|
756
|
+
return null;
|
|
757
|
+
}
|
|
758
|
+
/** The agent's provider transcript on disk holds `marker` (its last TAIL_BYTES). Never wakes the agent. Only a find counts. */
|
|
759
|
+
async function transcriptHas(home: string, agentId: string, marker: string): Promise<true | null> {
|
|
760
|
+
if (!marker) return null;
|
|
761
|
+
try {
|
|
762
|
+
const record = await agentRecord(home, agentId);
|
|
763
|
+
const file = record && await transcriptFile(record);
|
|
764
|
+
if (!file) return null;
|
|
765
|
+
const { tail } = await headAndTail(file);
|
|
766
|
+
const needle = JSON.stringify(marker).slice(1, -1);
|
|
767
|
+
return tail.some(line => line.includes(needle)) ? true : null;
|
|
768
|
+
} catch { return null; }
|
|
769
|
+
}
|