@phren/cli 0.3.11 → 0.3.13

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 (182) hide show
  1. package/dist/bridge/account-usage.d.ts +124 -0
  2. package/dist/bridge/account-usage.js +258 -0
  3. package/dist/bridge/agent-hook-stores.d.ts +3 -0
  4. package/dist/bridge/agent-hook-stores.js +5 -0
  5. package/dist/bridge/agent-hooks.d.ts +162 -5
  6. package/dist/bridge/agent-hooks.js +682 -49
  7. package/dist/bridge/approval-summary.d.ts +16 -0
  8. package/dist/bridge/approval-summary.js +133 -0
  9. package/dist/bridge/authority-command.d.ts +20 -0
  10. package/dist/bridge/authority-command.js +120 -0
  11. package/dist/bridge/authority.d.ts +223 -0
  12. package/dist/bridge/authority.js +231 -0
  13. package/dist/bridge/claude-account-setup.d.ts +14 -0
  14. package/dist/bridge/claude-account-setup.js +69 -0
  15. package/dist/bridge/claude-accounts.d.ts +49 -0
  16. package/dist/bridge/claude-accounts.js +195 -0
  17. package/dist/bridge/code-routes.js +2 -2
  18. package/dist/bridge/codex-app-server.d.ts +144 -0
  19. package/dist/bridge/codex-app-server.js +319 -0
  20. package/dist/bridge/codex-auth-refresh.d.ts +33 -0
  21. package/dist/bridge/codex-auth-refresh.js +71 -0
  22. package/dist/bridge/codex-hook-trust.d.ts +27 -0
  23. package/dist/bridge/codex-hook-trust.js +237 -0
  24. package/dist/bridge/codex-question-reply.d.ts +16 -0
  25. package/dist/bridge/codex-question-reply.js +57 -0
  26. package/dist/bridge/codex-review-mode.d.ts +10 -0
  27. package/dist/bridge/codex-review-mode.js +74 -0
  28. package/dist/bridge/codex-servers.d.ts +217 -0
  29. package/dist/bridge/codex-servers.js +636 -0
  30. package/dist/bridge/command.js +97 -4
  31. package/dist/bridge/computer-identity.d.ts +75 -0
  32. package/dist/bridge/computer-identity.js +166 -0
  33. package/dist/bridge/conductor-group.d.ts +91 -8
  34. package/dist/bridge/conductor-group.js +105 -9
  35. package/dist/bridge/conductor-role.d.ts +94 -0
  36. package/dist/bridge/conductor-role.js +176 -0
  37. package/dist/bridge/conductor-sets.d.ts +20 -0
  38. package/dist/bridge/conductor-sets.js +59 -0
  39. package/dist/bridge/dispatch-command.d.ts +3 -0
  40. package/dist/bridge/dispatch-command.js +82 -12
  41. package/dist/bridge/dispatch-returns.d.ts +128 -19
  42. package/dist/bridge/dispatch-returns.js +371 -54
  43. package/dist/bridge/dispatch.d.ts +128 -3
  44. package/dist/bridge/dispatch.js +303 -42
  45. package/dist/bridge/fanouts.d.ts +7 -1
  46. package/dist/bridge/fanouts.js +39 -4
  47. package/dist/bridge/folder-trust.d.ts +56 -0
  48. package/dist/bridge/folder-trust.js +195 -0
  49. package/dist/bridge/grants.d.ts +22 -1
  50. package/dist/bridge/grants.js +57 -9
  51. package/dist/bridge/hand-off-queue.d.ts +74 -0
  52. package/dist/bridge/hand-off-queue.js +235 -0
  53. package/dist/bridge/hand-off.d.ts +30 -10
  54. package/dist/bridge/hand-off.js +79 -46
  55. package/dist/bridge/harness-status.d.ts +11 -0
  56. package/dist/bridge/harness-status.js +32 -0
  57. package/dist/bridge/harnesses.d.ts +39 -0
  58. package/dist/bridge/harnesses.js +65 -0
  59. package/dist/bridge/health.d.ts +2 -0
  60. package/dist/bridge/health.js +1 -1
  61. package/dist/bridge/herdr.d.ts +11 -2
  62. package/dist/bridge/herdr.js +98 -23
  63. package/dist/bridge/hook-fast.d.ts +4 -0
  64. package/dist/bridge/hook-fast.js +68 -0
  65. package/dist/bridge/install.d.ts +16 -1
  66. package/dist/bridge/install.js +102 -21
  67. package/dist/bridge/launch-brief.d.ts +96 -0
  68. package/dist/bridge/launch-brief.js +164 -0
  69. package/dist/bridge/model-switch.d.ts +3 -0
  70. package/dist/bridge/model-switch.js +17 -1
  71. package/dist/bridge/models.d.ts +8 -4
  72. package/dist/bridge/models.js +24 -8
  73. package/dist/bridge/mux-wire.d.ts +9 -0
  74. package/dist/bridge/mux-wire.js +19 -0
  75. package/dist/bridge/opencode-pane-server.d.ts +113 -0
  76. package/dist/bridge/opencode-pane-server.js +332 -0
  77. package/dist/bridge/opencode-panes.d.ts +111 -0
  78. package/dist/bridge/opencode-panes.js +295 -0
  79. package/dist/bridge/pane-accounts.d.ts +8 -0
  80. package/dist/bridge/pane-accounts.js +46 -0
  81. package/dist/bridge/pane-status.d.ts +12 -0
  82. package/dist/bridge/pane-status.js +50 -1
  83. package/dist/bridge/prompt-startup.d.ts +5 -0
  84. package/dist/bridge/prompt-startup.js +24 -0
  85. package/dist/bridge/protocol.d.ts +5 -0
  86. package/dist/bridge/protocol.js +4 -0
  87. package/dist/bridge/push.d.ts +11 -4
  88. package/dist/bridge/push.js +27 -4
  89. package/dist/bridge/questions.d.ts +37 -2
  90. package/dist/bridge/questions.js +158 -15
  91. package/dist/bridge/resources.d.ts +9 -3
  92. package/dist/bridge/resources.js +24 -8
  93. package/dist/bridge/schedule-format.d.ts +2 -0
  94. package/dist/bridge/schedule-format.js +3 -0
  95. package/dist/bridge/schedule-launch.d.ts +2 -1
  96. package/dist/bridge/schedule-launch.js +27 -53
  97. package/dist/bridge/schedule-watch.d.ts +24 -1
  98. package/dist/bridge/schedule-watch.js +89 -2
  99. package/dist/bridge/server-launch.d.ts +22 -5
  100. package/dist/bridge/server-launch.js +238 -32
  101. package/dist/bridge/server-overview.d.ts +10 -3
  102. package/dist/bridge/server-overview.js +32 -15
  103. package/dist/bridge/server-pane-routes.d.ts +3 -0
  104. package/dist/bridge/server-pane-routes.js +150 -18
  105. package/dist/bridge/server-routes.d.ts +11 -0
  106. package/dist/bridge/server-routes.js +214 -36
  107. package/dist/bridge/server-stream.d.ts +2 -0
  108. package/dist/bridge/server-stream.js +22 -8
  109. package/dist/bridge/server.d.ts +6 -1
  110. package/dist/bridge/server.js +58 -13
  111. package/dist/bridge/session-activity.d.ts +93 -0
  112. package/dist/bridge/session-activity.js +139 -0
  113. package/dist/bridge/session-rename.d.ts +48 -0
  114. package/dist/bridge/session-rename.js +190 -0
  115. package/dist/bridge/session-servers.js +2 -2
  116. package/dist/bridge/settings-switch.d.ts +60 -0
  117. package/dist/bridge/settings-switch.js +287 -0
  118. package/dist/bridge/speech-voice.d.ts +55 -0
  119. package/dist/bridge/speech-voice.js +132 -0
  120. package/dist/bridge/speech.d.ts +70 -11
  121. package/dist/bridge/speech.js +169 -41
  122. package/dist/bridge/stalls.d.ts +22 -0
  123. package/dist/bridge/stalls.js +57 -0
  124. package/dist/bridge/sudo.d.ts +209 -0
  125. package/dist/bridge/sudo.js +501 -0
  126. package/dist/bridge/terminal-herdr.js +9 -3
  127. package/dist/bridge/terminal-tmux.d.ts +15 -3
  128. package/dist/bridge/terminal-tmux.js +103 -13
  129. package/dist/bridge/terminal.d.ts +27 -4
  130. package/dist/bridge/terminal.js +8 -1
  131. package/dist/bridge/transcript-claude.d.ts +4 -0
  132. package/dist/bridge/transcript-claude.js +186 -16
  133. package/dist/bridge/transcript-codex.d.ts +0 -2
  134. package/dist/bridge/transcript-codex.js +29 -4
  135. package/dist/bridge/transcript-preview.d.ts +1 -0
  136. package/dist/bridge/transcript-preview.js +24 -4
  137. package/dist/bridge/transcripts.d.ts +15 -2
  138. package/dist/bridge/transcripts.js +47 -16
  139. package/dist/bridge/turn-records.d.ts +85 -0
  140. package/dist/bridge/turn-records.js +143 -0
  141. package/dist/bridge/uploads.d.ts +3 -0
  142. package/dist/bridge/uploads.js +14 -0
  143. package/dist/bridge/usage.d.ts +56 -10
  144. package/dist/bridge/usage.js +190 -45
  145. package/dist/bridge-hook.mjs +27975 -20636
  146. package/dist/cli/claude-unmanaged.d.ts +12 -0
  147. package/dist/cli/claude-unmanaged.js +105 -0
  148. package/dist/cli/schedules.js +2 -1
  149. package/dist/cli/session-start.js +10 -1
  150. package/dist/cli/session-stop.js +9 -1
  151. package/dist/cli-registry.js +31 -6
  152. package/dist/data/task-receipts.d.ts +19 -0
  153. package/dist/data/task-receipts.js +68 -0
  154. package/dist/data/tasks.js +4 -1
  155. package/dist/generated/memory-ui-graph.browser.js +63 -63
  156. package/dist/graph-core/model.js +24 -3
  157. package/dist/graph-core/types.d.ts +4 -1
  158. package/dist/graph-core/types.js +1 -0
  159. package/dist/init/init-preset.js +7 -3
  160. package/dist/init/init-uninstall.js +2 -11
  161. package/dist/init/teardown.d.ts +3 -0
  162. package/dist/init/teardown.js +47 -0
  163. package/dist/link/context.js +21 -9
  164. package/dist/mcp/plugin-mode.js +1 -1
  165. package/dist/memory-ui-graph.runtime.js +63 -63
  166. package/dist/modules/code-package.d.ts +1 -0
  167. package/dist/modules/code-package.js +36 -7
  168. package/dist/modules/registry.js +17 -16
  169. package/dist/profile-store.d.ts +6 -0
  170. package/dist/profile-store.js +25 -1
  171. package/dist/shell/graph/glyphs.js +4 -0
  172. package/dist/shell/graph/graph-view.js +2 -0
  173. package/dist/status.js +7 -1
  174. package/dist/sync/task-claim.js +3 -2
  175. package/dist/task/lifecycle.js +25 -4
  176. package/dist/test-global-setup.js +5 -0
  177. package/dist/tools/dispatch.js +52 -4
  178. package/dist/tools/tasks.js +10 -1
  179. package/package.json +1 -1
  180. package/plugins/opencode/phren-transcript.js +87 -4
  181. package/starter/global/AGENTS.md +4 -0
  182. package/starter/global/skills/conductor/SKILL.md +51 -4
@@ -0,0 +1,235 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { lstat, open, readFile, readdir, unlink } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { z } from "zod";
5
+ import { atomicInPrivateDir, BridgeError, bridgeRoot, targetSchema, computerName } from "./protocol.js";
6
+ import { deliveryIdSchema } from "./prompt-once.js";
7
+ import { agentNotReady } from "./terminal.js";
8
+ export const queuedHandOffSchema = z.object({
9
+ target: targetSchema, text: z.string().min(1).max(32768).refine(t => !/[\x00-\x08\x0b-\x1f\x7f]/.test(t)),
10
+ deliveryId: deliveryIdSchema, origin: targetSchema.optional(), originComputer: computerName.optional(),
11
+ }).strict();
12
+ const rowSchema = queuedHandOffSchema.extend({
13
+ deliveryId: deliveryIdSchema.unwrap(), terminal: z.string().min(1).max(200),
14
+ state: z.enum(["queued", "attempting", "delivered", "uncertain", "failed"]),
15
+ createdAt: z.string().datetime(), updatedAt: z.string().datetime(), error: z.string().max(500).optional(),
16
+ notified: z.boolean().optional(),
17
+ });
18
+ const DAY = 86_400_000;
19
+ /** Settled rows (and notice tombstones) are kept this long, so a late retry of
20
+ * an old delivery id still replays instead of typing again. */
21
+ export const HAND_OFF_RETENTION_MS = 7 * DAY;
22
+ /** At most this many rows stay on disk; the oldest settled rows go first. */
23
+ export const HAND_OFF_MAX_ROWS = 512;
24
+ const settled = (row) => row.state !== "queued" && row.state !== "attempting";
25
+ const sameTarget = (a, b) => ["server", "workspace", "tab", "pane", "source", "session"].every(key => a[key] === b[key]);
26
+ /** A durable outbox on the receiving Hook. Persist 'attempting' before input,
27
+ * so a crash in the input/ack gap recovers as uncertain, never as a retry.
28
+ * Tombstones are retained for HAND_OFF_RETENTION_MS, so a retried delivery id
29
+ * replays instead of typing a second time; a queued or attempting row is never
30
+ * pruned. The sweep runs on enqueue and at most daily from tick(). */
31
+ export class HandOffQueue {
32
+ options;
33
+ pending = Promise.resolve();
34
+ root;
35
+ now;
36
+ lastPrune = -Infinity;
37
+ constructor(options) {
38
+ this.options = options;
39
+ this.root = options.root ?? path.join(bridgeRoot(), "hand-offs");
40
+ this.now = options.now ?? Date.now;
41
+ }
42
+ serial(run) {
43
+ const result = this.pending.then(run);
44
+ this.pending = result.catch(() => { });
45
+ return result;
46
+ }
47
+ file(id) { return path.join(this.root, `${deliveryIdSchema.unwrap().parse(id)}.json`); }
48
+ async save(row) {
49
+ row.updatedAt = new Date(this.now()).toISOString();
50
+ const file = this.file(row.deliveryId);
51
+ await atomicInPrivateDir(file, rowSchema.parse(row));
52
+ // Ensure the renamed entry survives a host crash as well as a service restart.
53
+ // Windows refuses fsync on a read-only handle (EPERM) and on directories.
54
+ if (process.platform !== "win32")
55
+ for (const target of [file, this.root]) {
56
+ const handle = await open(target, "r");
57
+ try {
58
+ await handle.sync();
59
+ }
60
+ finally {
61
+ await handle.close();
62
+ }
63
+ }
64
+ }
65
+ async read(id) {
66
+ const file = this.file(id), info = await lstat(file).catch(error => {
67
+ if (error.code === "ENOENT")
68
+ return undefined;
69
+ throw error;
70
+ });
71
+ if (!info)
72
+ return undefined;
73
+ if (!info.isFile() || info.isSymbolicLink() || info.size > 100_000)
74
+ throw new BridgeError(409, "The hand-off record cannot be read safely.");
75
+ const row = rowSchema.parse(JSON.parse(await readFile(file, "utf8")));
76
+ if (row.state === "attempting") {
77
+ row.state = "uncertain";
78
+ row.error = "The Hook restarted before delivery was confirmed.";
79
+ await this.save(row);
80
+ }
81
+ return row;
82
+ }
83
+ async rows() {
84
+ const names = await readdir(this.root).catch(error => { if (error.code === "ENOENT")
85
+ return []; throw error; });
86
+ const rows = [];
87
+ for (const name of names.sort())
88
+ if (/^[A-Za-z0-9_-]{8,64}\.json$/.test(name)) {
89
+ const row = await this.read(name.slice(0, -5));
90
+ if (row)
91
+ rows.push(row);
92
+ }
93
+ return rows.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.deliveryId.localeCompare(b.deliveryId));
94
+ }
95
+ /** Drops settled rows past retention, then the oldest settled rows over the
96
+ * cap (those still owing their sender a notice last). Returns what is kept. */
97
+ async prune(rows) {
98
+ this.lastPrune = this.now();
99
+ const now = this.now(), drop = new Set();
100
+ for (const row of rows)
101
+ if (settled(row) && now - Date.parse(row.updatedAt) > HAND_OFF_RETENTION_MS)
102
+ drop.add(row.deliveryId);
103
+ let excess = rows.length - drop.size - HAND_OFF_MAX_ROWS;
104
+ if (excess > 0) {
105
+ const owesNotice = (row) => (row.origin && !row.notified ? 1 : 0);
106
+ const candidates = rows.filter(row => settled(row) && !drop.has(row.deliveryId))
107
+ .sort((a, b) => owesNotice(a) - owesNotice(b) || a.updatedAt.localeCompare(b.updatedAt) || a.deliveryId.localeCompare(b.deliveryId));
108
+ for (const row of candidates) {
109
+ if (excess-- <= 0)
110
+ break;
111
+ drop.add(row.deliveryId);
112
+ }
113
+ }
114
+ for (const id of drop)
115
+ await unlink(this.file(id)).catch(error => { if (error.code !== "ENOENT")
116
+ throw error; });
117
+ return drop.size ? rows.filter(row => !drop.has(row.deliveryId)) : rows;
118
+ }
119
+ reply(row) {
120
+ return { ok: row.state === "delivered" || row.state === "queued", delivered: row.state === "delivered", queued: row.state === "queued",
121
+ deliveryId: row.deliveryId, state: row.state, target: row.target,
122
+ ...(row.state === "uncertain" ? { deliveryUncertain: true } : {}), ...(row.error ? { error: row.error } : {}) };
123
+ }
124
+ enqueue(input) {
125
+ return this.serial(async () => {
126
+ const data = queuedHandOffSchema.parse(input), id = data.deliveryId ?? randomUUID().replaceAll("-", "");
127
+ const prior = await this.read(id);
128
+ if (prior) {
129
+ if (!sameTarget(prior.target, data.target) || prior.text !== data.text)
130
+ throw new BridgeError(409, "This message id was already used for a different message.");
131
+ return { ...this.reply(prior), replayed: true };
132
+ }
133
+ const pane = await this.options.validate(data.target);
134
+ if (typeof pane.terminal_id !== "string")
135
+ throw new BridgeError(409, "This agent has no terminal binding.");
136
+ const at = new Date(this.now()).toISOString();
137
+ const row = { ...data, deliveryId: id, terminal: pane.terminal_id, state: "queued", createdAt: at, updatedAt: at };
138
+ await this.save(row);
139
+ // Older queued messages take precedence even if this one arrives at idle.
140
+ const ahead = (await this.prune(await this.rows())).some(other => other.deliveryId !== id && sameTarget(other.target, row.target) && other.state === "queued");
141
+ if (!ahead)
142
+ await this.attempt(row, pane);
143
+ return this.reply(row);
144
+ });
145
+ }
146
+ status(id, target) {
147
+ return this.serial(async () => { const row = await this.read(id); if (!row || !sameTarget(row.target, target))
148
+ throw new BridgeError(404, "No hand-off with this id and target."); return this.reply(row); });
149
+ }
150
+ async attempt(row, pane) {
151
+ try {
152
+ pane ??= await this.options.validate(row.target);
153
+ }
154
+ catch (error) {
155
+ if (error instanceof BridgeError && [404, 409].includes(error.status)) {
156
+ row.state = "failed";
157
+ row.error = error.message.slice(0, 500);
158
+ await this.save(row);
159
+ }
160
+ return; // Offline is not gone and does not discard a queued message.
161
+ }
162
+ if (pane.terminal_id !== row.terminal) {
163
+ row.state = "failed";
164
+ row.error = "The worker's terminal changed before delivery.";
165
+ await this.save(row);
166
+ return;
167
+ }
168
+ if (!["idle", "done"].includes(String(pane.agent_status)))
169
+ return;
170
+ let typed = false;
171
+ try {
172
+ const result = await this.options.send(row.target, row.text, row.deliveryId, async () => {
173
+ row.state = "attempting";
174
+ await this.save(row);
175
+ typed = true;
176
+ });
177
+ row.state = result.delivered === true && result.deliveryUncertain !== true && result.unsubmitted !== true ? "delivered" : "uncertain";
178
+ }
179
+ catch (error) {
180
+ if (agentNotReady(error) || (error instanceof BridgeError && error.details?.code === "hand-off-busy"))
181
+ row.state = "queued"; // Herdr guarantees no input was written.
182
+ else if (!typed) {
183
+ if (!(error instanceof BridgeError) || ![404, 409, 422].includes(error.status))
184
+ return;
185
+ row.state = "failed";
186
+ }
187
+ else
188
+ row.state = "uncertain";
189
+ row.error = (error instanceof Error ? error.message : "Delivery failed.").slice(0, 500);
190
+ }
191
+ if (row.state === "delivered")
192
+ delete row.error;
193
+ await this.save(row);
194
+ }
195
+ tick() {
196
+ return this.serial(async () => {
197
+ let rows = await this.rows();
198
+ if (this.now() - this.lastPrune >= DAY)
199
+ rows = await this.prune(rows);
200
+ const attempted = new Set();
201
+ for (const row of rows)
202
+ if (row.state === "queued") {
203
+ const key = JSON.stringify(row.target);
204
+ if (attempted.has(key))
205
+ continue;
206
+ attempted.add(key);
207
+ await this.attempt(row);
208
+ }
209
+ for (const row of rows)
210
+ if (row.origin && !row.notified && ["delivered", "failed", "uncertain"].includes(row.state)) {
211
+ // A notice is itself an idempotent queued hand-off, without an origin.
212
+ const id = `handoff-notice-${createHash("sha256").update(row.deliveryId).digest("hex").slice(0, 40)}`;
213
+ if (row.originComputer) {
214
+ const result = await this.options.notify?.(row.origin, `Hand-off ${row.deliveryId}: ${row.state}.`, id, row.originComputer).catch(() => undefined);
215
+ if (!result || (!result.queued && !result.delivered && !result.deliveryUncertain))
216
+ continue;
217
+ row.notified = true;
218
+ await this.save(row);
219
+ continue;
220
+ }
221
+ if (!await this.read(id)) {
222
+ const pane = await this.options.validate(row.origin).catch(() => undefined);
223
+ if (!pane || typeof pane.terminal_id !== "string")
224
+ continue;
225
+ const at = new Date(this.now()).toISOString();
226
+ await this.save({ deliveryId: id, target: row.origin, text: `Hand-off ${row.deliveryId}: ${row.state}.`, terminal: pane.terminal_id,
227
+ state: "queued", createdAt: at, updatedAt: at });
228
+ }
229
+ row.notified = true;
230
+ await this.save(row);
231
+ }
232
+ });
233
+ }
234
+ hasPending(target) { return this.serial(async () => (await this.rows()).some(row => sameTarget(row.target, target) && ["queued", "attempting", "uncertain"].includes(row.state))); }
235
+ }
@@ -1,5 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { type Target } from "./protocol.js";
3
+ import { computerLabel, type PeerFacts } from "./computer-identity.js";
4
+ export { computerLabel };
3
5
  export declare const handOffSchema: z.ZodObject<{
4
6
  computer: z.ZodOptional<z.ZodString>;
5
7
  target: z.ZodOptional<z.ZodObject<{
@@ -18,13 +20,26 @@ export declare const handOffSchema: z.ZodObject<{
18
20
  }, z.core.$strip>>;
19
21
  session: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodString]>>;
20
22
  project: z.ZodOptional<z.ZodString>;
21
- text: z.ZodString;
23
+ account: z.ZodOptional<z.ZodString>;
24
+ deliveryId: z.ZodOptional<z.ZodString>;
25
+ status: z.ZodOptional<z.ZodBoolean>;
26
+ text: z.ZodOptional<z.ZodString>;
22
27
  }, z.core.$strict>;
23
28
  export type HandOffInput = z.infer<typeof handOffSchema>;
24
- export declare function handOff(input: unknown): Promise<{
29
+ /** A stable delivery id names a message on the receiving Hook. The Hook
30
+ * queues busy targets and retains outcomes across restarts. */
31
+ export declare function handOff(input: unknown, options?: {
32
+ deliveryId?: string;
33
+ notifySender?: boolean;
34
+ }): Promise<{
25
35
  ok: boolean;
26
36
  delivered: boolean;
27
37
  target: Target;
38
+ queued?: boolean;
39
+ deliveryId?: string;
40
+ state?: string;
41
+ deliveryUncertain?: boolean;
42
+ unsubmitted?: boolean;
28
43
  label?: string;
29
44
  granted?: string;
30
45
  }>;
@@ -41,13 +56,16 @@ export interface LiveSession {
41
56
  branch?: string;
42
57
  model?: string;
43
58
  target?: Target;
59
+ /** Claude account id, when the Hook knows it; absent means the default account or an unknown one. */
60
+ account?: string;
44
61
  /** Seconds since the tab last changed, when the Hook has seen it change. */
45
62
  idleFor?: number;
63
+ /** Set when the main turn ended and this many background tasks keep the session `working`. */
64
+ backgroundTasks?: number;
65
+ stalled?: boolean;
66
+ stallFor?: number;
67
+ stalledSince?: string;
46
68
  }
47
- /** A computer name's first DNS label, lowercased: `Desk`, `desk.local` and
48
- * `Desk.example.net` are one computer. DHCP and Bonjour add domains to the
49
- * same machine's name, so full names do not identify a computer. */
50
- export declare function computerLabel(name: string): string;
51
69
  /** A registered computer this Hook cannot see, with the other names the store
52
70
  * registers it under. */
53
71
  export interface NotLinkedComputer {
@@ -55,10 +73,12 @@ export interface NotLinkedComputer {
55
73
  aliases?: string[];
56
74
  }
57
75
  /** Computers the store registers (machines.yaml) that this Hook has no
58
- * verified connection to, so their sessions cannot be listed from here.
59
- * Names are compared by first label against this computer's names and each
60
- * peer's name, address and aliases; names sharing a label collapse into one
61
- * entry. */
76
+ * verified connection to, so their sessions cannot be listed from here: the
77
+ * unlinked rows of `foldComputers`, which folds names by first label and by
78
+ * shared profile into the computers it can see. */
79
+ export declare function notLinkedFrom(store: string | null, here: string, peers: readonly PeerFacts[]): NotLinkedComputer[];
80
+ /** As `notLinkedFrom` for a flat list of names the linked computers answer
81
+ * to, each standing for its own computer. */
62
82
  export declare function notLinkedComputers(store: string | null, here: string, linked: readonly string[]): NotLinkedComputer[];
63
83
  export interface LiveSessions {
64
84
  sessions: LiveSession[];
@@ -1,21 +1,33 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { deliveryIdSchema } from "./prompt-once.js";
3
+ import { terminalPaneFromEnv } from "./terminal.js";
1
4
  import { z } from "zod";
2
5
  import { computerName } from "./computers.js";
3
6
  import { hookRequest } from "./client.js";
4
7
  import { projectName } from "./dispatch.js";
5
- import { grantLabel, listGrants, matchGrant } from "./grants.js";
8
+ import { isAccountSlug } from "./claude-accounts.js";
9
+ import { grantLabel, findGrant } from "./grants.js";
6
10
  import { hookPeers, optionalHookPeers, peerRequest } from "./peers.js";
7
11
  import { BridgeError, errorCode, object, objects, sessionId, targetSchema } from "./protocol.js";
8
12
  import { findPhrenPath } from "../phren-paths.js";
9
13
  import { listMachines } from "../profile-store.js";
10
14
  import { localNames } from "./computer-names.js";
15
+ import { computerLabel, foldComputers, linkedComputer } from "./computer-identity.js";
16
+ export { computerLabel };
11
17
  const promptText = z.string().min(1).max(32768).refine(value => !/[\x00-\x08\x0b-\x1f\x7f]/.test(value));
12
18
  export const handOffSchema = z.object({
13
19
  computer: computerName.optional().describe("Enrolled computer name. Omit for this computer."),
14
20
  target: targetSchema.optional().describe("Complete live target for the existing session."),
15
21
  session: sessionId.optional().describe("Session id to resolve through the Hook workspace overview."),
16
22
  project: projectName.optional().describe("Project slug this hand-off belongs to, for conductor grant matching."),
17
- text: promptText.describe("Prompt to deliver to the existing session, at most 32768 characters."),
23
+ account: z.string().refine(isAccountSlug, "Account must be default or a lowercase slug.").optional()
24
+ .describe("Claude account id the session must run under (default, or a slug). A session of another account is refused; a row without an account counts as default."),
25
+ deliveryId: deliveryIdSchema.describe("Stable message id to keep on retries or to check status."),
26
+ status: z.boolean().optional().describe("Read delivery status without sending; requires deliveryId."),
27
+ text: promptText.optional().describe("Prompt to deliver to the existing session, at most 32768 characters."),
18
28
  }).strict().superRefine((value, context) => {
29
+ if (value.status ? !value.deliveryId || value.text !== undefined : !value.text)
30
+ context.addIssue({ code: "custom", message: "A send requires text; a status query requires deliveryId and no text." });
19
31
  if ((value.target === undefined) === (value.session === undefined))
20
32
  context.addIssue({ code: "custom", message: "Provide exactly one of target or session." });
21
33
  });
@@ -25,6 +37,8 @@ function labelOf(group, tab) {
25
37
  const folder = typeof tab.cwd === "string" && tab.role !== "conductor" ? tab.cwd.split("/").filter(Boolean).at(-1) : undefined;
26
38
  return folder || (typeof group.label === "string" && group.label ? group.label : undefined);
27
39
  }
40
+ /** The account id an overview row runs under; a row without one is the default account. */
41
+ const accountOf = (tab) => typeof object(tab.account).id === "string" ? String(object(tab.account).id) : "default";
28
42
  async function findInOverview(request, match, server) {
29
43
  const route = server ? `/v1/workspaces?server=${encodeURIComponent(server)}` : "/v1/workspaces";
30
44
  const overview = await request(route);
@@ -32,41 +46,75 @@ async function findInOverview(request, match, server) {
32
46
  for (const tab of objects(group.children)) {
33
47
  const parsed = targetSchema.safeParse(tab.target);
34
48
  if (parsed.success && match(parsed.data))
35
- return { target: parsed.data, label: labelOf(group, tab) };
49
+ return { target: parsed.data, label: labelOf(group, tab), account: accountOf(tab) };
36
50
  }
37
51
  return undefined;
38
52
  }
39
- async function targetFromOverview(request, session, server) {
53
+ async function targetFromOverview(request, session, server, account) {
40
54
  const found = await findInOverview(request, target => target.session === session, server);
41
55
  if (!found)
42
56
  throw new BridgeError(404, "No live session with that id appears in the workspace overview.");
57
+ if (account && found.account !== account)
58
+ throw new BridgeError(409, `That session runs under account ${found.account}, not ${account}.`, { code: "account_mismatch" });
43
59
  return found;
44
60
  }
45
- export async function handOff(input) {
61
+ /** A stable delivery id names a message on the receiving Hook. The Hook
62
+ * queues busy targets and retains outcomes across restarts. */
63
+ export async function handOff(input, options = {}) {
46
64
  const data = handOffSchema.parse(input);
47
65
  let request;
48
66
  let peer;
49
67
  if (data.computer === undefined)
50
68
  request = (route, body) => hookRequest(route, body);
51
69
  else {
52
- peer = (await hookPeers()).find(candidate => candidate.name === data.computer);
53
- if (!peer)
54
- throw new BridgeError(404, "Unknown computer. Add its verified connection to hooks.yaml.");
55
- request = (route, body) => peerRequest(peer, route, body);
70
+ // No hooks.yaml only matters when the name turns out to be another computer.
71
+ let peersError;
72
+ const peers = await hookPeers().catch(error => { peersError = error; return []; });
73
+ // An alias or hostname (`Mac`, `Desk.local`) names the same computer as its hooks.yaml name.
74
+ const named = peers.some(candidate => candidate.name === data.computer) ? undefined : await linkedComputer(data.computer).catch(() => undefined);
75
+ if (named && "local" in named)
76
+ request = (route, body) => hookRequest(route, body);
77
+ else {
78
+ if (peersError)
79
+ throw peersError;
80
+ const found = peers.find(candidate => candidate.name === (named && "peer" in named ? named.peer : data.computer));
81
+ if (!found)
82
+ throw new BridgeError(404, "Unknown computer. Add its verified connection to hooks.yaml.");
83
+ peer = found;
84
+ request = (route, body) => peerRequest(found, route, body);
85
+ }
56
86
  }
57
- const resolved = data.target ? undefined : await targetFromOverview(request, data.session, peer?.server);
87
+ const resolved = data.target ? undefined : await targetFromOverview(request, data.session, peer?.server, data.account);
58
88
  const target = data.target ?? resolved.target;
59
89
  if (peer && target.server !== peer.server)
60
90
  throw new BridgeError(400, "The target belongs to a different Herdr server on that computer.");
61
- const grant = matchGrant(await listGrants(), { action: "hand_off", project: data.project, computer: data.computer });
62
- const result = await request("/v1/prompt", { target, text: data.text });
63
- const delivered = result.ok === true && result.deliveryUncertain !== true;
91
+ const grant = await findGrant({ action: "hand_off", project: data.project, computer: data.computer });
92
+ let origin;
93
+ if (!data.status && options.notifySender !== false) {
94
+ const here = await terminalPaneFromEnv();
95
+ if (here)
96
+ origin = await findInOverview((route, body) => hookRequest(route, body), found => found.server === here.server && found.pane === here.pane, here.server).then(found => found?.target, () => undefined);
97
+ }
98
+ const originComputer = peer && origin ? await hookRequest("/v1/health").then(health => object(health.computer).name, () => undefined) : undefined;
99
+ const deliveryId = data.deliveryId ?? options.deliveryId ?? randomUUID().replaceAll("-", "");
100
+ const result = await request(data.status ? "/v1/hand-off/status" : "/v1/hand-off", { target, deliveryId,
101
+ ...(!data.status ? { text: data.text, ...(origin ? { origin, ...(typeof originComputer === "string" ? { originComputer } : {}) } : {}) } : {}) });
102
+ // A bare ok only acknowledges typing. Even an unchanged, busy Codex pane
103
+ // may have kept the text in its composer instead of submitting a turn.
104
+ const delivered = result.ok === true && result.delivered === true && result.deliveryUncertain !== true && result.unsubmitted !== true;
64
105
  // A session id was resolved from the overview already; an explicit target
65
106
  // is looked up once more, best effort, for its label.
66
107
  const label = resolved ? resolved.label
67
108
  : await findInOverview(request, found => found.pane === target.pane && found.session === target.session, peer?.server)
68
109
  .then(found => found?.label, () => undefined);
69
- return { ok: delivered, delivered, target, ...(label ? { label } : {}), ...(grant ? { granted: grantLabel(grant) } : {}) };
110
+ const queued = result.queued === true && result.deliveryUncertain !== true;
111
+ return { ok: delivered || queued, delivered, target,
112
+ ...(queued ? { queued: true } : {}),
113
+ ...(typeof result.deliveryId === "string" ? { deliveryId: result.deliveryId } : {}),
114
+ ...(typeof result.state === "string" ? { state: result.state } : {}),
115
+ ...(!delivered && !queued && (result.ok === true || result.deliveryUncertain === true) ? { deliveryUncertain: true } : {}),
116
+ ...(result.unsubmitted === true ? { unsubmitted: true } : {}),
117
+ ...(label ? { label } : {}), ...(grant ? { granted: grantLabel(grant) } : {}) };
70
118
  }
71
119
  function sessionsFrom(overview, computer, local, now = Date.now()) {
72
120
  const sessions = [];
@@ -85,43 +133,30 @@ function sessionsFrom(overview, computer, local, now = Date.now()) {
85
133
  // A conductor sits in the store, not a project.
86
134
  sessions.push({ computer, local, project: tab.role === "conductor" ? undefined : text(cwd.split("/").filter(Boolean).at(-1)), label: text(label),
87
135
  title: text(tab.title), agent: tab.agent, status: text(tab.agentStatus), role: text(tab.role),
88
- branch: text(tab.branch), model: text(tab.model), ...(target.success ? { target: target.data } : {}),
136
+ branch: text(tab.branch), model: text(tab.model), ...(typeof object(tab.account).id === "string" ? { account: String(object(tab.account).id) } : {}), ...(target.success ? { target: target.data } : {}),
137
+ ...(typeof tab.backgroundTasks === "number" && tab.backgroundTasks > 0 ? { backgroundTasks: tab.backgroundTasks } : {}),
138
+ ...(tab.stalled === true ? { stalled: true, stallFor: Number(tab.stallFor), stalledSince: String(tab.stalledSince) } : {}),
89
139
  ...(Number.isFinite(changedAt) ? { idleFor: Math.max(0, Math.floor((now - changedAt) / 1000)) } : {}) });
90
140
  }
91
141
  return sessions;
92
142
  }
93
- /** A computer name's first DNS label, lowercased: `Desk`, `desk.local` and
94
- * `Desk.example.net` are one computer. DHCP and Bonjour add domains to the
95
- * same machine's name, so full names do not identify a computer. */
96
- export function computerLabel(name) {
97
- const value = name.trim().toLowerCase();
98
- // An IPv4 address is one name, not a label and a domain.
99
- return /^\d+(\.\d+){3}$/.test(value) ? value : value.split(".")[0] ?? "";
100
- }
101
143
  /** Computers the store registers (machines.yaml) that this Hook has no
102
- * verified connection to, so their sessions cannot be listed from here.
103
- * Names are compared by first label against this computer's names and each
104
- * peer's name, address and aliases; names sharing a label collapse into one
105
- * entry. */
106
- export function notLinkedComputers(store, here, linked) {
144
+ * verified connection to, so their sessions cannot be listed from here: the
145
+ * unlinked rows of `foldComputers`, which folds names by first label and by
146
+ * shared profile into the computers it can see. */
147
+ export function notLinkedFrom(store, here, peers) {
107
148
  if (!store)
108
149
  return [];
109
150
  const machines = listMachines(store);
110
151
  if (!machines.ok)
111
152
  return [];
112
- const known = new Set([here, ...localNames(), ...linked].map(computerLabel).filter(Boolean));
113
- const groups = new Map();
114
- for (const name of Object.keys(machines.data)) {
115
- const label = computerLabel(name);
116
- if (!label || known.has(label))
117
- continue;
118
- groups.set(label, [...(groups.get(label) ?? []), name]);
119
- }
120
- return [...groups.values()].map(names => {
121
- // The shortest name leads (usually the bare label); the rest are aliases.
122
- const [name, ...aliases] = [...names].sort((a, b) => a.length - b.length || a.localeCompare(b));
123
- return aliases.length ? { name, aliases } : { name };
124
- }).sort((a, b) => a.name.localeCompare(b.name));
153
+ return foldComputers({ local: { names: [here, ...localNames()] }, peers, machines: machines.data })
154
+ .filter(row => !row.linked).map(row => row.aliases.length ? { name: row.name, aliases: row.aliases } : { name: row.name });
155
+ }
156
+ /** As `notLinkedFrom` for a flat list of names the linked computers answer
157
+ * to, each standing for its own computer. */
158
+ export function notLinkedComputers(store, here, linked) {
159
+ return notLinkedFrom(store, here, linked.map(name => ({ name, address: name })));
125
160
  }
126
161
  /** Every live agent the conductor could hand work to: this computer's Herdr
127
162
  * overview plus each enrolled computer's, read through its verified Hook.
@@ -134,16 +169,14 @@ export async function listLiveSessions(options = {}) {
134
169
  const unreachable = [];
135
170
  // Names each peer answers to (its hostname, Bonjour name), so a computer
136
171
  // registered under another of its names is not reported as unlinked.
137
- const peerNames = [];
172
+ const peerNames = new Map();
138
173
  await Promise.all(peers.map(async (peer) => {
139
174
  try {
140
175
  const route = peer.server && peer.server !== "default" ? `/v1/workspaces?server=${encodeURIComponent(peer.server)}` : "/v1/workspaces";
141
176
  const [overview, health] = await Promise.all([peerRequest(peer, route), peerRequest(peer, "/v1/health").catch(() => ({}))]);
142
177
  sessions.push(...sessionsFrom(overview, peer.name, false));
143
178
  const computer = object(object(health).computer);
144
- for (const name of [computer.name, ...(Array.isArray(computer.aliases) ? computer.aliases : [])])
145
- if (typeof name === "string")
146
- peerNames.push(name);
179
+ peerNames.set(peer.name, [computer.name, ...(Array.isArray(computer.aliases) ? computer.aliases : [])].filter((name) => typeof name === "string"));
147
180
  }
148
181
  catch (error) {
149
182
  const code = errorCode(error);
@@ -151,6 +184,6 @@ export async function listLiveSessions(options = {}) {
151
184
  }
152
185
  }));
153
186
  const store = options.store !== undefined ? options.store : findPhrenPath();
154
- const notLinked = notLinkedComputers(store, here, [...peers.flatMap(peer => [peer.name, peer.address]), ...peerNames]);
187
+ const notLinked = notLinkedFrom(store, here, peers.map(peer => ({ name: peer.name, address: peer.address, names: peerNames.get(peer.name) })));
155
188
  return { sessions, unreachable, notLinked, enrolled: peers.length, ...(peerError ? { peerError } : {}) };
156
189
  }
@@ -1,5 +1,15 @@
1
1
  /** What phren's OpenCode plugin last recorded for any of `pids`, newest first. */
2
2
  export declare function opencodeProcessStatus(pids: number[], root?: string): Promise<string | undefined>;
3
+ type TurnStamps = {
4
+ session: string;
5
+ at: string;
6
+ busyAt?: string;
7
+ idleAt?: string;
8
+ };
9
+ /** The turn stamps phren's OpenCode plugin last recorded for any of `pids`,
10
+ * newest first: when the session went busy and when it went idle after that.
11
+ * Undefined when no file has them (an older plugin). */
12
+ export declare function opencodeTurnStamps(pids: number[], root?: string): Promise<TurnStamps | undefined>;
3
13
  /** The status a Copilot session log's lines leave the session in; undefined
4
14
  * when none of them says. Copilot writes a turn_start/turn_end pair per model
5
15
  * call, so only the turn that carried the final answer ends the work. */
@@ -10,3 +20,4 @@ export declare function copilotProcessStatus(pids: number[], home?: string): Pro
10
20
  /** The status `agent`'s own records give for a pane running `pids`, for the
11
21
  * harnesses whose lifecycle hooks say nothing about turns. */
12
22
  export declare function harnessStatus(agent: string, pids: number[]): Promise<string | undefined>;
23
+ export {};
@@ -43,6 +43,38 @@ export async function opencodeProcessStatus(pids, root = phrenStoreRoot()) {
43
43
  }
44
44
  return current;
45
45
  }
46
+ /** The turn stamps phren's OpenCode plugin last recorded for any of `pids`,
47
+ * newest first: when the session went busy and when it went idle after that.
48
+ * Undefined when no file has them (an older plugin). */
49
+ export async function opencodeTurnStamps(pids, root = phrenStoreRoot()) {
50
+ const folder = path.join(root, ".runtime", "sessions");
51
+ let current, latest = -Infinity;
52
+ for (const pid of pids.slice(0, 16)) {
53
+ const file = await open(path.join(folder, `opencode-status-${pid}.json`), "r").catch(() => undefined);
54
+ if (!file)
55
+ continue;
56
+ try {
57
+ if ((await file.stat()).size > 4_096)
58
+ continue;
59
+ const value = object(JSON.parse((await file.readFile()).toString("utf8")));
60
+ const at = Date.parse(String(value.at));
61
+ if (typeof value.session !== "string" || !(at > latest))
62
+ continue;
63
+ const busyAt = typeof value.busyAt === "string" ? value.busyAt : undefined, idleAt = typeof value.idleAt === "string" ? value.idleAt : undefined;
64
+ if (!busyAt && !idleAt)
65
+ continue;
66
+ current = { session: value.session, at: String(value.at), ...(busyAt ? { busyAt } : {}), ...(idleAt ? { idleAt } : {}) };
67
+ latest = at;
68
+ }
69
+ catch {
70
+ continue;
71
+ }
72
+ finally {
73
+ await file.close();
74
+ }
75
+ }
76
+ return current;
77
+ }
46
78
  /** The status a Copilot session log's lines leave the session in; undefined
47
79
  * when none of them says. Copilot writes a turn_start/turn_end pair per model
48
80
  * call, so only the turn that carried the final answer ends the work. */
@@ -0,0 +1,39 @@
1
+ import { type AccountRef, type AuthRunner } from "./claude-accounts.js";
2
+ import { type ToolVersion } from "./health.js";
3
+ export type HarnessSource = "claude" | "codex" | "opencode" | "copilot";
4
+ export interface HarnessAccount extends AccountRef {
5
+ signedIn: boolean;
6
+ usable: boolean;
7
+ plan?: string;
8
+ reason?: string;
9
+ }
10
+ export interface HarnessEntry {
11
+ source: HarnessSource;
12
+ installed: boolean;
13
+ version?: string;
14
+ usable: boolean;
15
+ reason?: string;
16
+ accounts?: HarnessAccount[];
17
+ }
18
+ export interface HarnessInventory {
19
+ harnesses: HarnessEntry[];
20
+ }
21
+ export interface HarnessDeps {
22
+ toolVersion?: (tool: string) => Promise<ToolVersion>;
23
+ authRunner?: AuthRunner;
24
+ env?: NodeJS.ProcessEnv;
25
+ }
26
+ export declare function harnessInventory(deps?: HarnessDeps): Promise<HarnessInventory>;
27
+ /** The inventory, or undefined when it is not ready within `ms` (a cold `claude auth status` can take seconds). */
28
+ export declare function harnessInventoryWithin(ms: number, deps?: HarnessDeps): Promise<HarnessInventory | undefined>;
29
+ /** `PHREN_LAUNCH_CHECK=off`: no early launch refusal and no `harnesses` advertised to dispatch (tests, or a misreporting computer). */
30
+ export declare function launchCheckOff(env?: NodeJS.ProcessEnv): boolean;
31
+ export type Availability = {
32
+ ok: true;
33
+ } | {
34
+ ok: false;
35
+ code: "harness_unavailable" | "account_unavailable";
36
+ reason: string;
37
+ };
38
+ /** Whether a launch of `source` (and `accountId`) should work on a computer with this inventory. */
39
+ export declare function hasUsable(inventory: HarnessInventory, source: string, accountId?: string): Availability;