@phren/cli 0.3.71 → 0.3.73

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 (164) hide show
  1. package/dist/bridge/agent-hooks.js +11 -1
  2. package/dist/bridge/browser-env.d.ts +5 -0
  3. package/dist/bridge/browser-env.js +110 -0
  4. package/dist/bridge/browser-protocol.d.ts +120 -0
  5. package/dist/bridge/browser-protocol.js +70 -0
  6. package/dist/bridge/browser-recordings.d.ts +63 -0
  7. package/dist/bridge/browser-recordings.js +148 -0
  8. package/dist/bridge/browser-registry.d.ts +64 -0
  9. package/dist/bridge/browser-registry.js +262 -0
  10. package/dist/bridge/browser-routes.d.ts +4 -0
  11. package/dist/bridge/browser-routes.js +39 -0
  12. package/dist/bridge/browser-shim/phren-playwright.cjs +184 -0
  13. package/dist/bridge/browser-socket.d.ts +2 -0
  14. package/dist/bridge/browser-socket.js +10 -0
  15. package/dist/bridge/browser-stream.d.ts +3 -0
  16. package/dist/bridge/browser-stream.js +129 -0
  17. package/dist/bridge/browser-watch.d.ts +12 -0
  18. package/dist/bridge/browser-watch.js +83 -0
  19. package/dist/bridge/claude-account-setup.js +3 -1
  20. package/dist/bridge/claude-accounts.d.ts +5 -1
  21. package/dist/bridge/claude-accounts.js +36 -6
  22. package/dist/bridge/codex-servers.d.ts +2 -0
  23. package/dist/bridge/codex-servers.js +1 -1
  24. package/dist/bridge/command.js +24 -5
  25. package/dist/bridge/dispatch-clone.d.ts +33 -0
  26. package/dist/bridge/dispatch-clone.js +176 -0
  27. package/dist/bridge/dispatch-command.d.ts +14 -0
  28. package/dist/bridge/dispatch-command.js +98 -13
  29. package/dist/bridge/dispatch-idempotency.d.ts +85 -0
  30. package/dist/bridge/dispatch-idempotency.js +235 -0
  31. package/dist/bridge/dispatch-returns.d.ts +6 -0
  32. package/dist/bridge/dispatch-returns.js +131 -1
  33. package/dist/bridge/dispatch-wait.d.ts +32 -0
  34. package/dist/bridge/dispatch-wait.js +177 -0
  35. package/dist/bridge/dispatch.d.ts +78 -2
  36. package/dist/bridge/dispatch.js +841 -25
  37. package/dist/bridge/dream-schedule.d.ts +133 -0
  38. package/dist/bridge/dream-schedule.js +322 -0
  39. package/dist/bridge/fanouts.js +20 -3
  40. package/dist/bridge/files.d.ts +1 -1
  41. package/dist/bridge/git-credential.d.ts +44 -0
  42. package/dist/bridge/git-credential.js +113 -0
  43. package/dist/bridge/git-host-auth.d.ts +9 -1
  44. package/dist/bridge/git-host-auth.js +18 -5
  45. package/dist/bridge/git-host-gitboy.js +8 -1
  46. package/dist/bridge/git-hosts.d.ts +12 -1
  47. package/dist/bridge/git-publish.js +3 -2
  48. package/dist/bridge/herdr.d.ts +4 -0
  49. package/dist/bridge/herdr.js +44 -9
  50. package/dist/bridge/install.d.ts +1 -1
  51. package/dist/bridge/install.js +12 -4
  52. package/dist/bridge/launch-brief.d.ts +11 -0
  53. package/dist/bridge/launch-brief.js +22 -0
  54. package/dist/bridge/launch-worktree.d.ts +2 -0
  55. package/dist/bridge/launch-worktree.js +5 -1
  56. package/dist/bridge/pane-status.js +1 -1
  57. package/dist/bridge/protocol.d.ts +7 -0
  58. package/dist/bridge/schedule-watch.js +13 -2
  59. package/dist/bridge/server-launch.d.ts +2 -0
  60. package/dist/bridge/server-launch.js +251 -145
  61. package/dist/bridge/server-routes.d.ts +3 -0
  62. package/dist/bridge/server-routes.js +33 -17
  63. package/dist/bridge/server-stream.d.ts +4 -0
  64. package/dist/bridge/server-stream.js +24 -5
  65. package/dist/bridge/server.js +35 -4
  66. package/dist/bridge/session-move.d.ts +10 -4
  67. package/dist/bridge/session-move.js +65 -34
  68. package/dist/bridge/simulator-stream.d.ts +2 -0
  69. package/dist/bridge/simulator-stream.js +2 -0
  70. package/dist/bridge/status-line-fast.d.ts +9 -0
  71. package/dist/bridge/status-line-fast.js +56 -0
  72. package/dist/bridge/tab-activity.d.ts +2 -0
  73. package/dist/bridge/tab-activity.js +15 -2
  74. package/dist/bridge/task-routes.d.ts +20 -16
  75. package/dist/bridge/task-routes.js +1 -1
  76. package/dist/bridge/terminal-herdr.d.ts +5 -1
  77. package/dist/bridge/terminal-herdr.js +67 -2
  78. package/dist/bridge/terminal-tmux.d.ts +2 -0
  79. package/dist/bridge/terminal-tmux.js +29 -7
  80. package/dist/bridge/terminal.d.ts +5 -1
  81. package/dist/bridge/transcript-claude.js +192 -112
  82. package/dist/bridge/transcript-preview.d.ts +2 -1
  83. package/dist/bridge/transcript-preview.js +85 -3
  84. package/dist/bridge/transcripts.js +17 -11
  85. package/dist/bridge/turn-records.js +16 -4
  86. package/dist/bridge/usage.d.ts +7 -1
  87. package/dist/bridge/usage.js +47 -31
  88. package/dist/bridge/worker-close.d.ts +15 -0
  89. package/dist/bridge/worker-close.js +304 -3
  90. package/dist/bridge/worker-identity.d.ts +51 -0
  91. package/dist/bridge/worker-identity.js +289 -0
  92. package/dist/bridge/worker-reports.js +15 -3
  93. package/dist/bridge-hook.mjs +39990 -36152
  94. package/dist/capabilities/mcp.js +1 -1
  95. package/dist/cli/browser-hint.d.ts +2 -0
  96. package/dist/cli/browser-hint.js +21 -0
  97. package/dist/cli/config-dreaming.d.ts +7 -0
  98. package/dist/cli/config-dreaming.js +72 -0
  99. package/dist/cli/config.js +6 -0
  100. package/dist/cli/dream.d.ts +59 -0
  101. package/dist/cli/dream.js +315 -0
  102. package/dist/cli/hooks-context.d.ts +2 -2
  103. package/dist/cli/hooks-context.js +3 -3
  104. package/dist/cli/hooks.js +20 -11
  105. package/dist/cli/namespaces-tasks.js +14 -0
  106. package/dist/cli-registry.js +28 -3
  107. package/dist/config/dreaming.d.ts +82 -0
  108. package/dist/config/dreaming.js +195 -0
  109. package/dist/config/resolve.js +11 -0
  110. package/dist/config/schema.d.ts +4 -4
  111. package/dist/config/schema.js +157 -1
  112. package/dist/content/citation-freshness.js +6 -0
  113. package/dist/content/learning.d.ts +1 -0
  114. package/dist/content/learning.js +2 -0
  115. package/dist/data/access.d.ts +1 -1
  116. package/dist/data/access.js +3 -1
  117. package/dist/data/task-contract.d.ts +5 -4
  118. package/dist/data/tasks.d.ts +5 -0
  119. package/dist/data/tasks.js +28 -2
  120. package/dist/dream/apply.d.ts +69 -0
  121. package/dist/dream/apply.js +372 -0
  122. package/dist/dream/budget.d.ts +78 -0
  123. package/dist/dream/budget.js +180 -0
  124. package/dist/dream/collect.d.ts +86 -0
  125. package/dist/dream/collect.js +449 -0
  126. package/dist/dream/eval/dream-adapter.d.ts +16 -0
  127. package/dist/dream/eval/dream-adapter.js +21 -0
  128. package/dist/dream/eval/fixture.d.ts +53 -0
  129. package/dist/dream/eval/fixture.js +172 -0
  130. package/dist/dream/eval/index.d.ts +40 -0
  131. package/dist/dream/eval/index.js +78 -0
  132. package/dist/dream/eval/score.d.ts +34 -0
  133. package/dist/dream/eval/score.js +99 -0
  134. package/dist/dream/eval/scripted-model.d.ts +19 -0
  135. package/dist/dream/eval/scripted-model.js +70 -0
  136. package/dist/dream/pages.d.ts +68 -0
  137. package/dist/dream/pages.js +220 -0
  138. package/dist/dream/privacy.d.ts +3 -0
  139. package/dist/dream/privacy.js +18 -0
  140. package/dist/dream/prompt.d.ts +13 -0
  141. package/dist/dream/prompt.js +84 -0
  142. package/dist/dream/run.d.ts +98 -0
  143. package/dist/dream/run.js +317 -0
  144. package/dist/dream/types.d.ts +74 -0
  145. package/dist/dream/types.js +4 -0
  146. package/dist/finding/lifecycle.d.ts +2 -2
  147. package/dist/finding/lifecycle.js +5 -2
  148. package/dist/finding/versions.d.ts +4 -0
  149. package/dist/finding/versions.js +28 -0
  150. package/dist/index.js +1 -0
  151. package/dist/modules/registry.js +10 -8
  152. package/dist/project-config.d.ts +3 -0
  153. package/dist/task/merge-links.d.ts +38 -0
  154. package/dist/task/merge-links.js +45 -0
  155. package/dist/task/reconcile.d.ts +39 -0
  156. package/dist/task/reconcile.js +201 -0
  157. package/dist/task/report-links.d.ts +10 -0
  158. package/dist/task/report-links.js +47 -0
  159. package/dist/tools/config.js +46 -4
  160. package/dist/tools/dispatch.js +2 -1
  161. package/dist/tools/dream.d.ts +3 -0
  162. package/dist/tools/dream.js +123 -0
  163. package/dist/tools/tasks.js +4 -1
  164. package/package.json +1 -1
@@ -1,5 +1,6 @@
1
1
  import { claudeQuestionResolutions, projectClaudeQuestionResolutions } from "./claude-question-lifecycle.js";
2
- import { readdir, realpath, lstat } from "node:fs/promises";
2
+ import { readdir, realpath } from "node:fs/promises";
3
+ import { lstatSync } from "node:fs";
3
4
  import { createHash } from "node:crypto";
4
5
  import { homedir } from "node:os";
5
6
  import { codexHome } from "../home-paths.js";
@@ -159,19 +160,24 @@ async function findPatternMatches(root, pattern) {
159
160
  const last = index === segments.length - 1;
160
161
  if (!segment.includes("*") && !segment.includes("?")) {
161
162
  const next = path.join(dir, segment);
163
+ // A Claude session is looked for in every project folder, and nearly all
164
+ // miss: a throwing lstat built an error for each one, the Hook's top cost.
165
+ let info;
162
166
  try {
163
- const info = await lstat(next);
164
- if (last) {
165
- // glob returns a symlink to a file here too; the caller's realpath
166
- // check is what rejects one pointing outside the provider folder.
167
- if (info.isFile() || info.isSymbolicLink())
168
- matches.push(next);
169
- }
170
- else if (info.isDirectory()) {
171
- await walk(next, index + 1);
172
- }
167
+ info = lstatSync(next, { throwIfNoEntry: false });
173
168
  }
174
169
  catch { /* no match */ }
170
+ if (!info)
171
+ return;
172
+ if (last) {
173
+ // glob returns a symlink to a file here too; the caller's realpath
174
+ // check is what rejects one pointing outside the provider folder.
175
+ if (info.isFile() || info.isSymbolicLink())
176
+ matches.push(next);
177
+ }
178
+ else if (info.isDirectory()) {
179
+ await walk(next, index + 1);
180
+ }
175
181
  return;
176
182
  }
177
183
  let entries;
@@ -174,13 +174,18 @@ export function backgroundLeft(count, stoppedAt, finishedTasks = []) {
174
174
  const stopped = Date.parse(stoppedAt);
175
175
  return Math.max(0, count - finishedTasks.filter(at => Date.parse(at) >= stopped).length);
176
176
  }
177
- async function readRecord(file) {
177
+ async function readRecord(file, cache) {
178
178
  try {
179
179
  const info = await lstat(file);
180
180
  if (!info.isFile() || info.size > MAX_RECORD_BYTES)
181
181
  return undefined;
182
+ const stamp = `${info.dev}:${info.ino}:${info.size}:${info.mtimeMs}`, cached = cache?.get(file);
183
+ if (cached?.stamp === stamp)
184
+ return cached.record;
182
185
  const parsed = turnRecordSchema.safeParse(JSON.parse(await readFile(file, "utf8")));
183
- return parsed.success ? parsed.data : undefined;
186
+ const record = parsed.success ? parsed.data : undefined;
187
+ cache?.set(file, { stamp, record });
188
+ return record;
184
189
  }
185
190
  catch {
186
191
  return undefined;
@@ -206,6 +211,9 @@ export function readTurn(server, pane) {
206
211
  }
207
212
  const STOP_TASKS_CACHE_MS = 2_000;
208
213
  let stopTasksCache;
214
+ /** Every pane's record, parsed, while its file is unchanged: the scan below runs every two seconds over
215
+ * hundreds of records, nearly all of them closed panes'. */
216
+ const stopRecordCache = new Map();
209
217
  /** The background tasks the latest Stop of conversation `session` listed, from whichever pane's record
210
218
  * holds it (the child tree knows the conversation, not its pane); undefined when no Stop listed any. */
211
219
  export async function latestStopTasks(source, session) {
@@ -216,10 +224,11 @@ export async function latestStopTasks(source, session) {
216
224
  // with the old process) outdates the list a closed pane's record still holds.
217
225
  // Panes are read in name order, and a record written in the same millisecond as another wins only when
218
226
  // its last event came after its own Stop (the pane that went on), so a tie never depends on directory order.
219
- const newest = new Map();
227
+ const newest = new Map(), seen = new Set();
220
228
  for (const server of (await readdir(root).catch(() => [])).sort()) {
221
229
  for (const name of (await readdir(path.join(root, server)).catch(() => [])).filter(name => name.endsWith(".json")).sort()) {
222
- const record = await readRecord(path.join(root, server, name));
230
+ seen.add(path.join(root, server, name));
231
+ const record = await readRecord(path.join(root, server, name), stopRecordCache);
223
232
  if (!record)
224
233
  continue;
225
234
  const key = `${record.source}\0${record.session}`, previous = newest.get(key);
@@ -228,6 +237,9 @@ export async function latestStopTasks(source, session) {
228
237
  newest.set(key, record);
229
238
  }
230
239
  }
240
+ for (const file of stopRecordCache.keys())
241
+ if (!seen.has(file))
242
+ stopRecordCache.delete(file);
231
243
  const found = new Map();
232
244
  for (const [key, record] of newest)
233
245
  if (record.stop?.tasks)
@@ -241,6 +241,12 @@ export declare class AccountUsageReader {
241
241
  private claude;
242
242
  private snapshotClaude;
243
243
  }
244
- /** Wrap an existing status line, preserving its input, output and options. */
244
+ /** Wrap the owner's status line, preserving its input, output and options. A status line already wrapped,
245
+ * by any node or Hook folder and any number of times over, is unwrapped to the owner's first, so one
246
+ * refresh never runs a chain of wrappers. */
245
247
  export declare function usageStatusLine(current: unknown, program: string, remove: boolean): unknown;
248
+ /** One status line report from Claude Code running in `configDir`: its normalized windows into that
249
+ * home's usage file and its session's cost into the home's ledger. Never session content. */
250
+ export declare function recordClaudeStatusLine(payload: unknown, configDir: string | undefined, now?: number): Promise<void>;
251
+ /** `bridge-hook.mjs usage-statusline`: the status line a version before the forwarder installed. */
246
252
  export declare function captureClaudeUsage(original: string): Promise<void>;
@@ -12,6 +12,7 @@ import { codexExecutable } from "./codex-binary.js";
12
12
  import { readSpeechKey } from "./speech-key.js";
13
13
  import { resolveSpeechRegion, SPEECH_REGIONS } from "./speech-voice.js";
14
14
  import { accountWindows } from "./account-choice.js";
15
+ import { unwrapStatusLine } from "./status-line-fast.js";
15
16
  import { CODEX_ACCOUNT, claudeAccountSubscription, claudeAccountEmail, claudeAccountRef, claudeAuthStatus, claudeHomeOfEnv, claudeHomes, claudePlanUnknown } from "./claude-accounts.js";
16
17
  import { claudeCredits, creditSummary, creditWindows, homeSessionCosts, recordSessionCost } from "./claude-credits.js";
17
18
  import { claudePlan, planName, subscriptionDate } from "./subscription.js";
@@ -953,27 +954,51 @@ export class AccountUsageReader {
953
954
  }
954
955
  }
955
956
  const quote = (value) => "'" + value.replace(/'/g, "'\\''") + "'";
956
- /** Wrap an existing status line, preserving its input, output and options. */
957
+ /** Wrap the owner's status line, preserving its input, output and options. A status line already wrapped,
958
+ * by any node or Hook folder and any number of times over, is unwrapped to the owner's first, so one
959
+ * refresh never runs a chain of wrappers. */
957
960
  export function usageStatusLine(current, program, remove) {
958
- const prefix = `${quote(process.execPath)} ${quote(program)} usage-statusline `;
959
- const command = object(current).command;
960
- if (typeof command === "string" && command.startsWith(prefix)) {
961
- if (!remove)
962
- return current;
963
- const encoded = command.slice(prefix.length);
964
- if (!/^[A-Za-z0-9+/=]+$/.test(encoded))
965
- throw new Error("Invalid Phren status line");
966
- return JSON.parse(Buffer.from(encoded, "base64").toString()) ?? undefined;
967
- }
961
+ const original = unwrapStatusLine(current) ?? undefined;
968
962
  if (remove)
969
- return current;
970
- if (current !== undefined && (object(current).type !== "command" || typeof command !== "string"))
971
- return current;
972
- const original = Buffer.from(JSON.stringify(current ?? null)).toString("base64");
973
- if (original.length > 32_768)
974
- return current;
975
- return { ...object(current), type: "command", command: prefix + original };
963
+ return original;
964
+ if (original !== undefined && (object(original).type !== "command" || typeof object(original).command !== "string"))
965
+ return original;
966
+ const encoded = Buffer.from(JSON.stringify(original ?? null)).toString("base64");
967
+ if (encoded.length > 32_768)
968
+ return original;
969
+ return { ...object(original), type: "command", command: `${quote(process.execPath)} ${quote(program)} usage-statusline ${encoded}` };
970
+ }
971
+ /** Last snapshot written per usage file, so a burst of refreshes with the same windows writes once. */
972
+ const statusLineWrites = new Map();
973
+ /** How long an unchanged snapshot goes unwritten; its `updatedAt` is how fresh the phone says it is. */
974
+ const STATUS_LINE_REWRITE_MS = 15_000;
975
+ const statusLineCosts = new Map();
976
+ /** One status line report from Claude Code running in `configDir`: its normalized windows into that
977
+ * home's usage file and its session's cost into the home's ledger. Never session content. */
978
+ export async function recordClaudeStatusLine(payload, configDir, now = Date.now()) {
979
+ // Homes are resolved without this process's CLAUDE_CONFIG_DIR: the reporter's own is `configDir`.
980
+ const home = claudeHomeOfEnv(configDir, { ...process.env, CLAUDE_CONFIG_DIR: undefined });
981
+ if (!home)
982
+ throw new Error("Unknown Claude home");
983
+ const snapshot = claudeUsage(payload, new Date(now));
984
+ const rate_limits = Object.fromEntries(snapshot.windows.map(w => [w.id, {
985
+ used_percentage: w.usedPercent, resets_at: w.resetsAt ? Date.parse(w.resetsAt) / 1000 : undefined,
986
+ }]));
987
+ const file = claudeFile(home), limits = JSON.stringify(rate_limits), last = statusLineWrites.get(file);
988
+ if (!last || last.limits !== limits || now - last.at >= STATUS_LINE_REWRITE_MS) {
989
+ await atomicInPrivateDir(file, JSON.stringify({ rate_limits, updatedAt: snapshot.updatedAt }));
990
+ statusLineWrites.set(file, { limits, at: now });
991
+ }
992
+ const value = object(payload), session = `${home.id}\0${String(value.session_id)}`, cost = object(value.cost).total_cost_usd;
993
+ if (statusLineCosts.get(session) === cost)
994
+ return;
995
+ await recordSessionCost(home, payload).catch(() => undefined);
996
+ statusLineCosts.delete(session);
997
+ statusLineCosts.set(session, cost);
998
+ while (statusLineCosts.size > 256)
999
+ statusLineCosts.delete(statusLineCosts.keys().next().value);
976
1000
  }
1001
+ /** `bridge-hook.mjs usage-statusline`: the status line a version before the forwarder installed. */
977
1002
  export async function captureClaudeUsage(original) {
978
1003
  if (!/^[A-Za-z0-9+/=]{1,32768}$/.test(original))
979
1004
  return;
@@ -983,22 +1008,13 @@ export async function captureClaudeUsage(original) {
983
1008
  if (Buffer.byteLength(input) > 1_048_576)
984
1009
  return;
985
1010
  }
1011
+ // The home Claude runs in names the file; an unknown CLAUDE_CONFIG_DIR records nothing.
986
1012
  try {
987
- // The home Claude runs in names the file; an unknown CLAUDE_CONFIG_DIR records nothing.
988
- // Homes are resolved without this process's CLAUDE_CONFIG_DIR: that is the account's own dir here, not the default.
989
- const home = claudeHomeOfEnv(process.env.CLAUDE_CONFIG_DIR, { ...process.env, CLAUDE_CONFIG_DIR: undefined });
990
- if (!home)
991
- throw new Error("Unknown Claude home");
992
- const snapshot = claudeUsage(JSON.parse(input));
993
- // Persist only normalized percentages/reset times; never session content.
994
- const rate_limits = Object.fromEntries(snapshot.windows.map(w => [w.id, {
995
- used_percentage: w.usedPercent, resets_at: w.resetsAt ? Date.parse(w.resetsAt) / 1000 : undefined,
996
- }]));
997
- await atomicInPrivateDir(claudeFile(home), JSON.stringify({ rate_limits, updatedAt: snapshot.updatedAt }));
998
- await recordSessionCost(home, JSON.parse(input)).catch(() => undefined);
1013
+ await recordClaudeStatusLine(JSON.parse(input), process.env.CLAUDE_CONFIG_DIR);
999
1014
  }
1000
1015
  catch { /* Status line rendering must survive unavailable usage storage. */ }
1001
- const previous = object(JSON.parse(Buffer.from(original, "base64").toString()));
1016
+ // A wrapper of a wrapper (an install under another node) runs the owner's status line once, not the chain.
1017
+ const previous = object(unwrapStatusLine(JSON.parse(Buffer.from(original, "base64").toString())));
1002
1018
  if (typeof previous.command === "string") {
1003
1019
  await new Promise(resolve => {
1004
1020
  // This is the user's original status-line command, invoked just as
@@ -1,9 +1,24 @@
1
1
  import { type Json, type Target, type StartingTarget } from "./protocol.js";
2
2
  import type { HandOffQueue } from "./hand-off-queue.js";
3
+ import { type Receipt } from "./dispatch.js";
3
4
  type ClosedTarget = Target | StartingTarget;
4
5
  export declare function markWorkerClosed(target: ClosedTarget, terminal: string): Promise<void>;
5
6
  export declare function intentionallyClosed(target: ClosedTarget): Promise<boolean>;
6
7
  export declare function markPaneClosed(server: string, pane: Json): Promise<void>;
8
+ /** Whether this pane still runs the session (or starting binding) the dispatch recorded. */
9
+ export type PaneBinding = "match" | "different" | "unknown";
10
+ /** The exact recorded binding: the session id, or a starting target's starting token. */
11
+ export declare function paneBinding(target: Target | StartingTarget, pane: Json | undefined, chat: Json): PaneBinding;
12
+ export declare function paneRunsTarget(target: Target | StartingTarget, pane: Json | undefined, chat: Json): boolean;
13
+ /**
14
+ * Cancel a running dispatch by id or idempotency key. The intent is recorded
15
+ * first; the pane is closed only while it still runs the recorded session, and
16
+ * the terminal `cancelled` return is written only after the pane is confirmed
17
+ * gone. A close that cannot be confirmed leaves the intent for a later retry.
18
+ */
19
+ export declare function cancelDispatch(input: unknown): Promise<Json>;
20
+ /** The one close path: exact binding, confirmed snapshot, terminal return only after it is gone. */
21
+ export declare function closeVerifiedWorker(receipt: Receipt): Promise<Json>;
7
22
  /** Called on the worker's computer only after the sender read the done return.
8
23
  * Recheck this exact ended turn and skip any new work, background work or inbox. */
9
24
  export declare function closeFinishedWorker(input: unknown, queue?: HandOffQueue): Promise<Json>;
@@ -2,11 +2,14 @@ import { createHash } from "node:crypto";
2
2
  import { lstat, readFile, rm } from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { z } from "zod";
5
- import { atomicInPrivateDir, BridgeError, bridgeRoot, targetSchema, startingTargetSchema } from "./protocol.js";
6
- import { validateTarget, paneChatState } from "./herdr.js";
5
+ import { atomicInPrivateDir, BridgeError, bridgeRoot, objects, targetSchema, startingTargetSchema } from "./protocol.js";
6
+ import { validateTarget, paneChatState, paneStartingToken, clearStartingToken, clearStartingTokenByToken } from "./herdr.js";
7
7
  import { terminalProvider } from "./terminal.js";
8
8
  import { paneTurn, workerStates, workerTurnKey } from "./dispatch-returns.js";
9
- import { originPaneSchema } from "./dispatch.js";
9
+ import { originPaneSchema, scanStartingToken, settleCancelledReservation, startingTargetFromPane, updateReceipt } from "./dispatch.js";
10
+ import { idempotencyKeySchema, withIdempotencyKeyLock } from "./dispatch-idempotency.js";
11
+ import { dispatchClonePaths, removeDispatchClone, removeDispatchSecrets } from "./dispatch-clone.js";
12
+ import { launchInProgress, removeWorkerFile, terminateWorker, workerAlive, workerPid } from "./worker-identity.js";
10
13
  const closedTargetSchema = z.union([targetSchema, startingTargetSchema]);
11
14
  const file = (target) => path.join(bridgeRoot(), "closed-workers", `${createHash("sha256").update(JSON.stringify([target.server, target.workspace, target.tab, target.pane, target.source, "session" in target ? target.session : target.startingToken])).digest("hex")}.json`);
12
15
  export async function markWorkerClosed(target, terminal) {
@@ -38,6 +41,294 @@ export async function markPaneClosed(server, pane) {
38
41
  if (starting.success)
39
42
  await markWorkerClosed(starting.data, String(pane.terminal_id));
40
43
  }
44
+ /** The exact recorded binding: the session id, or a starting target's starting token. */
45
+ export function paneBinding(target, pane, chat) {
46
+ if (!pane || pane.agent !== target.source)
47
+ return "different";
48
+ const paneSession = typeof pane.sessionId === "string" ? pane.sessionId : typeof pane.session_id === "string" ? pane.session_id : undefined;
49
+ if ("session" in target) {
50
+ const actual = paneSession ?? (typeof chat.sessionId === "string" ? chat.sessionId : undefined);
51
+ if (!actual)
52
+ return "unknown";
53
+ return actual === target.session ? "match" : "different";
54
+ }
55
+ const token = typeof pane.startingToken === "string" ? pane.startingToken
56
+ : typeof chat.startingToken === "string" ? chat.startingToken : undefined;
57
+ if (!token)
58
+ return "unknown";
59
+ return token === target.startingToken ? "match" : "different";
60
+ }
61
+ export function paneRunsTarget(target, pane, chat) {
62
+ return paneBinding(target, pane, chat) === "match";
63
+ }
64
+ async function retainCancelled(dispatchId, duringPlacement, paths) {
65
+ await finalizeCancelled(dispatchId, duringPlacement);
66
+ await removeDispatchSecrets(paths);
67
+ await updateReceipt(dispatchId, value => {
68
+ const ended = value.endedAt ?? value.closedAt ?? new Date().toISOString();
69
+ if (!value.endedAt)
70
+ value.endedAt = ended;
71
+ if (!value.retainedUntil)
72
+ value.retainedUntil = new Date(Date.parse(ended) + 7 * 24 * 60 * 60_000).toISOString();
73
+ return true;
74
+ }).catch(() => undefined);
75
+ }
76
+ async function finalizeCancelled(dispatchId, duringPlacement = false) {
77
+ const at = new Date().toISOString();
78
+ let cancelled = false;
79
+ await updateReceipt(dispatchId, value => {
80
+ if (value.closedAt)
81
+ return false;
82
+ value.closedAt = at;
83
+ value.state = "failed";
84
+ value.error = "cancelled";
85
+ value.returned = { state: "failed", at, error: "cancelled", read: false };
86
+ cancelled = true;
87
+ return true;
88
+ }, { duringPlacement });
89
+ return cancelled;
90
+ }
91
+ /**
92
+ * Cancel a running dispatch by id or idempotency key. The intent is recorded
93
+ * first; the pane is closed only while it still runs the recorded session, and
94
+ * the terminal `cancelled` return is written only after the pane is confirmed
95
+ * gone. A close that cannot be confirmed leaves the intent for a later retry.
96
+ */
97
+ export async function cancelDispatch(input) {
98
+ const data = z.union([
99
+ z.object({ dispatch: z.string().uuid() }).strict(),
100
+ z.object({ idempotencyKey: idempotencyKeySchema }).strict(),
101
+ ]).parse(input);
102
+ let dispatchId;
103
+ let record = undefined;
104
+ let placement = false;
105
+ let receipt;
106
+ const mark = (value, at) => {
107
+ placement = value.state === "launching" || value.state === "sending";
108
+ if (value.cancelRequestedAt)
109
+ return false;
110
+ value.cancelRequestedAt = at;
111
+ return true;
112
+ };
113
+ if ("dispatch" in data) {
114
+ dispatchId = data.dispatch;
115
+ receipt = await updateReceipt(dispatchId, value => mark(value, new Date().toISOString()), { duringPlacement: true });
116
+ }
117
+ else {
118
+ // The key lock serializes this marker with first-receipt creation.
119
+ await withIdempotencyKeyLock(data.idempotencyKey, async (current, save) => {
120
+ record = current;
121
+ dispatchId = current?.dispatchId;
122
+ if (!dispatchId)
123
+ return;
124
+ const at = new Date().toISOString();
125
+ const updated = await updateReceipt(dispatchId, value => mark(value, at), { duringPlacement: true });
126
+ if (updated)
127
+ receipt = updated;
128
+ else if (current && !current.cancelRequestedAt) {
129
+ current.cancelRequestedAt = at;
130
+ await save(current);
131
+ }
132
+ });
133
+ }
134
+ // An unknown key names no dispatch; a known one whose receipt is gone still
135
+ // answers with the id it named.
136
+ if (!dispatchId)
137
+ return { ok: true, closed: false };
138
+ if (!receipt) {
139
+ // Assigned inside the lock callback, so read it through its declared type.
140
+ const reserved = record;
141
+ if (reserved && (reserved.phase === "reserved" || reserved.phase === "launching")) {
142
+ if (await launchInProgress(reserved.dispatchId))
143
+ return { ok: true, dispatch: dispatchId, closed: false, pending: true };
144
+ await settleCancelledReservation(reserved);
145
+ return { ok: true, dispatch: dispatchId, closed: false };
146
+ }
147
+ return { ok: true, dispatch: dispatchId, closed: false };
148
+ }
149
+ if (receipt.closedAt)
150
+ return { ok: true, dispatch: dispatchId, closed: false };
151
+ // The launcher sees cancelRequestedAt and closes the pane it just created;
152
+ // this call reports the intent as pending.
153
+ if (placement)
154
+ return { ok: true, dispatch: dispatchId, closed: false, pending: true };
155
+ return closeVerifiedWorker(receipt);
156
+ }
157
+ /** Close the recorded pane only after the worker is gone and the pane is just its shell. */
158
+ async function closeIdlePane(server, target) {
159
+ try {
160
+ const snapshot = await terminalProvider().snapshot(server);
161
+ const pane = objects(snapshot.panes).find(p => p.pane_id === target.pane && p.tab_id === target.tab && p.workspace_id === target.workspace);
162
+ if (!pane || typeof pane.pane_id !== "string")
163
+ return;
164
+ const info = await terminalProvider().processes(server, pane.pane_id).catch(() => undefined);
165
+ // A replacement session in this pane is running something other than the
166
+ // shell; never close it. Only a bare shell prompt is safe to close.
167
+ if (!info || info.shellPid === undefined || info.foregroundPids.length === 0)
168
+ return;
169
+ if (!info.foregroundPids.every(pid => pid === info.shellPid))
170
+ return;
171
+ await terminalProvider().closePane(server, pane.pane_id).catch(() => undefined);
172
+ }
173
+ catch { /* leave the pane */ }
174
+ }
175
+ /** A keyed worker is closed by its durable process identity, never by a pane's inherited token. */
176
+ async function closeKeyedWorker(receipt, duringPlacement, cleanupPaths) {
177
+ const dispatchId = receipt.id;
178
+ const finalize = async (closed) => {
179
+ await retainCancelled(dispatchId, duringPlacement, cleanupPaths);
180
+ await removeWorkerFile(dispatchId);
181
+ clearStartingTokenByToken(receipt.startingToken ?? "");
182
+ return { ok: true, dispatch: dispatchId, closed, ...(closed ? {} : { gone: true }) };
183
+ };
184
+ const alive = await workerAlive(dispatchId, receipt.workerFile, receipt.submittedAt);
185
+ if (alive === "unknown")
186
+ return { ok: true, dispatch: dispatchId, closed: false, pending: true };
187
+ const closePaneIfIdle = async () => {
188
+ const server = receipt.launchServer ?? receipt.target?.server;
189
+ if (server && receipt.target)
190
+ await closeIdlePane(server, receipt.target);
191
+ };
192
+ if (alive === "gone") {
193
+ await closePaneIfIdle();
194
+ return finalize(false);
195
+ }
196
+ const worker = await workerPid(dispatchId, receipt.workerFile);
197
+ if (!worker)
198
+ return { ok: true, dispatch: dispatchId, closed: false, pending: true };
199
+ // Terminate through the recorded process identity first; never signal or
200
+ // close based on a PID match alone.
201
+ await terminateWorker(worker.pid, worker.start);
202
+ if (await workerAlive(dispatchId, receipt.workerFile, receipt.submittedAt) !== "gone") {
203
+ return { ok: true, dispatch: dispatchId, closed: false, pending: true };
204
+ }
205
+ await closePaneIfIdle();
206
+ return finalize(true);
207
+ }
208
+ /** The one close path: exact binding, confirmed snapshot, terminal return only after it is gone. */
209
+ export async function closeVerifiedWorker(receipt) {
210
+ const dispatchId = receipt.id;
211
+ const duringPlacement = receipt.state === "launching" || receipt.state === "sending";
212
+ const cleanupPaths = receipt.idempotencyKey
213
+ ? dispatchClonePaths(receipt.id)
214
+ : { cloneDir: receipt.cloneDir, gitConfigFile: receipt.gitConfigFile, agentTokenFile: receipt.agentTokenFile };
215
+ if (receipt.idempotencyKey)
216
+ return closeKeyedWorker(receipt, duringPlacement, cleanupPaths);
217
+ let target = receipt.target;
218
+ if (!target) {
219
+ // A launch whose reply was lost may still have started its worker: take
220
+ // the binding from the worker's own arrival record when there is one.
221
+ const { briefArrival } = await import("./launch-brief.js");
222
+ const arrival = await briefArrival(dispatchId).catch(() => undefined);
223
+ target = arrival?.accepted?.target ?? arrival?.started?.target;
224
+ if (target) {
225
+ receipt.target = target;
226
+ receipt.launchOutcome = "started";
227
+ await updateReceipt(dispatchId, value => {
228
+ if (!value.target)
229
+ value.target = target;
230
+ value.launchOutcome = "started";
231
+ return true;
232
+ }, { duringPlacement: true }).catch(() => undefined);
233
+ }
234
+ }
235
+ if (!target && receipt.launchOutcome === "not-started") {
236
+ // The launch request was never sent (or was refused before creating
237
+ // anything): no worker can be running, so finalize without a scan.
238
+ await retainCancelled(dispatchId, duringPlacement, cleanupPaths);
239
+ clearStartingTokenByToken(receipt.startingToken ?? "");
240
+ return { ok: true, dispatch: dispatchId, closed: false, gone: true };
241
+ }
242
+ if (!target) {
243
+ // The launch's own starting token is the proof: a successful snapshot
244
+ // with no pane carrying it, and no recovered session, means no worker.
245
+ const scan = await scanStartingToken(receipt);
246
+ if (scan.ok && scan.pane) {
247
+ const adopted = startingTargetFromPane(receipt, scan.pane);
248
+ if (adopted) {
249
+ target = adopted;
250
+ receipt.target = adopted;
251
+ receipt.launchOutcome = "started";
252
+ await updateReceipt(dispatchId, value => {
253
+ if (!value.target)
254
+ value.target = adopted;
255
+ value.launchOutcome = "started";
256
+ return true;
257
+ }, { duringPlacement: true }).catch(() => undefined);
258
+ }
259
+ }
260
+ else if (scan.ok && !duringPlacement) {
261
+ await retainCancelled(dispatchId, duringPlacement, cleanupPaths);
262
+ clearStartingTokenByToken(receipt.startingToken ?? "");
263
+ return { ok: true, dispatch: dispatchId, closed: false, gone: true };
264
+ }
265
+ }
266
+ if (!target)
267
+ return { ok: true, dispatch: dispatchId, closed: false, pending: true };
268
+ const { snapshot, findPane } = await import("./herdr.js");
269
+ for (let attempt = 0; attempt < 3; attempt++) {
270
+ if (attempt)
271
+ await new Promise(resolve => setTimeout(resolve, attempt === 1 ? 100 : 300));
272
+ let before;
273
+ try {
274
+ before = await snapshot(target.server);
275
+ }
276
+ catch {
277
+ return { ok: true, dispatch: dispatchId, closed: false, pending: true };
278
+ }
279
+ const pane = findPane(before, target);
280
+ if (!pane) {
281
+ // A successful snapshot with no pane is a vanished worker; a failed
282
+ // snapshot above stays pending instead of claiming success.
283
+ await retainCancelled(dispatchId, duringPlacement, cleanupPaths);
284
+ clearStartingTokenByToken(receipt.startingToken ?? "");
285
+ return { ok: true, dispatch: dispatchId, closed: false, gone: true };
286
+ }
287
+ const paneSession = typeof pane.sessionId === "string" ? pane.sessionId : typeof pane.session_id === "string" ? pane.session_id : undefined;
288
+ const paneToken = typeof pane.startingToken === "string" ? pane.startingToken : paneStartingToken(target.server, pane);
289
+ let chat = {};
290
+ if (!paneSession && !paneToken) {
291
+ try {
292
+ chat = await paneChatState(target.server, pane, { tokenWhenIdentified: false });
293
+ }
294
+ catch {
295
+ return { ok: true, dispatch: dispatchId, closed: false, pending: true };
296
+ }
297
+ }
298
+ const observed = paneToken && typeof pane.startingToken !== "string" ? { ...pane, startingToken: paneToken } : pane;
299
+ const binding = paneBinding(target, observed, chat);
300
+ if (binding === "different") {
301
+ // A replacement session now owns the pane: never close it.
302
+ return { ok: true, dispatch: dispatchId, closed: false };
303
+ }
304
+ if (binding === "unknown") {
305
+ // Missing identity evidence: fail closed and retry later.
306
+ return { ok: true, dispatch: dispatchId, closed: false, pending: true };
307
+ }
308
+ await markPaneClosed(target.server, pane).catch(() => undefined);
309
+ await terminalProvider().closePane(target.server, target.pane).catch(() => undefined);
310
+ let after;
311
+ try {
312
+ after = await snapshot(target.server);
313
+ }
314
+ catch {
315
+ return { ok: true, dispatch: dispatchId, closed: false, pending: true };
316
+ }
317
+ if (!findPane(after, target)) {
318
+ await retainCancelled(dispatchId, duringPlacement, cleanupPaths);
319
+ clearStartingTokenByToken(receipt.startingToken ?? "");
320
+ return { ok: true, dispatch: dispatchId, closed: true };
321
+ }
322
+ }
323
+ // The intent stays recorded; a later close retries it.
324
+ return { ok: true, dispatch: dispatchId, closed: false, pending: true };
325
+ }
326
+ /** The Hook that launched the worker owns its clone and token: a confirmed close removes both. */
327
+ async function releaseClosedFiles(dispatchId) {
328
+ const paths = dispatchClonePaths(dispatchId);
329
+ await removeDispatchSecrets(paths);
330
+ await removeDispatchClone(paths);
331
+ }
41
332
  /** Called on the worker's computer only after the sender read the done return.
42
333
  * Recheck this exact ended turn and skip any new work, background work or inbox. */
43
334
  export async function closeFinishedWorker(input, queue) {
@@ -76,6 +367,16 @@ export async function closeFinishedWorker(input, queue) {
76
367
  await rm(file(data.target), { force: true });
77
368
  throw error;
78
369
  }
370
+ // Clean up files only for the dispatch durably bound to this exact pane and
371
+ // session: a request naming another dispatch must never delete its clone.
372
+ const owner = await updateReceipt(data.dispatch, () => false).catch(() => undefined);
373
+ const bound = owner?.target && owner.target.server === data.target.server && owner.target.pane === data.target.pane
374
+ && owner.target.workspace === data.target.workspace && owner.target.tab === data.target.tab
375
+ // A starting target has no session yet: the binding can't be proven, so no cleanup.
376
+ && "session" in owner.target && owner.target.session === data.target.session;
377
+ if (bound)
378
+ await releaseClosedFiles(data.dispatch);
379
+ clearStartingToken(data.target.server, pane);
79
380
  return { ok: true, closed: true };
80
381
  }
81
382
  /** An agent closing the pane it runs in, once its work is committed and reported:
@@ -0,0 +1,51 @@
1
+ export interface LaunchLock {
2
+ file: string;
3
+ nonce: string;
4
+ pid: number;
5
+ start?: string;
6
+ }
7
+ export type WorkerLiveness = "alive" | "gone" | "unknown";
8
+ export declare const SUBMITTED_GRACE_MS = 120000;
9
+ export declare function workerFilePath(id: string): string;
10
+ export declare function launchLockFile(id: string): string;
11
+ export declare function submittedFilePath(id: string): string;
12
+ /** Mark a launch as submitted before its command is typed or spawned. */
13
+ export declare function markSubmitted(id: string, at?: Date): Promise<string>;
14
+ /** The process's start time, or undefined when no process has that PID. Throws when ps itself fails. */
15
+ export declare function processStartTime(pid: number): Promise<string | undefined>;
16
+ /** Whether the PID still belongs to the process that wrote `start`. */
17
+ export declare function processMatches(pid: number, start: string | undefined): Promise<WorkerLiveness>;
18
+ /** The recorded worker process, if the identity file is readable and well-formed. */
19
+ export declare function workerPid(id: string, file?: string): Promise<{
20
+ pid: number;
21
+ start: string;
22
+ } | undefined>;
23
+ /** A held launch lock whose owner is alive means the launch is still placing. */
24
+ export declare function launchInProgress(id: string): Promise<boolean>;
25
+ export type WorkerScan = {
26
+ ok: true;
27
+ worker?: {
28
+ pid: number;
29
+ start: string;
30
+ };
31
+ } | {
32
+ ok: false;
33
+ };
34
+ type ProcessScanner = (file: string) => Promise<WorkerScan>;
35
+ /** Only for tests: replace the real same-user process scan. */
36
+ export declare function setWorkerProcessScan(scanner: ProcessScanner | undefined): void;
37
+ /**
38
+ * The worker's liveness. A present identity file is authoritative. Without one,
39
+ * a same-user process carrying this launch's worker-file marker is adopted;
40
+ * otherwise the submitted marker and the launch lock decide whether no worker
41
+ * can still be starting.
42
+ */
43
+ export declare function workerAlive(id: string, file?: string, submittedAt?: string): Promise<WorkerLiveness>;
44
+ /** Hold the launch lock for one keyed dispatch; a stale lock is replaced. */
45
+ export declare function acquireLaunchLock(id: string): Promise<LaunchLock>;
46
+ export declare function releaseLaunchLock(lock: LaunchLock): Promise<void>;
47
+ /** Remove the worker identity and its temporary file after a confirmed termination. */
48
+ export declare function removeWorkerFile(id: string): Promise<void>;
49
+ /** SIGTERM the recorded process, then SIGKILL it if the same process is still alive after 10 s. */
50
+ export declare function terminateWorker(pid: number, start: string): Promise<void>;
51
+ export {};