@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
@@ -4,6 +4,7 @@ import { createServer } from "node:http";
4
4
  import path from "node:path";
5
5
  import { z } from "zod";
6
6
  import { DeliveryLog, parseGitboyPush, storePushMatches, verifyGitboySignature } from "../sync/gitboy-webhook.js";
7
+ import { parseScheduleEvent } from "./schedule-events.js";
7
8
  import { optionalHookPeers, peerRequest } from "./peers.js";
8
9
  const storeSchema = z.object({
9
10
  storeId: z.string().min(1).max(128), owner: z.string().min(1).max(256), name: z.string().min(1).max(256),
@@ -51,16 +52,18 @@ export class GitboyWebhooks {
51
52
  root;
52
53
  pull;
53
54
  nudge;
55
+ scheduleEvent;
54
56
  status = { configured: false, listening: false };
55
57
  server;
56
58
  deliveries = new DeliveryLog();
57
59
  bodies = new DeliveryLog();
58
60
  nudges = new Map();
59
61
  closed = false;
60
- constructor(root, pull, nudge = nudgePeers) {
62
+ constructor(root, pull, nudge = nudgePeers, scheduleEvent) {
61
63
  this.root = root;
62
64
  this.pull = pull;
63
65
  this.nudge = nudge;
66
+ this.scheduleEvent = scheduleEvent;
64
67
  }
65
68
  notify(store) {
66
69
  // Configuration may name a local attachment. Only the ID carried by that store is portable.
@@ -145,6 +148,27 @@ export class GitboyWebhooks {
145
148
  reply(401, "unauthorized");
146
149
  return;
147
150
  }
151
+ const githubEvent = request.headers["x-github-event"];
152
+ if (githubEvent === "workflow_run" || githubEvent === "check_run") {
153
+ if (!this.scheduleEvent) {
154
+ reply(404, "not-supported");
155
+ return;
156
+ }
157
+ const payload = JSON.parse(raw.toString("utf8"));
158
+ const repo = typeof payload?.repository?.full_name === "string" ? payload.repository.full_name.toLowerCase() : "";
159
+ if (!verified.some(store => `${store.owner}/${store.name}`.toLowerCase() === repo)) {
160
+ reply(401, "unauthorized");
161
+ return;
162
+ }
163
+ const event = parseScheduleEvent({ event: `github.${githubEvent}.completed`, deliveryId: request.headers["x-github-delivery"], payload });
164
+ if (payload.action !== "completed") {
165
+ reply(200, "non-matching");
166
+ return;
167
+ }
168
+ await this.scheduleEvent(event);
169
+ reply(202, "accepted");
170
+ return;
171
+ }
148
172
  const push = parseGitboyPush(raw, request.headers);
149
173
  if (!push?.repository) {
150
174
  reply(400, "malformed");
@@ -174,7 +198,7 @@ export class GitboyWebhooks {
174
198
  setImmediate(() => { if (!this.closed)
175
199
  for (const store of matching)
176
200
  this.notify(store); });
177
- })().catch(error => reply(typeof error === "number" ? error : 400, typeof error === "number" && error === 413 ? "too-large" : "malformed"));
201
+ })().catch(error => reply(typeof error === "number" ? error : typeof error?.status === "number" ? error.status : 400, typeof error === "number" && error === 413 ? "too-large" : "malformed"));
178
202
  });
179
203
  this.server = server;
180
204
  server.requestTimeout = 6000;
@@ -1,5 +1,6 @@
1
1
  import type { AccountRef } from "./claude-accounts.js";
2
2
  import { BridgeError, type Json, type Target, type StartingTarget } from "./protocol.js";
3
+ import { type TabActivityStamp } from "./tab-activity.js";
3
4
  export declare function herdrRoot(): string;
4
5
  /** Where Herdr's socket for `server` lives. */
5
6
  export declare function herdrSocketPath(server: string): string;
@@ -27,6 +28,10 @@ export declare const SERVER_LIST_REUSE_MS: number;
27
28
  * background work only: a route that answers the phone calls `servers()`. */
28
29
  export declare function recentServers(maxAgeMs?: number): Promise<Json[]>;
29
30
  export declare function servers(): Promise<Json[]>;
31
+ /** The running terminal servers for a safety check. Unlike `servers()`, a
32
+ * server that cannot be read (timeout, permission, unreachable) or a discovery
33
+ * failure fails the call; only a server that is actually stopped is left out. */
34
+ export declare function serversStrict(): Promise<Json[]>;
30
35
  /** How old a shared `session.snapshot` may be for readers that poll: open
31
36
  * chat and status streams and the activity timer. The overview and every
32
37
  * action take a fresh one, which the pollers then reuse. */
@@ -70,7 +75,7 @@ export declare function findPane(s: Json, address: PaneAddress): Json | undefine
70
75
  export declare function isConductorName(name: string | undefined): boolean;
71
76
  /** `conductorPane` is the pane the Hook records as the conductor (null for
72
77
  * none); left out, the agent's name decides, as before the record. */
73
- export declare function workspaceSnapshot(s: Json, contextUsedPercent?: ReadonlyMap<Json, number>, approvalPanes?: ReadonlySet<string>, lastChanged?: ReadonlyMap<string, string>, conductorPane?: string | null): Json;
78
+ export declare function workspaceSnapshot(s: Json, contextUsedPercent?: ReadonlyMap<Json, number>, approvalPanes?: ReadonlySet<string>, lastChanged?: ReadonlyMap<string, TabActivityStamp>, conductorPane?: string | null): Json;
74
79
  export declare function paneIdentity(server: string, pane: Json, fresh?: boolean): Promise<string | undefined>;
75
80
  /** Copilot CLI changes conversation inside one process (/new, /clear,
76
81
  * /resume) and runs its sessionStart hook only once that conversation's first
@@ -8,7 +8,7 @@ import path from "node:path";
8
8
  import { promisify } from "node:util";
9
9
  import { BridgeError, id, object, objects, requestID, serverName, provider, sessionId } from "./protocol.js";
10
10
  import { logger } from "../logger.js";
11
- import { boundSession, recordedSession } from "./agent-hook-stores.js";
11
+ import { recordedSession } from "./agent-hook-stores.js";
12
12
  import { paneRecord, recordTitle } from "./session-activity.js";
13
13
  import { tabActivityKey } from "./tab-activity.js";
14
14
  import { intervalFromEnv } from "./limits.js";
@@ -77,7 +77,10 @@ export async function rpc(server, method, params = {}, signal, timeoutMs = 10_00
77
77
  const client = connect(socket);
78
78
  const key = requestID();
79
79
  let pending = Buffer.alloc(0);
80
+ let deadline;
80
81
  const finish = (error, result) => {
82
+ if (deadline)
83
+ clearTimeout(deadline);
81
84
  signal?.removeEventListener("abort", abort);
82
85
  client.destroy();
83
86
  if (error)
@@ -91,7 +94,7 @@ export async function rpc(server, method, params = {}, signal, timeoutMs = 10_00
91
94
  return;
92
95
  }
93
96
  signal?.addEventListener("abort", abort, { once: true });
94
- client.setTimeout(timeoutMs, () => finish(new BridgeError(504, "Herdr did not answer. Refresh before trying again.", { code: "herdr-timeout" })));
97
+ deadline = setTimeout(() => finish(new BridgeError(504, "Herdr did not answer. Refresh before trying again.", { code: "herdr-timeout" })), timeoutMs);
95
98
  client.on("error", error => finish(herdrSocketError(error)));
96
99
  client.on("end", () => finish(new BridgeError(503, "Herdr closed the request before confirming it.")));
97
100
  client.on("connect", () => client.write(JSON.stringify({ id: key, method, params }) + "\n"));
@@ -158,6 +161,39 @@ export async function servers() {
158
161
  knownServers = running.map(server => String(server.session));
159
162
  return running;
160
163
  }
164
+ /** The running terminal servers for a safety check. Unlike `servers()`, a
165
+ * server that cannot be read (timeout, permission, unreachable) or a discovery
166
+ * failure fails the call; only a server that is actually stopped is left out. */
167
+ export async function serversStrict() {
168
+ const folder = path.join(herdrRoot(), "sessions");
169
+ let sessions;
170
+ try {
171
+ sessions = (await readdir(folder)).filter(name => serverName.safeParse(name).success);
172
+ }
173
+ catch (error) {
174
+ if (error.code === "ENOENT")
175
+ sessions = [];
176
+ else
177
+ throw new BridgeError(503, "Could not list this computer's Herdr servers.", { code: "herdr-discovery-failed" });
178
+ }
179
+ const names = ["default", ...sessions];
180
+ const results = await Promise.all(names.map(async (name) => {
181
+ try {
182
+ await rpc(name, "ping");
183
+ return { id: `herdr:${name}`, kind: "herdr", session: name, running: true };
184
+ }
185
+ catch (error) {
186
+ const code = error instanceof BridgeError ? error.details?.code : undefined;
187
+ if (code === "herdr-not-running" || code === "herdr-stale-socket")
188
+ return null;
189
+ throw error;
190
+ }
191
+ }));
192
+ const running = results.filter((value) => value !== null);
193
+ running.push(...await import("./terminal-tmux.js").then(tmux => tmux.tmuxServersStrict()));
194
+ knownServers = running.map(server => String(server.session));
195
+ return running;
196
+ }
161
197
  /** How old a shared `session.snapshot` may be for readers that poll: open
162
198
  * chat and status streams and the activity timer. The overview and every
163
199
  * action take a fresh one, which the pollers then reuse. */
@@ -257,6 +293,7 @@ export function workspaceSnapshot(s, contextUsedPercent, approvalPanes, lastChan
257
293
  children: objects(s.tabs).filter(t => t.workspace_id === w.workspace_id).map(t => {
258
294
  const panes = objects(s.panes).filter(p => p.tab_id === t.tab_id && p.workspace_id === t.workspace_id);
259
295
  const agent = panes.find(p => p.agent);
296
+ const activity = lastChanged?.get(tabActivityKey(t.workspace_id, t.tab_id));
260
297
  // Herdr's per-pane state_change_seq climbs with every agent status
261
298
  // change; the phone orders "just finished" ahead of "finished an hour ago" by it.
262
299
  const changed = Math.max(0, ...panes.map(p => Number.isSafeInteger(p.state_change_seq) ? Number(p.state_change_seq) : 0));
@@ -264,7 +301,8 @@ export function workspaceSnapshot(s, contextUsedPercent, approvalPanes, lastChan
264
301
  agent: agent?.agent, agentStatus: t.agent_status, cwd: agent?.foreground_cwd || agent?.cwd,
265
302
  role: (conductorPane === undefined ? isConductorName(paneAgentName(s, agent)) : !!agent && agent.pane_id === conductorPane) ? "conductor" : undefined,
266
303
  changedSeq: changed || undefined,
267
- lastChangedAt: lastChanged?.get(tabActivityKey(t.workspace_id, t.tab_id)),
304
+ lastChangedAt: activity?.lastChangedAt,
305
+ statusSince: activity?.statusSince,
268
306
  approvalPending: panes.some(p => approvalPanes?.has(String(p.pane_id))) || undefined,
269
307
  contextUsedPercent: agent && panes.filter(p => p.agent).length === 1 ? contextUsedPercent?.get(agent) : undefined,
270
308
  agentPaneCount: panes.filter(p => p.agent).length, paneCount: panes.length };
@@ -302,20 +340,28 @@ async function resolveIdentity(server, pane, fresh) {
302
340
  // A Codex pane on the Hook's own app-server: the registry follows `/new`
303
341
  // and `/resume` as they happen, while Herdr's report waits for a hook.
304
342
  const owned = pane.agent === "codex" && !!codexServers.forPane(server, String(pane.pane_id))?.threadId;
305
- // A `claude -p` run from the pane's shell inherits HERDR_*, and Herdr then
306
- // reports that run's session for the pane long after it exits. When the
307
- // Hook's own binding names another conversation, the processes decide.
308
- if (pane.agent !== "copilot" && !owned && reported.kind === "id" && reported.agent === pane.agent && typeof reported.value === "string" && sessionId.safeParse(reported.value).success
309
- && (pane.agent !== "claude" || [undefined, reported.value].includes(await boundSession(server, pane)))) {
343
+ // Claude's report and binding can both lag a conversation switch in the
344
+ // same process, or name a finished nested `claude -p`. The cached foreground
345
+ // probe decides even when the report and binding agree.
346
+ if (pane.agent !== "copilot" && pane.agent !== "claude" && !owned && reported.kind === "id" && reported.agent === pane.agent && typeof reported.value === "string" && sessionId.safeParse(reported.value).success) {
310
347
  countIdentity("reported");
311
348
  return { sessionId: reported.value, noTranscriptLogs: false };
312
349
  }
313
350
  const pids = await foregroundPids(server, pane);
314
351
  const key = identityKey(server, pane, pids);
315
352
  const cached = identities.get(key);
353
+ // Cache process evidence, not the fallback report: a new snapshot can carry
354
+ // a different report while the terminal and foreground PIDs stay the same.
355
+ const resolved = (identity) => {
356
+ if (pane.agent === "claude" && !identity.sessionId && identity.noTranscriptLogs
357
+ && reported.kind === "id" && reported.agent === "claude" && typeof reported.value === "string" && sessionId.safeParse(reported.value).success) {
358
+ return { sessionId: reported.value, noTranscriptLogs: false, pids };
359
+ }
360
+ return { ...identity, pids };
361
+ };
316
362
  if (!fresh && cached && Date.now() - cached.at < IDENTITY_CACHE_MS) {
317
363
  countIdentity("cached");
318
- return { ...await cached.result, pids };
364
+ return resolved(await cached.result);
319
365
  }
320
366
  countIdentity(fresh ? "probe-fresh" : "probe");
321
367
  const result = identityFromProcesses(server, pane, pids);
@@ -328,7 +374,7 @@ async function resolveIdentity(server, pane, fresh) {
328
374
  // brand-new conversation it just proved as starting.
329
375
  void result.then(() => { entry.at = Date.now(); }, () => { });
330
376
  identities.set(key, entry);
331
- return { ...await result, pids };
377
+ return resolved(await result);
332
378
  }
333
379
  export async function paneIdentity(server, pane, fresh = false) {
334
380
  return (await resolveIdentity(server, pane, fresh)).sessionId;
@@ -12,6 +12,8 @@
12
12
  // the git module itself and the hook module's settings entries are removed
13
13
  // when it is off, so the store's module config is not read here.
14
14
  import path from "node:path";
15
+ import { claudePromptEntryId } from "./prompt-identity.js";
16
+ import { claudeCallbackFacts, classifyClaudePromptText } from "./input-classification.js";
15
17
  /** The script's file name in a version's folder, beside `bridge-hook.mjs`. */
16
18
  export const FAST_HOOK_FILE = "claude-hook.mjs";
17
19
  export const fastHookPath = (versionDir) => path.join(versionDir, FAST_HOOK_FILE);
@@ -54,6 +56,11 @@ import path from "node:path";
54
56
  import { fileURLToPath, pathToFileURL } from "node:url";
55
57
  const env = process.env, source = process.argv[2];
56
58
  const hookOutput = ${hookOutput.toString()};
59
+ const claudePromptEntryId = ${claudePromptEntryId.toString()};
60
+ // The same classification the full callback forwards; embedded so this small
61
+ // script never needs the bundle to name a notification as owner input.
62
+ const classifyClaudePromptText = ${classifyClaudePromptText.toString()};
63
+ const claudeCallbackFacts = ${claudeCallbackFacts.toString()};
57
64
  async function full() {
58
65
  const bundle = path.join(path.dirname(fileURLToPath(import.meta.url)), "bridge-hook.mjs");
59
66
  process.argv = [process.argv[0], bundle, "hook", source];
@@ -84,9 +91,14 @@ async function forward(place) {
84
91
  .sort((a, b) => Number(b.running) - Number(a.running)).slice(0, ${STOP_TASKS_SENT}) : undefined;
85
92
  const stop = event !== "Stop" ? {} : { ...(tasks ? { background: tasks.length } : {}), ...(listed ? { backgroundTasks: listed } : {}),
86
93
  ...(typeof value.last_assistant_message === "string" && value.last_assistant_message.trim() ? { reply: value.last_assistant_message.slice(0, 16_384) } : {}) };
87
- const data = JSON.stringify({ target, event, ...(dispatchId ? { dispatchId } : {}),
94
+ const promptEntryId = source === "claude" && event === "UserPromptSubmit" ? claudePromptEntryId(value.prompt_id) : undefined;
95
+ const promptInput = source === "claude" && event === "UserPromptSubmit" ? classifyClaudePromptText(value.prompt) : undefined;
96
+ const data = JSON.stringify({ target, event, ...claudeCallbackFacts(value),
97
+ ...(typeof value.transcript_path === "string" ? { transcript: value.transcript_path.slice(0, 4096) } : {}), ...(dispatchId ? { dispatchId } : {}),
88
98
  tool: value.tool_name, input: value.tool_input, toolUseId: value.tool_use_id, cwd: value.cwd,
99
+ ...(promptInput && promptInput.category !== "owner" && !(claudeCallbackFacts(value).hasImage && promptInput.reason === "text:empty") ? { inputCategory: promptInput.category, inputReason: promptInput.reason } : {}),
89
100
  ...(event === "UserPromptSubmit" && typeof value.prompt === "string" ? { prompt: value.prompt.slice(0, 65_536) } : {}),
101
+ ...(promptEntryId ? { promptEntryId } : {}),
90
102
  ...(event === "SessionStart" && typeof value.source === "string" ? { startSource: value.source.slice(0, 32) } : {}), ...stop });
91
103
  const socketPath = path.join(env.PHREN_BRIDGE_HOME || path.join(homedir(), ".local/share/phren/bridge"), "agent.sock");
92
104
  // A tool call's callback fits its budget from process start, or is skipped.
@@ -0,0 +1,33 @@
1
+ /** Whose input a Claude row or callback is. */
2
+ export type InputCategory = "owner" | "notification" | "internal";
3
+ /** A category and a short, payload-free reason for it. */
4
+ export interface InputClassification {
5
+ category: InputCategory;
6
+ reason: string;
7
+ }
8
+ /** The facts a caller can supply. Absent facts are simply not evidence. */
9
+ export interface InputFacts {
10
+ text?: unknown;
11
+ hasImage?: boolean;
12
+ origin?: unknown;
13
+ commandMode?: unknown;
14
+ isMeta?: unknown;
15
+ isSidechain?: unknown;
16
+ isCompactSummary?: unknown;
17
+ /** The row's user content is only tool_result blocks. */
18
+ toolResult?: unknown;
19
+ /** The input arrived through the harness's notification delivery path
20
+ * (Claude's queued_command attachment, for example). */
21
+ notificationDelivery?: unknown;
22
+ }
23
+ /** A leading Claude envelope that says the input is the harness's own. Self-contained: hook-fast.ts
24
+ * embeds this function into the small forwarder, so it must not read module scope. */
25
+ export declare function classifyClaudePromptText(text: unknown): InputClassification;
26
+ /** Classify a Claude input from every fact a caller has. Provenance comes first, then row shape,
27
+ * then the leading text; ordinary prose that happens to name a tag stays the owner's. */
28
+ export declare function classifyClaudeInput(facts: InputFacts): InputClassification;
29
+ /** The validated category a callback may carry, or undefined for anything else. */
30
+ export declare function parseInputCategory(value: unknown): InputCategory | undefined;
31
+ /** Bounded payload facts shared by the generated and full forwarders. Keep
32
+ * self-contained: the fast script embeds it without importing the bundle. */
33
+ export declare function claudeCallbackFacts(value: Record<string, unknown>): Record<string, unknown>;
@@ -0,0 +1,84 @@
1
+ // One answer to "whose input is this?", shared by the Claude transcript
2
+ // normalizer, the lifecycle callbacks, the reply preview and the raw final-turn
3
+ // accounting. A background task's notification, a teammate's message or a
4
+ // harness envelope belongs to the turn already running: it must never be
5
+ // mistaken for the owner asking something new.
6
+ //
7
+ // The classification is deliberately built from enumerated provenance and
8
+ // leading envelopes, never from "has an origin object" or from any mention of
9
+ // a tag in ordinary prose. Only public facts cross: no task output, no system
10
+ // payload, and no prompt text is kept here.
11
+ /** The provenances this Hook understands. Anything else is not automatic. */
12
+ const NOTIFICATION_ORIGINS = new Set(["task-notification", "teammate-message"]);
13
+ const INTERNAL_ORIGINS = new Set(["auto-continuation", "scheduled"]);
14
+ const MONITOR_NOTICE = /^(?:[⏺●]\s*)?Monitor event\b/;
15
+ /** A leading Claude envelope that says the input is the harness's own. Self-contained: hook-fast.ts
16
+ * embeds this function into the small forwarder, so it must not read module scope. */
17
+ export function classifyClaudePromptText(text) {
18
+ const value = typeof text === "string" ? text.trimStart().slice(0, 65_536) : "";
19
+ if (!value)
20
+ return { category: "internal", reason: "text:empty" };
21
+ if (value.startsWith("<task-notification>"))
22
+ return { category: "notification", reason: "envelope:task-notification" };
23
+ if (value.startsWith("<system-reminder>") && value.includes("<task-notification>"))
24
+ return { category: "notification", reason: "envelope:system-reminder" };
25
+ if (value.startsWith("[SYSTEM NOTIFICATION - NOT USER INPUT]"))
26
+ return { category: "notification", reason: "preamble:system-notification" };
27
+ if (value.startsWith("<teammate-message"))
28
+ return { category: "notification", reason: "envelope:teammate-message" };
29
+ if (/^<(?:environment_context>|user_instructions>|permission_profile|system-reminder>|turn_context>)/.test(value))
30
+ return { category: "internal", reason: "text:harness-preamble" };
31
+ return { category: "owner", reason: "text:owner-prompt" };
32
+ }
33
+ /** Classify a Claude input from every fact a caller has. Provenance comes first, then row shape,
34
+ * then the leading text; ordinary prose that happens to name a tag stays the owner's. */
35
+ export function classifyClaudeInput(facts) {
36
+ const origin = facts.origin && typeof facts.origin === "object" && !Array.isArray(facts.origin)
37
+ ? facts.origin : undefined;
38
+ const kind = origin && typeof origin.kind === "string" ? origin.kind : undefined;
39
+ if (kind && NOTIFICATION_ORIGINS.has(kind))
40
+ return { category: "notification", reason: `origin:${kind}` };
41
+ if (kind && INTERNAL_ORIGINS.has(kind))
42
+ return { category: "internal", reason: `origin:${kind}` };
43
+ if (facts.commandMode === "task-notification")
44
+ return { category: "notification", reason: "delivery:task-notification" };
45
+ const text = typeof facts.text === "string" ? facts.text : "";
46
+ // A Monitor notice is automatic only when it came through the notification
47
+ // delivery path; the same words typed by the owner are an ordinary prompt.
48
+ if (facts.notificationDelivery === true && MONITOR_NOTICE.test(text.trimStart())) {
49
+ return { category: "notification", reason: "delivery:monitor-notice" };
50
+ }
51
+ // An established notification envelope precedes the row's hidden/meta shape:
52
+ // Claude sometimes files a task notification as a hidden user row.
53
+ const leading = classifyClaudePromptText(text);
54
+ if (leading.category === "notification")
55
+ return leading;
56
+ if (facts.toolResult === true)
57
+ return { category: "internal", reason: "row:tool-result" };
58
+ if (facts.isSidechain === true)
59
+ return { category: "internal", reason: "row:sidechain" };
60
+ if (facts.isMeta === true)
61
+ return { category: "internal", reason: "row:meta" };
62
+ if (facts.isCompactSummary === true)
63
+ return { category: "internal", reason: "row:compact-summary" };
64
+ if (facts.hasImage && leading.reason === "text:empty")
65
+ return { category: "owner", reason: "row:image" };
66
+ return leading;
67
+ }
68
+ /** The validated category a callback may carry, or undefined for anything else. */
69
+ export function parseInputCategory(value) {
70
+ return value === "owner" || value === "notification" || value === "internal" ? value : undefined;
71
+ }
72
+ /** Bounded payload facts shared by the generated and full forwarders. Keep
73
+ * self-contained: the fast script embeds it without importing the bundle. */
74
+ export function claudeCallbackFacts(value) {
75
+ const origin = value.origin && typeof value.origin === "object" ? value.origin : {};
76
+ const execution = value.execution_id ?? value.executionId;
77
+ return {
78
+ ...(typeof execution === "string" && /^[A-Za-z0-9._:-]{1,128}$/.test(execution) ? { executionId: execution } : {}),
79
+ ...(typeof origin.kind === "string" ? { origin: { kind: origin.kind.slice(0, 80) } } : {}),
80
+ ...(typeof value.commandMode === "string" ? { commandMode: value.commandMode.slice(0, 80) } : {}),
81
+ ...Object.fromEntries(["isMeta", "isCompactSummary", "notificationDelivery", "toolResult", "hasImage"].filter(key => value[key] === true).map(key => [key, true])),
82
+ ...(Array.isArray(value.content) && value.content.some(block => block && typeof block === "object" && block.type === "image") ? { hasImage: true } : {}),
83
+ };
84
+ }
@@ -24,9 +24,9 @@ export declare function claudeTeachAutoModeDialog(screen: string): boolean;
24
24
  * phren-agent's numbered rows count only with their "Esc to cancel" footer,
25
25
  * OpenCode's only as its own permission prompt. */
26
26
  export declare function screenDialog(agent: string, screen: string): boolean;
27
- /** The status of a pane after a look at its screen: blocked while a working
28
- * agent shows a dialog there (`screenDialog`), else `base` unchanged. `read`
29
- * answers the pane's visible lines; it runs only for a working pane, at most
27
+ /** The status of a pane after a look at its screen: blocked while its agent
28
+ * shows a dialog there (`screenDialog`), working after a confirmed dialog disappears.
29
+ * `read` answers the pane's visible lines for working or blocked panes, at most
30
30
  * once per DIALOG_READ_MS per pane. */
31
31
  export declare function dialogStatus(server: string, pane: string, terminal: string, agent: string, base: {
32
32
  status: string;
@@ -11,7 +11,7 @@
11
11
  //
12
12
  // A harness that draws a permission dialog in its terminal with no hook
13
13
  // behind it (Codex, OpenCode, Copilot, Claude's auto-mode fallback) still
14
- // looks "working" to all of that. While a pane is working its screen is read,
14
+ // looks "working" to all of that. While a pane is working or blocked its screen is read,
15
15
  // at most once per DIALOG_READ_MS, and a dialog there makes the pane blocked
16
16
  // until the dialog is gone.
17
17
  //
@@ -26,7 +26,7 @@ import { claudeQuestionDialog } from "./claude-question-dialog.js";
26
26
  import { intervalFromEnv } from "./limits.js";
27
27
  import { object } from "./protocol.js";
28
28
  import { numberedDialog, opencodePermissionDialog, visibleTerminalChoice } from "./terminal-choice.js";
29
- /** A working pane's screen is read for a dialog at most once per this window. */
29
+ /** A working or blocked pane's screen is read for a dialog at most once per this window. */
30
30
  const DIALOG_READ_MS = intervalFromEnv("PHREN_DIALOG_THROTTLE_MS", 3_000);
31
31
  const EVENT_STATUS = {
32
32
  SessionStart: "idle", UserPromptSubmit: "working", PreToolUse: "working", PostToolUse: "working",
@@ -36,6 +36,8 @@ const EVENT_STATUS = {
36
36
  export function eventStatus(event) {
37
37
  return typeof event === "string" && Object.hasOwn(EVENT_STATUS, event) ? EVENT_STATUS[event] : undefined;
38
38
  }
39
+ /** Statuses a binding may persist as the turn's effective lifecycle state. */
40
+ const PERSISTED_STATUSES = new Set(["idle", "working", "blocked", "waiting", "done"]);
39
41
  const entries = new Map();
40
42
  /** Climbs with every change, like Herdr's state_change_seq, so the phone can order "just finished" first. */
41
43
  let sequence = 0;
@@ -80,7 +82,9 @@ export async function paneStatus(server, pane, terminal) {
80
82
  return undefined;
81
83
  try {
82
84
  const value = object(JSON.parse(await readFile(bindingPath(server, pane), "utf8")));
83
- const status = eventStatus(value.event);
85
+ // Prefer the effective status the callback wrote over the bare event map:
86
+ // a notification-associated Stop leaves the foreground turn working.
87
+ const status = typeof value.status === "string" && PERSISTED_STATUSES.has(value.status) ? value.status : eventStatus(value.event);
84
88
  if (value.terminal !== terminal || !status)
85
89
  return undefined;
86
90
  const at = Date.parse(String(value.at));
@@ -110,13 +114,13 @@ export function screenDialog(agent, screen) {
110
114
  return /Esc to cancel/i.test(text) && !!numberedDialog(text);
111
115
  }
112
116
  const dialogs = new Map();
113
- /** The status of a pane after a look at its screen: blocked while a working
114
- * agent shows a dialog there (`screenDialog`), else `base` unchanged. `read`
115
- * answers the pane's visible lines; it runs only for a working pane, at most
117
+ /** The status of a pane after a look at its screen: blocked while its agent
118
+ * shows a dialog there (`screenDialog`), working after a confirmed dialog disappears.
119
+ * `read` answers the pane's visible lines for working or blocked panes, at most
116
120
  * once per DIALOG_READ_MS per pane. */
117
121
  export async function dialogStatus(server, pane, terminal, agent, base, read) {
118
122
  const id = key(server, pane);
119
- if (base?.status !== "working") {
123
+ if (base?.status !== "working" && base?.status !== "blocked") {
120
124
  dialogs.delete(id);
121
125
  return base;
122
126
  }
@@ -135,7 +139,11 @@ export async function dialogStatus(server, pane, terminal, agent, base, read) {
135
139
  const shown = await read().then(screen => screenDialog(agent, screen), () => undefined);
136
140
  if (shown === true && !entry.shown)
137
141
  entry.shown = { at: now, seq: ++sequence };
138
- else if (shown === false && entry.shown) {
142
+ else if (shown === false && entry.shown && now - entry.shown.at >= 3_000) {
143
+ if (base.status === "blocked") {
144
+ settleBlockedPane(server, pane);
145
+ base = await paneStatus(server, pane, terminal) ?? base;
146
+ }
139
147
  entry.shown = undefined;
140
148
  entry.cleared = ++sequence;
141
149
  }
@@ -46,6 +46,12 @@ export declare const IN_FLIGHT_MS = 45000;
46
46
  * labels. */
47
47
  export declare function promptKey(text: string): string;
48
48
  export declare const promptHash: (text: string) => string;
49
+ /** One raw Claude transcript row and the byte offset it starts at: the queue rows a phone message's
50
+ * identity is read from. */
51
+ export interface ClaudeQueueRow {
52
+ offset: number;
53
+ raw: Json;
54
+ }
49
55
  /** One message per record, bound to the pane it was typed into (server, pane,
50
56
  * agent kind), not to the conversation: a Codex thread or a Claude /clear can
51
57
  * replace the conversation while the agent still holds the typed text, and
@@ -67,7 +73,9 @@ export declare class PromptDeliveries {
67
73
  private static open;
68
74
  /** Open, or failed with its own hook's claim still waiting for its row (a late delivery). */
69
75
  private static claimable;
70
- /** Codex messages whose `cursor` is still being read. */
76
+ /** The queue bindings last read from each Claude conversation, and the transcript revision they describe. */
77
+ private queueCache;
78
+ /** Messages whose `cursor` is still being read. */
71
79
  private cursors;
72
80
  /** The size of a conversation's transcript: 0 before it has one, undefined when it cannot be read. */
73
81
  private size;
@@ -101,11 +109,12 @@ export declare class PromptDeliveries {
101
109
  private release;
102
110
  private open;
103
111
  /** A message Phren typed into `target`'s pane that no conversation there has submitted yet. */
104
- pending(target: Target, text: string): boolean;
112
+ pending(target: Target, text: string, id?: string): boolean;
105
113
  /** Whether `record` still holds its pane: open, and either young or in a pane whose hooks will settle it. */
106
114
  private inFlight;
107
- /** Whether any message typed into `target`'s pane is still waiting to be taken or refused. */
108
- holding(target: Pick<Target, "server" | "pane" | "source">): boolean;
115
+ /** Whether any message typed into `target`'s pane is still waiting to be taken or refused.
116
+ * A pre-typing guard can exclude only its own freshly registered reservation by id. */
117
+ holding(target: Pick<Target, "server" | "pane" | "source">, exceptId?: string): boolean;
109
118
  /** Whether phone message `id` may still be taken: held by the agent, and in flight as `holding` counts it. */
110
119
  held(id: string, target: Pick<Target, "server" | "pane" | "source">): boolean;
111
120
  /** Wait again for a message `expect` reported pending, after a second Enter. */
@@ -131,6 +140,20 @@ export declare class PromptDeliveries {
131
140
  forPane(target: Pick<Target, "server" | "pane" | "source">): ({
132
141
  deliveryId: string;
133
142
  } & DeliveryStatus)[];
143
+ /** The phone delivery each of a Claude conversation's queue rows belongs to, by byte offset: the
144
+ * enqueue a message was typed as, the `remove`/`popAll` that took it back, the prompt turn that
145
+ * delivered it, and the `dequeue` that handed it to the model. Reads the transcript tail, binds
146
+ * any occurrence not bound yet, and keeps the binding in `<file>.queue.json`, so a reopened chat,
147
+ * a reconnect snapshot or a Hook restart gives the same row the same phone id. */
148
+ claudeQueueBindings(target: Pick<Target, "server" | "pane" | "source" | "session">, file: string): Promise<Map<number, string> | undefined>;
149
+ /** Bind parsed Claude queue rows (with their byte offsets) to the phone messages tracked in
150
+ * `target`, oldest occurrence first, per pane and conversation. A message binds at most one
151
+ * enqueue, one removal, one submitted turn and one dequeue; a repeated identical enqueue takes
152
+ * the next unbound message, never the same occurrence twice. Only rows after the cursor captured
153
+ * before the send was typed can be its own, so an earlier identical turn keeps its own identity.
154
+ * Only bindings are recorded here: an enqueue is still held, never taken, and a cancellation or
155
+ * `popAll` is not a delivery. */
156
+ bindClaudeQueueRows(target: Pick<Target, "server" | "pane" | "source" | "session">, rows: ClaudeQueueRow[]): Promise<Map<number, string>>;
134
157
  /** Conversation `target` just submitted `prompt`. Its own record wins, then
135
158
  * the oldest open one in the same pane: the agent kept the text across a
136
159
  * conversation change, and the conversation now in the pane is where it
@@ -158,6 +181,9 @@ export declare class PromptDeliveries {
158
181
  private locate;
159
182
  /** Marks `record` delivered, in `session` when given. */
160
183
  private settle;
184
+ /** Settlement needs the same occurrence ownership as a transcript read, even if no
185
+ * client has opened that conversation. Custom transcript readers supply their own bindings. */
186
+ private refreshClaudeQueue;
161
187
  /** Whether the transcript shows the agent took `record`'s message, claiming the entry it settled with.
162
188
  * An entry settles one message: the table of records' `entry` offsets (per conversation) is the only
163
189
  * state, so neither this path nor the hook's can settle two messages with one turn. A user row is a