@phren/cli 0.3.58 → 0.3.61

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 (91) hide show
  1. package/README.md +1 -1
  2. package/dist/bridge/account-add.d.ts +30 -0
  3. package/dist/bridge/account-add.js +125 -19
  4. package/dist/bridge/account-failover.d.ts +9 -2
  5. package/dist/bridge/account-failover.js +1 -1
  6. package/dist/bridge/account-policy.d.ts +44 -0
  7. package/dist/bridge/account-policy.js +103 -0
  8. package/dist/bridge/account-pools.d.ts +35 -0
  9. package/dist/bridge/account-pools.js +171 -0
  10. package/dist/bridge/account-usage.d.ts +29 -4
  11. package/dist/bridge/account-usage.js +117 -8
  12. package/dist/bridge/agent-hook-callback.d.ts +6 -0
  13. package/dist/bridge/agent-hook-callback.js +10 -2
  14. package/dist/bridge/agent-hook-stores.d.ts +3 -0
  15. package/dist/bridge/agent-hook-stores.js +13 -0
  16. package/dist/bridge/agent-hooks.d.ts +12 -2
  17. package/dist/bridge/agent-hooks.js +41 -4
  18. package/dist/bridge/claude-account-setup.d.ts +16 -0
  19. package/dist/bridge/claude-account-setup.js +46 -2
  20. package/dist/bridge/claude-accounts.d.ts +9 -0
  21. package/dist/bridge/claude-accounts.js +53 -15
  22. package/dist/bridge/claude-credits.d.ts +8 -2
  23. package/dist/bridge/claude-credits.js +52 -31
  24. package/dist/bridge/codex-threads.js +50 -2
  25. package/dist/bridge/command.js +12 -3
  26. package/dist/bridge/continuation-launch.d.ts +32 -0
  27. package/dist/bridge/continuation-launch.js +112 -1
  28. package/dist/bridge/dispatch-command.js +22 -0
  29. package/dist/bridge/dispatch-returns.d.ts +23 -0
  30. package/dist/bridge/dispatch-returns.js +57 -0
  31. package/dist/bridge/dispatch.d.ts +26 -4
  32. package/dist/bridge/dispatch.js +100 -11
  33. package/dist/bridge/git-host-gitlab.js +2 -1
  34. package/dist/bridge/git-hosts.d.ts +8 -0
  35. package/dist/bridge/git-hosts.js +16 -2
  36. package/dist/bridge/git-publish.js +18 -2
  37. package/dist/bridge/git.d.ts +8 -0
  38. package/dist/bridge/git.js +24 -1
  39. package/dist/bridge/hand-off-queue.d.ts +71 -0
  40. package/dist/bridge/hand-off-queue.js +38 -0
  41. package/dist/bridge/harnesses.d.ts +12 -0
  42. package/dist/bridge/harnesses.js +20 -4
  43. package/dist/bridge/helper.d.ts +54 -0
  44. package/dist/bridge/helper.js +186 -0
  45. package/dist/bridge/herdr.js +6 -2
  46. package/dist/bridge/hook-fast.d.ts +3 -0
  47. package/dist/bridge/hook-fast.js +10 -2
  48. package/dist/bridge/move-computers.d.ts +15 -1
  49. package/dist/bridge/move-computers.js +123 -26
  50. package/dist/bridge/owner-inbox-sources.d.ts +12 -1
  51. package/dist/bridge/owner-inbox-sources.js +127 -49
  52. package/dist/bridge/peers.d.ts +2 -0
  53. package/dist/bridge/peers.js +35 -4
  54. package/dist/bridge/prompt-deliveries.d.ts +69 -2
  55. package/dist/bridge/prompt-deliveries.js +342 -28
  56. package/dist/bridge/schedule-watch.js +17 -3
  57. package/dist/bridge/server-routes.d.ts +6 -0
  58. package/dist/bridge/server-routes.js +98 -14
  59. package/dist/bridge/server-stream.js +6 -4
  60. package/dist/bridge/server.js +2 -1
  61. package/dist/bridge/session-move.d.ts +70 -1
  62. package/dist/bridge/session-move.js +311 -19
  63. package/dist/bridge/simulators.d.ts +19 -0
  64. package/dist/bridge/simulators.js +93 -13
  65. package/dist/bridge/speech-live.js +132 -22
  66. package/dist/bridge/task-routes.d.ts +16 -16
  67. package/dist/bridge/terminal-herdr.js +6 -1
  68. package/dist/bridge/terminal-tmux.js +9 -5
  69. package/dist/bridge/terminal.d.ts +9 -2
  70. package/dist/bridge/transcript-claude.d.ts +3 -0
  71. package/dist/bridge/transcript-claude.js +175 -29
  72. package/dist/bridge/transcript-preview.d.ts +11 -2
  73. package/dist/bridge/transcript-preview.js +90 -8
  74. package/dist/bridge/turn-records.d.ts +19 -0
  75. package/dist/bridge/turn-records.js +78 -3
  76. package/dist/bridge/usage.d.ts +17 -0
  77. package/dist/bridge/usage.js +3 -2
  78. package/dist/bridge-hook.mjs +11964 -10084
  79. package/dist/cli-registry.js +2 -2
  80. package/dist/content/citation.d.ts +4 -0
  81. package/dist/content/citation.js +21 -21
  82. package/dist/data/task-contract.d.ts +4 -4
  83. package/dist/governance/policy.js +5 -2
  84. package/dist/index.js +1 -1
  85. package/dist/modules/registry.js +5 -5
  86. package/dist/project-config.d.ts +14 -0
  87. package/dist/project-config.js +40 -1
  88. package/dist/tools/dispatch.js +1 -1
  89. package/dist/tools/helper.d.ts +3 -0
  90. package/dist/tools/helper.js +44 -0
  91. package/package.json +1 -1
@@ -11,22 +11,29 @@ const execFileAsync = promisify(execFile);
11
11
  * slot, for good. */
12
12
  const exec = (file, args, options) => execFileAsync(file, args, { ...options, killSignal: "SIGKILL", encoding: "utf8" });
13
13
  export const SIMULATOR_UDID = /^[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}$/i;
14
- /** The iOS simulators booted on this Mac, from `simctl`; none elsewhere. */
15
- export async function bootedSimulators() {
16
- if (process.platform !== "darwin")
17
- return [];
18
- const { stdout } = await exec("/usr/bin/xcrun", ["simctl", "list", "devices", "booted", "-j"], { timeout: 8_000, maxBuffer: 4_194_304 }).catch(() => ({ stdout: "{}" }));
19
- let parsed = {};
14
+ /** `simctl list devices [filter] -j`, parsed (every device without a filter); undefined when simctl failed, timed
15
+ * out or answered nonsense. */
16
+ async function listDevices(filter) {
17
+ const listed = await exec("/usr/bin/xcrun", ["simctl", "list", "devices", ...(filter ? [filter] : []), "-j"], { timeout: 8_000, maxBuffer: 8_388_608 }).catch(() => undefined);
18
+ if (!listed)
19
+ return undefined;
20
20
  try {
21
- parsed = JSON.parse(stdout);
21
+ return JSON.parse(listed.stdout);
22
22
  }
23
23
  catch {
24
- return [];
24
+ return undefined;
25
25
  }
26
+ }
27
+ /** com.apple.CoreSimulator.SimRuntime.iOS-26-1 → iOS 26.1 */
28
+ const runtimeName = (runtimeID) => runtimeID.replace(/^.*SimRuntime\./, "").replace(/-(\d+)-(\d+)$/, " $1.$2").replace(/-/g, " ");
29
+ /** The iOS simulators booted on this Mac, from `simctl`; none elsewhere. */
30
+ export async function bootedSimulators() {
31
+ if (process.platform !== "darwin")
32
+ return [];
33
+ const parsed = await listDevices("booted") ?? {};
26
34
  const list = [];
27
35
  for (const [runtimeID, devices] of Object.entries(parsed.devices ?? {})) {
28
- // com.apple.CoreSimulator.SimRuntime.iOS-26-1 → iOS 26.1
29
- const runtime = runtimeID.replace(/^.*SimRuntime\./, "").replace(/-(\d+)-(\d+)$/, " $1.$2").replace(/-/g, " ");
36
+ const runtime = runtimeName(runtimeID);
30
37
  for (const device of devices ?? []) {
31
38
  if (device.state !== "Booted" || !device.udid || !SIMULATOR_UDID.test(device.udid))
32
39
  continue;
@@ -37,6 +44,46 @@ export async function bootedSimulators() {
37
44
  }
38
45
  return list;
39
46
  }
47
+ /** Most devices `GET /v1/simulators?all=1` lists. */
48
+ export const SIMULATOR_DEVICE_LIMIT = 64;
49
+ /**
50
+ * Every iOS simulator this Mac can run (`simctl list devices available`), booted or not, with its `state`
51
+ * (`Booted`, `Shutdown`, `Booting`, `Shutting Down`): booted ones first, then the newest runtime, then by
52
+ * name, at most SIMULATOR_DEVICE_LIMIT. For the phone's device picker, which boots one from here.
53
+ */
54
+ export async function simulatorDevices() {
55
+ if (process.platform !== "darwin")
56
+ return [];
57
+ const parsed = await listDevices("available") ?? {};
58
+ const list = [];
59
+ for (const [runtimeID, devices] of Object.entries(parsed.devices ?? {})) {
60
+ if (!/SimRuntime\.iOS-/.test(runtimeID))
61
+ continue;
62
+ const version = (/iOS-(\d+)-(\d+)/.exec(runtimeID) ?? []).slice(1).map(Number);
63
+ for (const device of devices ?? []) {
64
+ if (device.isAvailable === false || !device.udid || !SIMULATOR_UDID.test(device.udid))
65
+ continue;
66
+ const state = typeof device.state === "string" && /^[A-Za-z ]{1,32}$/.test(device.state) ? device.state : "Unknown";
67
+ list.push({ udid: device.udid.toUpperCase(), name: String(device.name ?? "Simulator").slice(0, 120), runtime: runtimeName(runtimeID), state, version });
68
+ }
69
+ }
70
+ const newer = (a, b) => (b[0] ?? 0) - (a[0] ?? 0) || (b[1] ?? 0) - (a[1] ?? 0);
71
+ return list.sort((a, b) => Number(b.state === "Booted") - Number(a.state === "Booted") || newer(a.version, b.version) || a.name.localeCompare(b.name))
72
+ .slice(0, SIMULATOR_DEVICE_LIMIT).map(({ version: _version, ...device }) => device);
73
+ }
74
+ /** A simulator's state as `simctl` reports it now, from every device it has (a booted device whose runtime is no
75
+ * longer available still shuts down): `missing` when simctl lists no such device, undefined when it couldn't say. */
76
+ async function deviceState(udid) {
77
+ const listed = await listDevices();
78
+ if (!listed)
79
+ return undefined;
80
+ for (const devices of Object.values(listed.devices ?? {})) {
81
+ const device = devices?.find(d => d.udid?.toUpperCase() === udid.toUpperCase());
82
+ if (device)
83
+ return String(device.state ?? "");
84
+ }
85
+ return "missing";
86
+ }
40
87
  /** A PNG of one booted simulator's screen. */
41
88
  export async function simulatorScreenshot(udid) {
42
89
  if (!SIMULATOR_UDID.test(udid))
@@ -57,6 +104,8 @@ export async function simulatorScreenshot(udid) {
57
104
  await unlink(file).catch(() => undefined);
58
105
  }
59
106
  }
107
+ /** A drag's duration bounds, in ms. */
108
+ export const DRAG_DEFAULT_MS = 300, DRAG_MIN_MS = 50, DRAG_MAX_MS = 5_000;
60
109
  const HELPER_LABEL = { simtap: "simulator input helper", simcast: "simulator stream helper" };
61
110
  const building = new Map();
62
111
  function helper(name) {
@@ -156,17 +205,37 @@ const KEY_H = "4", KEY_L = "37";
156
205
  export async function simulatorAct(udid, request) {
157
206
  if (!SIMULATOR_UDID.test(udid))
158
207
  throw new BridgeError(400, "Invalid simulator identifier.");
159
- if (!["boot", "shutdown", "launch", "openurl", "home", "lock", "type", "tap", "screenshot-ready", "accessibility-settings"].includes(request.action))
208
+ if (!["boot", "shutdown", "launch", "openurl", "home", "lock", "type", "tap", "drag", "screenshot-ready", "accessibility-settings"].includes(request.action))
160
209
  throw new BridgeError(400, "Unknown simulator action.");
161
210
  if (process.platform !== "darwin")
162
211
  throw new BridgeError(404, "Simulators run on macOS only.");
163
212
  const simctl = (...args) => exec("/usr/bin/xcrun", ["simctl", ...args], { timeout: 30_000 }).catch(() => { throw new BridgeError(409, `simctl ${args[0]} failed for that simulator.`); });
213
+ // Boot and shutdown take any device, booted or not, and a device already in (or on its way to) the asked-for
214
+ // state is not a failure: the phone's picker may be a moment behind. A list that failed (simctl slow to start)
215
+ // is no reason to refuse; simctl itself then says.
216
+ const settle = async (verb, done) => {
217
+ const state = await deviceState(udid);
218
+ if (state === "missing")
219
+ throw new BridgeError(404, "No such simulator on this Mac.");
220
+ if (state !== undefined && done.includes(state))
221
+ return;
222
+ try {
223
+ await simctl(verb, udid);
224
+ }
225
+ catch (error) {
226
+ const now = await deviceState(udid);
227
+ if (now === undefined || !done.includes(now))
228
+ throw error;
229
+ }
230
+ };
164
231
  switch (request.action) {
165
232
  case "boot":
166
- await simctl("boot", udid);
233
+ await settle("boot", ["Booted", "Booting"]);
234
+ // Taps, drags and keys go to the device's window in the Simulator app, which booting alone doesn't open.
235
+ await exec("/usr/bin/open", ["-a", "Simulator", "--args", "-CurrentDeviceUDID", udid.toUpperCase()], { timeout: 15_000 }).catch(() => undefined);
167
236
  break;
168
237
  case "shutdown":
169
- await simctl("shutdown", udid);
238
+ await settle("shutdown", ["Shutdown", "Shutting Down"]);
170
239
  break;
171
240
  case "launch":
172
241
  if (typeof request.bundleId !== "string" || !/^[A-Za-z0-9][A-Za-z0-9.-]{2,199}$/.test(request.bundleId))
@@ -199,6 +268,17 @@ export async function simulatorAct(udid, request) {
199
268
  await simtap(await deviceName(udid), "tap", String(x), String(y));
200
269
  break;
201
270
  }
271
+ case "drag": {
272
+ // From and to are fractions of the screenshot, as a tap's are.
273
+ const { x1, y1, x2, y2 } = request, durationMs = request.durationMs ?? DRAG_DEFAULT_MS;
274
+ if (![x1, y1, x2, y2].every(v => typeof v === "number" && v >= 0 && v <= 1))
275
+ throw new BridgeError(400, "Drag outside the screen.");
276
+ if (typeof durationMs !== "number" || !Number.isInteger(durationMs) || durationMs < DRAG_MIN_MS || durationMs > DRAG_MAX_MS) {
277
+ throw new BridgeError(400, `A drag takes ${DRAG_MIN_MS} to ${DRAG_MAX_MS} ms.`);
278
+ }
279
+ await simtap(await deviceName(udid), "drag", String(x1), String(y1), String(x2), String(y2), String(durationMs));
280
+ break;
281
+ }
202
282
  case "screenshot-ready": break;
203
283
  case "accessibility-settings": {
204
284
  // The phone's "Open Accessibility settings": ask for the grant again and
@@ -107,6 +107,21 @@ export class SpeakableStream {
107
107
  return spoken.join(" ");
108
108
  }
109
109
  }
110
+ /** The characters of `text` that are not whitespace. */
111
+ function nonSpace(text) {
112
+ return text.replace(/\s+/g, "").length;
113
+ }
114
+ /** `text` after the last sentence its first `count` characters that are not whitespace end (within two of
115
+ * them, as a whole chunk is), so a sentence cut off is said again whole; all of it when they end none. */
116
+ function after(text, count) {
117
+ let rest = text;
118
+ for (const match of text.matchAll(/[.!?:;](?=\s|$)/g)) {
119
+ if (nonSpace(text.slice(0, match.index + 1)) > count + 2)
120
+ break;
121
+ rest = text.slice(match.index + 1).trim();
122
+ }
123
+ return rest;
124
+ }
110
125
  /** Seconds of audio in a chunk of the given format. */
111
126
  function seconds(format, bytes) {
112
127
  const mp3 = /^mp3_\d+_(\d+)$/.exec(format);
@@ -167,12 +182,15 @@ export function relayLiveSpeech(client, query, options = {}) {
167
182
  const formats = SPEECH_FORMATS.filter(format => format === "pcm_24000" || (accepted.has(format) && state.formatAllowed(format)));
168
183
  let models = chosen === FALLBACK_SPEECH_MODEL || state.benchedReason(chosen) ? [FALLBACK_SPEECH_MODEL] : [chosen, FALLBACK_SPEECH_MODEL];
169
184
  const text = new SpeakableStream();
170
- // Everything said so far, replayed into a fallback's socket.
171
- const said = [];
172
185
  let saidLength = 0, done = false, closed = false, started = false;
173
186
  let upstream, endpoint = "speech", format = "pcm_24000", elapsed = 0;
174
187
  /** The current socket's handshake and first-audio timers. */
175
188
  let watch;
189
+ /** Hands words to the current socket, which sends them once open. */
190
+ let put;
191
+ /** Set when a socket ended its audio before the reply was done: the words it never voiced, for the next
192
+ * socket, opened when they are there (at once, or with the reply's next text or its end). */
193
+ let resume;
176
194
  const finish = (code = 1000, reason = "") => {
177
195
  if (closed)
178
196
  return;
@@ -203,17 +221,29 @@ export function relayLiveSpeech(client, query, options = {}) {
203
221
  fail({ code: "speech-invalid", error: "This reply is too long to voice." });
204
222
  return;
205
223
  }
206
- said.push(words);
207
- if (upstream?.readyState === OPEN) {
208
- upstream.send(textFrame(words));
209
- if (saidLength >= FORCED_TEXT)
210
- watch?.voicing();
224
+ if (resume) {
225
+ resume.push(words);
226
+ reopen();
227
+ return;
211
228
  }
229
+ put?.(words);
230
+ };
231
+ /** The next socket for a reply whose last one ended early, with the words that one never voiced. */
232
+ const reopen = () => {
233
+ const words = resume ?? [];
234
+ resume = undefined;
235
+ open(words, true);
212
236
  };
213
- const open = () => {
237
+ /** One ElevenLabs socket, given the words it is to voice first: every word so far for the reply's first
238
+ * socket, what a failed one carried for its fallback, what an ended one never voiced for its successor. */
239
+ const open = (replay = [], resumed = false) => {
214
240
  const model = models[0];
215
241
  endpoint = liveEndpoint(model);
216
242
  format = formats[0];
243
+ // Stream-input times its alignment from its own stream's start; this socket's starts here.
244
+ const base = elapsed;
245
+ const sent = [];
246
+ let sentLength = 0, voicedChars = 0, sentAtFirstAudio = -1;
217
247
  const params = new URLSearchParams({ model_id: model, output_format: format, sync_alignment: "true" });
218
248
  if (endpoint === "speech") {
219
249
  params.set("auto_mode", "true");
@@ -237,6 +267,38 @@ export function relayLiveSpeech(client, query, options = {}) {
237
267
  },
238
268
  stop: () => { clearTimeout(handshake); clearTimeout(firstAudio); },
239
269
  };
270
+ const carry = (words) => {
271
+ sent.push(words);
272
+ sentLength += words.length;
273
+ if (socket.readyState === OPEN) {
274
+ socket.send(textFrame(words));
275
+ if (sentLength >= FORCED_TEXT)
276
+ watch?.voicing();
277
+ }
278
+ };
279
+ for (const words of replay)
280
+ carry(words);
281
+ put = words => { if (current())
282
+ carry(words); };
283
+ /** What this socket was sent and never voiced, by the characters its alignment covered, spaces left out
284
+ * on both sides (ElevenLabs may or may not time the spaces); a chunk short of at most two of its own
285
+ * characters counts as voiced, and one voiced in part is replayed from the sentence its voicing stopped
286
+ * in (a phone frame of several paragraphs is one chunk). Without alignment: what came after its first
287
+ * audio, or nothing once the reply is done (its close was sent with it). */
288
+ const unvoiced = () => {
289
+ if (!voicedChars)
290
+ return done ? [] : sent.slice(Math.max(0, sentAtFirstAudio));
291
+ let covered = 0;
292
+ for (const [index, words] of sent.entries()) {
293
+ const length = nonSpace(words), before = covered;
294
+ covered += length;
295
+ if (voicedChars < covered - Math.min(2, Math.floor(length / 2))) {
296
+ const rest = voicedChars > before ? after(words, voicedChars - before) : words;
297
+ return rest ? [rest, ...sent.slice(index + 1)] : sent.slice(index + 1);
298
+ }
299
+ }
300
+ return [];
301
+ };
240
302
  const detach = () => {
241
303
  clearTimeout(handshake);
242
304
  clearTimeout(firstAudio);
@@ -249,12 +311,14 @@ export function relayLiveSpeech(client, query, options = {}) {
249
311
  };
250
312
  // Before the first audio, the next model (Flash) takes the reply over;
251
313
  // with none left, the phone gets `failure`.
252
- const fallBack = (failure) => {
314
+ // `bench` false: the model voiced this reply already, so it is not set aside for the next.
315
+ const fallBack = (failure, bench = true) => {
253
316
  detach();
254
317
  if (models.length > 1) {
255
- state.bench(model, "failed");
318
+ if (bench)
319
+ state.bench(model, "failed");
256
320
  models = models.slice(1);
257
- open();
321
+ open([...sent], resumed);
258
322
  return;
259
323
  }
260
324
  fail(failure);
@@ -267,7 +331,7 @@ export function relayLiveSpeech(client, query, options = {}) {
267
331
  detach();
268
332
  state.refuseFormat(format);
269
333
  formats.shift();
270
- open();
334
+ open([...sent], resumed);
271
335
  return;
272
336
  }
273
337
  if (!accountFailure(status, code) && (status >= 500 || /model/.test(code))) {
@@ -284,11 +348,11 @@ export function relayLiveSpeech(client, query, options = {}) {
284
348
  return;
285
349
  clearTimeout(handshake);
286
350
  socket.send(JSON.stringify(endpoint === "dialogue" ? { voices: [voice], voice_settings: VOICE_SETTINGS } : { text: " ", voice_settings: VOICE_SETTINGS }));
287
- for (const words of said)
351
+ for (const words of sent)
288
352
  socket.send(textFrame(words));
289
353
  if (done)
290
354
  socket.send(closeFrame());
291
- if (said.length && (done || saidLength >= FORCED_TEXT))
355
+ if (sent.length && (done || sentLength >= FORCED_TEXT))
292
356
  watch?.voicing();
293
357
  });
294
358
  socket.on("message", data => {
@@ -317,15 +381,49 @@ export function relayLiveSpeech(client, query, options = {}) {
317
381
  tell({ type: "start", model, format, audioFormat: info.audio, sampleRate: info.sampleRate });
318
382
  started = true;
319
383
  }
384
+ if (!voiced)
385
+ sentAtFirstAudio = sent.length;
320
386
  voiced = true;
321
387
  clearTimeout(firstAudio);
322
388
  const audio = message.audio, length = Buffer.from(audio, "base64").length;
323
- tell({ type: "audio", audio, alignment: alignment(message.alignment) });
389
+ const timed = alignment(message.alignment, endpoint === "dialogue" ? elapsed : base);
390
+ voicedChars += nonSpace(timed?.characters.join("") ?? "");
391
+ tell({ type: "audio", audio, alignment: timed });
324
392
  elapsed += seconds(format, length);
325
393
  }
326
394
  if (message.isFinal === true || message.is_final === true) {
327
- tell({ type: "done" });
328
- finish();
395
+ // Text-to-dialogue (v4) ends a socket after the text it had, though the reply goes on: what it never
396
+ // voiced, and the reply's next text, go to a fresh socket, timed on from this one's audio.
397
+ // A socket given words (letters or digits: a lone emoji or rule has no sound) that voiced none of
398
+ // them falls back, the phone's done or not: a fresh socket ending just after that done would
399
+ // otherwise end the reply with its words never spoken.
400
+ if (!voiced) {
401
+ if (done && !sent.some(words => /[\p{L}\p{N}]/u.test(words))) {
402
+ tell({ type: "done" });
403
+ finish();
404
+ }
405
+ else
406
+ fallBack({ code: "speech-failed", error: "ElevenLabs ended without voicing the reply." }, !resumed);
407
+ return;
408
+ }
409
+ // Stream-input ends only after the close sent with the phone's done; text-to-dialogue may end after
410
+ // the text it had, done or not, with the reply's last words never voiced.
411
+ let left = done && endpoint === "speech" ? [] : unvoiced();
412
+ // The same words left again by a socket given only them (their one retry): its alignment and the
413
+ // text disagree, so they are taken as voiced rather than sent round again.
414
+ const again = resumed && left.length > 0 && left.length === replay.length && left.every((words, index) => words === replay[index]);
415
+ if (again)
416
+ left = [];
417
+ if (done && !left.length) {
418
+ tell({ type: "done" });
419
+ finish();
420
+ return;
421
+ }
422
+ detach();
423
+ put = undefined;
424
+ resume = left;
425
+ if (left.length)
426
+ reopen();
329
427
  return;
330
428
  }
331
429
  if (message.error)
@@ -354,9 +452,9 @@ export function relayLiveSpeech(client, query, options = {}) {
354
452
  fallBack({ code: "speech-failed", error: "ElevenLabs didn't answer." });
355
453
  });
356
454
  };
357
- /** In seconds from the start of this socket's audio. Stream-input counts
358
- * from the start of its stream; text-to-dialogue from each chunk. */
359
- const alignment = (raw) => {
455
+ /** In seconds from the start of this socket's audio, `offset` on from where the reply's audio stood:
456
+ * stream-input counts from the start of its own stream, text-to-dialogue from each chunk. */
457
+ const alignment = (raw, offset) => {
360
458
  const value = raw;
361
459
  const characters = value?.chars, starts = value?.charStartTimesMs ?? value?.char_start_times_ms, durations = value?.charDurationsMs ?? value?.char_durations_ms;
362
460
  if (!Array.isArray(characters) || !Array.isArray(starts) || !Array.isArray(durations) || !characters.length)
@@ -365,7 +463,6 @@ export function relayLiveSpeech(client, query, options = {}) {
365
463
  return null;
366
464
  if (!characters.every(c => typeof c === "string") || ![...starts, ...durations].every(t => typeof t === "number" && Number.isFinite(t)))
367
465
  return null;
368
- const offset = endpoint === "dialogue" ? elapsed : 0;
369
466
  const round = (t) => Math.round(t * 1_000) / 1_000;
370
467
  return { characters, starts: starts.map(t => round(offset + t / 1_000)), ends: starts.map((t, i) => round(offset + (t + durations[i]) / 1_000)) };
371
468
  };
@@ -392,6 +489,16 @@ export function relayLiveSpeech(client, query, options = {}) {
392
489
  finish();
393
490
  return;
394
491
  }
492
+ // The last socket ended and nothing it left, or came since, is waiting to be voiced.
493
+ if (resume) {
494
+ if (resume.length)
495
+ reopen();
496
+ else {
497
+ tell({ type: "done" });
498
+ finish();
499
+ }
500
+ return;
501
+ }
395
502
  if (upstream?.readyState === OPEN) {
396
503
  upstream.send(closeFrame());
397
504
  watch?.voicing();
@@ -404,10 +511,13 @@ export function relayLiveSpeech(client, query, options = {}) {
404
511
  fail({ code: "speech-invalid", error: "This reply is too long to voice." });
405
512
  return;
406
513
  }
514
+ // The words of the phone's early frames, for the first socket.
515
+ const before = [];
516
+ put = words => { before.push(words); };
407
517
  for (const data of early)
408
518
  handle(data);
409
519
  early = [];
410
520
  if (!closed)
411
- open();
521
+ open(before);
412
522
  })();
413
523
  }
@@ -69,10 +69,6 @@ export declare function getTaskRoute(base: string, url: URL): {
69
69
  };
70
70
  items: {
71
71
  [k: string]: {
72
- responsibility: import("../data/task-contract.js").TaskResponsibility;
73
- readiness: "ready" | "waiting-on-human" | "waiting-on-task";
74
- prerequisites: import("../data/task-contract.js").TaskPrerequisite[];
75
- identity: import("../data/task-contract.js").TaskDependency | null;
76
72
  id: string;
77
73
  stableId?: string;
78
74
  identityAmbiguous?: boolean;
@@ -99,6 +95,10 @@ export declare function getTaskRoute(base: string, url: URL): {
99
95
  taskContractRecords?: string[];
100
96
  taskContractLines?: string[];
101
97
  opaqueContinuationLines?: string[];
98
+ responsibility: import("../data/task-contract.js").TaskResponsibility;
99
+ readiness: "ready" | "waiting-on-human" | "waiting-on-task";
100
+ prerequisites: import("../data/task-contract.js").TaskPrerequisite[];
101
+ identity: import("../data/task-contract.js").TaskDependency | null;
102
102
  }[];
103
103
  };
104
104
  };
@@ -126,10 +126,6 @@ export declare function updateTaskRoute(base: string, input: unknown): {
126
126
  };
127
127
  items: {
128
128
  [k: string]: {
129
- responsibility: import("../data/task-contract.js").TaskResponsibility;
130
- readiness: "ready" | "waiting-on-human" | "waiting-on-task";
131
- prerequisites: import("../data/task-contract.js").TaskPrerequisite[];
132
- identity: import("../data/task-contract.js").TaskDependency | null;
133
129
  id: string;
134
130
  stableId?: string;
135
131
  identityAmbiguous?: boolean;
@@ -156,6 +152,10 @@ export declare function updateTaskRoute(base: string, input: unknown): {
156
152
  taskContractRecords?: string[];
157
153
  taskContractLines?: string[];
158
154
  opaqueContinuationLines?: string[];
155
+ responsibility: import("../data/task-contract.js").TaskResponsibility;
156
+ readiness: "ready" | "waiting-on-human" | "waiting-on-task";
157
+ prerequisites: import("../data/task-contract.js").TaskPrerequisite[];
158
+ identity: import("../data/task-contract.js").TaskDependency | null;
159
159
  }[];
160
160
  };
161
161
  };
@@ -185,10 +185,6 @@ export declare function createTaskRoute(base: string, input: unknown): {
185
185
  };
186
186
  items: {
187
187
  [k: string]: {
188
- responsibility: import("../data/task-contract.js").TaskResponsibility;
189
- readiness: "ready" | "waiting-on-human" | "waiting-on-task";
190
- prerequisites: import("../data/task-contract.js").TaskPrerequisite[];
191
- identity: import("../data/task-contract.js").TaskDependency | null;
192
188
  id: string;
193
189
  stableId?: string;
194
190
  identityAmbiguous?: boolean;
@@ -215,6 +211,10 @@ export declare function createTaskRoute(base: string, input: unknown): {
215
211
  taskContractRecords?: string[];
216
212
  taskContractLines?: string[];
217
213
  opaqueContinuationLines?: string[];
214
+ responsibility: import("../data/task-contract.js").TaskResponsibility;
215
+ readiness: "ready" | "waiting-on-human" | "waiting-on-task";
216
+ prerequisites: import("../data/task-contract.js").TaskPrerequisite[];
217
+ identity: import("../data/task-contract.js").TaskDependency | null;
218
218
  }[];
219
219
  };
220
220
  };
@@ -244,10 +244,6 @@ export declare function saveTaskRoute(base: string, input: unknown): {
244
244
  };
245
245
  items: {
246
246
  [k: string]: {
247
- responsibility: import("../data/task-contract.js").TaskResponsibility;
248
- readiness: "ready" | "waiting-on-human" | "waiting-on-task";
249
- prerequisites: import("../data/task-contract.js").TaskPrerequisite[];
250
- identity: import("../data/task-contract.js").TaskDependency | null;
251
247
  id: string;
252
248
  stableId?: string;
253
249
  identityAmbiguous?: boolean;
@@ -274,6 +270,10 @@ export declare function saveTaskRoute(base: string, input: unknown): {
274
270
  taskContractRecords?: string[];
275
271
  taskContractLines?: string[];
276
272
  opaqueContinuationLines?: string[];
273
+ responsibility: import("../data/task-contract.js").TaskResponsibility;
274
+ readiness: "ready" | "waiting-on-human" | "waiting-on-task";
275
+ prerequisites: import("../data/task-contract.js").TaskPrerequisite[];
276
+ identity: import("../data/task-contract.js").TaskDependency | null;
277
277
  }[];
278
278
  };
279
279
  };
@@ -144,7 +144,12 @@ export const herdrTerminal = {
144
144
  }
145
145
  },
146
146
  async create(server, { workspace, label, cwd, env }) {
147
- await rpc(server, workspace ? "tab.create" : "workspace.create", { workspace_id: workspace, label, cwd, focus: false, env: env ?? {} });
147
+ const created = await rpc(server, workspace ? "tab.create" : "workspace.create", { workspace_id: workspace, label, cwd, focus: false, env: env ?? {} });
148
+ // Both answers name the new tab's first pane.
149
+ const root = object(object(created).root_pane);
150
+ if (typeof root.pane_id === "string" && typeof root.tab_id === "string" && typeof root.workspace_id === "string") {
151
+ return { workspace: root.workspace_id, tab: root.tab_id, pane: root.pane_id };
152
+ }
148
153
  },
149
154
  // `agent.start` takes no environment; the pane's shell got it at `create`.
150
155
  async startAgent(server, pane, agent) {
@@ -430,12 +430,16 @@ export const tmuxTerminal = {
430
430
  async create(server, { workspace, label, cwd }) {
431
431
  const directory = cwd && path.isAbsolute(cwd) ? ["-c", cwd] : [];
432
432
  const name = label ? ["-n", label.replace(/[\x00-\x1f\x7f]/g, " ").slice(0, 100)] : [];
433
- if (workspace) {
434
- await tmux(server, ["new-window", "-d", "-t", `${toTmuxId(workspace, "s")}:`, ...directory, ...name]);
435
- return;
436
- }
433
+ // `-P -F` prints the new pane's ids, so the caller knows it without diffing the pane list.
434
+ const printed = ["-P", "-F", "#{session_id} #{window_id} #{pane_id}"];
435
+ const created = (output) => {
436
+ const [session, window, pane] = output.trim().split(/\s+/).map(fromTmuxId);
437
+ return session && window && pane ? { workspace: session, tab: window, pane } : undefined;
438
+ };
439
+ if (workspace)
440
+ return created(await tmux(server, ["new-window", "-d", ...printed, "-t", `${toTmuxId(workspace, "s")}:`, ...directory, ...name]));
437
441
  const taken = new Set((await tmux(server, ["list-sessions", "-F", "#{session_name}"]).catch(() => "")).split("\n").filter(Boolean));
438
- await tmux(server, ["new-session", "-d", "-s", sessionName(label, taken), "-x", "200", "-y", "50", ...directory, ...name]);
442
+ return created(await tmux(server, ["new-session", "-d", ...printed, "-s", sessionName(label, taken), "-x", "200", "-y", "50", ...directory, ...name]));
439
443
  },
440
444
  async startAgent(server, pane, { name, kind, args, timeoutMs, env }) {
441
445
  if (!["claude", "codex", "copilot", "opencode", "phren"].includes(kind))
@@ -7,6 +7,12 @@ export declare function terminalPaneFromEnv(env?: NodeJS.ProcessEnv): Promise<{
7
7
  tab: string;
8
8
  pane: string;
9
9
  } | undefined>;
10
+ /** The pane `create` opened, in the Hook's ids. */
11
+ export interface CreatedPane {
12
+ workspace: string;
13
+ tab: string;
14
+ pane: string;
15
+ }
10
16
  /** A pane as the multiplexer lists it. `server` names the multiplexer instance
11
17
  * (a Herdr session, a tmux socket), `workspace` and `tab` its place in it
12
18
  * (a Herdr workspace and tab, a tmux session and window). */
@@ -100,8 +106,9 @@ export interface TerminalProvider {
100
106
  prompt(server: string, pane: string, text: string, signal?: AbortSignal): Promise<void>;
101
107
  /** Run an owner-selected command at an empty pane's shell prompt. */
102
108
  shellCommand?(server: string, pane: string, command: string): Promise<void>;
103
- /** Opens a pane; the caller finds it in the next `listPanes`. */
104
- create(server: string, placement: PanePlacement): Promise<void>;
109
+ /** Opens a pane, answering which one when the multiplexer says (Herdr's `root_pane`, tmux's `-P`); else the
110
+ * caller finds it in the next `listPanes`, which another pane opened at the same time can confuse. */
111
+ create(server: string, placement: PanePlacement): Promise<CreatedPane | void>;
105
112
  startAgent(server: string, pane: string, agent: AgentStart): Promise<void>;
106
113
  /** The variables a process started for `pane` outside it needs to be
107
114
  * recognized as running there (a Codex app-server whose hooks report the
@@ -6,6 +6,9 @@ import type { ChildAgentRelation } from "./transcripts.js";
6
6
  * too: Git routes must fail explicitly when a checkout disappears, never
7
7
  * substitute the parent repository. */
8
8
  export declare function claudeChildCheckout(file: string): Promise<Pick<ChildAgentRelation, "cwd" | "worktreeName" | "branch">>;
9
+ /** How long after a Stop its list of running background agents is believed: a session that exits leaves its
10
+ * last Stop behind, and an agent of it that never finished must not run forever. */
11
+ export declare const CLAUDE_STOP_TRUST_MS: number;
9
12
  export declare function claudeChildAgents(file: string, session: string): Promise<ChildAgentRelation[]>;
10
13
  /** How long a background skill's transcript may sit unchanged before it is
11
14
  * taken as finished: the parent records no end for it, and a session that