@phren/cli 0.3.28 → 0.3.31

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 (65) hide show
  1. package/dist/bridge/agent-hooks.d.ts +5 -55
  2. package/dist/bridge/agent-hooks.js +22 -155
  3. package/dist/bridge/codex-servers.d.ts +12 -0
  4. package/dist/bridge/codex-servers.js +35 -3
  5. package/dist/bridge/codex-thread-origin.d.ts +12 -0
  6. package/dist/bridge/codex-thread-origin.js +31 -0
  7. package/dist/bridge/hand-off-queue.d.ts +16 -0
  8. package/dist/bridge/hand-off-queue.js +62 -19
  9. package/dist/bridge/hook-main.js +12 -2
  10. package/dist/bridge/prompt-deliveries.d.ts +99 -0
  11. package/dist/bridge/prompt-deliveries.js +327 -0
  12. package/dist/bridge/prompt-once.d.ts +2 -0
  13. package/dist/bridge/prompt-once.js +2 -0
  14. package/dist/bridge/resources.d.ts +21 -0
  15. package/dist/bridge/resources.js +58 -2
  16. package/dist/bridge/server-launch.js +2 -1
  17. package/dist/bridge/server-pane-routes.js +72 -34
  18. package/dist/bridge/server-routes.d.ts +1 -0
  19. package/dist/bridge/server-routes.js +34 -3
  20. package/dist/bridge/server-stream.js +4 -2
  21. package/dist/bridge/server.js +12 -3
  22. package/dist/bridge/simulators.d.ts +3 -1
  23. package/dist/bridge/simulators.js +40 -5
  24. package/dist/bridge/sudo.d.ts +1 -1
  25. package/dist/bridge/sudo.js +51 -17
  26. package/dist/bridge/task-routes.d.ts +282 -0
  27. package/dist/bridge/task-routes.js +162 -0
  28. package/dist/bridge/uploads.d.ts +4 -0
  29. package/dist/bridge/uploads.js +15 -0
  30. package/dist/bridge-hook.mjs +18218 -15566
  31. package/dist/cli/namespaces-store.js +32 -1
  32. package/dist/cli/namespaces-tasks.d.ts +1 -0
  33. package/dist/cli/namespaces-tasks.js +55 -4
  34. package/dist/cli/ops.d.ts +2 -1
  35. package/dist/cli/ops.js +20 -4
  36. package/dist/cli-registry.js +5 -4
  37. package/dist/data/task-contract.d.ts +75 -0
  38. package/dist/data/task-contract.js +161 -0
  39. package/dist/data/task-format.d.ts +20 -0
  40. package/dist/data/task-format.js +55 -0
  41. package/dist/data/task-metadata.d.ts +10 -0
  42. package/dist/data/task-metadata.js +24 -0
  43. package/dist/data/task-store-directory.d.ts +21 -0
  44. package/dist/data/task-store-directory.js +37 -0
  45. package/dist/data/tasks.d.ts +38 -2
  46. package/dist/data/tasks.js +221 -28
  47. package/dist/generated/memory-ui-graph.browser.js +328 -333
  48. package/dist/init/setup.js +2 -2
  49. package/dist/memory-ui-graph.runtime.js +328 -333
  50. package/dist/modules/registry.js +3 -3
  51. package/dist/shell/input.js +49 -4
  52. package/dist/shell/state-store.d.ts +1 -0
  53. package/dist/shell/state-store.js +2 -0
  54. package/dist/shell/view.js +19 -3
  55. package/dist/store-registry.d.ts +12 -1
  56. package/dist/store-registry.js +52 -4
  57. package/dist/sync/task-claim.d.ts +1 -0
  58. package/dist/sync/task-claim.js +8 -1
  59. package/dist/sync/task-merge.d.ts +0 -9
  60. package/dist/sync/task-merge.js +48 -1
  61. package/dist/tools/tasks.js +31 -18
  62. package/dist/ui/page.js +1 -0
  63. package/dist/ui/scripts.js +64 -5
  64. package/dist/ui/server.js +18 -0
  65. package/package.json +8 -8
@@ -23,6 +23,61 @@ export const RESOURCES_MAX_AGE_MS = intervalFromEnv("PHREN_RESOURCES_MAX_AGE_MS"
23
23
  /** Below this much free disk, or above twice the cores in load, a computer is stressed. */
24
24
  export const LOW_DISK_BYTES = 10 * 1024 ** 3;
25
25
  const GB = 1024 ** 3;
26
+ /** `system_profiler SPHardwareDataType -json` → model and chip. Intel Macs name
27
+ * the processor in `cpu_type` instead of `chip_type`. */
28
+ export function parseMacHardware(json) {
29
+ const item = JSON.parse(json).SPHardwareDataType?.[0] ?? {};
30
+ const text = (value) => typeof value === "string" && value.trim() ? value.trim().slice(0, 80) : undefined;
31
+ const model = text(item.machine_name), chip = text(item.chip_type) ?? text(item.cpu_type);
32
+ return { ...(model ? { model } : {}), ...(chip ? { chip } : {}) };
33
+ }
34
+ /** DMI vendor and product → "Dell XPS 13 9310", "Lenovo ThinkPad X1 Carbon";
35
+ * placeholder strings firmware leaves in are dropped. */
36
+ export function linuxModel(vendor, product, version) {
37
+ const clean = (value) => {
38
+ const text = value?.replace(/\s+/g, " ").trim();
39
+ return text && !/^(to be filled|default string|system (product name|manufacturer)|not specified|none|o\.e\.m\.?|unknown)/i.test(text) ? text : undefined;
40
+ };
41
+ const brand = clean(vendor)?.replace(/,?\s+(Inc\.?|Corporation|Corp\.?|Co\.,? Ltd\.?|Ltd\.?|GmbH|Technology)$/i, "");
42
+ // Lenovo puts the marketing name in product_version and a part number in product_name.
43
+ const name = brand === "LENOVO" || brand === "Lenovo" ? clean(version) ?? clean(product) : clean(product);
44
+ if (!name)
45
+ return brand;
46
+ const label = brand && !name.toLowerCase().startsWith(brand.toLowerCase()) ? `${brand === "LENOVO" ? "Lenovo" : brand} ${name}` : name;
47
+ return label.slice(0, 80);
48
+ }
49
+ /** /proc/cpuinfo's first `model name`, without the (R)/(TM) marks, "CPU" and clock. */
50
+ export function linuxChip(cpuinfo) {
51
+ const raw = /^model name\s*:\s*(.+)$/m.exec(cpuinfo)?.[1];
52
+ const chip = raw?.replace(/\((R|TM|tm|r)\)/g, "").replace(/\s+@\s+.*$/, "").replace(/\bCPU\b/g, "")
53
+ .replace(/\b\d+-Core Processor\b/i, "").replace(/\s+/g, " ").trim();
54
+ return chip ? chip.slice(0, 80) : undefined;
55
+ }
56
+ let hardwareRead;
57
+ /** Read once; the answer can't change while the Hook runs. */
58
+ export function computerHardware(platform = process.platform) {
59
+ hardwareRead ??= (async () => {
60
+ const base = { memoryBytes: totalmem(), cores: cpus().length || 1 };
61
+ if (platform === "darwin") {
62
+ // system_profiler takes about half a second, more under load.
63
+ const found = await exec("/usr/sbin/system_profiler", ["SPHardwareDataType", "-json"], { timeout: 20_000, maxBuffer: 1024 * 1024 })
64
+ .then(result => parseMacHardware(result.stdout)).catch(() => undefined);
65
+ // A failed read is tried again on the next collection rather than kept.
66
+ if (!found)
67
+ hardwareRead = undefined;
68
+ return { ...found, ...base };
69
+ }
70
+ if (platform === "linux") {
71
+ const dmi = (name) => readFile(`/sys/devices/virtual/dmi/id/${name}`, "utf8").catch(() => undefined);
72
+ const [vendor, product, version, cpuinfo] = await Promise.all([dmi("sys_vendor"), dmi("product_name"), dmi("product_version"),
73
+ readFile("/proc/cpuinfo", "utf8").catch(() => "")]);
74
+ const model = linuxModel(vendor, product, version), chip = linuxChip(cpuinfo);
75
+ return { ...(model ? { model } : {}), ...(chip ? { chip } : {}), ...base };
76
+ }
77
+ return base;
78
+ })();
79
+ return hardwareRead;
80
+ }
26
81
  /** `ps -axo pid=,ppid=,pgid=,pcpu=,rss=,comm=` paired with the `args=` listing by
27
82
  * pid. The older five-column stats (no pgid) still parse, with pgid 0. */
28
83
  export function parsePs(stats, args) {
@@ -341,7 +396,7 @@ export async function collectResources(deps) {
341
396
  const cores = cpus().length || 1;
342
397
  const platform = deps.platform;
343
398
  const registry = deps.jobs ?? new JobRegistry();
344
- const [memory, disk, battery, rows, registered] = await Promise.all([
399
+ const [memory, disk, battery, rows, registered, hardware] = await Promise.all([
345
400
  platform === "darwin" ? darwinMemory()
346
401
  : platform === "linux" ? readFile("/proc/meminfo", "utf8").then(parseMeminfo).catch(() => ({ totalBytes: totalmem() }))
347
402
  : Promise.resolve({ totalBytes: totalmem() }),
@@ -350,6 +405,7 @@ export async function collectResources(deps) {
350
405
  : platform === "linux" ? linuxBattery() : Promise.resolve(undefined),
351
406
  deps.processes().catch(() => []),
352
407
  registry.list().catch(() => []),
408
+ (deps.hardware ?? (() => computerHardware(platform)))().catch(() => undefined),
353
409
  ]);
354
410
  // Pane pids cost one terminal call per pane: only when there is a job to name.
355
411
  const preliminary = heavyProcesses(rows, new Map(), registered);
@@ -361,7 +417,7 @@ export async function collectResources(deps) {
361
417
  const value = {
362
418
  collectedAt: new Date(deps.now()).toISOString(), platform, uptimeSeconds: Math.round(uptime()),
363
419
  cpu: { cores, load1: round(one), load5: round(five), load15: round(fifteen), loadPerCore: round(one / cores) },
364
- memory, ...(disk ? { disk } : {}), ...(battery ? { battery } : {}),
420
+ memory, ...(disk ? { disk } : {}), ...(battery ? { battery } : {}), ...(hardware ? { hardware } : {}),
365
421
  heavy: owners.size || jobs.length ? heavyProcesses(rows, owners, jobs) : preliminary,
366
422
  };
367
423
  return { ...value, ...assess(value) };
@@ -514,7 +514,8 @@ async function startSession(server, data, options) {
514
514
  }
515
515
  return { ok: true, ...created, agent: kind, agentStatus, role, sessionId, target, ...(account ? { account } : {}), ...(permissionMode ? { permissionMode } : {}), ...(unchecked.length ? { unchecked } : {}),
516
516
  // The caller types the brief itself unless it went with the launch.
517
- ...(brief ? { briefLaunched: appServer ? briefTurn !== undefined : !!briefLaunch || !!servedBrief } : {}),
517
+ ...(brief ? { briefLaunched: appServer ? briefTurn !== undefined : !!briefLaunch || !!servedBrief,
518
+ briefState: appServer ? briefTurn ?? "unconfirmed" : served ? (servedBrief?.delivered ? "sent" : "uncertain") : briefLaunch ? "sent" : "unconfirmed" } : {}),
518
519
  ...(worktree ? { worktree: { path: worktree.path, branch: worktree.branch } } : {}) };
519
520
  }
520
521
  export async function workspaceAction(server, operation, data) {
@@ -126,7 +126,7 @@ async function resubmitIfIdle(agentHooks, target, text) {
126
126
  } };
127
127
  if (await status() === "working")
128
128
  return "pending";
129
- const late = agentHooks.awaitLateDelivery(target, text);
129
+ const late = agentHooks.deliveries.awaitLate(target, text);
130
130
  await terminalProvider().sendKeys(target.server, target.pane, ["enter"]);
131
131
  const outcome = await late;
132
132
  if (outcome !== "pending")
@@ -143,7 +143,7 @@ export function followQueuedDelivery(agentHooks, target, terminal, text, interva
143
143
  const started = Date.now();
144
144
  let finishedLooks = 0;
145
145
  const look = async () => {
146
- if (!agentHooks.deliveryPending(target, text) || Date.now() - started > 600_000)
146
+ if (!agentHooks.deliveries.pending(target, text) || Date.now() - started > 600_000)
147
147
  return;
148
148
  let pane;
149
149
  try {
@@ -247,13 +247,35 @@ async function servedPrompt(target, session, text, typing) {
247
247
  return undefined;
248
248
  return sent.delivered ? { ok: true, delivered: true } : { ok: true, deliveryUncertain: true };
249
249
  }
250
+ /** A known message's reply by its id: `state` plus the legacy flags. */
251
+ function deliveryReply(agentHooks, id, target, text) {
252
+ const parsed = targetSchema.safeParse(target);
253
+ if (!parsed.success)
254
+ return undefined;
255
+ if (!agentHooks.deliveries.sameMessage(id, parsed.data, text))
256
+ throw new BridgeError(409, "This message id was already used for a different message.");
257
+ const status = agentHooks.deliveries.status(id, parsed.data);
258
+ if (status.state === "unknown")
259
+ return undefined;
260
+ return { ok: status.state !== "failed", state: status.state, ...(status.state === "delivered" ? { delivered: true } : {}),
261
+ ...(status.state === "queued" ? { queued: true } : {}), ...(status.reason ? { reason: status.reason } : {}) };
262
+ }
250
263
  export async function paneRoute(ctx, url, data, response) {
251
264
  if (url.pathname !== "/v1/prompt")
252
265
  return paneRouteOnce(ctx, url, data, response, () => { });
253
266
  // A retried send carries its first attempt's id; the Hook answers it with
254
267
  // that attempt's reply instead of typing the message a second time.
255
268
  const id = deliveryIdSchema.parse(data.deliveryId);
256
- return promptOnce.run(id, promptScope(object(data.target), String(data.text ?? "")), async (typing) => object(await paneRouteOnce(ctx, url, data, response, typing)));
269
+ const scope = promptScope(object(data.target), String(data.text ?? ""));
270
+ // The Hook keeps each message's state by its id (prompt-deliveries.ts), so
271
+ // a retry, even after a Hook restart, answers with where the message is
272
+ // now. Only a failed one is typed again, under the same id.
273
+ const known = id ? deliveryReply(ctx.agentHooks, id, object(data.target), String(data.text ?? "")) : undefined;
274
+ if (known && known.state !== "failed")
275
+ return { ...known, replayed: true };
276
+ if (known)
277
+ promptOnce.forget(id);
278
+ return promptOnce.run(id, scope, async (typing) => object(await paneRouteOnce(ctx, url, data, response, typing)));
257
279
  }
258
280
  export async function paneRouteOnce(ctx, url, data, response, typing) {
259
281
  const { agentHooks, modelSwitcher, settingsSwitcher, permissionModeSwitcher, codexQuestions, sideQuestions } = ctx;
@@ -358,6 +380,8 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
358
380
  }
359
381
  const text = typeof data.text === "string" && data.text && data.text.length <= 32768 && !/[\x00-\x08\x0b-\x1f\x7f]/.test(data.text) ? data.text : undefined;
360
382
  const served = text === undefined ? undefined : await servedPrompt(target, target.session, text, typing);
383
+ if (served?.delivered && text)
384
+ agentHooks.deliveries.delivered(deliveryIdSchema.parse(data.deliveryId), target, text);
361
385
  if (served)
362
386
  return served;
363
387
  }
@@ -381,30 +405,48 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
381
405
  }
382
406
  if (target.source === "codex" && /^\s*\/model\s+\S/i.test(text))
383
407
  throw new BridgeError(422, "Use the model picker to switch Codex models.");
384
- // A Codex pane on the Hook's own app-server takes the prompt as a turn on
385
- // its thread, acknowledged with the turn id; nothing is typed. A slash
408
+ // A Codex pane on the Hook's own app-server takes the prompt on its
409
+ // thread, as the TUI takes Enter: steered into a running turn, else a new
410
+ // turn; nothing is typed. The turn id only says Codex has it: the model
411
+ // reads it at its next step, possibly after a long tool call, and Codex's
412
+ // UserPromptSubmit says when. Until then it is queued, like typed text. A slash
386
413
  // command is the TUI's own and is still typed. An unreachable server
387
414
  // sent nothing, so the pane is typed into instead; a request that may
388
415
  // have reached it is reported uncertain and never retried.
389
416
  const owned = text.trim().startsWith("/") ? undefined : codexServers.forTarget(target);
390
417
  if (owned) {
391
418
  await typing();
419
+ const id = deliveryIdSchema.parse(data.deliveryId), refused = new AbortController();
420
+ // An idle thread starts the turn and confirms in about two seconds; a
421
+ // running one takes the text only after its current step.
422
+ const taken = agentHooks.deliveries.expect(target, text, owned.activeTurn ? 300 : 4_000, refused.signal, id, typeof pane.terminal_id === "string" ? pane.terminal_id : undefined);
392
423
  try {
393
- const { turnId } = await codexServers.prompt(owned, text);
394
- return { ok: true, delivered: true, turnId };
424
+ const { turnId } = await codexServers.send(owned, text);
425
+ if (await taken === "delivered")
426
+ return { ok: true, delivered: true, state: "delivered", turnId };
427
+ if (id)
428
+ agentHooks.deliveries.queue(id, target);
429
+ return { ok: true, queued: true, ...(id ? { state: "queued" } : {}), turnId };
395
430
  }
396
431
  catch (error) {
397
- if (error instanceof AppServerRpcError)
432
+ if (error instanceof AppServerRpcError) {
433
+ refused.abort();
398
434
  throw new BridgeError(409, `Codex refused the message: ${error.message}`);
399
- if (!(error instanceof CodexServerUnavailable))
400
- return { ok: true, deliveryUncertain: true };
435
+ }
436
+ if (error instanceof CodexServerUnavailable)
437
+ refused.abort();
438
+ else {
439
+ if (id)
440
+ agentHooks.deliveries.queue(id, target);
441
+ return { ok: true, deliveryUncertain: true, ...(id ? { state: "queued" } : {}) };
442
+ }
401
443
  }
402
444
  }
403
445
  const deliveryId = deliveryIdSchema.parse(data.deliveryId);
404
446
  let busy = String(pane.agent_status) === "working";
405
447
  let outcome = await promptWithStartupRetry(async () => {
406
448
  const refused = new AbortController();
407
- const expected = agentHooks.expectDelivery(target, text, busy && target.source !== "claude" ? 300 : 1_500, refused.signal, deliveryId);
449
+ const expected = agentHooks.deliveries.expect(target, text, busy && target.source !== "claude" ? 300 : 1_500, refused.signal, deliveryId, typeof pane.terminal_id === "string" ? pane.terminal_id : undefined);
408
450
  await typing();
409
451
  try {
410
452
  await terminalProvider().prompt(target.server, target.pane, text);
@@ -435,45 +477,40 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
435
477
  else
436
478
  followQueuedDelivery(agentHooks, target, pane.terminal_id, text);
437
479
  }
438
- const refusedHere = () => new BridgeError(409, "The conversation in this pane changed; the message was not delivered. Reopen the chat and send it again.");
439
- if (outcome === "blocked")
440
- throw refusedHere();
441
480
  // A bare slash command opens the agent's own menu; the phone may
442
481
  // walk it with keys for the next half minute. The command rides
443
482
  // along so a Codex /permissions walk can find its confirmation.
444
483
  if (/^\/[a-z][a-z0-9_-]*$/i.test(text.trim()))
445
484
  agentHooks.menuOpened(target, text.trim());
446
485
  if (outcome === "delivered")
447
- result = { ok: true, delivered: true };
486
+ result = { ok: true, delivered: true, state: "delivered" };
448
487
  else if (outcome === "unsubmitted") {
449
- result = { ok: true, deliveryUncertain: true, unsubmitted: true };
488
+ const reason = "The agent did not take the message; it may still be in its input line.";
489
+ if (deliveryId)
490
+ agentHooks.deliveries.fail(deliveryId, target, reason);
491
+ result = { ok: true, deliveryUncertain: true, unsubmitted: true, ...(deliveryId ? { state: "failed", reason } : {}) };
450
492
  }
451
493
  else {
452
- // The agent has not submitted it yet (a busy agent queues typed
453
- // input). Recheck fresh identity and never retry; a late
454
- // submission to another conversation is still refused above. A bare
455
- // ok acknowledges transport only, even if this is still the same
456
- // conversation. Callers needing a submitted turn require delivered.
494
+ // The agent has not submitted it yet: a busy agent holds typed input
495
+ // until its turn ends. The record is bound to the pane, so whichever
496
+ // conversation is there then takes it, and the Hook fails it loudly if
497
+ // the agent closes, restarts or ends its turn without it. A failed
498
+ // identity probe still says deliveryUncertain to phones without
499
+ // `paneDeliveries`. Never retried here.
457
500
  let confirmed = false;
458
501
  try {
459
502
  const current = findPane(await snapshot(target.server), target);
460
503
  confirmed = !!current && current.terminal_id === pane.terminal_id && await paneIdentity(target.server, current, true) === target.session;
461
504
  }
462
505
  catch { /* No reliable post-delivery identity. */ }
463
- // The hook can take it while the identity probe runs; its answer,
464
- // keyed by the delivery id, beats the probe.
465
- const late = deliveryId ? agentHooks.deliveryState(deliveryId, target) : "unknown";
466
- if (late === "blocked")
467
- throw refusedHere();
506
+ // The hook can take it while the identity probe runs.
507
+ const late = deliveryId ? agentHooks.deliveries.status(deliveryId, target).state : "unknown";
468
508
  if (late === "delivered")
469
- result = { ok: true, delivered: true };
509
+ result = { ok: true, delivered: true, state: "delivered" };
470
510
  else {
471
- // Still this conversation, in the same terminal: the agent holds the
472
- // message (a busy turn queues it) and its hook has not submitted it
473
- // yet. Queued, not delivered; `/v1/prompt/status` says when it lands.
474
- if (confirmed && deliveryId)
475
- agentHooks.queueDelivery(deliveryId, target);
476
- result = { ok: true, ...(!confirmed ? { deliveryUncertain: true } : { queued: true }) };
511
+ if (deliveryId)
512
+ agentHooks.deliveries.queue(deliveryId, target);
513
+ result = { ok: true, ...(!confirmed ? { deliveryUncertain: true } : { queued: true }), ...(deliveryId ? { state: "queued" } : {}) };
477
514
  }
478
515
  }
479
516
  }
@@ -482,7 +519,8 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
482
519
  const id = deliveryIdSchema.parse(data.deliveryId);
483
520
  if (!id)
484
521
  throw new BridgeError(400, "Name the message by its deliveryId.");
485
- result = { ok: true, state: agentHooks.deliveryState(id, target) };
522
+ // Bound to the pane: the conversation that took it may be a newer one.
523
+ result = { ok: true, ...agentHooks.deliveries.status(id, target) };
486
524
  }
487
525
  else if (url.pathname === "/v1/side-question/dismiss") {
488
526
  result = sideQuestions.dismiss(target, z.string().uuid().parse(data.id));
@@ -119,6 +119,7 @@ export declare const capabilities: {
119
119
  promptOnce: boolean;
120
120
  promptStatus: boolean;
121
121
  deliveryFrames: boolean;
122
+ paneDeliveries: boolean;
122
123
  resources: boolean;
123
124
  sudo: boolean;
124
125
  sudoOutcome: boolean;
@@ -1,3 +1,4 @@
1
+ import { getTaskRoute, getTaskDirectoryRoute, updateTaskRoute, createTaskRoute, saveTaskRoute, launchTaskRoute } from "./task-routes.js";
1
2
  import { ownerInboxView } from "./owner-inbox-view.js";
2
3
  import { closeFinishedWorker } from "./worker-close.js";
3
4
  import { reportWorker, readIntegrator, setIntegrator } from "./worker-reports.js";
@@ -31,7 +32,7 @@ import { gitRoot, launchDirectory, repositoryBranch, webServers } from "./projec
31
32
  import { approvalDecisions, BridgeError, bridgeRoot, MAX_FRAME, object, objects, PROTOCOL, provider, serverName, targetFromURL, targetSchema } from "./protocol.js";
32
33
  import { bootedSimulators, simulatorAct, simulatorApps, simulatorScreenshot } from "./simulators.js";
33
34
  import { childAgentTree, historicalImage, publicChildAgents, refreshTranscript, runningChildAgents, targetTranscriptPath } from "./transcripts.js";
34
- import { listUploads, saveUpload, uploadImage } from "./uploads.js";
35
+ import { listUploads, removeUpload, saveUpload, uploadImage } from "./uploads.js";
35
36
  import { currentModel, currentStep } from "./steps.js";
36
37
  import { capacityRoom, usageForCaller } from "./usage.js";
37
38
  import { readFinalTurn } from "./schedule-watch.js";
@@ -73,13 +74,20 @@ async function childActivity(source, session) {
73
74
  export const capabilities = { transcript: true, progress: true, images: true, prompt: true, stop: true,
74
75
  terminal: "ssh-pty", shell: "ssh-pty", herdr: true, sessionRename: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
75
76
  approvals: true, questions: false, accountUsage: true, providers: ["codex", "claude", "copilot", "opencode"],
76
- files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, deliveryFrames: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true };
77
+ files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true };
77
78
  export function capabilitiesForModules(snapshot) {
78
79
  const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
79
80
  const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
80
81
  for (const name of ["memory", "tasks", "hook", "git", "schedules"])
81
82
  if (snapshot.has(name))
82
83
  result[name] = true;
84
+ if (snapshot.has("tasks")) {
85
+ result.taskDependencies = true;
86
+ result.taskWriterSafety = true;
87
+ result.taskAtomicCreate = true;
88
+ result.taskAtomicSave = true;
89
+ result.taskBoundLaunch = true;
90
+ }
83
91
  return result;
84
92
  }
85
93
  export function requireRoute(snapshot, method, route) {
@@ -297,6 +305,12 @@ export function createRouteHandler(ctx) {
297
305
  }
298
306
  else if (request.method === "GET") {
299
307
  switch (url.pathname) {
308
+ case "/v1/tasks":
309
+ result = getTaskRoute(modules.store, url);
310
+ break;
311
+ case "/v1/tasks/stores":
312
+ result = await getTaskDirectoryRoute(modules.store);
313
+ break;
300
314
  case "/v1/health":
301
315
  result = { ...info, codePackage: await codePackageStatus(scheduleStore, modules.has("code")) };
302
316
  break;
@@ -623,7 +637,19 @@ export function createRouteHandler(ctx) {
623
637
  }
624
638
  else if (request.method === "POST") {
625
639
  const data = await body(request);
626
- if (url.pathname === "/v1/subagents/resume") {
640
+ if (url.pathname === "/v1/tasks/launch") {
641
+ result = await launches.run(async () => launchTaskRoute(modules.store, selectedServer(url), data));
642
+ }
643
+ else if (url.pathname === "/v1/tasks/save") {
644
+ result = saveTaskRoute(modules.store, data);
645
+ }
646
+ else if (url.pathname === "/v1/tasks/create") {
647
+ result = createTaskRoute(modules.store, data);
648
+ }
649
+ else if (url.pathname === "/v1/tasks/update") {
650
+ result = updateTaskRoute(modules.store, data);
651
+ }
652
+ else if (url.pathname === "/v1/subagents/resume") {
627
653
  result = await fanoutMessages.send(data);
628
654
  }
629
655
  else if (url.pathname === "/v1/subagents/archive-finished") {
@@ -766,6 +792,11 @@ export function createRouteHandler(ctx) {
766
792
  const { name, bytes } = uploadBody(data);
767
793
  result = { ok: true, path: await saveUpload("files", name, bytes) };
768
794
  }
795
+ else if (url.pathname === "/v1/files/delete") {
796
+ // One of those files, removed by the path the listing gave.
797
+ await removeUpload("files", z.string().parse(data.path));
798
+ result = { ok: true };
799
+ }
769
800
  else if (url.pathname === "/v1/projects/add") {
770
801
  // Enrolling a repository with phren from the phone: an existing
771
802
  // checkout, or a clone. Serialized like launches — one at a time.
@@ -219,11 +219,13 @@ export function transcriptStreams(ctx) {
219
219
  }
220
220
  }
221
221
  if (deliveryFrames) {
222
- for (const { deliveryId, state } of agentHooks.deliveriesFor(target)) {
222
+ // Every message typed into this pane, also those sent while an
223
+ // earlier conversation was showing there.
224
+ for (const { deliveryId, state, reason } of agentHooks.deliveries.forPane(target)) {
223
225
  if (sentDelivery.get(deliveryId) === state)
224
226
  continue;
225
227
  sentDelivery.set(deliveryId, state);
226
- send(client, { type: "delivery", ...conversation, deliveryId, state });
228
+ send(client, { type: "delivery", ...conversation, deliveryId, state, ...(reason ? { reason } : {}) });
227
229
  }
228
230
  }
229
231
  first = false;
@@ -27,7 +27,7 @@ import { CodeReindexer, CodeRoutes } from "./code-routes.js";
27
27
  import { WorkspaceContextUsage } from "./context.js";
28
28
  import { DispatchService } from "./dispatch.js";
29
29
  import { DispatchReturns, hookWorkers } from "./dispatch-returns.js";
30
- import { findPane, paneChatState, recentServers, sharedSnapshot, snapshot, validateTarget } from "./herdr.js";
30
+ import { findPane, paneChatState, paneIdentity, recentServers, sharedSnapshot, snapshot, validateTarget } from "./herdr.js";
31
31
  import { LaunchLimiter } from "./limits.js";
32
32
  import { locateProject } from "./locate.js";
33
33
  import { BridgeError, bridgeRoot, objects, PROTOCOL, provider, socketPath, targetSchema } from "./protocol.js";
@@ -84,7 +84,7 @@ export async function serve(version, options = {}) {
84
84
  : undefined;
85
85
  const locatedDirectories = new Set();
86
86
  const journal = new ActivityJournal();
87
- const agentHooks = new AgentHooks(undefined, modules);
87
+ const agentHooks = new AgentHooks(undefined, modules, path.join(bridgeRoot(), "deliveries.json"));
88
88
  // Follows what dispatched workers do and tells the dispatching agent.
89
89
  const returns = dispatches ? new DispatchReturns({
90
90
  localWorkers: hookWorkers(agentHooks),
@@ -140,6 +140,11 @@ export async function serve(version, options = {}) {
140
140
  const sideQuestions = new SideQuestions();
141
141
  const handOffs = dispatches ? new HandOffQueue({
142
142
  validate: target => validateTarget(target, false, true),
143
+ current: async (target) => {
144
+ const pane = findPane(await snapshot(target.server), target);
145
+ const session = pane ? await paneIdentity(target.server, pane, true) : undefined;
146
+ return pane && session ? { session, terminal: pane.terminal_id } : undefined;
147
+ },
143
148
  notify: (target, text, deliveryId, computer) => handOff({ computer, target, text, deliveryId }, { notifySender: false }),
144
149
  send: async (target, text, deliveryId, typing) => await paneRouteOnce({ agentHooks, modelSwitcher, settingsSwitcher, permissionModeSwitcher, codexQuestions, sideQuestions }, new URL("http://phren.local/v1/prompt"), { target, text, deliveryId, hookQueued: true }, {}, typing),
145
150
  }) : undefined;
@@ -257,7 +262,8 @@ export async function serve(version, options = {}) {
257
262
  // Codex panes on the Hook's own app-servers: their requests become
258
263
  // approval cards, and servers a previous Hook started are rejoined.
259
264
  codexServers.setSink({ request: (target, request, answer) => agentHooks.codexRequest(target, request, answer),
260
- resolved: (target, requestId) => agentHooks.codexResolved(target, requestId) });
265
+ resolved: (target, requestId) => agentHooks.codexResolved(target, requestId),
266
+ threadChanged: previous => agentHooks.deliveries.threadChanged(previous) });
261
267
  await codexServers.adopt().catch(() => { });
262
268
  void scheduler?.tick().catch(() => { });
263
269
  const scheduleTimer = scheduler ? setInterval(() => { countTick("schedules"); void scheduler.tick().catch(() => { }); }, 30_000) : undefined;
@@ -288,6 +294,9 @@ export async function serve(version, options = {}) {
288
294
  const name = String(server.session), current = await sharedSnapshot(name, 4000);
289
295
  await tabActivity.observe(name, current);
290
296
  await journal.record(name, objects(current.panes));
297
+ // Phone messages a pane still holds: fail loudly when it closed,
298
+ // restarted or finished without them.
299
+ await agentHooks.deliveries.observe(name, objects(current.panes)).catch(() => { });
291
300
  // A Codex app-server whose pane closed is stopped; a dead one forgotten.
292
301
  await codexServers.reap(name, current).catch(() => { });
293
302
  // Approvals drawn in a terminal reach a phone with phren closed.
@@ -7,7 +7,7 @@ export declare function simulatorScreenshot(udid: string): Promise<Buffer>;
7
7
  * URL go through simctl; touches and keys go through the Simulator app's
8
8
  * window with UI scripting, which needs Accessibility for the Hook's node. */
9
9
  export type SimulatorAction = {
10
- action: "boot" | "shutdown" | "home" | "lock" | "screenshot-ready";
10
+ action: "boot" | "shutdown" | "home" | "lock" | "screenshot-ready" | "accessibility-settings";
11
11
  } | {
12
12
  action: "launch";
13
13
  bundleId: string;
@@ -23,6 +23,8 @@ export type SimulatorAction = {
23
23
  text: string;
24
24
  submit?: boolean;
25
25
  };
26
+ /** The steps for the Accessibility grant, for the 403 and the docs. */
27
+ export declare function accessibilityHelp(binary: string): string;
26
28
  export declare function simulatorAct(udid: string, request: SimulatorAction): Promise<Json>;
27
29
  /** The apps a simulator has, for the launcher. */
28
30
  export declare function simulatorApps(udid: string): Promise<Json[]>;
@@ -56,7 +56,8 @@ export async function simulatorScreenshot(udid) {
56
56
  /** The native helper (native/simtap.swift) that finds the Simulator window
57
57
  * through the Accessibility API and posts touches and keys with CGEvent.
58
58
  * AppleScript would need Automation consent, which a launchd agent can never
59
- * be prompted for; the helper needs one Accessibility grant, added by hand.
59
+ * be prompted for; the helper needs one Accessibility grant. Its `prompt`
60
+ * command puts it in the Accessibility list and shows the system dialog.
60
61
  * Compiled once per Hook version with swiftc, which any Mac with the
61
62
  * simulators has. */
62
63
  let building;
@@ -99,20 +100,27 @@ function simtap(name, ...args) {
99
100
  inputQueue = task;
100
101
  return task;
101
102
  }
102
- async function executeSimtap(name, ...args) {
103
+ /** The helper, hashed again right before it runs. */
104
+ async function verifiedHelper() {
103
105
  const binary = await helper();
104
106
  const saved = await readFile(binary + ".sha256", "utf8").then(JSON.parse).catch(() => undefined);
105
107
  const binarySha = createHash("sha256").update(await readFile(binary)).digest("hex");
106
108
  if (!saved || saved.binarySha !== binarySha)
107
109
  throw new BridgeError(409, "Simulator input helper integrity check failed.");
110
+ return binary;
111
+ }
112
+ async function executeSimtap(name, ...args) {
113
+ const binary = await verifiedHelper();
108
114
  try {
109
115
  await exec(binary, [name, ...args], { timeout: 60_000 });
110
116
  }
111
117
  catch (error) {
112
118
  const failure = error;
113
119
  const message = String(failure?.stderr ?? failure?.message ?? "");
114
- if (/accessibility/.test(message))
115
- throw new BridgeError(403, `Touches and keys need one permission on the Mac: System Settings → Privacy & Security → Accessibility → add ${binary}`);
120
+ if (/accessibility/.test(message)) {
121
+ await promptAccessibility(binary, false);
122
+ throw new BridgeError(403, accessibilityHelp(binary), { code: "simulator-accessibility", helper: binary });
123
+ }
116
124
  if (/no window/.test(message))
117
125
  throw new BridgeError(409, "That simulator has no window on screen.");
118
126
  if (/not running/.test(message))
@@ -120,12 +128,29 @@ async function executeSimtap(name, ...args) {
120
128
  throw new BridgeError(409, `The simulator did not take that: ${message.slice(0, 160) || "unknown error"}`);
121
129
  }
122
130
  }
131
+ /** The steps for the Accessibility grant, for the 403 and the docs. */
132
+ export function accessibilityHelp(binary) {
133
+ return "Touches and keys need Accessibility for Phren's simulator helper. On the Mac, open System Settings → Privacy & Security → Accessibility and switch on simtap. "
134
+ + `If it isn't listed, click +, press ⌘⇧G, paste ${binary} and click Open.`;
135
+ }
136
+ /** Asks macOS for the helper's Accessibility grant: the helper joins the
137
+ * Accessibility list, switched off, and the system dialog shows. Once per Hook
138
+ * run unless the person asks again, so a burst of taps raises one dialog.
139
+ * Resolves whether the helper is already trusted. */
140
+ let prompted = false;
141
+ async function promptAccessibility(binary, force) {
142
+ if (prompted && !force)
143
+ return false;
144
+ prompted = true;
145
+ return exec(binary, ["-", "prompt"], { timeout: 15_000 }).then(() => true, () => false);
146
+ }
147
+ const ACCESSIBILITY_PANE = "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility";
123
148
  // macOS virtual key codes.
124
149
  const KEY_H = "4", KEY_L = "37";
125
150
  export async function simulatorAct(udid, request) {
126
151
  if (!UDID.test(udid))
127
152
  throw new BridgeError(400, "Invalid simulator identifier.");
128
- if (!["boot", "shutdown", "launch", "openurl", "home", "lock", "type", "tap", "screenshot-ready"].includes(request.action))
153
+ if (!["boot", "shutdown", "launch", "openurl", "home", "lock", "type", "tap", "screenshot-ready", "accessibility-settings"].includes(request.action))
129
154
  throw new BridgeError(400, "Unknown simulator action.");
130
155
  if (process.platform !== "darwin")
131
156
  throw new BridgeError(404, "Simulators run on macOS only.");
@@ -169,6 +194,16 @@ export async function simulatorAct(udid, request) {
169
194
  break;
170
195
  }
171
196
  case "screenshot-ready": break;
197
+ case "accessibility-settings": {
198
+ // The phone's "Open Accessibility settings": ask for the grant again and
199
+ // open the pane on this Mac, where the switch is.
200
+ const binary = await verifiedHelper();
201
+ const trusted = await promptAccessibility(binary, true);
202
+ await exec("/usr/bin/open", [ACCESSIBILITY_PANE], { timeout: 15_000 }).catch(() => {
203
+ throw new BridgeError(409, "Couldn't open System Settings on the Mac.");
204
+ });
205
+ return { ok: true, trusted, helper: binary };
206
+ }
172
207
  default: throw new BridgeError(400, "Unknown simulator action.");
173
208
  }
174
209
  return { ok: true };
@@ -91,7 +91,7 @@ export interface ProcessRecord {
91
91
  line: string;
92
92
  /** Environment names, where the platform shows them (Linux). */
93
93
  env?: string[];
94
- /** When it started (`ps -o lstart`), to tell it from a later process with its pid. */
94
+ /** When it started (procfs start ticks on Linux, `ps -o lstart` elsewhere), to distinguish a recycled pid. */
95
95
  started?: string;
96
96
  }
97
97
  /** One process's parent, effective uid, name and arguments. */