@phren/cli 0.3.67 → 0.3.69

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 (83) hide show
  1. package/dist/bridge/agent-hook-callback.js +11 -2
  2. package/dist/bridge/agent-hooks.d.ts +11 -1
  3. package/dist/bridge/agent-hooks.js +259 -40
  4. package/dist/bridge/changes.d.ts +2 -2
  5. package/dist/bridge/changes.js +11 -9
  6. package/dist/bridge/checkpoints.d.ts +24 -0
  7. package/dist/bridge/checkpoints.js +423 -0
  8. package/dist/bridge/claude-input-state.d.ts +14 -0
  9. package/dist/bridge/claude-input-state.js +58 -0
  10. package/dist/bridge/claude-queue.js +5 -2
  11. package/dist/bridge/claude-suggestion.d.ts +3 -0
  12. package/dist/bridge/claude-suggestion.js +10 -0
  13. package/dist/bridge/codex-threads.d.ts +7 -1
  14. package/dist/bridge/codex-threads.js +185 -56
  15. package/dist/bridge/conversation-search.d.ts +20 -0
  16. package/dist/bridge/conversation-search.js +928 -0
  17. package/dist/bridge/git-watch.d.ts +46 -0
  18. package/dist/bridge/git-watch.js +351 -0
  19. package/dist/bridge/git-worktree-remove.d.ts +44 -0
  20. package/dist/bridge/git-worktree-remove.js +140 -0
  21. package/dist/bridge/git-worktrees.d.ts +14 -0
  22. package/dist/bridge/git-worktrees.js +7 -3
  23. package/dist/bridge/git-write-policy.js +1 -1
  24. package/dist/bridge/gitboy-webhooks.d.ts +3 -1
  25. package/dist/bridge/gitboy-webhooks.js +26 -2
  26. package/dist/bridge/herdr.d.ts +6 -1
  27. package/dist/bridge/herdr.js +56 -10
  28. package/dist/bridge/hook-fast.js +13 -1
  29. package/dist/bridge/input-classification.d.ts +33 -0
  30. package/dist/bridge/input-classification.js +84 -0
  31. package/dist/bridge/pane-status.d.ts +3 -3
  32. package/dist/bridge/pane-status.js +16 -8
  33. package/dist/bridge/prompt-deliveries.d.ts +30 -4
  34. package/dist/bridge/prompt-deliveries.js +365 -13
  35. package/dist/bridge/prompt-identity.d.ts +8 -0
  36. package/dist/bridge/prompt-identity.js +15 -0
  37. package/dist/bridge/request-origin.js +2 -1
  38. package/dist/bridge/schedule-events.d.ts +17 -0
  39. package/dist/bridge/schedule-events.js +53 -0
  40. package/dist/bridge/schedule-format.d.ts +22 -2
  41. package/dist/bridge/schedule-format.js +40 -5
  42. package/dist/bridge/schedule-update.js +2 -1
  43. package/dist/bridge/schedule-watch.js +15 -5
  44. package/dist/bridge/schedules.d.ts +9 -0
  45. package/dist/bridge/schedules.js +120 -7
  46. package/dist/bridge/server-pane-routes.d.ts +7 -8
  47. package/dist/bridge/server-pane-routes.js +186 -82
  48. package/dist/bridge/server-routes.d.ts +26 -2
  49. package/dist/bridge/server-routes.js +180 -56
  50. package/dist/bridge/server-stream.js +66 -15
  51. package/dist/bridge/server.js +25 -7
  52. package/dist/bridge/session-activity.d.ts +49 -4
  53. package/dist/bridge/session-activity.js +47 -0
  54. package/dist/bridge/session-evidence.d.ts +18 -0
  55. package/dist/bridge/session-evidence.js +72 -0
  56. package/dist/bridge/session-seen.d.ts +23 -0
  57. package/dist/bridge/session-seen.js +69 -0
  58. package/dist/bridge/tab-activity.d.ts +26 -1
  59. package/dist/bridge/tab-activity.js +64 -9
  60. package/dist/bridge/terminal-resolve.d.ts +20 -0
  61. package/dist/bridge/terminal-resolve.js +145 -0
  62. package/dist/bridge/terminal-tmux.d.ts +8 -3
  63. package/dist/bridge/terminal-tmux.js +59 -7
  64. package/dist/bridge/transcript-claude.d.ts +12 -2
  65. package/dist/bridge/transcript-claude.js +91 -13
  66. package/dist/bridge/transcript-index.d.ts +4 -2
  67. package/dist/bridge/transcript-index.js +6 -5
  68. package/dist/bridge/transcript-preview.d.ts +16 -1
  69. package/dist/bridge/transcript-preview.js +171 -27
  70. package/dist/bridge/transcripts.d.ts +41 -1
  71. package/dist/bridge/transcripts.js +181 -23
  72. package/dist/bridge/turn-queue-pane.d.ts +6 -0
  73. package/dist/bridge/turn-queue-pane.js +30 -0
  74. package/dist/bridge/turn-queue.d.ts +86 -0
  75. package/dist/bridge/turn-queue.js +280 -0
  76. package/dist/bridge/turn-records.d.ts +18 -0
  77. package/dist/bridge/turn-records.js +77 -5
  78. package/dist/bridge-hook.mjs +7074 -3173
  79. package/dist/cli/config-shared.js +2 -1
  80. package/dist/cli/schedules.js +6 -1
  81. package/dist/content/secrets.js +1 -1
  82. package/dist/modules/registry.js +12 -11
  83. package/package.json +1 -1
@@ -11,6 +11,8 @@ import { isLocalComputer } from "./dispatch-hosts.js";
11
11
  import { hookPeers, peerRequest } from "./peers.js";
12
12
  import { handOff } from "./hand-off.js";
13
13
  import { sessionStalls } from "./stalls.js";
14
+ import { TurnQueue } from "./turn-queue.js";
15
+ import { turnQueuePaneReader } from "./turn-queue-pane.js";
14
16
  import { HandOffQueue } from "./hand-off-queue.js";
15
17
  import { paneRouteOnce, promptGuards } from "./server-pane-routes.js";
16
18
  import { FanoutMessages } from "./fanout-messages.js";
@@ -53,9 +55,10 @@ import { ALERT_CHECK_MS, HealthAlerts } from "./machine-health-alerts.js";
53
55
  import { createScheduleLauncher, Scheduler, scheduleRunsFile } from "./schedules.js";
54
56
  import { dailyCanaryDue, runCanary } from "./canary.js";
55
57
  import { defaultPhrenPath } from "../shared.js";
56
- import { capabilitiesForModules, createRouteHandler, requireRoute, selectedServer, workspacesReader } from "./server-routes.js";
58
+ import { capabilitiesForModules, createRouteHandler, effectiveStatusRows, requireRoute, selectedServer, workspacesReader } from "./server-routes.js";
57
59
  import { typedMuxRequest } from "./mux-wire.js";
58
60
  import { overviewStream } from "./server-overview.js";
61
+ import { GitWatch } from "./git-watch.js";
59
62
  import { transcriptStreams } from "./server-stream.js";
60
63
  import { launchSession } from "./server-launch.js";
61
64
  import { copyClaudeConversation, SessionMover, transcriptTail } from "./session-move.js";
@@ -149,6 +152,14 @@ export async function serve(version, options = {}) {
149
152
  const permissionModeSwitcher = new PermissionModeSwitcher(agentHooks);
150
153
  const sideQuestions = new SideQuestions();
151
154
  const sendPrompt = async (target, text, deliveryId, typing) => await paneRouteOnce({ agentHooks, modelSwitcher, settingsSwitcher, permissionModeSwitcher, codexQuestions, sideQuestions }, new URL("http://phren.local/v1/prompt"), { target, text, deliveryId, hookQueued: true }, {}, typing);
155
+ const turnQueue = new TurnQueue(path.join(root, "turn-queue.json"), {
156
+ current: turnQueuePaneReader(agentHooks),
157
+ holding: (target, exceptId) => agentHooks.deliveries.holding(target, exceptId),
158
+ send: sendPrompt,
159
+ delivery: (target, id) => agentHooks.deliveries.status(id, target),
160
+ });
161
+ // Never send while the Stop callback is held: the harness must first resume.
162
+ agentHooks.onTurnStopped = () => { setImmediate(() => { void turnQueue.tick().catch(() => { }); }); };
152
163
  const handOffs = dispatches ? new HandOffQueue({
153
164
  forward: (target, text, deliveryId) => succession?.forward(target, text, deliveryId) ?? Promise.resolve(undefined),
154
165
  validate: target => validateTarget(target, false, true),
@@ -257,7 +268,7 @@ export async function serve(version, options = {}) {
257
268
  await unlink(socketPath());
258
269
  }
259
270
  const storePulls = new StorePulls(scheduleStore);
260
- const gitboyWebhooks = new GitboyWebhooks(root, storeId => storePulls.request(storeId));
271
+ const gitboyWebhooks = new GitboyWebhooks(root, storeId => storePulls.request(storeId), undefined, scheduler ? event => scheduler.ingestEvent(event) : undefined);
261
272
  const stopRetention = modules.has("git") ? await startChangeRetention() : () => { };
262
273
  if (modules.has("git"))
263
274
  await rm(path.join(root, "changes-scratch"), { recursive: true, force: true });
@@ -265,16 +276,17 @@ export async function serve(version, options = {}) {
265
276
  const { stream } = streams;
266
277
  // The phone's overview, pushed over a WebSocket when it changes.
267
278
  const overview = overviewStream({
268
- read: workspacesReader({ modules, info, agentHooks, journal, tabActivity, contextUsage }),
279
+ read: workspacesReader({ modules, info, agentHooks, journal, tabActivity, contextUsage, turnQueue }),
269
280
  info: () => ({ ...info, capabilities: info.capabilities }),
270
281
  renew: server => agentHooks.overview.renew(server),
271
282
  resources: () => resources.read(),
272
283
  sudo: agentHooks.sudo,
273
284
  });
285
+ const gitWatch = new GitWatch();
274
286
  // 256 KiB: gitboy's /memory/files asks about up to 500 paths in one query string.
275
287
  const http = createServer({ maxHeaderSize: 256 * 1024 }, createRouteHandler({ version, modules, info, computerID, scheduleStore, scheduler, dispatches, agentHooks,
276
288
  journal, tabActivity, contextUsage, modelCatalog, modelSwitcher, settingsSwitcher, permissionModeSwitcher, sideQuestions, accountUsage, resources, codexQuestions, launches, locatedDirectories,
277
- fanoutMessages, canary, streams, returns, handOffs, inbox, mover, succession, storePulls, gitboyWebhooks }));
289
+ fanoutMessages, canary, streams, returns, handOffs, inbox, mover, succession, storePulls, gitboyWebhooks, turnQueue }));
278
290
  http.requestTimeout = 20_000;
279
291
  http.headersTimeout = 10_000;
280
292
  http.maxHeadersCount = 32;
@@ -283,7 +295,7 @@ export async function serve(version, options = {}) {
283
295
  http.on("upgrade", (request, socket, head) => {
284
296
  try {
285
297
  const url = new URL(request.url || "/", "http://phren.local");
286
- if (!["/v1/transcripts", "/v1/status", "/v1/overview", "/v1/speech/transcribe", "/v1/speech/live", "/v1/simulators/stream"].includes(url.pathname) || url.origin !== "http://phren.local") {
298
+ if (!["/v1/transcripts", "/v1/status", "/v1/overview", "/v1/git/watch", "/v1/speech/transcribe", "/v1/speech/live", "/v1/simulators/stream"].includes(url.pathname) || url.origin !== "http://phren.local") {
287
299
  socket.destroy();
288
300
  return;
289
301
  }
@@ -304,6 +316,10 @@ export async function serve(version, options = {}) {
304
316
  overview(client, overviewServer, url.searchParams.get("watchApprovals") === "1", url.searchParams.get("resources") === "1", typedMuxRequest(url), url.searchParams.get("sudo") === "1");
305
317
  return;
306
318
  }
319
+ if (url.pathname === "/v1/git/watch") {
320
+ void gitWatch.stream(client, url);
321
+ return;
322
+ }
307
323
  if (url.pathname === "/v1/speech/transcribe") {
308
324
  void relayTranscription(client, url.searchParams).catch(() => failRelay(client));
309
325
  return;
@@ -365,7 +381,7 @@ export async function serve(version, options = {}) {
365
381
  for (const server of live) {
366
382
  try {
367
383
  const name = String(server.session), current = await sharedSnapshot(name, 4000);
368
- await tabActivity.observe(name, current);
384
+ const { generation } = await tabActivity.observe(name, current);
369
385
  await journal.record(name, objects(current.panes));
370
386
  // Phone messages a pane still holds: fail loudly when it closed,
371
387
  // restarted or finished without them.
@@ -381,12 +397,14 @@ export async function serve(version, options = {}) {
381
397
  await sessionStalls.observe(parsed.data, pane);
382
398
  return parsed.success ? parsed.data : undefined;
383
399
  });
400
+ await tabActivity.recordStatus(name, await effectiveStatusRows(name, current, undefined, agentHooks), generation);
384
401
  }
385
402
  catch { /* A disconnected computer keeps its previous local activity. */ }
386
403
  }
387
404
  await codexServers.sweep(live.map(server => String(server.session))).catch(() => { });
388
405
  // Dispatch returns ride this tick and its shared snapshots. The returns
389
406
  // loop throttles its own peer polls and never holds up activity.
407
+ void turnQueue.tick().catch(() => { });
390
408
  void handOffs?.tick().catch(() => { });
391
409
  void mover.reconcile().catch(() => { });
392
410
  void succession?.reconcile().catch(() => { });
@@ -395,7 +413,7 @@ export async function serve(version, options = {}) {
395
413
  })().finally(() => { recording = false; }).catch(() => { });
396
414
  }, 5000);
397
415
  await new Promise(resolve => {
398
- const stop = () => { gitboyWebhooks.stop(); storePulls.stop(); storeSync.stop(); fanoutMessages.close(); stopRetention(); clearInterval(scheduleTimer); clearInterval(canaryTimer); clearInterval(healthTimer); clearInterval(codexAuthTimer); clearInterval(activityTimer); scheduler?.close(); codeReindexer?.close(); codexServers.close(); agentHooks.close(); ws.clients.forEach(c => c.terminate()); ws.close(); http.close(() => resolve()); http.closeAllConnections(); };
416
+ const stop = () => { gitboyWebhooks.stop(); storePulls.stop(); storeSync.stop(); fanoutMessages.close(); stopRetention(); clearInterval(scheduleTimer); clearInterval(canaryTimer); clearInterval(healthTimer); clearInterval(codexAuthTimer); clearInterval(activityTimer); scheduler?.close(); codeReindexer?.close(); codexServers.close(); gitWatch.close(); agentHooks.close(); ws.clients.forEach(c => c.terminate()); ws.close(); http.close(() => resolve()); http.closeAllConnections(); };
399
417
  process.once("SIGTERM", stop);
400
418
  process.once("SIGINT", stop);
401
419
  });
@@ -37,10 +37,11 @@ export declare const BACKGROUND_STALE_MS: number;
37
37
  * after it. Undefined once none are left or the Stop is BACKGROUND_STALE_MS old. */
38
38
  export declare function recordedBackground(record: TurnRecord | undefined, finishedTasks?: readonly string[], now?: number): number | undefined;
39
39
  /** What may still be open in a pane whose turn record says it ended: Claude
40
- * starts a turn on its own when a background agent finishes (its task
41
- * notification, with no UserPromptSubmit), and that turn can open a dialog
42
- * Herdr still reads as working (plan approval, an MCP elicitation, a
43
- * permission request the Hook holds). Pasted text plus Enter would answer it. */
40
+ * starts a turn on its own when a background agent finishes. That turn's
41
+ * UserPromptSubmit carries the notification, not the owner's prompt
42
+ * (input-classification.ts), and it can open a dialog Herdr still reads as
43
+ * working (plan approval, an MCP elicitation, a permission request the Hook
44
+ * holds). Pasted text plus Enter would answer it. */
44
45
  export interface PromptGuards {
45
46
  /** An approval the Hook holds, a terminal prompt or a question it serves for this pane. */
46
47
  held?: () => boolean;
@@ -77,6 +78,39 @@ export declare function awaitedShells(record: TurnRecord | undefined, final: Fin
77
78
  * fan-out jobs) the caller counted. Leftover shells are awaited by neither, so
78
79
  * they do not hold a session or a dispatched worker open. */
79
80
  export declare function liveWork(record: TurnRecord | undefined, final: FinalTurn | undefined, runningChildren?: number, now?: number): number | undefined;
81
+ /** The evidence every surface may have when it asks what a pane is doing. */
82
+ export interface EffectiveStatusInput {
83
+ /** The terminal's own snapshot (`pane.agent_status`). */
84
+ paneStatus?: unknown;
85
+ /** The pane's guarded turn record (turn-records.ts). */
86
+ record?: TurnRecord;
87
+ /** The transcript's final turn, when the caller already read it. */
88
+ final?: FinalTurn;
89
+ runningChildren?: number;
90
+ /** A real held approval or question the Hook serves. */
91
+ held?: boolean;
92
+ /** A confirmed dialog in the pane. */
93
+ dialog?: boolean;
94
+ /** A conversation/terminal replacement or an agent exit: old state is void. */
95
+ replaced?: boolean;
96
+ now?: number;
97
+ }
98
+ /**
99
+ * One answer to "what is this pane doing?", shared by the transcript/status
100
+ * streams, the overview and tmux lifecycle status. It resolves the separate
101
+ * definitions (terminal snapshot, hook order, transcript final turn,
102
+ * background enrichment) once, in this order:
103
+ *
104
+ * 1. a conversation/terminal replacement or agent exit invalidates old state;
105
+ * 2. a real held ask or confirmed dialog wins (`waiting` / `blocked`);
106
+ * 3. an unanswered owner prompt is working, though the terminal says idle;
107
+ * 4. a confirmed foreground end applies the bounded background rules;
108
+ * 5. without usable turn evidence the terminal snapshot is the answer.
109
+ *
110
+ * A notification never advances the prompt, so it cannot make an unanswered
111
+ * foreground turn look ended here.
112
+ */
113
+ export declare function resolveEffectiveStatus(input: EffectiveStatusInput): string | undefined;
80
114
  /** Every background task the finished turn left running, awaited or not, less
81
115
  * the endless streams (a log tail, a dev server): the Stop's count less the
82
116
  * tasks finished since, else the transcript's own count, and nothing once the
@@ -100,6 +134,17 @@ export declare function liveBackground(record: TurnRecord | undefined, readFinal
100
134
  * sits on a tab with a live turn.
101
135
  */
102
136
  export declare function markBackground(tab: Json, count: number | undefined): void;
137
+ /** A finished turn's identity on a session row: its conversation and Stop
138
+ * sequence, with when it stopped. The id is opaque to clients. */
139
+ export interface TurnCompletion {
140
+ id: string;
141
+ at: string;
142
+ entry?: string;
143
+ }
144
+ /** The latest finished turn of the conversation a record holds: absent while
145
+ * a prompt is still unanswered, and for a Stop with no prompt before it (hooks
146
+ * installed mid-conversation). */
147
+ export declare function turnCompletion(record: TurnRecord | undefined): TurnCompletion | undefined;
103
148
  /** How much of a turn's last reply a session row carries. */
104
149
  export declare const REPLY_EXCERPT_CHARS = 240;
105
150
  /**
@@ -105,6 +105,44 @@ export function liveWork(record, final, runningChildren = 0, now = Date.now()) {
105
105
  const total = (awaitedShells(record, final, now) ?? 0) + runningChildren;
106
106
  return total || undefined;
107
107
  }
108
+ /**
109
+ * One answer to "what is this pane doing?", shared by the transcript/status
110
+ * streams, the overview and tmux lifecycle status. It resolves the separate
111
+ * definitions (terminal snapshot, hook order, transcript final turn,
112
+ * background enrichment) once, in this order:
113
+ *
114
+ * 1. a conversation/terminal replacement or agent exit invalidates old state;
115
+ * 2. a real held ask or confirmed dialog wins (`waiting` / `blocked`);
116
+ * 3. an unanswered owner prompt is working, though the terminal says idle;
117
+ * 4. a confirmed foreground end applies the bounded background rules;
118
+ * 5. without usable turn evidence the terminal snapshot is the answer.
119
+ *
120
+ * A notification never advances the prompt, so it cannot make an unanswered
121
+ * foreground turn look ended here.
122
+ */
123
+ export function resolveEffectiveStatus(input) {
124
+ const terminal = typeof input.paneStatus === "string" ? input.paneStatus : undefined;
125
+ if (input.replaced)
126
+ return terminal;
127
+ if (input.held)
128
+ return "waiting";
129
+ if (input.dialog)
130
+ return "blocked";
131
+ // The terminal's own blocked/waiting report is real waiting, not an idle
132
+ // snapshot: keep it even when the turn record has no dialog evidence.
133
+ if (terminal === "blocked" || terminal === "waiting")
134
+ return terminal;
135
+ const phase = input.record ? turnPhase(input.record) : undefined;
136
+ if (phase?.phase === "working")
137
+ return "working";
138
+ const background = liveWork(input.record, input.final, input.runningChildren ?? 0, input.now);
139
+ if (background)
140
+ return "working";
141
+ if (phase?.phase === "ended") {
142
+ return terminal === "done" ? "done" : "idle";
143
+ }
144
+ return terminal;
145
+ }
108
146
  /** Every background task the finished turn left running, awaited or not, less
109
147
  * the endless streams (a log tail, a dev server): the Stop's count less the
110
148
  * tasks finished since, else the transcript's own count, and nothing once the
@@ -152,6 +190,15 @@ export function markBackground(tab, count) {
152
190
  else if (typeof tab.backgroundTasks === "number")
153
191
  tab.backgroundTasks = Math.max(tab.backgroundTasks, count);
154
192
  }
193
+ /** The latest finished turn of the conversation a record holds: absent while
194
+ * a prompt is still unanswered, and for a Stop with no prompt before it (hooks
195
+ * installed mid-conversation). */
196
+ export function turnCompletion(record) {
197
+ const prompt = record?.prompt, stop = record?.stop;
198
+ if (!record || !prompt || !stop || stop.seq <= prompt.seq)
199
+ return undefined;
200
+ return { id: `${record.session}:${stop.seq}`, at: stop.at };
201
+ }
155
202
  /** How much of a turn's last reply a session row carries. */
156
203
  export const REPLY_EXCERPT_CHARS = 240;
157
204
  /**
@@ -0,0 +1,18 @@
1
+ import type { AgentHooks } from "./agent-hooks.js";
2
+ import type { CodexQuestions } from "./questions.js";
3
+ import { type Json, type Provider } from "./protocol.js";
4
+ import { type EffectiveStatusInput } from "./session-activity.js";
5
+ import { type TurnRecord } from "./turn-records.js";
6
+ interface ChildActivity {
7
+ runningChildren: number;
8
+ childProviders: Provider[];
9
+ }
10
+ export declare function childActivity(source: Provider, session: string): Promise<ChildActivity>;
11
+ /** Evidence already in memory must not wait on children, transcripts or dialogs. */
12
+ export declare function availablePaneEvidence(server: string, pane: Json, session: string, record?: TurnRecord, hooks?: AgentHooks): EffectiveStatusInput;
13
+ /** Every caller gets the same guarded foreground evidence, with whatever
14
+ * enrichment is ready inside one bounded window. Late work never mutates it. */
15
+ export declare function effectivePaneEvidence(server: string, pane: Json, session: string, hooks?: AgentHooks, questions?: CodexQuestions, knownRecord?: TurnRecord): Promise<EffectiveStatusInput & {
16
+ children?: ChildActivity;
17
+ }>;
18
+ export {};
@@ -0,0 +1,72 @@
1
+ import { provider, bridgeRoot } from "./protocol.js";
2
+ import { childAgentTree, runningChildAgents } from "./transcripts.js";
3
+ import { readFinalTurn } from "./schedule-watch.js";
4
+ import { paneRecord } from "./session-activity.js";
5
+ import { turnPhase } from "./turn-records.js";
6
+ const CHILD_ACTIVITY_CACHE_MS = 5_000;
7
+ const childActivityCache = new Map();
8
+ export async function childActivity(source, session) {
9
+ const key = `${source}\0${session}`, now = Date.now(), cached = childActivityCache.get(key);
10
+ // A slow tree still belongs to the next overview. Expiring an in-flight
11
+ // read every five seconds starts it over before any answer can be reused.
12
+ if (cached && (cached.pending || now - cached.at < CHILD_ACTIVITY_CACHE_MS))
13
+ return cached.result;
14
+ const result = childAgentTree(source, session).then(tree => {
15
+ const running = runningChildAgents(tree);
16
+ return { runningChildren: running.length, childProviders: [...new Set(running.map(child => child.provider))].sort() };
17
+ }).catch(() => ({ runningChildren: 0, childProviders: [] }));
18
+ const entry = { at: now, pending: true, result };
19
+ void result.then(() => { entry.at = Date.now(); entry.pending = false; });
20
+ childActivityCache.set(key, entry);
21
+ while (childActivityCache.size > 128)
22
+ childActivityCache.delete(childActivityCache.keys().next().value);
23
+ return result;
24
+ }
25
+ /** Wait for optional enrichment without holding transcript delivery indefinitely. */
26
+ async function bounded(work, ms = 100) {
27
+ let timer;
28
+ try {
29
+ return await Promise.race([work.catch(() => undefined), new Promise(resolve => { timer = setTimeout(() => resolve(undefined), ms); })]);
30
+ }
31
+ finally {
32
+ clearTimeout(timer);
33
+ }
34
+ }
35
+ /** Evidence already in memory must not wait on children, transcripts or dialogs. */
36
+ export function availablePaneEvidence(server, pane, session, record, hooks) {
37
+ const target = { server, pane: String(pane.pane_id), workspace: String(pane.workspace_id), tab: String(pane.tab_id), source: pane.agent, session };
38
+ const held = !!(hooks?.approval?.(target) || hooks?.servedQuestion?.(target));
39
+ return { paneStatus: pane.agent_status, record, held, dialog: !!hooks?.terminalPrompt?.(target) };
40
+ }
41
+ const finalReads = new Map();
42
+ function finalEvidence(record) {
43
+ if (record.source === "phren")
44
+ return Promise.resolve(undefined);
45
+ const key = `${bridgeRoot()}:${record.source}:${record.session}:${record.stop?.seq}`, cached = finalReads.get(key);
46
+ if (cached)
47
+ return cached;
48
+ const result = readFinalTurn(record.source, record.session).catch(() => undefined);
49
+ finalReads.set(key, result);
50
+ void result.then(() => { if (finalReads.get(key) === result)
51
+ finalReads.delete(key); });
52
+ while (finalReads.size > 128)
53
+ finalReads.delete(finalReads.keys().next().value);
54
+ return result;
55
+ }
56
+ /** Every caller gets the same guarded foreground evidence, with whatever
57
+ * enrichment is ready inside one bounded window. Late work never mutates it. */
58
+ export async function effectivePaneEvidence(server, pane, session, hooks, questions, knownRecord) {
59
+ const record = knownRecord ?? await bounded(paneRecord(server, pane, session));
60
+ const phase = record ? turnPhase(record) : undefined;
61
+ const target = { server, pane: String(pane.pane_id), workspace: String(pane.workspace_id), tab: String(pane.tab_id), source: pane.agent, session };
62
+ let children, final;
63
+ let question = false;
64
+ await bounded(Promise.all([
65
+ record && phase?.phase === "ended" ? finalEvidence(record).then(value => { final = value; }) : undefined,
66
+ provider.safeParse(pane.agent).success ? childActivity(pane.agent, session).then(value => { children = value; }) : undefined,
67
+ hooks?.syncTerminalDialog?.(target, ["blocked", "waiting"].includes(String(pane.agent_status)) || phase?.phase === "working"),
68
+ pane.agent === "codex" ? questions?.pending(target).then(value => { question = !!value?.length; }) : undefined,
69
+ ]));
70
+ const available = availablePaneEvidence(server, pane, session, record, hooks);
71
+ return { ...available, final, children, runningChildren: children?.runningChildren, held: available.held || question };
72
+ }
@@ -0,0 +1,23 @@
1
+ import { z } from "zod";
2
+ import { type Json } from "./protocol.js";
3
+ /** `{ server, pane, completion }` marks a finished turn seen; `unread: true`
4
+ * clears the stored `seenCompletion` again, but only when it equals the
5
+ * completion the client sent. */
6
+ export declare const seenRequest: z.ZodObject<{
7
+ server: z.ZodString;
8
+ pane: z.ZodString;
9
+ completion: z.ZodString;
10
+ unread: z.ZodOptional<z.ZodLiteral<true>>;
11
+ }, z.core.$strip>;
12
+ export declare function seenPath(server: string, pane: string): string;
13
+ /** The completion a client last marked seen for `pane`, absent when none was. */
14
+ export declare function readSessionSeen(server: string, pane: string): Promise<string | undefined>;
15
+ export declare function setSessionSeen(server: string, pane: string, completionId: string, unread?: boolean): Promise<void>;
16
+ /** Everything the route touches outside this file; tests pass their own. */
17
+ export interface SeenDeps {
18
+ snapshot(server: string): Promise<Json>;
19
+ }
20
+ /** `POST /v1/sessions/seen`: stores what the client sent (last writer wins),
21
+ * or clears `seenCompletion` when `unread: true` and the stored mark equals
22
+ * the completion sent. */
23
+ export declare function markSessionSeen(data: Json, deps?: SeenDeps): Promise<Json>;
@@ -0,0 +1,69 @@
1
+ // Which finished turn of a pane a person last marked seen, on the phone or on
2
+ // the desktop. One tiny file per pane beside its turn record (turn-records.ts),
3
+ // written atomically, so the mark survives a Hook restart and every client
4
+ // reads the same one. A session row carries it as `seenCompletion`; the phone
5
+ // calls it unread while the row's own `completion.id` differs.
6
+ import { lstat, readFile, unlink } from "node:fs/promises";
7
+ import path from "node:path";
8
+ import { z } from "zod";
9
+ import { snapshot } from "./herdr.js";
10
+ import { atomicInPrivateDir, BridgeError, bridgeRoot, id, objects, serverName } from "./protocol.js";
11
+ const completion = z.string().min(1).max(256).refine(value => !/[\x00-\x1f\x7f]/.test(value));
12
+ const seenSchema = z.object({ completion });
13
+ const MAX_SEEN_BYTES = 4_096;
14
+ /** `{ server, pane, completion }` marks a finished turn seen; `unread: true`
15
+ * clears the stored `seenCompletion` again, but only when it equals the
16
+ * completion the client sent. */
17
+ export const seenRequest = z.object({ server: serverName, pane: id, completion, unread: z.literal(true).optional() });
18
+ export function seenPath(server, pane) {
19
+ return path.join(bridgeRoot(), "turns", encodeURIComponent(serverName.parse(server)), encodeURIComponent(pane) + ".seen.json");
20
+ }
21
+ /** The completion a client last marked seen for `pane`, absent when none was. */
22
+ export async function readSessionSeen(server, pane) {
23
+ try {
24
+ const file = seenPath(server, pane);
25
+ const info = await lstat(file);
26
+ if (!info.isFile() || info.size > MAX_SEEN_BYTES)
27
+ return undefined;
28
+ const parsed = seenSchema.safeParse(JSON.parse(await readFile(file, "utf8")));
29
+ return parsed.success ? parsed.data.completion : undefined;
30
+ }
31
+ catch {
32
+ return undefined;
33
+ }
34
+ }
35
+ /** Records `completion` as the pane's seen turn, or clears the mark when
36
+ * `unread` names it. Last writer wins; each pane's read/compare/delete or
37
+ * write runs whole, so a stale clear never removes a concurrent write. */
38
+ let writes = Promise.resolve();
39
+ export function setSessionSeen(server, pane, completionId, unread = false) {
40
+ const run = writes.then(async () => {
41
+ const file = seenPath(server, pane);
42
+ if (unread) {
43
+ if (await readSessionSeen(server, pane) !== completionId)
44
+ return;
45
+ try {
46
+ await unlink(file);
47
+ }
48
+ catch (error) {
49
+ if (error.code !== "ENOENT")
50
+ throw error;
51
+ }
52
+ return;
53
+ }
54
+ await atomicInPrivateDir(file, { completion: completionId });
55
+ });
56
+ writes = run.catch(() => undefined);
57
+ return run;
58
+ }
59
+ /** `POST /v1/sessions/seen`: stores what the client sent (last writer wins),
60
+ * or clears `seenCompletion` when `unread: true` and the stored mark equals
61
+ * the completion sent. */
62
+ export async function markSessionSeen(data, deps = { snapshot }) {
63
+ const { server, pane, completion: completionId, unread } = seenRequest.parse(data);
64
+ const s = await deps.snapshot(server);
65
+ if (!objects(s.panes).some(value => value.pane_id === pane))
66
+ throw new BridgeError(404, "No pane with that id on this computer.");
67
+ await setSessionSeen(server, pane, completionId, unread === true);
68
+ return { ok: true };
69
+ }
@@ -1,4 +1,20 @@
1
1
  import { type Json } from "./protocol.js";
2
+ type Stamp = {
3
+ signature: string;
4
+ statusSignature?: string;
5
+ lastChangedAt: string;
6
+ statusSince: string;
7
+ };
8
+ type StatusRow = {
9
+ workspace: unknown;
10
+ tab: unknown;
11
+ status: unknown;
12
+ };
13
+ export type TabActivityStamp = Pick<Stamp, "lastChangedAt" | "statusSince">;
14
+ export type TabActivityObservation = {
15
+ generation: number;
16
+ stamps: ReadonlyMap<string, TabActivityStamp>;
17
+ };
2
18
  export declare const tabActivityKey: (workspace: unknown, tab: unknown) => string;
3
19
  /** A clock for Herdr's clockless state counters. Only successful snapshots
4
20
  * prune tabs; each activity pass also prunes missing servers. Writes are ordered
@@ -10,9 +26,18 @@ export declare class TabActivityStore {
10
26
  private loaded;
11
27
  private dirty;
12
28
  private pending;
29
+ private nextGeneration;
30
+ private committedGeneration;
13
31
  constructor(file?: string, now?: () => Date);
14
- observe(server: string, snapshot: Json): Promise<ReadonlyMap<string, string>>;
32
+ observe(server: string, snapshot: Json): Promise<TabActivityObservation>;
33
+ /** The status clock follows the final `agentStatus` the overview sends, after
34
+ * background work and other decoration change it. Keep this off `observe`:
35
+ * the background activity timer polls raw snapshots and must not reset it.
36
+ * `generation` comes from the observation that started this enrichment, so an
37
+ * older snapshot that finishes later cannot overwrite a newer one. */
38
+ recordStatus(server: string, rows: readonly StatusRow[], generation: number): Promise<ReadonlyMap<string, TabActivityStamp>>;
15
39
  private load;
16
40
  private persist;
17
41
  pruneServers(servers: string[]): Promise<void>;
18
42
  }
43
+ export {};
@@ -14,6 +14,8 @@ export class TabActivityStore {
14
14
  loaded = false;
15
15
  dirty = false;
16
16
  pending = Promise.resolve();
17
+ nextGeneration = new Map();
18
+ committedGeneration = new Map();
17
19
  constructor(file = path.join(bridgeRoot(), "tab-activity.json"), now = () => new Date()) {
18
20
  this.file = file;
19
21
  this.now = now;
@@ -22,8 +24,10 @@ export class TabActivityStore {
22
24
  const at = this.now().toISOString();
23
25
  const operation = this.pending.catch(() => { }).then(async () => {
24
26
  await this.load();
27
+ const generation = (this.nextGeneration.get(server) ?? 0) + 1;
28
+ this.nextGeneration.set(server, generation);
25
29
  const prefix = JSON.stringify(server) + ":";
26
- const seen = new Set(), times = new Map();
30
+ const seen = new Set(), stamps = new Map();
27
31
  let changed = false;
28
32
  for (const tab of objects(snapshot.tabs)) {
29
33
  const tabKey = tabActivityKey(tab.workspace_id, tab.tab_id), key = prefix + tabKey;
@@ -34,13 +38,17 @@ export class TabActivityStore {
34
38
  .map(p => [p.pane_id, p.agent, p.agent_status, p.state_change_seq, p.title || p.terminal_title_stripped])
35
39
  .sort((a, b) => String(a[0]).localeCompare(String(b[0])));
36
40
  const signature = digest(JSON.stringify([tab.agent_status, tab.state_change_seq, tab.label, tab.title, panes]));
37
- let stamp = this.entries.get(key);
38
- if (stamp?.signature !== signature) {
39
- stamp = { signature, lastChangedAt: at };
40
- this.entries.set(key, stamp);
41
+ const stamp = this.entries.get(key);
42
+ if (!stamp) {
43
+ this.entries.set(key, { signature, lastChangedAt: at, statusSince: at });
41
44
  changed = true;
42
45
  }
43
- times.set(tabKey, stamp.lastChangedAt);
46
+ else if (stamp.signature !== signature) {
47
+ this.entries.set(key, { ...stamp, signature, lastChangedAt: at });
48
+ changed = true;
49
+ }
50
+ const current = this.entries.get(key);
51
+ stamps.set(tabKey, { lastChangedAt: current.lastChangedAt, statusSince: current.statusSince });
44
52
  }
45
53
  for (const key of this.entries.keys()) {
46
54
  if (key.startsWith(prefix) && !seen.has(key)) {
@@ -50,7 +58,48 @@ export class TabActivityStore {
50
58
  }
51
59
  this.dirty ||= changed;
52
60
  await this.persist();
53
- return times;
61
+ return { generation, stamps };
62
+ });
63
+ this.pending = operation;
64
+ return operation;
65
+ }
66
+ /** The status clock follows the final `agentStatus` the overview sends, after
67
+ * background work and other decoration change it. Keep this off `observe`:
68
+ * the background activity timer polls raw snapshots and must not reset it.
69
+ * `generation` comes from the observation that started this enrichment, so an
70
+ * older snapshot that finishes later cannot overwrite a newer one. */
71
+ recordStatus(server, rows, generation) {
72
+ const at = this.now().toISOString();
73
+ const operation = this.pending.catch(() => { }).then(async () => {
74
+ await this.load();
75
+ const prefix = JSON.stringify(server) + ":";
76
+ const stamps = new Map();
77
+ const committed = this.committedGeneration.get(server) ?? 0, stale = generation < committed;
78
+ if (!stale)
79
+ this.committedGeneration.set(server, generation);
80
+ let changed = false;
81
+ for (const row of rows) {
82
+ const tabKey = tabActivityKey(row.workspace, row.tab), key = prefix + tabKey;
83
+ const stamp = this.entries.get(key);
84
+ if (!stamp)
85
+ continue;
86
+ const statusSignature = digest(JSON.stringify([row.status]));
87
+ if (!stale) {
88
+ if (stamp.statusSignature === undefined) {
89
+ this.entries.set(key, { ...stamp, statusSignature });
90
+ changed = true;
91
+ }
92
+ else if (stamp.statusSignature !== statusSignature) {
93
+ this.entries.set(key, { ...stamp, statusSignature, statusSince: at });
94
+ changed = true;
95
+ }
96
+ }
97
+ const current = this.entries.get(key);
98
+ stamps.set(tabKey, { lastChangedAt: current.lastChangedAt, statusSince: current.statusSince });
99
+ }
100
+ this.dirty ||= changed;
101
+ await this.persist();
102
+ return stamps;
54
103
  });
55
104
  this.pending = operation;
56
105
  return operation;
@@ -63,8 +112,14 @@ export class TabActivityStore {
63
112
  if (typeof stamp.signature === "string" && typeof stamp.lastChangedAt === "string"
64
113
  && Number.isFinite(Date.parse(stamp.lastChangedAt))) {
65
114
  const hashed = /^[a-f0-9]{64}$/.test(stamp.signature);
66
- this.entries.set(key, { signature: hashed ? stamp.signature : digest(stamp.signature), lastChangedAt: stamp.lastChangedAt });
67
- this.dirty ||= !hashed;
115
+ const savedStatus = typeof stamp.statusSignature === "string" ? stamp.statusSignature : undefined;
116
+ const statusHashed = savedStatus !== undefined && /^[a-f0-9]{64}$/.test(savedStatus);
117
+ const statusSince = typeof stamp.statusSince === "string" && Number.isFinite(Date.parse(stamp.statusSince))
118
+ ? stamp.statusSince : stamp.lastChangedAt;
119
+ this.entries.set(key, { signature: hashed ? stamp.signature : digest(stamp.signature),
120
+ statusSignature: savedStatus === undefined ? undefined : statusHashed ? savedStatus : digest(savedStatus),
121
+ lastChangedAt: stamp.lastChangedAt, statusSince });
122
+ this.dirty ||= !hashed || savedStatus === undefined || !statusHashed || statusSince !== stamp.statusSince;
68
123
  }
69
124
  }
70
125
  this.loaded = true;
@@ -0,0 +1,20 @@
1
+ import { type Json } from "./protocol.js";
2
+ /** A terminal reference from chat text: a Herdr pane (`w2E:p1`) or tab
3
+ * (`w2E:t1`) id, optionally prefixed by the computer it belongs to. */
4
+ export interface TerminalReference {
5
+ computer?: string;
6
+ id: string;
7
+ }
8
+ /** The reference itself, never a URL, path or a longer code-like token. */
9
+ export declare function parseTerminalReference(value: string | null | undefined): TerminalReference;
10
+ export interface TerminalResolveOptions {
11
+ /** This Hook's computer, as /v1/health reports it. */
12
+ computer: {
13
+ name: string;
14
+ aliases?: readonly string[];
15
+ };
16
+ /** The pane the text came from, when the client knows it. */
17
+ from?: string | null;
18
+ }
19
+ /** The terminal a chat reference names, on this computer or a verified peer. */
20
+ export declare function resolveTerminalReference(value: string | null | undefined, options: TerminalResolveOptions): Promise<Json>;