paseo-follow-up 2.4.0-beta.9 → 2.4.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.
Files changed (97) hide show
  1. package/CHANGELOG.md +159 -0
  2. package/OVERVIEW.md +1 -1
  3. package/README.md +81 -22
  4. package/client/agents.tsx +8 -26
  5. package/client/brief-since.tsx +4 -3
  6. package/client/compass-settings.tsx +156 -87
  7. package/client/display.tsx +2 -1
  8. package/client/header.tsx +2 -2
  9. package/client/home-chrome.tsx +24 -13
  10. package/client/home-data.ts +1 -1
  11. package/client/home-list.tsx +2 -1
  12. package/client/home-view.ts +7 -9
  13. package/client/home.tsx +9 -4
  14. package/client/job-rows.tsx +56 -7
  15. package/client/list-keys.ts +2 -1
  16. package/client/morning-brief-settings.tsx +11 -1
  17. package/client/new-entry.tsx +42 -2
  18. package/client/new-settings.tsx +29 -13
  19. package/client/new.tsx +89 -43
  20. package/client/onboarding.tsx +75 -29
  21. package/client/release-notes.tsx +11 -7
  22. package/client/reviewers.tsx +1 -1
  23. package/client/row-badges.tsx +37 -0
  24. package/client/search-focus.ts +85 -0
  25. package/client/search-key.ts +6 -12
  26. package/client/stacks.tsx +9 -2
  27. package/docs/screenshots/follow-up-slide-1-cover.png +0 -0
  28. package/docs/screenshots/follow-up-slide-2-decision.png +0 -0
  29. package/docs/screenshots/follow-up-slide-3-overseer.png +0 -0
  30. package/docs/screenshots/follow-up-slide-4-repairs.png +0 -0
  31. package/docs/screenshots/follow-up-slide-5-deploy.png +0 -0
  32. package/docs/screenshots/follow-up-slide-6-catch-up.png +0 -0
  33. package/index.client.tsx +12 -6
  34. package/index.server.ts +89 -25
  35. package/package.json +4 -3
  36. package/paseo-plugin.json +7 -9
  37. package/server/about.ts +4 -1
  38. package/server/agent-hook.mjs +12 -4
  39. package/server/agent-settings.ts +19 -3
  40. package/server/brief-sources.ts +4 -2
  41. package/server/compass.ts +310 -41
  42. package/server/daemon.ts +11 -3
  43. package/server/dispatch.ts +3 -2
  44. package/server/engine.ts +19 -6
  45. package/server/github-api.ts +17 -6
  46. package/server/github-setup.ts +126 -0
  47. package/server/github.ts +28 -0
  48. package/server/hook-source.ts +12 -4
  49. package/server/host-features.ts +21 -1
  50. package/server/linear-issues.ts +4 -3
  51. package/server/linear-queue.ts +3 -0
  52. package/server/mcp-source.ts +5 -3
  53. package/server/mcp.mjs +5 -3
  54. package/server/memory.ts +47 -19
  55. package/server/onboarding.ts +3 -2
  56. package/server/pr-actions.ts +12 -1
  57. package/server/pr-stats-sync.ts +4 -2
  58. package/server/pr-stats.ts +4 -0
  59. package/server/ranker.ts +4 -2
  60. package/server/reviewer-config.ts +3 -1
  61. package/server/session-mcp.ts +3 -2
  62. package/server/session-prompt.ts +34 -8
  63. package/server/wait-for-checks.ts +9 -0
  64. package/shared/agent-settings.ts +17 -9
  65. package/shared/attention.ts +4 -0
  66. package/shared/brief-sources.ts +23 -8
  67. package/shared/changelog.ts +32 -8
  68. package/shared/compass.ts +155 -25
  69. package/shared/contracts.ts +2 -2
  70. package/shared/dispatch.ts +61 -6
  71. package/shared/display.ts +4 -1
  72. package/shared/github-setup.ts +46 -0
  73. package/shared/job-rows.ts +40 -6
  74. package/shared/list-entries.ts +3 -2
  75. package/shared/model.ts +6 -0
  76. package/shared/new-name.ts +27 -0
  77. package/shared/new-view.ts +11 -8
  78. package/shared/onboarding.ts +77 -15
  79. package/shared/provider-support.ts +70 -0
  80. package/shared/recommend.ts +3 -2
  81. package/shared/row-badges.ts +24 -0
  82. package/shared/search-focus.ts +76 -0
  83. package/shared/search-key.ts +3 -2
  84. package/shared/settings-nav.ts +2 -1
  85. package/docs/screenshots/follow-up-home.png +0 -0
  86. package/docs/screenshots/follow-up-linked-items.png +0 -0
  87. package/docs/screenshots/follow-up-notes-home.png +0 -0
  88. package/docs/screenshots/follow-up-notes-panel.png +0 -0
  89. package/docs/screenshots/follow-up-panel.png +0 -0
  90. package/docs/screenshots/follow-up-phone.png +0 -0
  91. package/docs/screenshots/follow-up-pill.png +0 -0
  92. package/docs/screenshots/follow-up-pr-sheet.png +0 -0
  93. package/docs/screenshots/follow-up-questions.png +0 -0
  94. package/docs/screenshots/follow-up-send-to-paseo-dark.png +0 -0
  95. package/docs/screenshots/follow-up-send-to-paseo-light.png +0 -0
  96. package/docs/screenshots/follow-up-setup.png +0 -0
  97. package/docs/screenshots/follow-up-sidebar.png +0 -0
package/server/compass.ts CHANGED
@@ -1,16 +1,19 @@
1
1
  import { randomBytes } from "node:crypto";
2
- import { join } from "node:path";
2
+ import { readFile as fsReadFile, stat as fsStat } from "node:fs/promises";
3
+ import { basename, isAbsolute, join } from "node:path";
3
4
  import { JsonFileStore } from "./json-file-store";
4
5
  import { NoSourceError, type SourceDirectory } from "./source-tools";
5
6
  import type { AiJobs } from "./ai-jobs";
6
7
  import type { MorningBriefStore } from "./morning-brief";
7
8
  import { artifactLinks, parseChatRefs } from "../shared/morning-brief";
8
- import { isWorkday, zoned, type Clock } from "../shared/linear-queue";
9
+ import { isWorkday, priorityName, zoned, type Clock, type QueueIssue } from "../shared/linear-queue";
10
+ import { parseEvents, rangeArgs } from "../shared/brief-sources";
9
11
  import { compassSince, digestLines, suggestions, type CompassSince, type Suggestion } from "../shared/nobody";
10
12
  import {
11
13
  COMPASS, EXTRACT_SYSTEM, ROLE_INFO, applyCompassChange, batchItems, compassFileSchema, emptyCompassFile, extractPrompt, extractReplySchema, guardedProvider,
12
14
  HAND_LABEL, HAND_SOURCE, applyNoteAction, cadenceMs, noteLines, noteWho, tellText, type NoteAction,
13
15
  noteRole, parseConversation, placeKey, placeNote, presetsView, rankNotes, settleNotes, unguardedWhy, validateExtraction, whoFilter,
16
+ DOC_FILE, READER_MISSING, docBlocks, fileDocId, priorityStrength, ruleUntil, shortHash, syncRuleNotes, trackerRef, type Readers, type Role, type RuleItem,
14
17
  type CompassChange, type CompassFile, type CompassItem, type CompassNote, type CompassSettings, type CompassSource, type Place, type PlaceIndex, type RankCompassNote, type RefuseCode,
15
18
  } from "../shared/compass";
16
19
 
@@ -33,8 +36,12 @@ export type CompassDeps = {
33
36
  sweepAt: () => Promise<string>;
34
37
  /** Built once per read from state the worker holds: workspaces, issue keys → workspace, no reads of its own. */
35
38
  index: () => Promise<Omit<PlaceIndex, "glossary">>;
36
- /** The brief's Chat switch: which servers may be read (a chat source turned off isn't read). Throws when off. */
37
- allowed?: () => Promise<((server: string) => boolean) | undefined>;
39
+ /** The brief's switch for a recipe: which servers may be read (a source turned off isn't read). Throws when off. */
40
+ allowed?: (recipe: "chat" | "doc" | "calendar") => Promise<((server: string) => boolean) | undefined>;
41
+ /** The Linear queue's snapshot (the sweep's, no read of its own): a Linear tracker place reads its projects and milestones. */
42
+ queue?: () => Promise<QueueIssue[]>;
43
+ /** Follow-up's in-process GitHub reads (a GET as the repository owner's account): a GitHub tracker place's issues. */
44
+ github?: { rest(repo: string, path: string): Promise<unknown> };
38
45
  tight?: () => boolean;
39
46
  /**
40
47
  * Tell the agent (compass-reaches-an-agent-only-by-a-click): one queued message to the workspace's main agent
@@ -71,9 +78,44 @@ function readError(e: unknown): string {
71
78
  /** The cursor a page reply carries for the next page ("cursor: `…`", or JSON next_cursor). */
72
79
  const nextCursor = (reply: string) => /next_cursor"?\s*[:=]\s*"([^"]+)"/.exec(reply)?.[1] ?? /cursor[^`\n]{0,40}`([^`]{4,200})`/.exec(reply)?.[1] ?? null;
73
80
 
81
+ export type FindKind = "people" | "channels" | "docs" | "file" | "trackers" | "calendars";
82
+
83
+ /** A docs tool's text: the JSON reply's text field when it has one (markdown, text, content), else the reply itself. */
84
+ function docText(reply: string): string {
85
+ try {
86
+ const j = JSON.parse(reply) as Record<string, unknown>;
87
+ for (const k of ["markdown", "text", "content", "body", "plain_text"]) if (typeof j[k] === "string") return j[k] as string;
88
+ } catch { /* text form */ }
89
+ return reply;
90
+ }
91
+ /** A docs tool's search results: objects with an id and a title or name (a link when it has one). At most 10. */
92
+ function parseDocRefs(reply: string): { id: string; name: string; url: string | null }[] {
93
+ const out: { id: string; name: string; url: string | null }[] = []; const seen = new Set<string>();
94
+ const walk = (v: unknown, depth: number) => {
95
+ if (depth > 6 || out.length >= 10) return;
96
+ if (typeof v === "string" && /^\s*[[{]/.test(v)) { try { walk(JSON.parse(v), depth + 1); } catch { /* text */ } return; }
97
+ if (Array.isArray(v)) { for (const x of v) walk(x, depth + 1); return; }
98
+ if (!v || typeof v !== "object") return;
99
+ const o = v as Record<string, unknown>;
100
+ const id = typeof o.id === "string" ? o.id : null; const name = [o.title, o.name].find(x => typeof x === "string") as string | undefined;
101
+ if (id && name && !seen.has(id) && id.length <= 300) { seen.add(id); out.push({ id, name: name.slice(0, 100), url: typeof o.url === "string" && /^https:\/\//.test(o.url) ? o.url.slice(0, 500) : null }); }
102
+ for (const x of Object.values(o)) walk(x, depth + 1);
103
+ };
104
+ try { walk(JSON.parse(reply), 0); } catch { /* not JSON */ }
105
+ return out;
106
+ }
107
+ /** A local file's read error in one line, never its path. */
108
+ function fileError(e: unknown): string {
109
+ const code = (e as { code?: unknown })?.code;
110
+ if (code === "ENOENT") return "The file is gone. Pick it again in the source.";
111
+ if (code === "EACCES" || code === "EPERM") return "Follow-up isn't allowed to read the file.";
112
+ const m = (e as { message?: unknown })?.message;
113
+ return typeof m === "string" && !m.includes("/") ? m.slice(0, 200) : "The file can't be read.";
114
+ }
115
+
74
116
  export type CompassView = {
75
117
  settings: CompassSettings;
76
- readers: { conversation: boolean; history: boolean };
118
+ readers: Readers & { history: boolean };
77
119
  presets: ReturnType<typeof presetsView>;
78
120
  /** Null: Compass reads. Else the one line why it doesn't (the Summaries provider has no guard). */
79
121
  blocked: string | null;
@@ -96,18 +138,23 @@ export type CompassView = {
96
138
  */
97
139
  export class Compass {
98
140
  private reading: Promise<CompassFile["lastRead"]> | null = null;
141
+ private queued: Promise<CompassFile["lastRead"]> | null = null;
99
142
  constructor(private d: CompassDeps) {}
100
143
  private now() { return this.d.now?.() ?? Date.now(); }
101
144
  private newId(prefix: string) { return this.d.newId?.() ?? `${prefix}${randomBytes(5).toString("hex")}`; }
102
145
 
103
146
  async settings(): Promise<CompassSettings> { return (await this.d.settings.read()).compass; }
104
147
 
105
- /** Which readers a connected tool has, from what discovery last found (Settings answers at once; unknown counts as there). */
106
- async readers(fresh = false): Promise<{ conversation: boolean; history: boolean }> {
148
+ /**
149
+ * Which readers this host has, from what discovery last found (Settings answers at once; unknown counts as there): a
150
+ * chat tool, a docs tool (a local file always works), a tracker (the Linear queue's recipe, or GitHub), a calendar.
151
+ */
152
+ async readers(fresh = false): Promise<Readers & { history: boolean }> {
107
153
  const found = fresh ? await this.d.tools.discover().catch(() => null) : this.d.tools.cached();
108
- if (!found) return { conversation: true, history: true };
154
+ if (!found) return { conversation: true, history: true, doc: true, tracker: true, calendar: true };
109
155
  const chat = found.matched.filter(m => m.recipe === "chat");
110
- return { conversation: chat.some(m => m.roles.messages || m.roles.history), history: chat.some(m => m.roles.history) };
156
+ const has = (id: string) => found.matched.some(m => m.recipe === id);
157
+ return { conversation: chat.some(m => m.roles.messages || m.roles.history), history: chat.some(m => m.roles.history), doc: has("doc"), tracker: has("linear") || !!this.d.github, calendar: has("calendar") };
111
158
  }
112
159
 
113
160
  /** Null when Compass may read: the Summaries role runs on a provider Follow-up can guard (Claude, Codex). */
@@ -179,9 +226,15 @@ export class Compass {
179
226
  await this.read("day");
180
227
  }
181
228
 
182
- /** Read now (Settings' Read now, read_compass): every enabled source, or one. Joins a read already going. */
229
+ /**
230
+ * Read now (Settings' Read now, read_compass): every enabled source, or one. A scheduled read joins one already going;
231
+ * a read someone asked for (a new place, Read now) waits for it and runs after, once for every such ask meanwhile, so
232
+ * a source added during another's first read still gets its own.
233
+ */
183
234
  read(trigger: "morning" | "day" | "manual" | "agent" | "added", opts: { source?: string; plans?: boolean } = {}): Promise<CompassFile["lastRead"]> {
184
- return this.reading ??= this.readOnce(trigger, opts).finally(() => { this.reading = null; });
235
+ if (!this.reading) return this.reading = this.readOnce(trigger, opts).finally(() => { this.reading = null; });
236
+ if (trigger === "morning" || trigger === "day") return this.reading;
237
+ return this.queued ??= this.reading.catch(() => undefined).then(() => { this.queued = null; return this.read(trigger, opts.plans ? opts : {}); });
185
238
  }
186
239
  /** Read now, waiting at most `ms`; then `running` (read_compass). */
187
240
  async readWithin(trigger: "manual" | "agent", ms = COMPASS.waitMs): Promise<{ running: true } | { running: false; lastRead: CompassFile["lastRead"] }> {
@@ -208,7 +261,7 @@ export class Compass {
208
261
  let made = 0; const errors: string[] = [];
209
262
  for (const source of sources) {
210
263
  for (const place of source.places) {
211
- try { made += await this.readPlace(source, place, settings, index); }
264
+ try { made += await this.readPlace(source, place, settings, index, trigger); }
212
265
  catch (e) { errors.push(`${source.label}: ${readError(e)}`); }
213
266
  }
214
267
  }
@@ -216,23 +269,27 @@ export class Compass {
216
269
  return finish(!errors.length, made, errors[0] ?? null);
217
270
  }
218
271
 
219
- /** One place: read since its cursor, keep the source's words, extract, validate, place, settle. Returns notes made. */
220
- private async readPlace(source: CompassSource, place: Place, settings: CompassSettings, index: PlaceIndex): Promise<number> {
272
+ /** One place: read since its cursor, by its kind's reader, then extract (words) or apply rules (structured items). Returns notes made. */
273
+ private async readPlace(source: CompassSource, place: Place, settings: CompassSettings, index: PlaceIndex, trigger: string): Promise<number> {
221
274
  const key = placeKey(place);
222
275
  const now = this.now();
223
276
  const readAt = new Date(now).toISOString();
224
277
  const file = await this.d.store.read();
225
278
  const cursor = file.cursors[key];
226
- const since = cursor?.at ? Date.parse(cursor.at) : now - COMPASS.firstReadDays * 86_400_000;
227
279
  const setCursor = (patch: Partial<CompassFile["cursors"][string]> & { status: CompassFile["cursors"][string]["status"] }) =>
228
- this.d.store.mutate(f => { f.cursors[key] = { at: f.cursors[key]?.at ?? cursor?.at ?? null, readAt, error: null, ...patch }; });
229
- if (place.kind !== "conversation") { await setCursor({ status: "failed", error: "No reader for this kind of place in this release." }); return 0; }
230
-
280
+ this.d.store.mutate(f => { const was = f.cursors[key]; f.cursors[key] = { at: was?.at ?? cursor?.at ?? null, readAt, error: null, hash: was?.hash ?? null, seen: was?.seen ?? [], stat: was?.stat ?? null, ...patch }; });
281
+ if (place.kind === "tracker" || place.kind === "calendar") {
282
+ // Structured places become notes by rule, with no model: they use none of the day's extractions.
283
+ try { return place.kind === "tracker" ? await this.readTracker(source, place, settings, index, cursor, trigger, setCursor) : await this.readCalendar(source, place, index, setCursor); }
284
+ catch (e) { await setCursor({ status: "failed", error: e instanceof NoSourceError ? READER_MISSING[place.kind] : readError(e) }); throw e; }
285
+ }
231
286
  const clock = await this.d.clock();
232
287
  const today = zoned(now, clock.timeZone).day;
233
288
  const used = file.day?.date === today ? file.day.extractions : 0;
234
289
  if (used >= COMPASS.extractionsPerDay) { await setCursor({ status: "paused", error: `Paused until tomorrow: ${COMPASS.extractionsPerDay} reads today.` }); return 0; }
290
+ if (place.kind === "doc") return this.readDocPlace(source, place, settings, index, cursor, setCursor, { used, today, clock });
235
291
 
292
+ const since = cursor?.at ? Date.parse(cursor.at) : now - COMPASS.firstReadDays * 86_400_000;
236
293
  let read: { messages: ReturnType<typeof parseConversation>; slow: boolean; partial: boolean };
237
294
  try { read = await this.readConversation(place, since); }
238
295
  catch (e) {
@@ -240,9 +297,9 @@ export class Compass {
240
297
  await setCursor({ status: "failed", error: e instanceof NoSourceError ? "No connected chat tool can read this conversation." : readError(e) });
241
298
  throw e;
242
299
  }
243
- const self = await this.d.tools.selfId(await this.d.allowed?.()).catch(() => null);
300
+ const self = await this.d.tools.selfId(await this.d.allowed?.("chat")).catch(() => null);
244
301
  const whose = whoFilter(source.who, self);
245
- const items: CompassItem[] = [];
302
+ let items: CompassItem[] = [];
246
303
  let newest = since;
247
304
  // Oldest first, one item per message (a page overlap reads a message twice).
248
305
  const seen = new Set<string>();
@@ -255,6 +312,17 @@ export class Compass {
255
312
  const kind = whose(m.by);
256
313
  if (kind) items.push({ id: `m${items.length + 1}`, by: m.by, at: m.at, link: m.link, text: m.text, ...(kind === "context" ? { context: true } : {}) });
257
314
  }
315
+ // Everyone in a place (decision R1): one read takes its newest COMPASS.items messages, in one extraction; the older
316
+ // ones are skipped and the place says so. A busy channel never runs the day's extractions down.
317
+ let skipped = 0;
318
+ if (source.who.kind === "anyone") {
319
+ const words = items.filter(i => !i.context);
320
+ if (words.length > COMPASS.items) {
321
+ const from = words[words.length - COMPASS.items].at;
322
+ skipped = words.length - COMPASS.items;
323
+ items = items.filter(i => i.at >= from);
324
+ }
325
+ }
258
326
  // Plans come from Compass on arrival: the newest claude.ai artifact the source's people shared here.
259
327
  if (source.roles.includes("plan") && this.d.onPlan) {
260
328
  const posted = items.filter(i => !i.context).flatMap(i => artifactLinks(i.text).map(url => ({ url, at: i.at }))).sort((a, b) => b.at.localeCompare(a.at))[0];
@@ -262,26 +330,43 @@ export class Compass {
262
330
  if (posted) await this.d.onPlan({ url: posted.url, postedAt: posted.at, where, source: source.id }).catch(() => false);
263
331
  }
264
332
  const status = read.slow ? "slow-path" as const : "ok" as const;
265
- const partialNote = read.partial ? `More than ${COMPASS.pagesMax * COMPASS.pageSize} messages since the last read; the newest were read.` : null;
333
+ const note = read.partial ? `More than ${COMPASS.pagesMax * COMPASS.pageSize} messages since the last read; the newest were read.`
334
+ : skipped ? `A busy place: this read took its newest ${COMPASS.items} messages and skipped ${skipped} older.` : null;
266
335
  if (!items.some(i => !i.context)) {
267
- await setCursor({ status, at: new Date(newest).toISOString(), error: partialNote });
336
+ // Nothing new: a note the last read left (newest only, older skipped) stays until a read takes new words.
337
+ const kept = cursor && (cursor.status === "ok" || cursor.status === "slow-path") ? cursor.error : null;
338
+ await setCursor({ status, at: new Date(newest).toISOString(), error: note ?? kept });
268
339
  return 0;
269
340
  }
341
+ const r = await this.extract(source, key, items, settings, index, { used, today, clock, once: source.who.kind === "anyone" });
342
+ if (r.failed) { await setCursor({ status: "failed", at: r.cursorAt > since ? new Date(r.cursorAt).toISOString() : cursor?.at ?? null, error: r.failed }); return r.made; }
343
+ await setCursor({ status: r.all ? status : "paused", at: new Date(r.all ? newest : r.cursorAt).toISOString(), error: r.all ? note : `Paused until tomorrow: ${COMPASS.extractionsPerDay} reads today.` });
344
+ return r.made;
345
+ }
346
+
347
+ /**
348
+ * Items through the extraction job, a batch at a time (at most COMPASS.items and COMPASS.chars, oldest first), until
349
+ * they're done, the day's extractions run out, or `once`. Each batch's notes are validated, placed and settled.
350
+ */
351
+ private async extract(source: CompassSource, key: string, items: CompassItem[], settings: CompassSettings, index: PlaceIndex, o: { used: number; today: string; clock: Clock; once?: boolean }):
352
+ Promise<{ made: number; all: boolean; cursorAt: number; done: Set<string>; failed: string | null }> {
353
+ const now = this.now(); const readAt = new Date(now).toISOString();
270
354
  const role = await this.d.role();
271
- const open = file.notes.filter(n => n.state === "live" && n.source === source.id);
272
- let made = 0; let extractions = used; let rest = items; let cursorAt = since;
355
+ const open = (await this.d.store.read()).notes.filter(n => n.state === "live" && n.source === source.id);
356
+ let made = 0; let extractions = o.used; let rest = items; let cursorAt = 0;
357
+ const done = new Set<string>();
273
358
  const refused: RefuseCode[] = [];
274
359
  while (rest.some(i => !i.context)) {
275
360
  if (extractions >= COMPASS.extractionsPerDay) break;
276
361
  const { batch } = batchItems(rest);
277
362
  const r = await this.d.jobs.run({
278
363
  name: "compass-extract", outside: true, system: EXTRACT_SYSTEM, schema: extractReplySchema, provider: role.provider, model: role.model ?? undefined, thinking: role.thinking,
279
- prompt: extractPrompt({ source, global: settings.instructions, items: batch, open, now, clock }), maxPromptChars: 24_000, maxOutputChars: 8_000, timeoutMs: 90_000,
364
+ prompt: extractPrompt({ source, global: settings.instructions, items: batch, open, now, clock: o.clock }), maxPromptChars: 24_000, maxOutputChars: 8_000, timeoutMs: 90_000,
280
365
  });
281
366
  extractions++;
282
- await this.d.store.mutate(f => { f.day = { date: today, extractions }; });
283
- if (!r.ok) { await setCursor({ status: "failed", at: cursorAt ? new Date(cursorAt).toISOString() : null, error: `The model couldn't read it (${r.reason}).` }); return made; }
284
- const v = validateExtraction(r.value, { source, items: batch, open, glossary: settings.glossary, instructions: settings.instructions, clock, now, newId: () => this.newId("n-") });
367
+ await this.d.store.mutate(f => { f.day = { date: o.today, extractions }; });
368
+ if (!r.ok) return { made, all: false, cursorAt, done, failed: `The model couldn't read it (${r.reason}).` };
369
+ const v = validateExtraction(r.value, { source, items: batch, open, glossary: settings.glossary, instructions: settings.instructions, clock: o.clock, now, newId: () => this.newId("n-") });
285
370
  refused.push(...v.refused);
286
371
  const fresh = v.notes.map(n => { const note = { ...n, place: key }; return { ...note, match: placeNote(note, index) }; });
287
372
  made += fresh.length;
@@ -290,12 +375,149 @@ export class Compass {
290
375
  if (v.refused.length) f.refused = [...f.refused, ...v.refused.map(code => ({ at: readAt, code }))].slice(-50);
291
376
  });
292
377
  cursorAt = Math.max(cursorAt, ...batch.map(i => Date.parse(i.at)));
293
- const done = new Set(batch.map(i => i.id));
378
+ for (const i of batch) done.add(i.id);
294
379
  rest = rest.filter(i => !done.has(i.id));
380
+ if (o.once) { rest = []; break; }
295
381
  }
296
382
  if (refused.length) this.d.log?.(`[follow-up] compass: refused ${refused.length} note(s): ${[...new Set(refused)].join(", ")}`);
297
- const all = !rest.some(i => !i.context);
298
- await setCursor({ status: all ? status : "paused", at: new Date(all ? newest : cursorAt).toISOString(), error: all ? partialNote : `Paused until tomorrow: ${COMPASS.extractionsPerDay} reads today.` });
383
+ return { made, all: !rest.some(i => !i.context), cursorAt, done, failed: null };
384
+ }
385
+
386
+ /**
387
+ * A doc place: a page a docs tool serves (the doc recipe's read, by the tool's own id), or a Markdown or text file on
388
+ * this machine (decision R2: read in process only when its modified time or size moved; at most COMPASS.docBytes).
389
+ * An unchanged doc makes no model call; a changed one sends only its new or changed blocks. The path never reaches a
390
+ * log or an error.
391
+ */
392
+ private async readDocPlace(source: CompassSource, place: Extract<Place, { kind: "doc" }>, settings: CompassSettings, index: PlaceIndex, cursor: CompassFile["cursors"][string] | undefined,
393
+ setCursor: (patch: Partial<CompassFile["cursors"][string]> & { status: CompassFile["cursors"][string]["status"] }) => Promise<unknown>, o: { used: number; today: string; clock: Clock }): Promise<number> {
394
+ const now = this.now();
395
+ let text: string; let stat: string | null = null;
396
+ try {
397
+ if (place.path) {
398
+ const st = await fsStat(place.path);
399
+ if (!st.isFile()) throw new Error("The file isn't a regular file any more.");
400
+ stat = `${Math.round(st.mtimeMs)}:${st.size}`;
401
+ if (cursor?.stat === stat && cursor.hash && cursor.status !== "failed" && cursor.status !== "paused") { await setCursor({ status: "ok" }); return 0; }
402
+ if (st.size > COMPASS.docBytes) throw new Error(`The file is over ${COMPASS.docBytes / 1024} KB, so Compass doesn't read it.`);
403
+ text = await fsReadFile(place.path, "utf8");
404
+ } else {
405
+ const allowed = await this.d.allowed?.("doc");
406
+ text = docText(await this.d.tools.call("doc", "read", { id: place.id, page_id: place.id, pageId: place.id, document_id: place.id, documentId: place.id, doc_id: place.id, url: place.link ?? place.id }, { reason: "read the developer's Compass", timeoutMs: 30_000, allowed }));
407
+ }
408
+ } catch (e) {
409
+ const why = e instanceof NoSourceError ? READER_MISSING.doc : place.path ? fileError(e) : readError(e);
410
+ await setCursor({ status: "failed", error: why });
411
+ throw new Error(why);
412
+ }
413
+ text = text.slice(0, COMPASS.docBytes);
414
+ const hash = shortHash(text);
415
+ if (cursor?.hash === hash && cursor.status !== "paused") { await setCursor({ status: "ok", stat, at: cursor.at }); return 0; }
416
+ const blocks = docBlocks(text);
417
+ const seen = new Set(cursor?.seen ?? []);
418
+ const who = source.who;
419
+ const by = who.kind === "person" ? who.person : who.kind === "people" ? who.people[0] : who.kind === "me" ? { id: "developer", name: "You" } : { id: "doc", name: place.name };
420
+ const at = new Date(now).toISOString();
421
+ const fresh = blocks.filter(b => !seen.has(b.hash));
422
+ const items: CompassItem[] = fresh.map((b, i) => ({ id: `d${i + 1}`, by, at, link: place.link ?? null, text: b.text }));
423
+ if (source.roles.includes("plan") && this.d.onPlan) {
424
+ const posted = fresh.flatMap(b => artifactLinks(b.text))[0];
425
+ if (posted) await this.d.onPlan({ url: posted, postedAt: at, where: place.name, source: source.id }).catch(() => false);
426
+ }
427
+ // Blocks still in the doc stay remembered; ones gone from it are forgotten (the hashes are bounded).
428
+ const keep = (done: Set<string>) => blocks.map(b => b.hash).filter(h => seen.has(h) || done.has(h)).slice(-COMPASS.docBlocks);
429
+ if (!items.length) { await setCursor({ status: "ok", at, hash, stat, seen: keep(new Set()) }); return 0; }
430
+ const r = await this.extract(source, placeKey(place), items, settings, index, o);
431
+ const doneHashes = new Set(fresh.filter((_, i) => r.done.has(`d${i + 1}`)).map(b => b.hash));
432
+ if (r.failed) { await setCursor({ status: "failed", error: r.failed, seen: keep(doneHashes) }); return r.made; }
433
+ // Not every block was read (the day's cap): the hash stays unset, so the next read takes the rest.
434
+ await setCursor({ status: r.all ? "ok" : "paused", at, hash: r.all ? hash : null, stat: r.all ? stat : null, seen: keep(doneHashes), error: r.all ? null : `Paused until tomorrow: ${COMPASS.extractionsPerDay} reads today.` });
435
+ return r.made;
436
+ }
437
+
438
+ /**
439
+ * A tracker place, by rule: a Linear project or milestone from the queue's own snapshot (no read of its own), or a
440
+ * GitHub label or milestone through Follow-up's in-process GitHub reads (at most once per COMPASS.trackerEveryMs, or
441
+ * on Read now). Each open issue in scope is a note quoting its own fields; one that leaves the scope ends its note.
442
+ */
443
+ private async readTracker(source: CompassSource, place: Extract<Place, { kind: "tracker" }>, _settings: CompassSettings, index: PlaceIndex, cursor: CompassFile["cursors"][string] | undefined, trigger: string,
444
+ setCursor: (patch: Partial<CompassFile["cursors"][string]> & { status: CompassFile["cursors"][string]["status"] }) => Promise<unknown>): Promise<number> {
445
+ const ref = trackerRef(place.id);
446
+ if (!ref) throw new Error("This tracker place isn't one Compass reads. Pick it again.");
447
+ const now = this.now();
448
+ const role = noteRole(source.roles) ?? "priorities";
449
+ const plan = role === "plan";
450
+ let items: RuleItem[];
451
+ if (ref.tracker === "linear") {
452
+ if (!this.d.queue) throw new NoSourceError("linear", "list_issues");
453
+ const issues = (await this.d.queue()).filter(i => (ref.scope === "project" ? i.project : i.milestone)?.toLowerCase() === ref.value.toLowerCase());
454
+ items = issues.map(i => ({
455
+ ref: i.key, key: i.key, title: i.title, kind: "issue" as const, link: i.url, at: i.updatedAt ?? new Date(now).toISOString(),
456
+ quote: [`${i.key} ${i.title}`, i.due ? `due ${i.due.slice(0, 10)}` : null, priorityName(i.priority), i.state].filter(Boolean).join(" · "),
457
+ until: ruleUntil(i.due, now), strength: plan ? "low" as const : priorityStrength(i.priority) ?? "normal",
458
+ }));
459
+ } else {
460
+ if (!this.d.github) throw new NoSourceError("github" as never, "issues");
461
+ const fresh = cursor?.status === "ok" && now - Date.parse(cursor.readAt) < COMPASS.trackerEveryMs;
462
+ if (fresh && trigger !== "manual" && trigger !== "agent" && trigger !== "added") return 0;
463
+ const q = ref.scope === "label" ? `labels=${encodeURIComponent(ref.value)}` : `milestone=${ref.value}`;
464
+ const raw = await this.d.github.rest(ref.repo, `repos/${ref.repo}/issues?state=open&per_page=50&${q}`);
465
+ const list = (Array.isArray(raw) ? raw : []) as { number?: unknown; title?: unknown; html_url?: unknown; updated_at?: unknown; pull_request?: unknown; milestone?: { due_on?: unknown } | null }[];
466
+ items = list.filter(i => !i.pull_request && typeof i.number === "number" && typeof i.title === "string").map(i => {
467
+ const key = `${ref.repo}#${i.number}`;
468
+ const due = typeof i.milestone?.due_on === "string" ? i.milestone.due_on.slice(0, 10) : null;
469
+ return {
470
+ ref: key, key, title: i.title as string, kind: "issue" as const, link: typeof i.html_url === "string" ? i.html_url : null, at: typeof i.updated_at === "string" ? i.updated_at : new Date(now).toISOString(),
471
+ quote: [`${key} ${i.title}`, ref.scope === "label" ? `label ${ref.value}` : `milestone ${place.name}`, due ? `due ${due}` : null].filter(Boolean).join(" · "),
472
+ // A label the developer named as a source is the ask itself; a milestone is a plan of work.
473
+ until: ruleUntil(due, now), strength: plan ? "low" as const : ref.scope === "label" ? "high" as const : "normal" as const,
474
+ };
475
+ });
476
+ }
477
+ items.sort((a, b) => ({ high: 0, normal: 1, low: 2 })[a.strength] - ({ high: 0, normal: 1, low: 2 })[b.strength] || (a.until ?? "9999").localeCompare(b.until ?? "9999") || a.ref.localeCompare(b.ref, undefined, { numeric: true }));
478
+ return this.applyRules(source, placeKey(place), role, items, index, true, COMPASS.trackerNotes, setCursor);
479
+ }
480
+
481
+ /**
482
+ * A calendar place, by rule: the calendar recipe's events over the next COMPASS.calendarDays, re-read each read. An
483
+ * event lends its date to the work it matches (the glossary, then a title score); one that matches nothing isn't kept.
484
+ */
485
+ private async readCalendar(source: CompassSource, place: Extract<Place, { kind: "calendar" }>, index: PlaceIndex,
486
+ setCursor: (patch: Partial<CompassFile["cursors"][string]> & { status: CompassFile["cursors"][string]["status"] }) => Promise<unknown>): Promise<number> {
487
+ const now = this.now();
488
+ const clock = await this.d.clock();
489
+ const allowed = await this.d.allowed?.("calendar");
490
+ const tool = await this.d.tools.tool("calendar", "events", allowed);
491
+ if (!tool) throw new NoSourceError("calendar", "events");
492
+ const start = new Date(now).toISOString(); const end = new Date(now + COMPASS.calendarDays * 86_400_000).toISOString();
493
+ const args = { ...rangeArgs(await this.d.tools.props(tool), start, end, clock.timeZone), ...(place.id !== "primary" ? { calendarId: place.id, calendar_id: place.id } : {}) };
494
+ const events = parseEvents(await this.d.tools.call("calendar", "events", args, { reason: "read the developer's Compass", timeoutMs: 30_000, allowed }));
495
+ const filter = place.filter ?? "all";
496
+ const role = noteRole(source.roles) ?? "deadlines";
497
+ const items: RuleItem[] = events.flatMap(e => {
498
+ const t = e.start ? Date.parse(e.start) : NaN;
499
+ if (Number.isNaN(t) || t < now - 3_600_000) return [];
500
+ // Unknown guests count as guests: a reply that doesn't say never hides a meeting (unknown is not off).
501
+ if (filter === "with-guests" && e.guests === 0) return [];
502
+ const dayOf = zoned(t, clock.timeZone).day;
503
+ // A meeting that names an issue ("APP-142 review") goes to that issue, as a note's own key would.
504
+ const key = /(?:^|[^A-Za-z0-9-])([A-Z][A-Z0-9]{1,9}-\d{1,7})(?![A-Za-z0-9])/.exec(e.title)?.[1] ?? null;
505
+ return [{ ref: `${e.title}|${e.start}`, key, title: e.title, kind: "event" as const, link: e.url, at: new Date(now).toISOString(), quote: `${e.title} · ${e.start}`, until: dayOf, strength: "normal" as const }];
506
+ });
507
+ return this.applyRules(source, placeKey(place), role, items, index, false, COMPASS.calendarNotes, setCursor);
508
+ }
509
+
510
+ private async applyRules(source: CompassSource, key: string, role: Role, items: RuleItem[], index: PlaceIndex, keepUnplaced: boolean, cap: number,
511
+ setCursor: (patch: Partial<CompassFile["cursors"][string]> & { status: CompassFile["cursors"][string]["status"] }) => Promise<unknown>): Promise<number> {
512
+ const now = this.now();
513
+ let made = 0; let ended = 0;
514
+ await this.d.store.mutate(f => {
515
+ const r = syncRuleNotes(f.notes as CompassNote[], { source, place: key, role, items, now, index, newId: () => this.newId("n-"), keepUnplaced, cap });
516
+ made = r.made; ended = r.ended;
517
+ if (r.made || r.ended || r.notes.some((n, i) => n !== f.notes[i])) f.notes = r.notes;
518
+ });
519
+ await setCursor({ status: "ok", at: new Date(now).toISOString() });
520
+ if (ended) this.d.onChange?.();
299
521
  return made;
300
522
  }
301
523
 
@@ -305,7 +527,7 @@ export class Compass {
305
527
  * message search sorted by time, one day at a time (the slower path, said so on the place).
306
528
  */
307
529
  private async readConversation(place: Extract<Place, { kind: "conversation" }>, since: number): Promise<{ messages: ReturnType<typeof parseConversation>; slow: boolean; partial: boolean }> {
308
- const allowed = await this.d.allowed?.();
530
+ const allowed = await this.d.allowed?.("chat");
309
531
  const opts = { reason: "read the developer's Compass", timeoutMs: 30_000, allowed };
310
532
  const history = await this.d.tools.tool("chat", "history", allowed);
311
533
  const oldest = (since / 1000).toFixed(6);
@@ -333,17 +555,64 @@ export class Compass {
333
555
  }
334
556
 
335
557
  /**
336
- * compass_find: people and conversations from the chat tool's own search, the only way an agent learns a place id. A
337
- * person comes with their DM as a place (the conversation tools take a person's id for a DM).
558
+ * compass_find: the only way a place gets its id (compass-reads-only-what-was-named). People and channels from the
559
+ * chat tool's own search (a person comes with their DM); docs from the docs tool's search; a local file by its
560
+ * absolute path, checked first (Markdown or text, at most COMPASS.docBytes); tracker scopes from the Linear queue's
561
+ * snapshot (projects, milestones) or a GitHub repository's labels and milestones ("owner/repo", then words to
562
+ * narrow); calendars from the calendar tool.
338
563
  */
339
- async find(kind: "people" | "channels", query: string): Promise<{ results: { id: string; name: string; place: Place | null }[]; error: string | null }> {
340
- const allowed = await this.d.allowed?.().catch(() => undefined);
341
- const words = query.trim().split(/\s+/).filter(Boolean).slice(0, 4);
564
+ async find(kind: FindKind, query: string): Promise<{ results: { id: string; name: string; place: Place | null; detail?: string }[]; error: string | null }> {
565
+ const q = query.trim();
342
566
  try {
343
- const reply = await this.d.tools.call("chat", kind, { keywords: words, query: query.trim(), natural_language_query: "", limit: 10, response_format: "detailed", ...(kind === "channels" ? { channel_types: "public_channel,private_channel" } : {}) }, { reason: "set up the developer's Compass", timeoutMs: 20_000, allowed });
344
- const results = parseChatRefs(reply, kind).flatMap(r => r.id ? [{ id: r.id, name: r.name, place: { kind: "conversation" as const, sub: kind === "people" ? "dm" as const : "channel" as const, id: r.id, name: r.name } }] : []);
345
- return { results, error: null };
346
- } catch (e) { return { results: [], error: e instanceof NoSourceError ? "No chat search is connected." : readError(e) }; }
567
+ if (kind === "people" || kind === "channels") {
568
+ const allowed = await this.d.allowed?.("chat").catch(() => undefined);
569
+ const words = q.split(/\s+/).filter(Boolean).slice(0, 4);
570
+ const reply = await this.d.tools.call("chat", kind, { keywords: words, query: q, natural_language_query: "", limit: 10, response_format: "detailed", ...(kind === "channels" ? { channel_types: "public_channel,private_channel" } : {}) }, { reason: "set up the developer's Compass", timeoutMs: 20_000, allowed });
571
+ const results = parseChatRefs(reply, kind).flatMap(r => r.id ? [{ id: r.id, name: r.name, place: { kind: "conversation" as const, sub: kind === "people" ? "dm" as const : "channel" as const, id: r.id, name: r.name } }] : []);
572
+ return { results, error: null };
573
+ }
574
+ if (kind === "docs") {
575
+ const allowed = await this.d.allowed?.("doc").catch(() => undefined);
576
+ const reply = await this.d.tools.call("doc", "search", { query: q, q, limit: 10 }, { reason: "set up the developer's Compass", timeoutMs: 20_000, allowed });
577
+ return { results: parseDocRefs(reply).map(d => ({ id: d.id, name: d.name, place: { kind: "doc" as const, id: d.id, name: d.name, ...(d.url ? { link: d.url } : {}) } })), error: null };
578
+ }
579
+ if (kind === "file") {
580
+ if (!isAbsolute(q)) return { results: [], error: "Give the file's full path, like /home/user/notes/now.md." };
581
+ if (!DOC_FILE.test(q)) return { results: [], error: "Compass reads Markdown or text files (.md, .txt)." };
582
+ const st = await fsStat(q).catch(() => null);
583
+ if (!st?.isFile()) return { results: [], error: "There's no file there that Follow-up can read." };
584
+ if (st.size > COMPASS.docBytes) return { results: [], error: `That file is over ${COMPASS.docBytes / 1024} KB; Compass reads smaller ones.` };
585
+ const name = basename(q).slice(0, 100);
586
+ return { results: [{ id: fileDocId(q), name, place: { kind: "doc", id: fileDocId(q), name, path: q }, detail: "A file on this machine" }], error: null };
587
+ }
588
+ if (kind === "calendars") {
589
+ const tool = await this.d.tools.tool("calendar", "events", await this.d.allowed?.("calendar").catch(() => undefined));
590
+ if (!tool) return { results: [], error: READER_MISSING.calendar };
591
+ return { results: [{ id: "primary", name: "Your calendar", place: { kind: "calendar", id: "primary", name: "Your calendar", filter: "with-guests" }, detail: "Meetings with guests" }], error: null };
592
+ }
593
+ // Trackers: "owner/repo [words]" reads that repository's labels and milestones; anything else, the queue's projects and milestones.
594
+ const repo = /^([\w.-]+\/[\w.-]+)(?:\s+(.*))?$/.exec(q);
595
+ const want = (name: string) => !(repo ? repo[2] ?? "" : q).trim() || name.toLowerCase().includes((repo ? repo[2] ?? "" : q).trim().toLowerCase());
596
+ if (repo) {
597
+ if (!this.d.github) return { results: [], error: READER_MISSING.tracker };
598
+ const [labels, milestones] = await Promise.all([this.d.github.rest(repo[1], `repos/${repo[1]}/labels?per_page=100`), this.d.github.rest(repo[1], `repos/${repo[1]}/milestones?state=open&per_page=50`)]);
599
+ const out: { id: string; name: string; place: Place; detail: string }[] = [];
600
+ for (const l of (Array.isArray(labels) ? labels : []) as { name?: unknown }[]) if (typeof l.name === "string" && want(l.name)) out.push({ id: `github:${repo[1]}:label:${l.name}`, name: l.name, place: { kind: "tracker", scope: "label", id: `github:${repo[1]}:label:${l.name}`, name: l.name }, detail: `Label in ${repo[1]}` });
601
+ for (const m of (Array.isArray(milestones) ? milestones : []) as { number?: unknown; title?: unknown }[]) if (typeof m.number === "number" && typeof m.title === "string" && want(m.title)) out.push({ id: `github:${repo[1]}:milestone:${m.number}`, name: m.title, place: { kind: "tracker", scope: "milestone", id: `github:${repo[1]}:milestone:${m.number}`, name: m.title }, detail: `Milestone in ${repo[1]}` });
602
+ return { results: out.slice(0, 20), error: null };
603
+ }
604
+ if (!this.d.queue) return { results: [], error: "No Linear queue here. For GitHub, search \"owner/repo\"." };
605
+ const issues = await this.d.queue();
606
+ const seen = new Map<string, { scope: "project" | "milestone"; name: string; n: number }>();
607
+ for (const i of issues) for (const [scope, name] of [["project", i.project], ["milestone", i.milestone]] as const) {
608
+ if (!name || !want(name)) continue;
609
+ const k = `${scope}:${name}`; const was = seen.get(k);
610
+ seen.set(k, { scope, name, n: (was?.n ?? 0) + 1 });
611
+ }
612
+ return { results: [...seen.values()].sort((a, b) => b.n - a.n).slice(0, 20).map(x => ({ id: `linear:${x.scope}:${x.name}`, name: x.name, place: { kind: "tracker" as const, scope: x.scope, id: `linear:${x.scope}:${x.name}`, name: x.name }, detail: `Linear ${x.scope} · ${x.n} of your issues` })), error: null };
613
+ } catch (e) {
614
+ return { results: [], error: e instanceof NoSourceError ? (kind === "people" || kind === "channels" ? "No chat search is connected." : kind === "docs" ? READER_MISSING.doc : READER_MISSING.tracker) : readError(e) };
615
+ }
347
616
  }
348
617
 
349
618
  /**
package/server/daemon.ts CHANGED
@@ -299,6 +299,9 @@ async function readSince(client: Daemon, agentId: string, since: Cursor): Promis
299
299
 
300
300
  /** A Paseo project's GitHub repository (owner/name), from its remote key; null for local or non-GitHub projects. */
301
301
  export const projectRepo = (key: string) => /^remote:github\.com\/([\w.-]+\/[\w.-]+?)(?:\.git)?$/.exec(key)?.[1] ?? null;
302
+ /** The agent whose session is opening, from the session_open request: Paseo doesn't list it until its first session is open. */
303
+ export type OpeningAgent = { id: string; workspaceId: string; provider: string; cwd: string; title?: string | null; labels: Record<string, string> };
304
+ const openingAgent = (a: OpeningAgent): Agent => ({ id: a.id, workspaceId: a.workspaceId, provider: a.provider, cwd: a.cwd, title: a.title ?? null, labels: a.labels, status: "initializing", activeTurn: null, archivedAt: null, lastUserMessageAt: null, pendingPermissions: [] } as unknown as Agent);
302
305
  export class PaseoGateway implements Gateway {
303
306
  /** Each discovered workspace's project repository, for its PR workflow before it has PRs. */
304
307
  readonly workspaceRepos = new Map<string, string>();
@@ -310,6 +313,8 @@ export class PaseoGateway implements Gateway {
310
313
  turnTimeline: TurnTimeline | null = null;
311
314
  /** Whether the host advertises features.backgroundAgents (server/host-features.ts); false on Paseo 0.15. */
312
315
  backgroundAgents: () => Promise<boolean> = async () => false;
316
+ /** Whether the host draws plugin workspace-row badges (Paseo 0.17.1+, server/host-features.ts): no Done label there. */
317
+ rowBadges: () => Promise<boolean> = async () => false;
313
318
  /**
314
319
  * Linked items' passive ingress: references in the entries this poll read for loaded agents (shared/linked-extract.ts),
315
320
  * per workspace. Only entries past the cached cursor count, so a re-read overlap is never a second sighting.
@@ -339,7 +344,7 @@ export class PaseoGateway implements Gateway {
339
344
  * or, when there is none (the next turn already started, or no turn cursor yet), with its own read of that agent, so
340
345
  * nothing a nudge saw is left for the timer's tick to read later.
341
346
  */
342
- async discover(state: State, workspaceId?: string, scope?: { workspaces: ReadonlySet<string> }): Promise<DiscoveredWorkspace[]> {
347
+ async discover(state: State, workspaceId?: string, scope?: { workspaces: ReadonlySet<string> }, opening?: OpeningAgent): Promise<DiscoveredWorkspace[]> {
343
348
  await this.histories.load();
344
349
  const now = this.now();
345
350
  const windowMs = this.windowMs = activeWindowMs(state);
@@ -351,12 +356,15 @@ export class PaseoGateway implements Gateway {
351
356
  const listsIt = (r: DirectoryRows) => r.workspaces.some(w => w.id === workspaceId);
352
357
  const hasAgent = (r: DirectoryRows) => r.agents.some(({ agent }) => agent.workspaceId === workspaceId && !agent.archivedAt);
353
358
  if (workspaceId && !listsIt(rows)) rows = await this.directory.read({ fresh: true });
354
- if (workspaceId && listsIt(rows)) for (const wait of [0, ...TRACK_RETRY_MS]) {
359
+ // an-agent-s-first-session-gets-its-tools: at session open the opening agent counts itself. Paseo runs session_open
360
+ // before it lists the agent it is creating, so no re-listing could find it there; it only delays the agent's start.
361
+ if (workspaceId && listsIt(rows) && !opening) for (const wait of [0, ...TRACK_RETRY_MS]) {
355
362
  if (hasAgent(rows)) break;
356
363
  if (wait) await new Promise(resolve => setTimeout(resolve, wait));
357
364
  rows = await this.directory.read({ fresh: "agents", force: true });
358
365
  }
359
- const { agents, workspaces, projects } = rows;
366
+ const { workspaces, projects } = rows;
367
+ const agents = opening && !rows.agents.some(({ agent }) => agent.id === opening.id) ? [...rows.agents, { agent: openingAgent(opening) }] : rows.agents;
360
368
  if (this.unknownParentsFor !== rows) { this.unknownParents.clear(); this.unknownParentsFor = rows; }
361
369
  const parents = new Map<string, WorkspaceAgent | null>(agents.map(({ agent }) => [agent.id, agent]));
362
370
  const findParent = async (id: string) => {
@@ -16,6 +16,7 @@ import type { LinearIssue } from "../shared/linear-issues";
16
16
  import { holderOf } from "../shared/issue-workspace";
17
17
  export type { DispatchPlan, ExistingWorkspace, SourceRoute } from "../shared/dispatch";
18
18
  import type { LinearList } from "./linear-issues";
19
+ import { NEW_OF, NEW_WORK } from "../shared/new-name";
19
20
 
20
21
  /**
21
22
  * New's worker side (docs/dispatch.md): the dispatch store (`dispatch.json`), reading a source, the preview every
@@ -197,7 +198,7 @@ export class DispatchService {
197
198
  const action = input.actionId ? effectiveActions(file.actions).find(a => a.id === input.actionId) ?? null : offered[0] ?? null;
198
199
  if (input.actionId && !action) blockers.push(`No action "${input.actionId}". dispatch_actions lists them.`);
199
200
  else if (action && !action.appliesTo.includes(source.kind === "pr" ? "pr" : "issue")) blockers.push(`${action.name} isn't offered for a ${KIND_WORD[source.kind]}.`);
200
- else if (!action) blockers.push("No action is shown. Turn one on in Settings → New work.");
201
+ else if (!action) blockers.push(`No action is shown. Turn one on in Settings → ${NEW_WORK}.`);
201
202
  const existing = await this.d.existing(source).catch(() => null);
202
203
  const where = resolveWhere({ source, projects, picked: input.projectId ?? null, rules: file.rules, learned: await this.d.learned().catch(() => ({})), lastProjectId: file.lastProjectId, workspaceProjectId: existing?.projectId ?? null, noTeam: file.noTeam });
203
204
  if (!where.projectId) blockers.push(`${where.reason}${where.candidates.length ? ` Projects: ${where.candidates.slice(0, 8).map(c => `${c.name} (${c.id})`).join(", ")}.` : ""}`);
@@ -220,7 +221,7 @@ export class DispatchService {
220
221
  }, input.note) : "";
221
222
  const gate = await this.d.gate?.(actor, source.kind === "linear" ? source.key ?? null : null).catch(() => null);
222
223
  if (gate) blockers.push(gate);
223
- const agent: AgentChoice = action ? await this.d.agent(withAgent(action, input.agent)).catch(() => ({ label: "New's default agent", config: {} })) : { label: "", config: {} };
224
+ const agent: AgentChoice = action ? await this.d.agent(withAgent(action, input.agent)).catch(() => ({ label: `${NEW_OF} default agent`, config: {} })) : { label: "", config: {} };
224
225
  return {
225
226
  source, action: action ? { id: action.id, name: action.name } : null,
226
227
  actions: offered.map(a => ({ id: a.id, name: a.name, icon: a.icon, description: a.description })),