paseo-follow-up 2.2.0-beta.1 → 2.2.0-beta.3

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.
@@ -2,8 +2,8 @@ import { readFile } from "node:fs/promises";
2
2
  import { isAbsolute, join, relative, resolve } from "node:path";
3
3
  import { realpathSync } from "node:fs";
4
4
  import { tmpdir } from "node:os";
5
- import { MESSAGE_STUCK_MS, PASEO_UNREACHABLE, PROBE_MS, PROBE_SLOW_MS, PROBE_BACKOFF_AFTER_MS, envelopeText, AMBIGUOUS_MS, QUEUE_ATTEMPT_MS, QUEUE_CAP_MS, QUEUE_QUIET_MS, QUEUE_RECENT, neverLeftDelay, queueFileSchema, queueItemSchema, type QueueFile, type QueueItem, type QueueItemInput, type NewQueueItem, type QueueKind } from "../shared/queue";
6
- import { ConversationGone, DeliveryDeferred, realTimers, stableMessageId, withDeadline, type Timers } from "./delivery";
5
+ import { MESSAGE_STUCK_MS, PASEO_UNREACHABLE, PROBE_MS, PROBE_SLOW_MS, PROBE_BACKOFF_AFTER_MS, envelopeText, ambiguousDelay, GONE_REASON, QUEUE_ATTEMPT_MS, QUEUE_CAP_MS, QUEUE_QUIET_MS, QUEUE_RECENT, neverLeftDelay, queueFileSchema, queueItemSchema, type QueueFile, type QueueItem, type QueueItemInput, type NewQueueItem, type QueueKind } from "../shared/queue";
6
+ import { ConversationGone, DeliveryDeferred, idRefused, realTimers, stableMessageId, withDeadline, type Timers } from "./delivery";
7
7
  import { WriteBehind, type WriteHealth } from "./write-behind";
8
8
  import type { Workspace } from "../shared/model";
9
9
 
@@ -17,7 +17,8 @@ import type { Workspace } from "../shared/model";
17
17
  * forever, and at once on worker start and when the daemon connection comes back. It never ends in failed.
18
18
  * - A send that left unconfirmed (an error after the message went out, the attempt's deadline) is `uncertain`: before
19
19
  * any resend the agent's chat is read for the messageId (Courier.arrived). There: sent. Not there: resent. Unknown:
20
- * the next AMBIGUOUS_MS step, and failed only after the whole ladder. Paseo never refuses a resend by messageId (it
20
+ * the next AMBIGUOUS_MS step, its last step repeating until the chat can tell: never failed. Only a gone conversation
21
+ * (ConversationGone) ends failed, the one way out that isn't delivered or a next try. Paseo never refuses a resend by messageId (it
21
22
  * only skips the timeline row; the provider runs the prompt again), so a blind resend arrives twice.
22
23
  * - The recipient is resolved when the envelope goes out (Channel.resolve), never at enqueue: an answer whose asker was
23
24
  * archived reaches the workspace's agent, and a workspace no longer followed cancels it with a reason on the card.
@@ -49,6 +50,8 @@ export interface Courier {
49
50
  }
50
51
 
51
52
  export const QUEUE_FILE = "queue.json";
53
+ /** Why an uncertain item waits (Retrying's reason): the same words the card shows from the first unconfirmed send. */
54
+ export const UNKNOWN_REASON = "Paseo didn't confirm it";
52
55
 
53
56
  /**
54
57
  * FOLLOW_UP_QUEUE_TIME_SCALE shrinks the retry ladder, for harness runs only. It counts only when the data dir is under
@@ -99,13 +102,18 @@ export class MessageQueue {
99
102
 
100
103
  register(kind: QueueKind, channel: Channel): void { this.channels.set(kind, channel); }
101
104
 
102
- /** Reads queue.json. A send a reload interrupted is `uncertain`: its chat is read before anything is resent. */
105
+ /**
106
+ * Reads queue.json. A send a reload interrupted is `uncertain`: its chat is read before anything is resent. A Failed
107
+ * item whose target isn't gone (an older version gave up after the ladder of unknowns) goes back to checking, so no
108
+ * message stays stopped short across an upgrade (a-queued-message-never-stops-short).
109
+ */
103
110
  async load(): Promise<void> {
104
111
  let file: QueueFile = { version: 1, items: [], recent: [], migrations: [] };
105
112
  try { file = queueFileSchema.parse(JSON.parse(await readFile(join(this.directory, QUEUE_FILE), "utf8"))); }
106
113
  catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") console.warn(`[follow-up] queue.json unreadable, starting empty: ${error instanceof Error ? error.message : String(error)}`); }
107
114
  for (const item of file.items) {
108
115
  if (item.state === "sending") Object.assign(item, { state: "uncertain", reason: "Follow-up reloaded mid-send", nextAt: this.iso() });
116
+ else if (item.state === "failed" && !item.gone) Object.assign(item, item.envelope ? { state: "uncertain", reason: UNKNOWN_REASON, nextAt: this.iso() } : { state: "queued", reason: null, nextAt: this.iso() });
109
117
  this.items.set(item.id, item);
110
118
  }
111
119
  this.recent = file.recent; this.migrations = file.migrations; this.loaded = true;
@@ -265,9 +273,10 @@ export class MessageQueue {
265
273
  const arrived = await this.check(item, r.target);
266
274
  if (arrived.found) { await this.settle(item, "sent", null, arrived.found); return null; }
267
275
  if (arrived.unknown) {
276
+ // An unknown isn't a no: check again on the ladder, its last step for as long as the chat can't tell. Never
277
+ // failed here (a-queued-message-never-stops-short): only a gone target stops a message.
278
+ Object.assign(item, { reason: UNKNOWN_REASON, nextAt: this.iso(ambiguousDelay(item.unknowns) * this.scale) });
268
279
  item.unknowns++;
269
- if (item.unknowns >= AMBIGUOUS_MS.length) { item.state = "failed"; item.nextAt = null; item.reason = "Follow-up couldn't confirm the agent got it."; }
270
- else item.nextAt = this.iso(AMBIGUOUS_MS[item.unknowns] * this.scale);
271
280
  await this.project(item); this.save();
272
281
  return null;
273
282
  }
@@ -277,9 +286,13 @@ export class MessageQueue {
277
286
  private async check(item: QueueItem, target: Target): Promise<{ found: string | null; unknown: boolean }> {
278
287
  const env = item.envelope!;
279
288
  const marker = item.text.split("\n")[0]!.slice(0, 200);
289
+ // Every id it went out under: a resend under a fresh id (a refused one) mustn't hide that the first one landed.
290
+ const ids = [...new Set([...item.sentIds, env.messageId])];
291
+ // An earlier id went out before this envelope: read back to the item's start for it.
292
+ const since = ids.length > 1 ? item.createdAt : env.at;
280
293
  let unknown = false;
281
- for (const agentId of env.to ? [env.to] : target.recipients) {
282
- const seen = await this.courier.arrived(agentId, env.messageId, env.at, marker).catch(() => null);
294
+ for (const agentId of env.to ? [env.to] : target.recipients) for (const id of ids) {
295
+ const seen = await this.courier.arrived(agentId, id, since, marker).catch(() => null);
283
296
  if (seen === true) return { found: agentId, unknown: false };
284
297
  if (seen === null) unknown = true;
285
298
  }
@@ -291,9 +304,12 @@ export class MessageQueue {
291
304
  * the chat showed it missing is the same message again.
292
305
  */
293
306
  private async send(items: QueueItem[], target: Target): Promise<void> {
294
- const messageId = items.length === 1 ? items[0]!.messageId : stableMessageId(`envelope:${items.map(i => i.id).join("|")}`);
307
+ const base = items.length === 1 ? items[0]!.messageId : stableMessageId(`envelope:${items.map(i => i.id).join("|")}`);
308
+ // A messageId Paseo refused for good (a stuck receipt) is replaced by one derived from it, the same on every resend.
309
+ const generation = Math.max(...items.map(i => i.generation));
310
+ const messageId = generation ? stableMessageId(`${base}:${generation}`) : base;
295
311
  const at = this.iso();
296
- for (const item of items) Object.assign(item, { state: "sending", envelope: { messageId, to: null, at }, nextAt: null });
312
+ for (const item of items) Object.assign(item, { state: "sending", envelope: { messageId, to: null, at }, nextAt: null, sentIds: item.sentIds.includes(messageId) ? item.sentIds : [...item.sentIds, messageId].slice(-50) });
297
313
  await this.saveNow();
298
314
  for (const item of items) await this.project(item);
299
315
  if (this.stopped) return;
@@ -308,8 +324,14 @@ export class MessageQueue {
308
324
  if (this.stopped) return;
309
325
  for (const item of items) {
310
326
  if (error instanceof DeliveryDeferred) { item.envelope = null; await this.neverLeft(item, error.message); continue; }
311
- if (error instanceof ConversationGone) { Object.assign(item, { state: "failed", nextAt: null, gone: error.agentId, reason: "The agent's conversation is gone, so it can't take messages." }); await this.project(item); continue; }
312
- Object.assign(item, { state: "uncertain", reason: "Paseo didn't confirm it", nextAt: this.iso(AMBIGUOUS_MS[Math.min(item.unknowns, AMBIGUOUS_MS.length - 1)] * this.scale) });
327
+ if (error instanceof ConversationGone) { Object.assign(item, { state: "failed", nextAt: null, gone: error.agentId, reason: GONE_REASON }); await this.project(item); continue; }
328
+ // Each unconfirmed send climbs the same ladder as a check that can't tell, so an agent Paseo can't load yet
329
+ // (every send times out, every check says it isn't there) is tried at 15 s, 1 min, 5 min, then every 15 min,
330
+ // not every 15 s.
331
+ Object.assign(item, { state: "uncertain", reason: UNKNOWN_REASON, nextAt: this.iso(ambiguousDelay(item.unknowns) * this.scale) });
332
+ item.unknowns++;
333
+ // Paseo refused this id for good: the resend (only after the chat shows it missing) goes under a fresh one.
334
+ if (idRefused(error) && item.generation === generation) item.generation++;
313
335
  await this.project(item);
314
336
  }
315
337
  if (!(error instanceof DeliveryDeferred)) console.warn(`[follow-up] message to ${target.recipients.join(", ")} not confirmed: ${error instanceof Error ? error.message : String(error)}`);
@@ -160,6 +160,62 @@ const HEAD_BYTES = 256 * 1024;
160
160
  export type TranscriptItem = { type: "user_message" | "assistant_message" | "tool_call"; text?: string; name?: string; detail?: { output: string } };
161
161
 
162
162
  /** The first and last bytes of a file; lines cut at the edges are dropped. */
163
+ /**
164
+ * Whether a transcript's read part holds `marker` since `sinceMs`: true when a line has it; false only when the read
165
+ * part provably reaches back to `sinceMs` (the whole file was read, or its first dated line is no later) and no line has
166
+ * it; null otherwise. Lines are JSONL (Claude and Codex both date each line with `timestamp`).
167
+ */
168
+ export function markerSince(lines: readonly string[], whole: boolean, sinceMs: number, marker: string): boolean | null {
169
+ if (!marker) return null;
170
+ const needle = JSON.stringify(marker).slice(1, -1);
171
+ if (lines.some(line => line.includes(needle))) return true;
172
+ return whole || reachesBack(lines, sinceMs) ? false : null;
173
+ }
174
+ /** Whether the first dated line (`"timestamp"`) is no later than `sinceMs`: the lines cover everything since then. */
175
+ function reachesBack(lines: readonly string[], sinceMs: number): boolean {
176
+ for (const line of lines) {
177
+ const m = /"timestamp"\s*:\s*"([^"]+)"/.exec(line);
178
+ if (!m) continue;
179
+ const at = Date.parse(m[1]!);
180
+ if (Number.isFinite(at)) return at <= sinceMs;
181
+ }
182
+ return false;
183
+ }
184
+
185
+
186
+ /** How far back from its end a transcript is read for a send's marker, in chunks. Only an unconfirmed send reads it. */
187
+ export const MARKER_READ_MAX_BYTES = 32 * 1024 * 1024;
188
+ const MARKER_CHUNK_BYTES = 1024 * 1024;
189
+
190
+ /**
191
+ * Whether the transcript at `path` holds `marker` since `sinceMs`, read backwards from its end in 1 MB chunks until a
192
+ * chunk reaches back past `sinceMs`, the file's start, or MARKER_READ_MAX_BYTES: a busy agent writes megabytes between a
193
+ * send and its check, so a fixed tail can't say "not there". Each chunk is searched raw for the marker first; only the
194
+ * chunk's first dated line is parsed. Same answers as markerSince.
195
+ */
196
+ export async function markerInFile(path: string, sinceMs: number, marker: string, maxBytes = MARKER_READ_MAX_BYTES): Promise<boolean | null> {
197
+ if (!marker) return null;
198
+ const needle = Buffer.from(JSON.stringify(marker).slice(1, -1));
199
+ const handle = await open(path, "r");
200
+ try {
201
+ const size = (await handle.stat()).size;
202
+ let end = size; let carry = Buffer.alloc(0);
203
+ while (end > 0 && size - end < maxBytes) {
204
+ const start = Math.max(0, end - MARKER_CHUNK_BYTES);
205
+ const buf = Buffer.alloc(end - start);
206
+ const { bytesRead } = await handle.read(buf, 0, buf.length, start);
207
+ // The chunk plus the next one's head, so a marker cut at the edge is still found.
208
+ const joined = Buffer.concat([buf.subarray(0, bytesRead), carry.subarray(0, needle.length)]);
209
+ if (joined.includes(needle)) return true;
210
+ if (start === 0) return false;
211
+ const lines = buf.subarray(0, bytesRead).toString("utf8").split("\n"); lines.shift();
212
+ if (reachesBack(lines, sinceMs)) return false;
213
+ carry = buf.subarray(0, bytesRead); end = start;
214
+ }
215
+ return null;
216
+ } finally { await handle.close(); }
217
+ }
218
+
163
219
  export async function headAndTail(path: string): Promise<{ head: string[]; tail: string[] }> {
164
220
  const handle = await open(path, "r");
165
221
  try {
@@ -196,8 +196,9 @@ function computeNeedsYou(w: Workspace, now: number): NeedItem[] {
196
196
  const numbers = a.prs.map(key => `#${key.split("#")[1]}`).join(", ");
197
197
  items.push({ kind: "check", key: `check:${a.id}`, actionId: a.id, ...(a.prs.length === 1 ? linkFor(a.prs[0]) : {}), title: `Check the ${a.kind === "merge" ? "merge" : a.kind === "request_reviewers" ? "reviewer request" : "merge-when-ready change"} on ${numbers}`, detail: a.result });
198
198
  }
199
- // The queue's rare loud case (a-message-is-saved-before-sent-and-arrives-once): the chat couldn't confirm the answer
200
- // after the whole retry ladder, so it is the developer's to check and Retry. Everything else retries on its own.
199
+ // The queue's rare loud case (a-message-is-saved-before-sent-and-arrives-once): the agent's conversation is gone, so
200
+ // it is the developer's to check and Retry. Everything else, an unknown arrival included, retries on its own
201
+ // (a-queued-message-never-stops-short).
201
202
  for (const q of questions.filter(q => q.answer?.delivery.state === "failed"))
202
203
  items.push({ kind: "answer", key: `answer:${q.id}`, questionId: q.id, title: `Your ${q.id} answer: Failed`, detail: deliveryStatus({ state: "failed", reason: q.answer!.delivery.reason }).detail });
203
204
  // A message with no card of its own that didn't go out (a-message-is-saved-before-sent-and-arrives-once).
@@ -0,0 +1,312 @@
1
+ // Catch up: everything in Needs you, one card at a time (docs/design/catch-up.md).
2
+ // Pure: the deck's cards and their order come from Home's model, the inbox rows and the workspaces already on the
3
+ // client, so opening Catch up costs no read of its own. The session's order (skips, More context parking a
4
+ // workspace, its return) is a pure state machine here, so the client, the agent tool and the tests agree.
5
+ import { z } from "zod";
6
+ import type { HomeModel, Workstream } from "./home";
7
+ import type { InboxRow } from "./inbox";
8
+ import type { NeedItem } from "./attention";
9
+
10
+ export type CardKind = "permission" | "question" | "item" | "brief" | "finished";
11
+ /**
12
+ * One card: one thing to act on. A workspace with two questions and a merge is three cards, kept together so its
13
+ * context is read once. `key` is stable across refreshes, so the deck can tell a card that went away from a new one.
14
+ */
15
+ export type DeckCard = { key: string; kind: CardKind; s: Workstream; questionId?: string; item?: NeedItem };
16
+
17
+ type Source = {
18
+ model: Pick<HomeModel, "groups">;
19
+ rows: readonly Pick<InboxRow, "agentId" | "needs" | "brief">[];
20
+ /** The workspace's Needs-you items in block order (stopped questions first), from `needsYou`. */
21
+ items: (workspaceId: string) => readonly NeedItem[];
22
+ };
23
+
24
+ const BRIEF_CARD_KINDS = ["decision", "action", "review"];
25
+
26
+ /**
27
+ * The deck, in Home's Needs-you order: the order the developer already sees in the list (blocking asks first, then
28
+ * decisions, then finished turns; inside a tier the chosen sort, AI priority included). Inside a workstream: a pending
29
+ * permission, then each open question, then every other item, then the agent's own ask when nothing above speaks for it.
30
+ */
31
+ export function deckCards({ model, rows, items }: Source): DeckCard[] {
32
+ const needs = model.groups.find(g => g.id === "needs")?.items ?? [];
33
+ const out: DeckCard[] = [];
34
+ for (const s of needs) {
35
+ const row = s.agentId ? rows.find(r => r.agentId === s.agentId) ?? null : null;
36
+ const reasons = row?.needs?.reasons.map(r => r.reason) ?? [];
37
+ const before = out.length;
38
+ if (reasons.includes("permission")) out.push({ key: `${s.key}|permission`, kind: "permission", s });
39
+ const asks = s.workspaceId ? items(s.workspaceId) : [];
40
+ for (const item of asks) {
41
+ if (item.kind === "question") out.push({ key: `${s.key}|${item.questionId}`, kind: "question", s, questionId: item.questionId, item });
42
+ else out.push({ key: `${s.key}|${item.key}`, kind: "item", s, item });
43
+ }
44
+ const brief = row?.brief as { kind?: string; questionIds?: string[] } | null | undefined;
45
+ const pointsAtQuestion = !!brief?.questionIds?.length && out.slice(before).some(c => c.kind === "question");
46
+ if (brief && !pointsAtQuestion && BRIEF_CARD_KINDS.includes(brief.kind ?? "")) out.push({ key: `${s.key}|brief`, kind: "brief", s });
47
+ if (out.length === before) out.push({ key: `${s.key}|finished`, kind: "finished", s });
48
+ }
49
+ return out;
50
+ }
51
+
52
+ /** The workstream a card key belongs to (`agent:<id>` or `ws:<id>`): cards of one workstream move together. */
53
+ export const groupOf = (key: string) => key.slice(0, key.indexOf("|") < 0 ? key.length : key.indexOf("|"));
54
+
55
+ /** What happened to a card this session. `gone`: it left Needs you elsewhere (answered on another device, the agent moved on). */
56
+ export type Outcome = "done" | "skipped" | "later" | "gone";
57
+ export type SessionStats = { done: number; skipped: number; later: number; gone: number; waiting: number };
58
+
59
+ /**
60
+ * A Catch up session. `order` is every card key seen this session (done ones stay, so Back works); `pos` is the card
61
+ * on screen, `order.length` once nothing is left. `parked` maps a workstream waiting for More context to its request.
62
+ */
63
+ export type Session = { order: string[]; pos: number; outcomes: Record<string, Outcome>; parked: Record<string, string>; lapped?: boolean };
64
+
65
+ export const startSession = (cards: readonly Pick<DeckCard, "key">[]): Session => ({ order: cards.map(c => c.key), pos: 0, outcomes: {}, parked: {} });
66
+
67
+ /** Still to act on: not done, later or gone. Skipped cards stay open; they come round again after the rest. */
68
+ const open = (s: Session, key: string) => { const o = s.outcomes[key]; return !o || o === "skipped"; };
69
+ /** A card forward moves may land on: open, and not in a workstream waiting for context. */
70
+ const landable = (s: Session, key: string) => open(s, key) && !s.parked[groupOf(key)];
71
+
72
+ /**
73
+ * The next card after `from`: the next landable one in order, else the first skipped one from the start (one second
74
+ * pass, `lapped`), else `order.length` (finished). On the second pass a skip moves forward only, so skipping everything
75
+ * ends at the finished screen with "Catch up on N skipped" instead of going round for ever.
76
+ */
77
+ export function advance(s: Session, from: number): Pick<Session, "pos" | "lapped"> {
78
+ for (let i = from + 1; i < s.order.length; i++) if (landable(s, s.order[i]) && (s.lapped || s.outcomes[s.order[i]] !== "skipped")) return { pos: i, lapped: s.lapped };
79
+ if (!s.lapped) for (let i = 0; i < s.order.length; i++) if (i !== from && landable(s, s.order[i])) return { pos: i, lapped: true };
80
+ return { pos: s.order.length, lapped: s.lapped };
81
+ }
82
+ export const nextPos = (s: Session, from: number): number => advance(s, from).pos;
83
+
84
+ /** Back: the card before, whatever happened to it (done cards show what was sent; a parked one shows it is asking). */
85
+ export const prevPos = (s: Session): number => Math.max(0, Math.min(s.pos, s.order.length) - 1);
86
+
87
+ /** Records what happened to the card on screen and moves on. */
88
+ export function settle(s: Session, outcome: Outcome, key = s.order[s.pos]): Session {
89
+ if (key === undefined) return s;
90
+ const next = { ...s, outcomes: { ...s.outcomes, [key]: outcome } };
91
+ return s.order[s.pos] === key ? { ...next, ...advance(next, s.pos) } : next;
92
+ }
93
+
94
+ /**
95
+ * More context was asked about the card on screen: its workstream waits (every card of it, so its context is read
96
+ * once when it returns) and the deck moves on to the next workstream at once. Tom, 2026-11-17: "Getting more context
97
+ * may take a bit, so make it skip to the next workspace".
98
+ */
99
+ export function park(s: Session, requestId: string, key = s.order[s.pos]): Session {
100
+ if (key === undefined) return s;
101
+ const next = { ...s, parked: { ...s.parked, [groupOf(key)]: requestId } };
102
+ return s.order[s.pos] !== undefined && groupOf(s.order[s.pos]) === groupOf(key) ? { ...next, ...advance(next, s.pos) } : next;
103
+ }
104
+
105
+ /**
106
+ * The live deck changed: cards that left Needs you are `gone`, new ones join at the end (never jumping the queue under
107
+ * the developer's thumb), and a parked workstream whose request settled comes back as the very next card: its open
108
+ * cards move to right after the one on screen (or become the current one when the deck had finished). The card on
109
+ * screen never changes under the developer, except to `gone`.
110
+ */
111
+ export function sync(s: Session, live: readonly Pick<DeckCard, "key">[], settled: (requestId: string) => boolean): Session {
112
+ const liveKeys = new Set(live.map(c => c.key));
113
+ const known = new Set(s.order);
114
+ let order = [...s.order, ...live.map(c => c.key).filter(k => !known.has(k))];
115
+ const outcomes = { ...s.outcomes };
116
+ for (const k of order) if (!liveKeys.has(k) && open({ ...s, outcomes }, k)) outcomes[k] = "gone";
117
+ let pos = s.pos;
118
+ const parked = { ...s.parked };
119
+ for (const [group, requestId] of Object.entries(s.parked)) {
120
+ if (!settled(requestId)) continue;
121
+ delete parked[group];
122
+ const current = order[pos];
123
+ const back = order.filter(k => groupOf(k) === group && k !== current && open({ ...s, outcomes }, k));
124
+ if (!back.length) continue;
125
+ const rest = order.filter(k => !back.includes(k));
126
+ const at = current === undefined ? rest.length : rest.indexOf(current) + 1;
127
+ order = [...rest.slice(0, at), ...back, ...rest.slice(at)];
128
+ pos = current === undefined ? at : order.indexOf(current);
129
+ }
130
+ return { order, pos, outcomes, parked };
131
+ }
132
+
133
+ /** The progress line's numbers: the card on screen out of every card this session, and what is waiting for context. */
134
+ export function statsOf(s: Session): SessionStats {
135
+ const out: SessionStats = { done: 0, skipped: 0, later: 0, gone: 0, waiting: 0 };
136
+ for (const o of Object.values(s.outcomes)) out[o]++;
137
+ out.waiting = s.order.filter(k => s.parked[groupOf(k)] && open(s, k)).length;
138
+ return out;
139
+ }
140
+
141
+ /** The keys, one place, so the help line, the tooltips and the handler agree. Option letters pick; these never collide with A–H. */
142
+ /**
143
+ * Catch up's keys (desktop web): one list that the handler (`catchUpKey`), the S sheet and the hint line read, so
144
+ * they never disagree. `combos` spell each key the way Paseo's bundle does (PASEO_BOUND, shared/search-key.ts):
145
+ * tests/catch-up-keys.test.ts fails if one is a combo Paseo binds, Home's search key, or one of the search-from-
146
+ * anywhere presets. Paseo takes Shift+? (its shortcuts dialog) and Escape (interrupt agent) when focus is outside a
147
+ * field, which is exactly when these fire, so the sheet is S and leaving is X.
148
+ */
149
+ export type CatchUpAction = "pick" | "own" | "send" | "skip" | "back" | "more" | "chip" | "ask-overseer" | "ask-agent" | "note" | "later" | "chat" | "rail" | "rail-up" | "rail-down" | "keys" | "leave";
150
+ /** A key as this platform spells it: ⌘ on a Mac, Ctrl elsewhere (as the Send button's own hint reads). */
151
+ export const keyLabel = (key: string, mac: boolean) => mac ? key : key.replace("⌘", "Ctrl ");
152
+
153
+ export const CATCH_UP_KEYS: readonly { key: string; what: string; action: CatchUpAction; combos: readonly string[]; when?: "more" | "rail" }[] = [
154
+ { key: "A–H", what: "Pick an option", action: "pick", combos: ["A", "B", "C", "D", "E", "F", "G", "H"] },
155
+ { key: "W", what: "Write your own answer", action: "own", combos: ["W"] },
156
+ { key: "⌘↵", what: "Send", action: "send", combos: ["Cmd+Enter", "Ctrl+Enter"] },
157
+ { key: "J / →", what: "Skip", action: "skip", combos: ["J", "ArrowRight"] },
158
+ { key: "K / ←", what: "Back", action: "back", combos: ["K", "ArrowLeft"] },
159
+ { key: "M", what: "More context", action: "more", combos: ["M"] },
160
+ { key: "1–4", what: "Pick a More context ask", action: "chip", combos: ["Digit"], when: "more" },
161
+ { key: "⌘↵", what: "Ask the Overseer", action: "ask-overseer", combos: ["Cmd+Enter", "Ctrl+Enter"], when: "more" },
162
+ { key: "⌘⇧↵", what: "Ask the agent", action: "ask-agent", combos: ["Cmd+Shift+Enter", "Ctrl+Shift+Enter"], when: "more" },
163
+ { key: "N", what: "Add a note", action: "note", combos: ["N"] },
164
+ { key: "L", what: "Later", action: "later", combos: ["L"] },
165
+ { key: "O", what: "Open chat", action: "chat", combos: ["O"] },
166
+ { key: "R", what: "Go to the queue, and back", action: "rail", combos: ["R"] },
167
+ { key: "↑ / ↓", what: "Move in the queue (Enter opens)", action: "rail-up", combos: ["ArrowUp", "ArrowDown"], when: "rail" },
168
+ { key: "S", what: "Show the keys", action: "keys", combos: ["S"] },
169
+ { key: "X", what: "Leave Catch up", action: "leave", combos: ["X"] },
170
+ ];
171
+
172
+ export type KeyPress = { key: string; meta: boolean; ctrl: boolean; alt: boolean; shift: boolean; composing?: boolean; mac: boolean };
173
+ /**
174
+ * What a key press does in Catch up, or null to leave it alone (Paseo's, the field's, the browser's). Pure, so the
175
+ * map is tested without a DOM. `typing`: focus is in a text field, where only the More context box's ⌘↵ and ⌘⇧↵ act
176
+ * (a card field's ⌘↵ is its own SubmitScope's). `inRail`: focus is in the queue.
177
+ */
178
+ export function catchUpKey(e: KeyPress, at: { typing: boolean; inMore: boolean; moreOpen: boolean; inRail: boolean }): { action: CatchUpAction; arg?: string } | null {
179
+ if (e.composing || e.alt) return null;
180
+ const mod = e.mac ? e.meta : e.ctrl;
181
+ if (e.key === "Enter" && mod && (e.mac ? !e.ctrl : !e.meta)) {
182
+ if (e.shift) return at.moreOpen && (!at.typing || at.inMore) ? { action: "ask-agent" } : null;
183
+ if (at.moreOpen && (!at.typing || at.inMore)) return { action: "ask-overseer" };
184
+ return at.typing ? null : { action: "send" };
185
+ }
186
+ if (at.typing || e.meta || e.ctrl) return null;
187
+ if (at.inRail && (e.key === "ArrowUp" || e.key === "ArrowDown")) return { action: e.key === "ArrowUp" ? "rail-up" : "rail-down" };
188
+ if (e.key === "ArrowRight") return { action: "skip" };
189
+ if (e.key === "ArrowLeft") return { action: "back" };
190
+ if (at.moreOpen && /^[1-4]$/.test(e.key)) return { action: "chip", arg: e.key };
191
+ if (e.shift || e.key.length !== 1) return null;
192
+ const k = e.key.toLowerCase();
193
+ if (/^[a-h]$/.test(k)) return { action: "pick", arg: k.toUpperCase() };
194
+ const byLetter: Record<string, CatchUpAction> = { w: "own", j: "skip", k: "back", m: "more", n: "note", l: "later", o: "chat", r: "rail", s: "keys", x: "leave" };
195
+ return byLetter[k] ? { action: byLetter[k] } : null;
196
+ }
197
+
198
+ /**
199
+ * The mode's name in every place it shows, so renaming it is one edit. Tom picked Catch up (2026-11-17: "people know
200
+ * the name"); code identifiers say `catch-up` too. The Home button counts cards, not workspaces, and says so.
201
+ */
202
+ export const MODE = {
203
+ name: "Catch up",
204
+ button: (n: number) => `Catch up · ${n}`,
205
+ /** The button's accessible name and tooltip: the number is cards, which can differ from Needs you's workspaces. */
206
+ buttonLabel: (n: number) => `Catch up on ${n} ${n === 1 ? "thing" : "things"} that need you, one at a time`,
207
+ command: "Follow-up: Catch up on what needs you",
208
+ progress: (at: number, of: number) => `Catch up ${at} of ${of}`,
209
+ waiting: (n: number) => `${n} getting context`,
210
+ finished: "All caught up",
211
+ /** The end of a deck with cards still skipped or waiting: not caught up, so it does not say so. */
212
+ endOfDeck: "End of the deck",
213
+ empty: "Nothing needs you",
214
+ } as const;
215
+
216
+ // More context ------------------------------------------------------------------------------------------------------
217
+
218
+ /** Who answers: the Overseer from what it already knows (wakes no one), or the card's own agent (Tom asked, so it may wake). */
219
+ export const CONTEXT_TARGETS = ["overseer", "agent"] as const;
220
+ export type ContextTarget = typeof CONTEXT_TARGETS[number];
221
+ /** asking → answered (the reply came with context_reply), chat (the agent ended its turn without it: read its chat), failed. */
222
+ export const CONTEXT_STATES = ["asking", "answered", "chat", "failed"] as const;
223
+ export type ContextState = typeof CONTEXT_STATES[number];
224
+
225
+ /**
226
+ * The suggestions, first one first. Tom, 2026-11-17: "most of the time, the question is just not understood and needs
227
+ * a simple explaining and more context", so "I don't get it" leads.
228
+ */
229
+ export const CONTEXT_ASKS = [
230
+ { id: "explain", label: "I don't get it", text: "I don't get it. Explain this in plain words: what is being asked, why, and what each choice would mean. Add the context I need to decide." },
231
+ { id: "why", label: "Why does it matter?", text: "Why does this matter, and what happens if it waits?" },
232
+ { id: "tried", label: "What did it try?", text: "What has been tried so far, and what happened?" },
233
+ { id: "recommend", label: "What if I take the recommendation?", text: "What happens if I take the recommendation?" },
234
+ ] as const;
235
+
236
+ export const CONTEXT_ANSWER_MAX = 4000;
237
+ const iso = z.string().max(40);
238
+ export const contextRequestSchema = z.object({
239
+ id: z.string().min(1).max(80),
240
+ workspaceId: z.string().nullable(),
241
+ /** The card's agent (the one that asked); the request's own recipient is `askedOf`. */
242
+ agentId: z.string().nullable(),
243
+ cardKey: z.string().min(1).max(400),
244
+ /** One line naming what the card asks ("Q12: Which retry policy?"), for the prompt and the agent tool. */
245
+ card: z.string().max(300),
246
+ target: z.enum(CONTEXT_TARGETS),
247
+ /** The developer's words, or a suggestion's text. */
248
+ ask: z.string().min(1).max(2000),
249
+ /** The agent that should reply (the card's agent, or the Overseer once it is known). */
250
+ askedOf: z.string().nullable(),
251
+ state: z.enum(CONTEXT_STATES),
252
+ answer: z.string().max(CONTEXT_ANSWER_MAX).nullable(),
253
+ error: z.string().max(500).nullable(),
254
+ askedAt: iso,
255
+ settledAt: iso.nullable(),
256
+ /**
257
+ * When the ask actually reached `askedOf` (the queue sent it, or the Overseer took it). The first turn end after this
258
+ * without a context_reply settles it as `chat`, so a prompt steered into a running turn counts too. Absent in files
259
+ * from before it existed.
260
+ */
261
+ deliveredAt: iso.nullable().default(null),
262
+ /** Who asked: "developer" or "agent:<id>" (agent parity). */
263
+ by: z.string().max(120),
264
+ });
265
+ export type ContextRequest = z.infer<typeof contextRequestSchema>;
266
+ export const contextFileSchema = z.object({ requests: z.array(contextRequestSchema) });
267
+ export type ContextFile = z.infer<typeof contextFileSchema>;
268
+
269
+ /** Settled requests are kept this long (the card shows the answer when it returns), and at most this many. */
270
+ export const CONTEXT_KEEP_MS = 24 * 3_600_000;
271
+ export const CONTEXT_MAX = 50;
272
+ export const contextSettled = (r: Pick<ContextRequest, "state">) => r.state !== "asking";
273
+
274
+ /** The tool an asked agent replies with (native tools carry the follow_ prefix; the stdio bridge doesn't). */
275
+ const REPLY_TOOL = "context_reply";
276
+
277
+ /** The message the card's agent gets. It asks for an explanation, not action, and never counts as the developer's answer. */
278
+ export function agentContextPrompt(r: Pick<ContextRequest, "id" | "card" | "ask">): string {
279
+ return [
280
+ `The developer is catching up on what needs them and is looking at your ask: ${r.card}`,
281
+ `They want more context before they answer: "${r.ask}"`,
282
+ `Explain in plain words, short (under ${CONTEXT_ANSWER_MAX} characters), with what they need to decide. This isn't their answer: don't act on the ask yet, and keep it open.`,
283
+ `Reply with ${REPLY_TOOL} (follow_${REPLY_TOOL} as a native tool) and requestId "${r.id}" so the answer shows on their card, then end your turn.`,
284
+ ].join("\n");
285
+ }
286
+
287
+ /** The Overseer's version: it answers from what it can read without waking anyone, and doesn't forward the ask. */
288
+ export function overseerContextPrompt(r: Pick<ContextRequest, "id" | "card" | "ask">, workspace: string): string {
289
+ return [
290
+ `The developer is catching up on what needs them and is looking at a card from ${workspace}: ${r.card}`,
291
+ `They want more context before they answer: "${r.ask}"`,
292
+ `Answer from what you can read (workstreams, agent_digest) without waking agents and without forwarding this to the agent. Plain words, short (under ${CONTEXT_ANSWER_MAX} characters).`,
293
+ `Reply with ${REPLY_TOOL} and requestId "${r.id}" so the answer shows on their card.`,
294
+ ].join("\n");
295
+ }
296
+
297
+ /** A request older than CONTEXT_KEEP_MS goes, then the oldest past CONTEXT_MAX; an asking one is kept while it is young. */
298
+ export function pruneContext(requests: readonly ContextRequest[], now: number): ContextRequest[] {
299
+ const young = requests.filter(r => now - Date.parse(r.askedAt) < CONTEXT_KEEP_MS);
300
+ return young.slice(Math.max(0, young.length - CONTEXT_MAX));
301
+ }
302
+
303
+ /**
304
+ * A context answer as the card shows it: plain words. Agents often answer in Markdown, which the card would show as
305
+ * literal ** and # marks, so emphasis, heading and quote marks go; links and line breaks stay.
306
+ */
307
+ export function plainAnswer(text: string): string {
308
+ return text.replace(/\*\*(.+?)\*\*|__(.+?)__/g, (_m, a, b) => a ?? b).replace(/^\s{0,3}(#{1,6}|>)\s+/gm, "").trim();
309
+ }
310
+
311
+ /** The ask as the card's header quotes it: its first sentence ("I don't get it."), not the whole prompt. */
312
+ export const askHeadline = (ask: string): string => (ask.match(/^.+?[.?!](?=\s|$)/)?.[0] ?? ask).slice(0, 120);
package/shared/chat.ts CHANGED
@@ -155,7 +155,7 @@ export const TOOL_PRESENTATION: Record<string, "routine" | "moment"> = {
155
155
  follow_settings: "routine", set_follow_settings: "routine", project_settings: "routine", set_project_tracking: "routine", pr_workflow: "routine",
156
156
  set_pr_workflow: "routine", reviewer_settings: "routine", reviewer_suggestions: "routine", save_reviewers: "routine", set_agent_setting: "routine",
157
157
  set_wait_for_jobs: "routine", onboarding_status: "routine", onboarding_checks: "routine", set_onboarding: "routine", rank_status: "routine",
158
- rerank_priorities: "routine", overseer_status: "routine", overseer_start: "routine", overseer_restart: "routine", overseer_ask: "routine",
158
+ rerank_priorities: "routine", overseer_status: "routine", overseer_start: "routine", overseer_restart: "routine", overseer_ask: "routine", catch_up_deck: "routine", context_requests: "routine", ask_context: "routine", context_reply: "routine",
159
159
  inbox_brief: "routine", brief_action: "routine", queue_list: "routine", queue_action: "routine", inbox_act: "routine", answer_question: "routine", run_recovery: "routine",
160
160
  set_workspace_spec: "routine", link_item: "routine", unlink_item: "routine", link_items: "routine", set_linked_items: "routine", set_task_trigger: "routine", pr_controls: "routine", browser_status: "routine", trust_bypass_status: "routine",
161
161
  release_notes: "routine", updates_status: "routine", check_updates: "routine", set_updates: "routine", install_update: "routine", retry_move: "routine", report_issue: "routine", report_send: "routine", make_main_agent: "routine", wait_prepare_job: "routine", wait_for_job: "routine", wait_get_job: "routine",
@@ -9,6 +9,7 @@ import { aboutViewSchema } from "./about";
9
9
  import { LINKED_KINDS, linkedItemSchema } from "./linked";
10
10
  import { AGENT_ROLES, agentSettingsViewSchema, savedRoleSchema } from "./agent-settings";
11
11
  import { defineRpc, type PluginSubscriptionContract } from "@getpaseo/plugin";
12
+ import { CONTEXT_ANSWER_MAX, CONTEXT_TARGETS, contextRequestSchema } from "./catch-up";
12
13
  import { ONBOARDING_ACTIONS, ONBOARDING_STEPS, checksSchema, onboardingViewSchema } from "./onboarding";
13
14
  import { z } from "zod";
14
15
  import { inboxRowSchema } from "./inbox";
@@ -205,6 +206,18 @@ export const overseerStatusSchema = z.object({ enabled: z.boolean(), agentId: z.
205
206
  export const overseerStatusRpc = defineRpc({ name: "follow.overseer-status", input: z.object({}), output: overseerStatusSchema });
206
207
  export const overseerStartRpc = defineRpc({ name: "follow.overseer-start", input: z.object({}), output: overseerStatusSchema });
207
208
  export const overseerAskRpc = defineRpc({ name: "follow.overseer-ask", input: z.strictObject({ text: z.string().trim().min(1).max(2000) }), output: overseerStatusSchema });
209
+ // Catch up's More context (docs/needs-you.md#catch-up): ask the Overseer or the card's agent, list the asks, and the
210
+ // asked agent's reply. The ask answers once it is recorded; the send to the agent goes through the message queue.
211
+ export const contextAskRpc = defineRpc({ name: "follow.context-ask", input: z.strictObject({
212
+ workspaceId: z.string().min(1).max(200).nullable(), agentId: z.string().min(1).max(200).nullable(), cardKey: z.string().min(1).max(400),
213
+ card: z.string().trim().min(1).max(300), target: z.enum(CONTEXT_TARGETS), ask: z.string().trim().min(1).max(2000) }),
214
+ output: z.object({ request: contextRequestSchema, fresh: z.boolean() }) });
215
+ export const contextListRpc = defineRpc({ name: "follow.context-list", input: z.strictObject({ workspaceId: z.string().max(200).optional() }), output: z.object({ requests: z.array(contextRequestSchema) }) });
216
+ /** Catch up's deck as the developer's Home would deal it (agent parity: an agent sees what the developer goes through). */
217
+ export const catchUpDeckRpc = defineRpc({ name: "follow.catch-up-deck", input: z.strictObject({}), output: z.object({
218
+ cards: z.array(z.object({ key: z.string(), kind: z.string(), workspaceId: z.string().nullable(), agentId: z.string().nullable(), title: z.string(), line: z.string(),
219
+ questionId: z.string().nullable(), item: z.string().nullable(), context: contextRequestSchema.pick({ id: true, state: true, target: true }).nullable() })) }) });
220
+ export const contextReplyRpc = defineRpc({ name: "follow.context-reply", input: z.strictObject({ agentId: z.string().min(1).max(200), requestId: z.string().min(1).max(80), text: z.string().trim().min(1).max(CONTEXT_ANSWER_MAX) }), output: z.object({ ok: z.boolean() }) });
208
221
  export const rankStatusSchema = z.object({ enabled: z.boolean(), running: z.boolean(), lastRunAt: z.string().nullable(), healthLine: z.string(), error: z.string().nullable(), costUsd: z.number().nullable(), notStarted: z.number().int(),
209
222
  last: z.object({ ok: z.boolean(), skipped: z.string().nullable(), top: z.string().nullable(), provider: z.string().nullable(), inputTokens: z.number().nullable(), outputTokens: z.number().nullable() }).nullable() });
210
223
  export const rankStatusRpc = defineRpc({ name: "follow.rank-status", input: z.object({}), output: rankStatusSchema });
@@ -296,6 +309,8 @@ export const homeFeed = subscription("follow.home-feed", z.object({}), z.object(
296
309
  usage: usageSchema.nullable(),
297
310
  /** False when Smart Session's data directory can't be watched: the client reads usage once a minute instead. */
298
311
  usageLive: z.boolean(),
312
+ /** Catch up's More context asks (pushed when one is asked or answered); absent from an older worker. */
313
+ context: z.array(contextRequestSchema).optional(),
299
314
  }));
300
315
  export const displayFeed = subscription("follow.display-feed", z.object({}), z.object({ status: z.string(), revision: z.string().optional(), values: z.unknown().optional() }));
301
316
  export const FEEDS = [workspacesFeed, inboxFeed, homeFeed, displayFeed] as const;
package/shared/display.ts CHANGED
@@ -7,6 +7,10 @@ import { SEARCH_SHORTCUTS } from "./search-key";
7
7
  export const HOME_DETAIL_DEFAULT = 0.42;
8
8
  export const HOME_DETAIL_MIN = 0.2;
9
9
  export const HOME_DETAIL_MAX = 0.8;
10
+ /** Catch up's queue rail on desktop (side-panes-are-resizable): its share of the width. */
11
+ export const CATCH_UP_RAIL_DEFAULT = 0.28;
12
+ export const CATCH_UP_RAIL_MIN = 0.16;
13
+ export const CATCH_UP_RAIL_MAX = 0.5;
10
14
 
11
15
  export const displayPreferences = defineSettings({
12
16
  id: "display",
@@ -36,6 +40,9 @@ export const displayPreferences = defineSettings({
36
40
  // 2.1: the share of Home's width the right pane (the brief or the selected item) takes, set by dragging the divider
37
41
  // (client/split.tsx). A fraction, so it carries across window sizes; absent means HOME_DETAIL_DEFAULT.
38
42
  home_detail_fraction: z.number().min(HOME_DETAIL_MIN).max(HOME_DETAIL_MAX).optional(),
43
+ // 2.2: the share of Catch up's width its queue rail takes on desktop (client/catch-up.tsx, client/split.tsx).
44
+ // Absent means CATCH_UP_RAIL_DEFAULT.
45
+ catch_up_rail_fraction: z.number().min(CATCH_UP_RAIL_MIN).max(CATCH_UP_RAIL_MAX).optional(),
39
46
  // 2.1: the key that opens Home with the cursor in its search from anywhere in Paseo (shared/search-key.ts).
40
47
  // Absent means DEFAULT_SEARCH_SHORTCUT (⌘/ or Ctrl+/); "none" turns it off.
41
48
  search_shortcut: z.enum(SEARCH_SHORTCUTS).optional() }),
@@ -152,7 +152,7 @@ export type AnswerDraft = {
152
152
  /** Remove note is on offer: the field is a note the developer opened. */
153
153
  canRemoveNote: boolean;
154
154
  };
155
- export function answerDraft(q: { id: string; options: readonly unknown[] }, s: { choice: string | null; words: string; noteOpen: boolean }): AnswerDraft {
155
+ export function answerDraft(q: { id: string; options: readonly { letter?: string; label?: string }[] }, s: { choice: string | null; words: string; noteOpen: boolean }): AnswerDraft {
156
156
  const words = s.words.trim();
157
157
  if (!q.options.length) return { field: "answer", own: false, answer: words || null, placeholder: "Your answer", heading: null, label: `Your answer to ${q.id}`, hint: null, canAddNote: false, canRemoveNote: false };
158
158
  const own = isOther(s.choice) || (!s.choice && !!words);
@@ -160,9 +160,14 @@ export function answerDraft(q: { id: string; options: readonly unknown[] }, s: {
160
160
  // A lettered pick: the field is a note, shown once asked for (or once it holds words, e.g. Something else's words
161
161
  // kept when the developer picks a letter after all, so they read as the note they now are).
162
162
  const field = s.choice && (s.noteOpen || !!words) ? "note" as const : null;
163
- return { field, own, answer: s.choice, note: field && words ? words : undefined, placeholder: "Add a note for the agent (optional)", heading: s.choice ? `Note, sent with ${s.choice}` : null,
163
+ return { field, own, answer: s.choice, note: field && words ? words : undefined, placeholder: "Add a note for the agent (optional)", heading: s.choice ? noteHeading(q, s.choice) : null,
164
164
  label: `Note for the agent, sent with ${s.choice} on ${q.id}, optional`, hint: s.choice ? null : PICK_HINT, canAddNote: !!s.choice && !field, canRemoveNote: field === "note" };
165
165
  }
166
+ /** "Note, sent with A · The English text": the option by name too, since it may have scrolled out of view. */
167
+ function noteHeading(q: { options: readonly { letter?: string; label?: string }[] }, choice: string): string {
168
+ const label = q.options.find(o => o.letter === choice)?.label?.replace(/\s+/g, " ").trim();
169
+ return `Note, sent with ${choice}${label ? ` · ${label.length > 48 ? `${label.slice(0, 47)}…` : label}` : ""}`;
170
+ }
166
171
  const quoted = (words: string | undefined | null) => `"${(words ?? "").trim()}"`;
167
172
 
168
173
  /**