@phren/cli 0.3.50 → 0.3.51

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.
@@ -16824,13 +16824,13 @@ var init_json_schema_processors = __esm({
16824
16824
  ...params,
16825
16825
  path: [...params.path, "propertyNames"]
16826
16826
  });
16827
- let pending2 = pendingRecords.get(ctx);
16828
- if (!pending2) {
16829
- pending2 = [];
16830
- pendingRecords.set(ctx, pending2);
16827
+ let pending3 = pendingRecords.get(ctx);
16828
+ if (!pending3) {
16829
+ pending3 = [];
16830
+ pendingRecords.set(ctx, pending3);
16831
16831
  ctx.deferred.push(() => rewriteKeyNames(ctx));
16832
16832
  }
16833
- pending2.push(schema);
16833
+ pending3.push(schema);
16834
16834
  }
16835
16835
  json2.additionalProperties = processSchema(def.valueType, ctx, {
16836
16836
  ...params,
@@ -25943,8 +25943,8 @@ async function codexThreadPreview(session) {
25943
25943
  const history = await openReadOnly(path15.join(codexHome(), "thread_history_1.sqlite"));
25944
25944
  if (!history) return void 0;
25945
25945
  try {
25946
- const pending2 = pendingMessage(history, session);
25947
- return pending2?.text ? { turnStartedAt: pending2.turnStartedAt, text: pending2.text } : void 0;
25946
+ const pending3 = pendingMessage(history, session);
25947
+ return pending3?.text ? { turnStartedAt: pending3.turnStartedAt, text: pending3.text } : void 0;
25948
25948
  } catch {
25949
25949
  return void 0;
25950
25950
  } finally {
@@ -25954,8 +25954,8 @@ async function codexThreadPreview(session) {
25954
25954
  async function materializeCodexThread(session) {
25955
25955
  if (!sessionId.safeParse(session).success) return void 0;
25956
25956
  const key4 = materializedPath(session);
25957
- const pending2 = materializations.get(key4);
25958
- if (pending2) return pending2;
25957
+ const pending3 = materializations.get(key4);
25958
+ if (pending3) return pending3;
25959
25959
  const work = materializeThread(session);
25960
25960
  materializations.set(key4, work);
25961
25961
  try {
@@ -25982,7 +25982,7 @@ async function materializeThread(session) {
25982
25982
  const turn = object2(history.prepare("select turn_id, status from thread_turns where thread_id = ? order by rollout_ordinal desc limit 1").get(session));
25983
25983
  const turnSignature = JSON.stringify(turn);
25984
25984
  if (!fresh2 && state.count === Number(summary.n) && state.lastOrdinal === Number(summary.last) && state.maxUpdated === Number(summary.updated) && state.turnSignature === turnSignature) return file4;
25985
- const pending2 = pendingMessage(history, session);
25985
+ const pending3 = pendingMessage(history, session);
25986
25986
  const rows2 = objects(history.prepare("select rollout_ordinal, item_type, item_json, updated_at_ordinal from thread_items where thread_id = ? order by rollout_ordinal limit ?").all(session, MAX_ITEMS));
25987
25987
  const lines = [];
25988
25988
  if (fresh2) {
@@ -26002,7 +26002,7 @@ async function materializeThread(session) {
26002
26002
  continue;
26003
26003
  }
26004
26004
  const id2 = String(item.id ?? `ordinal-${row.rollout_ordinal}`), emitted = state.done[id2];
26005
- if (item.type === "agentMessage" && id2 === pending2?.id) continue;
26005
+ if (item.type === "agentMessage" && id2 === pending3?.id) continue;
26006
26006
  const calls = callRows(item), output2 = outputRow(item);
26007
26007
  if (emitted === "queued" && item.type === "userMessage" && item.status !== "queued") {
26008
26008
  lines.push(JSON.stringify({ type: "phren_queue_consumed", key: queueKey(session, id2) }));
@@ -26364,8 +26364,8 @@ var init_lookup_cache = __esm({
26364
26364
  const timeout = new Promise((_2, reject) => {
26365
26365
  timer = setTimeout(() => reject(new BridgeError(504, "Lookup did not finish within the request time limit.", { code: "lookup-timeout" })), this.pendingTimeout);
26366
26366
  });
26367
- const pending2 = Promise.race([Promise.resolve().then(read), timeout]).then((data) => {
26368
- if (this.entries.get(key4) === current2 && current2.pending === pending2) {
26367
+ const pending3 = Promise.race([Promise.resolve().then(read), timeout]).then((data) => {
26368
+ if (this.entries.get(key4) === current2 && current2.pending === pending3) {
26369
26369
  const previous = current2.value;
26370
26370
  const keepSuccess = previous && this.available(previous.data) && !this.available(data) && !this.revokes(data) && Date.now() - previous.at < this.maxAge;
26371
26371
  if (!keepSuccess) current2.value = { data, at: Date.now() };
@@ -26373,9 +26373,9 @@ var init_lookup_cache = __esm({
26373
26373
  return data;
26374
26374
  }).finally(() => {
26375
26375
  clearTimeout(timer);
26376
- if (current2.pending === pending2) current2.pending = void 0;
26376
+ if (current2.pending === pending3) current2.pending = void 0;
26377
26377
  });
26378
- entry2.pending = pending2;
26378
+ entry2.pending = pending3;
26379
26379
  }
26380
26380
  if (cached3 && age < maxAge && !this.revokes(cached3.data)) {
26381
26381
  void entry2.pending.catch(() => {
@@ -26517,16 +26517,16 @@ async function git(cwd, ...args) {
26517
26517
  const budget = gitReadBudget.getStore();
26518
26518
  const timeout = budget ? remainingGitTime(budget) : 1e4;
26519
26519
  countGit("projects");
26520
- let pending2;
26520
+ let pending3;
26521
26521
  try {
26522
- pending2 = exec("git", ["-C", cwd, "--no-pager", ...args], {
26522
+ pending3 = exec("git", ["-C", cwd, "--no-pager", ...args], {
26523
26523
  timeout,
26524
26524
  maxBuffer: 4194304,
26525
26525
  env: checkoutGitEnv(),
26526
26526
  ...budget ? { signal: budget.controller.signal, killSignal: "SIGKILL" } : {}
26527
26527
  });
26528
- budget?.pending.add(pending2);
26529
- const result = await pending2;
26528
+ budget?.pending.add(pending3);
26529
+ const result = await pending3;
26530
26530
  if (budget) remainingGitTime(budget);
26531
26531
  return result.stdout;
26532
26532
  } catch (error62) {
@@ -26539,7 +26539,7 @@ async function git(cwd, ...args) {
26539
26539
  const [status, code, message] = failure2.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER" ? [413, "git-output-limit", "Git output exceeded the 4 MiB limit. Narrow the selection."] : failure2.killed || failure2.signal ? [504, "git-timeout", "Git did not finish within its time limit. Retry when the repository is idle."] : /index\.lock/.test(stderr) ? [409, "git-index-locked", "Git could not lock the index. Wait for the other Git operation to finish; the Hook has not removed the lock."] : /not a git repository/.test(stderr) ? [409, "git-not-repository", "This folder is not a Git repository."] : [503, "git-failed", `Git ${args[0]} failed: ${stderr.trim().slice(0, 1e3) || "the command could not complete"}`];
26540
26540
  throw new BridgeError(status, message, { code, ...failure2.code !== void 0 ? { exitCode: String(failure2.code) } : {} });
26541
26541
  } finally {
26542
- if (pending2) budget?.pending.delete(pending2);
26542
+ if (pending3) budget?.pending.delete(pending3);
26543
26543
  }
26544
26544
  }
26545
26545
  async function gitRoot(dir) {
@@ -28598,15 +28598,15 @@ async function directChildAgents(file4) {
28598
28598
  const append = cached3 && cached3.dev === metadata.dev && cached3.ino === metadata.ino && metadata.size > cached3.fileSize && await sameBytes(file4, cached3.completeOffset - cached3.tail.length, cached3.tail);
28599
28599
  const start = append ? cached3.completeOffset : 0;
28600
28600
  const found = append ? new Map(cached3.relations) : /* @__PURE__ */ new Map();
28601
- let pending2 = Buffer.alloc(0), completeOffset = start;
28601
+ let pending3 = Buffer.alloc(0), completeOffset = start;
28602
28602
  const input2 = metadata.size > start ? createReadStream2(file4, { start, end: metadata.size - 1 }) : void 0;
28603
28603
  for await (const chunk of input2 ?? []) {
28604
- pending2 = Buffer.concat([pending2, Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)]);
28604
+ pending3 = Buffer.concat([pending3, Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)]);
28605
28605
  let newline;
28606
- while ((newline = pending2.indexOf(10)) >= 0) {
28607
- addChildRelation(pending2.subarray(0, newline).toString("utf8"), found);
28606
+ while ((newline = pending3.indexOf(10)) >= 0) {
28607
+ addChildRelation(pending3.subarray(0, newline).toString("utf8"), found);
28608
28608
  completeOffset += newline + 1;
28609
- pending2 = pending2.subarray(newline + 1);
28609
+ pending3 = pending3.subarray(newline + 1);
28610
28610
  }
28611
28611
  }
28612
28612
  const tail2 = completeOffset > 0 ? await readAt(file4, Math.max(0, completeOffset - TAIL_CHECK), Math.min(TAIL_CHECK, completeOffset)) : Buffer.alloc(0);
@@ -36703,7 +36703,7 @@ var init_package_metadata = __esm({
36703
36703
  __dirname = path35.dirname(fileURLToPath2(import.meta.url));
36704
36704
  ROOT = path35.join(__dirname, "..");
36705
36705
  PACKAGE_JSON_PATH = path35.join(ROOT, "package.json");
36706
- BUNDLED_VERSION = true ? "0.3.50" : "0.0.0";
36706
+ BUNDLED_VERSION = true ? "0.3.51" : "0.0.0";
36707
36707
  PACKAGE_JSON = readPackageJson();
36708
36708
  PACKAGE_NAME = PACKAGE_JSON.name || "phren";
36709
36709
  VERSION = PACKAGE_JSON.version || BUNDLED_VERSION;
@@ -38011,7 +38011,8 @@ var init_registry = __esm({
38011
38011
  "agentFolder",
38012
38012
  "launchPermissionMode",
38013
38013
  "sessionMove",
38014
- "moveNewChat"
38014
+ "moveNewChat",
38015
+ "moveConductor"
38015
38016
  ],
38016
38017
  storeFiles: [".runtime/sessions/opencode-*.events.jsonl", ".runtime/approvals/opencode-*.json"],
38017
38018
  localFiles: ["<bridge>/installed.json", "<bridge>/versions/**", "<bridge>/current", "<bridge>/dispatch", "<bridge>/askpass", "<bridge>/computer-id", "<bridge>/canary.json", "<bridge>/canary-daily", "<bridge>/moves/*.json"],
@@ -39056,7 +39057,7 @@ async function liveClaudeUsage(now, home) {
39056
39057
  function readCodexLimits(executable2 = codexExecutable()) {
39057
39058
  return new Promise((resolve17) => {
39058
39059
  const child = spawn3(executable2, ["app-server"], { cwd: homedir9(), stdio: ["pipe", "pipe", "ignore"] });
39059
- let pending2 = "", bytes = 0, initialized = false, done = false;
39060
+ let pending3 = "", bytes = 0, initialized = false, done = false;
39060
39061
  const finish = (result) => {
39061
39062
  if (done) return;
39062
39063
  done = true;
@@ -39085,11 +39086,11 @@ function readCodexLimits(executable2 = codexExecutable()) {
39085
39086
  finish();
39086
39087
  return;
39087
39088
  }
39088
- pending2 += chunk;
39089
+ pending3 += chunk;
39089
39090
  let newline;
39090
- while (!done && (newline = pending2.indexOf("\n")) >= 0) {
39091
- const line = pending2.slice(0, newline);
39092
- pending2 = pending2.slice(newline + 1);
39091
+ while (!done && (newline = pending3.indexOf("\n")) >= 0) {
39092
+ const line = pending3.slice(0, newline);
39093
+ pending3 = pending3.slice(newline + 1);
39093
39094
  try {
39094
39095
  const response = object2(JSON.parse(line));
39095
39096
  if (response.id === 0 && !initialized) {
@@ -39380,7 +39381,7 @@ var init_usage = __esm({
39380
39381
  if (!cached3 || this.now() - cached3.at >= 6e4) {
39381
39382
  const at2 = this.now();
39382
39383
  if (!this.spendingPending.has(key4)) {
39383
- const pending2 = Promise.all([
39384
+ const pending3 = Promise.all([
39384
39385
  this.openCode(at2),
39385
39386
  bounded(this.readOpenCodeGo(new Date(at2)), () => unanswered("opencode-go", "OpenCode Go")),
39386
39387
  bounded(this.readOpenRouter(new Date(at2)), () => void 0),
@@ -39392,7 +39393,7 @@ var init_usage = __esm({
39392
39393
  }).finally(() => {
39393
39394
  this.spendingPending.delete(key4);
39394
39395
  });
39395
- this.spendingPending.set(key4, pending2);
39396
+ this.spendingPending.set(key4, pending3);
39396
39397
  }
39397
39398
  }
39398
39399
  return this.spendingPending.get(key4) ?? cached3.value;
@@ -39431,8 +39432,8 @@ var init_usage = __esm({
39431
39432
  this.claudePending.delete(home.dir);
39432
39433
  }));
39433
39434
  }
39434
- const pending2 = this.claudePending.get(home.dir);
39435
- const live = pending2 ? await pending2 : this.claudeCached.get(home.dir)?.value;
39435
+ const pending3 = this.claudePending.get(home.dir);
39436
+ const live = pending3 ? await pending3 : this.claudeCached.get(home.dir)?.value;
39436
39437
  if (live?.windows.length) return live;
39437
39438
  }
39438
39439
  return this.snapshotClaude(home);
@@ -40258,6 +40259,10 @@ function upgradeKeys(text5) {
40258
40259
  let changed = 0;
40259
40260
  const result = text5.split(/(?<=\n)/).map((line) => {
40260
40261
  const parsed = keyOptions(line);
40262
+ if (parsed && parsed.options[0] === "restrict" && /^\s+ssh-ed25519 [A-Za-z0-9+/=]+ phren-computer:[A-Za-z0-9_.-]+\s*$/.test(parsed.rest) && parsed.options.includes(forcedCommand)) {
40263
+ changed++;
40264
+ return parsed.options.filter((option) => option !== "pty" && option.toLowerCase() !== "port-forwarding" && !option.toLowerCase().startsWith("permitopen=")).map((option) => option === forcedCommand ? peerForcedCommand : option).join(",") + parsed.rest;
40265
+ }
40261
40266
  if (!parsed || parsed.options[0] !== "restrict" || !/^\s+ssh-ed25519 [A-Za-z0-9+/=]+ phren-(?:iphone|android)\s*$/.test(parsed.rest)) return line;
40262
40267
  const old = /^command="(?:\/usr\/bin\/false|python3 ~\/\.local\/share\/phren\/chat-progress\.py|sh ~\/\.local\/share\/phren\/bridge\/dispatch)"$/;
40263
40268
  if (!parsed.options.some((option) => old.test(option))) return line;
@@ -40708,7 +40713,7 @@ async function rollback() {
40708
40713
  await carryCodexHookTrust(program, codexHooksBefore(edits));
40709
40714
  await atomic(path51.join(bridgeRoot(), "installed.json"), JSON.stringify({ version: config4.previous, previous: config4.version, ...config4.store ? { store: config4.store } : {} }) + "\n");
40710
40715
  }
40711
- var exec6, label, unit, forcedCommand, quote3, xml, MANAGED_ENVIRONMENT, systemdQuote, scopedGatewayPath, launchAgentPlist, CODEX_TURN_WAIT_MS, currentHasFastHook, opencodePluginsDir, OPENCODE_PLUGIN_MARKER, codexHooksBefore;
40716
+ var exec6, label, unit, peerForcedCommand, forcedCommand, quote3, xml, MANAGED_ENVIRONMENT, systemdQuote, scopedGatewayPath, launchAgentPlist, CODEX_TURN_WAIT_MS, currentHasFastHook, opencodePluginsDir, OPENCODE_PLUGIN_MARKER, codexHooksBefore;
40712
40717
  var init_install = __esm({
40713
40718
  "src/bridge/install.ts"() {
40714
40719
  "use strict";
@@ -40730,6 +40735,7 @@ var init_install = __esm({
40730
40735
  exec6 = promisify6(execFile7);
40731
40736
  label = "com.phren.hook";
40732
40737
  unit = "phren-hook.service";
40738
+ peerForcedCommand = 'command="sh ~/.local/share/phren/bridge/dispatch-scoped peer"';
40733
40739
  forcedCommand = 'command="sh ~/.local/share/phren/bridge/dispatch"';
40734
40740
  quote3 = (s) => "'" + s.replace(/'/g, "'\\''") + "'";
40735
40741
  xml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
@@ -40761,7 +40767,7 @@ function publicComputerKey(value2) {
40761
40767
  return `ssh-ed25519 ${match[1]}`;
40762
40768
  }
40763
40769
  function computerKeyLine(name, publicKey) {
40764
- return `restrict,pty,${forcedCommand} ${publicComputerKey(publicKey)} phren-computer:${computerName.parse(name)}`;
40770
+ return `restrict,${peerForcedCommand} ${publicComputerKey(publicKey)} phren-computer:${computerName.parse(name)}`;
40765
40771
  }
40766
40772
  async function regularFile(file4) {
40767
40773
  const info = await lstat12(file4).catch((error62) => {
@@ -40803,9 +40809,10 @@ async function enrollComputer(name, root = bridgeRoot()) {
40803
40809
  }
40804
40810
  async function acceptComputer(name, input2, sshDirectory = path52.join(homedir12(), ".ssh")) {
40805
40811
  computerName.parse(name);
40806
- const prefix = `restrict,pty,${forcedCommand} `;
40812
+ const prefixes = [`restrict,${peerForcedCommand} `, `restrict,pty,${forcedCommand} `];
40807
40813
  const raw = input2.trim();
40808
- const publicKey = publicComputerKey(raw.startsWith(prefix) ? raw.slice(prefix.length) : raw);
40814
+ const prefix = prefixes.find((value2) => raw.startsWith(value2));
40815
+ const publicKey = publicComputerKey(prefix ? raw.slice(prefix.length) : raw);
40809
40816
  const line = computerKeyLine(name, publicKey);
40810
40817
  const encoded = publicKey.split(" ")[1];
40811
40818
  await appendAuthorizedKey(
@@ -42325,7 +42332,7 @@ function grantLabel(grant) {
42325
42332
  async function mutateGrants(root, action) {
42326
42333
  const key4 = path56.resolve(root);
42327
42334
  const previous = mutations.get(key4) ?? Promise.resolve();
42328
- const pending2 = previous.catch(() => {
42335
+ const pending3 = previous.catch(() => {
42329
42336
  }).then(async () => {
42330
42337
  const release = tryFileLock(grantFile(key4));
42331
42338
  if (!release) throw new BridgeError(409, "Conductor grants are being updated. Try again.");
@@ -42335,11 +42342,11 @@ async function mutateGrants(root, action) {
42335
42342
  release();
42336
42343
  }
42337
42344
  });
42338
- mutations.set(key4, pending2);
42345
+ mutations.set(key4, pending3);
42339
42346
  try {
42340
- return await pending2;
42347
+ return await pending3;
42341
42348
  } finally {
42342
- if (mutations.get(key4) === pending2) mutations.delete(key4);
42349
+ if (mutations.get(key4) === pending3) mutations.delete(key4);
42343
42350
  }
42344
42351
  }
42345
42352
  async function addGrant(input2, root = bridgeRoot()) {
@@ -42479,7 +42486,7 @@ function lowerMode(a, b) {
42479
42486
  async function mutate(file4, action) {
42480
42487
  const key4 = path57.resolve(file4);
42481
42488
  const previous = mutations2.get(key4) ?? Promise.resolve();
42482
- const pending2 = previous.catch(() => {
42489
+ const pending3 = previous.catch(() => {
42483
42490
  }).then(async () => {
42484
42491
  await mkdir17(path57.dirname(key4), { recursive: true, mode: 448 });
42485
42492
  const release = tryFileLock(key4);
@@ -42490,11 +42497,11 @@ async function mutate(file4, action) {
42490
42497
  release();
42491
42498
  }
42492
42499
  });
42493
- mutations2.set(key4, pending2);
42500
+ mutations2.set(key4, pending3);
42494
42501
  try {
42495
- return await pending2;
42502
+ return await pending3;
42496
42503
  } finally {
42497
- if (mutations2.get(key4) === pending2) mutations2.delete(key4);
42504
+ if (mutations2.get(key4) === pending3) mutations2.delete(key4);
42498
42505
  }
42499
42506
  }
42500
42507
  async function writeAuthority(root, projects, by) {
@@ -42785,6 +42792,46 @@ var init_conductor_group = __esm({
42785
42792
  }
42786
42793
  });
42787
42794
 
42795
+ // src/bridge/dispatch-origins.ts
42796
+ function trackDispatchOrigin() {
42797
+ const entry2 = { root: bridgeRoot(), aliases: [] };
42798
+ pending.add(entry2);
42799
+ return {
42800
+ rewrite: (origin) => origin && (entry2.aliases.find((alias) => samePane(alias.from, origin))?.to ?? origin),
42801
+ finish: () => {
42802
+ pending.delete(entry2);
42803
+ entry2.aliases = [];
42804
+ }
42805
+ };
42806
+ }
42807
+ function prepareDispatchOriginHandover(from, to) {
42808
+ const root = bridgeRoot();
42809
+ const before = new Map([...pending].filter((entry2) => entry2.root === root).map((entry2) => [entry2, entry2.aliases]));
42810
+ return () => {
42811
+ for (const entry2 of pending) {
42812
+ if (entry2.root !== root) continue;
42813
+ entry2.aliases = (before.get(entry2) ?? entry2.aliases).filter((alias) => !samePane(alias.from, to) && !samePane(alias.from, from)).map((alias) => samePane(alias.to, from) ? { ...alias, to } : alias);
42814
+ entry2.aliases.push({ from, to });
42815
+ }
42816
+ };
42817
+ }
42818
+ function conductorOriginChanged(conductor) {
42819
+ const root = bridgeRoot();
42820
+ for (const entry2 of pending) {
42821
+ if (entry2.root !== root) continue;
42822
+ entry2.aliases = entry2.aliases.filter((alias) => conductor && samePane(alias.to, conductor) && (conductor.source === void 0 || alias.to.agent === conductor.source) && (conductor.workspace === void 0 || alias.to.workspace === conductor.workspace) && (conductor.tab === void 0 || alias.to.tab === conductor.tab));
42823
+ }
42824
+ }
42825
+ var pending, samePane;
42826
+ var init_dispatch_origins = __esm({
42827
+ "src/bridge/dispatch-origins.ts"() {
42828
+ "use strict";
42829
+ init_protocol();
42830
+ pending = /* @__PURE__ */ new Set();
42831
+ samePane = (left3, right) => left3.server === right.server && left3.pane === right.pane && (left3.terminal === void 0 || left3.terminal === right.terminal);
42832
+ }
42833
+ });
42834
+
42788
42835
  // src/bridge/conductor-role.ts
42789
42836
  import { lstatSync as lstatSync2, readFileSync as readFileSync26 } from "node:fs";
42790
42837
  import path58 from "node:path";
@@ -42813,6 +42860,7 @@ async function writeRoleState(state) {
42813
42860
  const file4 = roleFile();
42814
42861
  await atomicInPrivateDir(file4, JSON.stringify(state, null, 2) + "\n");
42815
42862
  cached2 = { file: file4, state };
42863
+ conductorOriginChanged(state.conductor);
42816
42864
  }
42817
42865
  function serialized(run4) {
42818
42866
  const next = queue.then(run4, run4);
@@ -42884,6 +42932,18 @@ function recordConductor(server, pane, by, session) {
42884
42932
  return record4;
42885
42933
  });
42886
42934
  }
42935
+ function transferConductor(expected, server, pane, session, handOver = (commit) => commit()) {
42936
+ return serialized(async () => {
42937
+ const state = await readRoleState();
42938
+ const current2 = state?.conductor;
42939
+ if (!current2 || !recordSchema.keyof().options.every((field) => current2[field] === expected[field])) {
42940
+ throw new BridgeError(409, "The conductor changed during the move; nothing was transferred.");
42941
+ }
42942
+ const record4 = recordFor(server, pane, "owner", session);
42943
+ await handOver(() => writeRoleState({ ...state, version: 1, conductor: record4 }));
42944
+ return record4;
42945
+ });
42946
+ }
42887
42947
  function noteConductorSession(server, pane, session) {
42888
42948
  return serialized(async () => {
42889
42949
  const state = await readRoleState();
@@ -42918,6 +42978,7 @@ var init_conductor_role = __esm({
42918
42978
  "src/bridge/conductor-role.ts"() {
42919
42979
  "use strict";
42920
42980
  init_zod();
42981
+ init_dispatch_origins();
42921
42982
  init_herdr();
42922
42983
  init_protocol();
42923
42984
  recordSchema = external_exports.object({
@@ -42986,26 +43047,95 @@ async function dispatchProjectDirectory(project, home = homeDir()) {
42986
43047
  }
42987
43048
  throw new BridgeError(404, `Project ${name} is not on this computer: the store names no folder for ${getMachineName()} that exists here, and there is no ~/Projects/${name} checkout.`);
42988
43049
  }
42989
- async function save(receipt) {
43050
+ function save(receipt, originWindow) {
43051
+ return serializeReceiptUpdate(async () => {
43052
+ const origin = originWindow.rewrite(receipt.origin);
43053
+ if (origin !== receipt.origin && !receipt.closedAt) {
43054
+ receipt.origin = origin;
43055
+ if (receipt.returned && !receipt.returned.read) delete receipt.returned.notifiedAt;
43056
+ }
43057
+ await saveReceipt(receipt);
43058
+ });
43059
+ }
43060
+ async function saveReceipt(receipt) {
42990
43061
  const root = path59.join(bridgeRoot(), "dispatches");
42991
43062
  await mkdir18(root, { recursive: true, mode: 448 });
42992
43063
  await atomic(path59.join(root, `${receipt.id}.json`), receipt);
42993
43064
  }
42994
43065
  function updateReceipt(receiptID, change) {
42995
- const run4 = receiptUpdates.then(async () => {
42996
- const file4 = path59.join(bridgeRoot(), "dispatches", `${external_exports.string().uuid().parse(receiptID)}.json`);
42997
- const info = await lstat16(file4).catch(() => void 0);
42998
- if (!info?.isFile() || info.isSymbolicLink() || info.size > MAX_RECEIPT_BYTES) return void 0;
42999
- const receipt = receiptSchema.parse(JSON.parse(await readFile29(file4, "utf8")));
43000
- if (["launching", "sending"].includes(receipt.state)) return void 0;
43001
- if (!change(receipt)) return receipt;
43002
- receipt.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
43003
- await atomic(file4, receiptSchema.parse(receipt));
43004
- return receipt;
43005
- });
43066
+ return serializeReceiptUpdate(() => changeReceipt(receiptID, change));
43067
+ }
43068
+ function serializeReceiptUpdate(change) {
43069
+ const run4 = receiptUpdates.then(change);
43006
43070
  receiptUpdates = run4.catch(() => void 0);
43007
43071
  return run4;
43008
43072
  }
43073
+ async function readReceipt(receiptID) {
43074
+ const file4 = path59.join(bridgeRoot(), "dispatches", `${external_exports.string().uuid().parse(receiptID)}.json`);
43075
+ const info = await lstat16(file4).catch((error62) => {
43076
+ if (error62.code !== "ENOENT") throw error62;
43077
+ return void 0;
43078
+ });
43079
+ if (!info?.isFile() || info.isSymbolicLink() || info.size > MAX_RECEIPT_BYTES) return void 0;
43080
+ return receiptSchema.parse(JSON.parse(await readFile29(file4, "utf8")));
43081
+ }
43082
+ async function changeReceipt(receiptID, change) {
43083
+ const receipt = await readReceipt(receiptID);
43084
+ if (!receipt || ["launching", "sending"].includes(receipt.state)) return void 0;
43085
+ if (!change(receipt)) return receipt;
43086
+ receipt.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
43087
+ await saveReceipt(receiptSchema.parse(receipt));
43088
+ return receipt;
43089
+ }
43090
+ function repointDispatchOrigins(from, to, commit) {
43091
+ return serializeReceiptUpdate(async () => {
43092
+ const seal = prepareDispatchOriginHandover(from, to);
43093
+ const names = await readdir10(path59.join(bridgeRoot(), "dispatches")).catch((error62) => {
43094
+ if (error62.code !== "ENOENT") throw error62;
43095
+ return [];
43096
+ });
43097
+ const matches = (origin) => origin?.server === from.server && origin.pane === from.pane && (from.terminal === void 0 || origin.terminal === from.terminal);
43098
+ const selected = [];
43099
+ for (const name of names.filter((name2) => /^[a-f0-9-]{36}\.json$/.test(name2))) {
43100
+ const receipt = await readReceipt(name.slice(0, -5));
43101
+ if (!receipt || receipt.closedAt || !matches(receipt.origin)) continue;
43102
+ if (["launching", "sending"].includes(receipt.state)) throw new BridgeError(409, "A conductor dispatch is still being placed; retry the move after it settles.");
43103
+ selected.push(receipt);
43104
+ }
43105
+ const changed = [];
43106
+ try {
43107
+ for (const before of selected) {
43108
+ await changeReceipt(before.id, (receipt) => {
43109
+ if (receipt.closedAt || !matches(receipt.origin)) return false;
43110
+ receipt.origin = to;
43111
+ if (receipt.returned && !receipt.returned.read) delete receipt.returned.notifiedAt;
43112
+ return true;
43113
+ });
43114
+ changed.push(before);
43115
+ }
43116
+ await commit();
43117
+ seal();
43118
+ } catch (error62) {
43119
+ const failures = [];
43120
+ for (const before of changed.reverse()) {
43121
+ try {
43122
+ await changeReceipt(before.id, (receipt) => {
43123
+ receipt.origin = before.origin;
43124
+ if (receipt.returned && receipt.returned.at === before.returned?.at) {
43125
+ if (before.returned.notifiedAt) receipt.returned.notifiedAt = before.returned.notifiedAt;
43126
+ else delete receipt.returned.notifiedAt;
43127
+ }
43128
+ return true;
43129
+ });
43130
+ } catch (rollback2) {
43131
+ failures.push(`${before.id}: ${failureReason(rollback2)}`);
43132
+ }
43133
+ }
43134
+ if (failures.length) throw new Error(`${failureReason(error62)} Receipt routing rollback failed: ${failures.join("; ")}`);
43135
+ throw error62;
43136
+ }
43137
+ });
43138
+ }
43009
43139
  async function receiptNames(root) {
43010
43140
  try {
43011
43141
  return await readdir10(root);
@@ -43020,7 +43150,10 @@ function failureReason(error62) {
43020
43150
  const message = error62 instanceof Error ? error62.message.split("\n")[0] : String(error62);
43021
43151
  return `${typeof code === "string" && !(error62 instanceof BridgeError) ? `${code}: ` : ""}${message}`.replace(/[\x00-\x1f\x7f]/g, " ").slice(0, 200);
43022
43152
  }
43023
- async function dispatchStatus() {
43153
+ function dispatchStatus() {
43154
+ return serializeReceiptUpdate(readDispatchStatus);
43155
+ }
43156
+ async function readDispatchStatus() {
43024
43157
  const root = path59.join(bridgeRoot(), "dispatches");
43025
43158
  const names = (await receiptNames(root)).filter((name) => /^[a-f0-9-]{36}\.json$/.test(name)).slice(0, 1024);
43026
43159
  const receipts = [];
@@ -43223,6 +43356,7 @@ var init_dispatch = __esm({
43223
43356
  init_authority();
43224
43357
  init_peers();
43225
43358
  init_conductor_group();
43359
+ init_dispatch_origins();
43226
43360
  init_conductor_role();
43227
43361
  init_computer_identity();
43228
43362
  init_dispatch_hosts();
@@ -43375,6 +43509,7 @@ var init_dispatch = __esm({
43375
43509
  if (data.permissionMode && data.harness === "opencode") throw new BridgeError(400, "OpenCode takes its permissions from its own config; permissionMode is for Claude, Codex and Copilot workers.");
43376
43510
  if (this.active) throw new BridgeError(429, "A dispatch is already being placed. Try again after its receipt arrives.");
43377
43511
  this.active = true;
43512
+ const originWindow = trackDispatchOrigin();
43378
43513
  let holding = true, placed;
43379
43514
  const release = () => {
43380
43515
  if (holding) {
@@ -43468,7 +43603,7 @@ var init_dispatch = __esm({
43468
43603
  ...origin ? { origin } : {},
43469
43604
  ...continues ? { continues } : {}
43470
43605
  };
43471
- await save(receipt);
43606
+ await save(receipt, originWindow);
43472
43607
  try {
43473
43608
  const launched = await peer.request(
43474
43609
  `/v1/workspaces/launch?server=${encodeURIComponent(peer.server)}`,
@@ -43485,10 +43620,10 @@ var init_dispatch = __esm({
43485
43620
  const ignored = data.permissionMode && launched.permissionMode !== data.permissionMode ? IGNORED_MODE : void 0;
43486
43621
  if (launched.briefLaunched === true) {
43487
43622
  receipt.brief = "launch";
43488
- await this.confirmLaunched(peer, receipt, launched);
43623
+ await this.confirmLaunched(peer, receipt, launched, originWindow);
43489
43624
  if (ignored) receipt.error = [receipt.error, ignored].filter(Boolean).join(" ").slice(0, 500);
43490
43625
  receipt.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
43491
- await save(receipt);
43626
+ await save(receipt, originWindow);
43492
43627
  return { ok: receipt.state === "accepted", ...receipt };
43493
43628
  }
43494
43629
  receipt.brief = "typed";
@@ -43502,7 +43637,7 @@ var init_dispatch = __esm({
43502
43637
  receipt.target = target2;
43503
43638
  receipt.state = "sending";
43504
43639
  receipt.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
43505
- await save(receipt);
43640
+ await save(receipt, originWindow);
43506
43641
  if (!("starting" in target2)) {
43507
43642
  const result = await sendBrief(peer, target2, prompt, `dispatch-${receipt.id}`);
43508
43643
  receipt.state = result.ok === true && result.deliveryUncertain !== true ? "accepted" : "uncertain";
@@ -43520,9 +43655,10 @@ var init_dispatch = __esm({
43520
43655
  }
43521
43656
  }
43522
43657
  receipt.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
43523
- await save(receipt);
43658
+ await save(receipt, originWindow);
43524
43659
  return { ok: receipt.state === "accepted", ...receipt };
43525
43660
  } finally {
43661
+ originWindow.finish();
43526
43662
  release();
43527
43663
  if (placed) {
43528
43664
  const left3 = this.inFlight(placed) - 1;
@@ -43592,12 +43728,12 @@ var init_dispatch = __esm({
43592
43728
  * itself, so that is not a failure. Neither confirmed nor held reads
43593
43729
  * uncertain, and the returns loop keeps asking.
43594
43730
  */
43595
- async confirmLaunched(peer, receipt, launched) {
43731
+ async confirmLaunched(peer, receipt, launched, originWindow) {
43596
43732
  const known2 = remoteTarget.safeParse(launched.target);
43597
43733
  if (known2.success && known2.data.source === receipt.harness && known2.data.server === peer.server) receipt.target = known2.data;
43598
43734
  receipt.state = "sending";
43599
43735
  receipt.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
43600
- await save(receipt);
43736
+ await save(receipt, originWindow);
43601
43737
  const held = (status2) => ["blocked", "waiting"].includes(String(status2));
43602
43738
  const arrival = held(launched.agentStatus) ? await arrivalOf(peer, receipt.id).catch(() => void 0) ?? {} : await awaitArrival(peer, receipt.id, this.settleIntervalMs);
43603
43739
  const named = arrival.accepted?.target ?? arrival.started?.target;
@@ -44683,7 +44819,7 @@ function returnRow(receipt) {
44683
44819
  };
44684
44820
  }
44685
44821
  function noticeDeliveryId(receipts) {
44686
- return `notice-${createHash18("sha256").update(receipts.map((receipt) => `${receipt.id}@${receipt.returned.at}`).sort().join(",")).digest("hex").slice(0, 32)}`;
44822
+ return `notice-${createHash18("sha256").update(receipts.map((receipt) => `${receipt.id}@${receipt.returned.at}@${receipt.origin ? originKey(receipt.origin) : ""}`).sort().join(",")).digest("hex").slice(0, 32)}`;
44687
44823
  }
44688
44824
  var REPLY_LIMIT, POLL_MS, LAUNCH_GRACE_MS, NOTICE_MS, WATCH_MS, BACKGROUND_WAIT_MS, SNAPSHOT_AGE_MS, workerTarget, workerRequestSchema, run, defaultReaders, workerReaders, paneDirectory, observationSchema, movedSchema, approvalObservation, INTERRUPTED, originKey, DispatchReturns;
44689
44825
  var init_dispatch_returns = __esm({
@@ -44981,6 +45117,10 @@ var init_dispatch_returns = __esm({
44981
45117
  const at2 = new Date(this.now()).toISOString();
44982
45118
  for (const receipt of receipts) {
44983
45119
  await updateReceipt(receipt.id, (current2) => {
45120
+ if (!current2.origin || originKey(current2.origin) !== key4) {
45121
+ busy = true;
45122
+ return false;
45123
+ }
44984
45124
  if (!current2.returned || current2.returned.read || current2.returned.at !== receipt.returned.at) return false;
44985
45125
  current2.returned.notifiedAt = at2;
44986
45126
  return true;
@@ -45769,9 +45909,9 @@ var init_schedules = __esm({
45769
45909
  if (this.recovered || !resume) return;
45770
45910
  this.recovered = true;
45771
45911
  const open30 = await this.exclusive(async () => {
45772
- const pending2 = (await readScheduleRuns(this.runsFile)).filter((run4) => runningStatuses.has(run4.status) && !this.own.has(run4.id));
45773
- for (const run4 of pending2) this.own.add(run4.id);
45774
- return pending2;
45912
+ const pending3 = (await readScheduleRuns(this.runsFile)).filter((run4) => runningStatuses.has(run4.status) && !this.own.has(run4.id));
45913
+ for (const run4 of pending3) this.own.add(run4.id);
45914
+ return pending3;
45775
45915
  });
45776
45916
  for (const run4 of open30) {
45777
45917
  let schedule;
@@ -51874,12 +52014,14 @@ async function saveMove(record4) {
51874
52014
  const run4 = writes3.then(async () => {
51875
52015
  await mkdir21(movesRoot(), { recursive: true, mode: 448 });
51876
52016
  await atomic(recordFile(record4.id), moveRecordSchema.parse(record4));
52017
+ landedMoves.delete(recordFile(record4.id));
51877
52018
  });
51878
52019
  writes3 = run4.catch(() => void 0);
51879
52020
  return run4;
51880
52021
  }
51881
52022
  async function readMove(id2) {
51882
52023
  const file4 = recordFile(id2);
52024
+ if (landedMoves.has(file4)) return structuredClone(landedMoves.get(file4));
51883
52025
  const info = await lstat22(file4).catch(() => void 0);
51884
52026
  if (!info?.isFile() || info.size > MAX_RECORD_BYTES2) return void 0;
51885
52027
  try {
@@ -52083,7 +52225,7 @@ function fallbackHandoff(input2) {
52083
52225
  const head = lines.join("\n");
52084
52226
  return input2.original ? withOriginalBrief(head, input2.original, Number.MAX_SAFE_INTEGER, "the original brief file") : head;
52085
52227
  }
52086
- function handoffDocument(record4, body2, observed, at2) {
52228
+ function handoffDocument(record4, body2, observed, at2, conductor = false) {
52087
52229
  return [
52088
52230
  `# Hand-off from ${harnessName({ harness: record4.from.target.source, account: record4.from.account })} to ${harnessName(record4.to)}`,
52089
52231
  "",
@@ -52099,6 +52241,7 @@ function handoffDocument(record4, body2, observed, at2) {
52099
52241
  "```",
52100
52242
  ""
52101
52243
  ] : [],
52244
+ ...conductor ? ["## Conductor role", "", "You will become the conductor when the Hook confirms the hand-over; until then don't dispatch or answer workers.", ""] : [],
52102
52245
  body2.trim(),
52103
52246
  "",
52104
52247
  observed,
@@ -52125,13 +52268,14 @@ async function transcriptTail(file4, bytes = 512 * 1024) {
52125
52268
  await handle.close();
52126
52269
  }
52127
52270
  }
52128
- var run2, moveRequestSchema, MOVE_STATES, timestamp4, moveRecordSchema, EXIT_COMMANDS, HARNESS_NAMES, MOVE_KEEP_MS, MAX_MOVES, MAX_RECORD_BYTES2, PROMPT_LIMIT2, recordFile, handoffPath, writes3, markers, placeOf, briefText, DEFAULT_HANDOFF_MS, SessionMover;
52271
+ var run2, moveRequestSchema, MOVE_STATES, timestamp4, moveRecordSchema, EXIT_COMMANDS, HARNESS_NAMES, MOVE_KEEP_MS, MAX_MOVES, MAX_RECORD_BYTES2, PROMPT_LIMIT2, recordFile, handoffPath, landedMoves, writes3, markers, placeOf, briefText, DEFAULT_HANDOFF_MS, SessionMover;
52129
52272
  var init_session_move = __esm({
52130
52273
  "src/bridge/session-move.ts"() {
52131
52274
  "use strict";
52132
52275
  init_zod();
52133
52276
  init_logger();
52134
52277
  init_account_failover();
52278
+ init_conductor_role();
52135
52279
  init_claude_accounts();
52136
52280
  init_dispatch();
52137
52281
  init_harnesses();
@@ -52159,6 +52303,7 @@ var init_session_move = __esm({
52159
52303
  from: external_exports.object({ target: targetSchema, account: external_exports.string().max(64).optional(), label: external_exports.string().max(200).optional() }).strict(),
52160
52304
  to: moveToSchema,
52161
52305
  mode: external_exports.enum(["replace", "new-chat"]).optional(),
52306
+ modeForced: external_exports.literal("conductor").optional(),
52162
52307
  handedOffTo: external_exports.object({ target: external_exports.union([targetSchema, startingTargetSchema]) }).strict().optional(),
52163
52308
  handedOffFrom: external_exports.object({ target: targetSchema, title: external_exports.string().max(200) }).strict().optional(),
52164
52309
  cwd: external_exports.string().max(4096),
@@ -52183,6 +52328,7 @@ var init_session_move = __esm({
52183
52328
  PROMPT_LIMIT2 = 32768;
52184
52329
  recordFile = (id2) => path89.join(movesRoot(), `${external_exports.string().uuid().parse(id2)}.json`);
52185
52330
  handoffPath = (id2) => path89.join(briefRoot(), id2, "handoff.md");
52331
+ landedMoves = /* @__PURE__ */ new Map();
52186
52332
  writes3 = Promise.resolve();
52187
52333
  markers = (id2) => {
52188
52334
  const short = id2.replaceAll("-", "").slice(0, 8);
@@ -52207,11 +52353,12 @@ var init_session_move = __esm({
52207
52353
  return this.deps.pollMs ?? 2e3;
52208
52354
  }
52209
52355
  /** Checks the move can happen, records it and starts it. Refuses before anything is typed. */
52210
- async start(input2) {
52356
+ async start(input2, caller = {}) {
52211
52357
  const data = moveRequestSchema.parse(input2);
52212
52358
  if (data.id) {
52213
52359
  const earlier = await readMove(data.id);
52214
52360
  if (earlier) {
52361
+ if (earlier.modeForced === "conductor" && !caller.owner) throw new BridgeError(403, "Only the owner can move the conductor.");
52215
52362
  const from = earlier.from.target;
52216
52363
  if (from.server !== data.target.server || from.pane !== data.target.pane || from.session !== data.target.session) throw new BridgeError(409, "This move id was already used for another session.");
52217
52364
  return earlier;
@@ -52226,7 +52373,13 @@ var init_session_move = __esm({
52226
52373
  if (pane.agent !== target2.source) throw new BridgeError(409, `That pane no longer runs ${HARNESS_NAMES[target2.source] ?? target2.source}.`);
52227
52374
  const session = await this.deps.identity(target2.server, pane).catch(() => void 0);
52228
52375
  if (session && session !== target2.session) throw new BridgeError(409, "That pane runs another conversation now.");
52229
- if (await this.deps.isConductor?.(target2.server, pane).catch(() => false)) throw new BridgeError(409, "This pane is the conductor. Stop it as conductor first, or make the new agent the conductor after starting it.");
52376
+ const holdsRole = await this.deps.isConductor?.(target2.server, pane) ?? false;
52377
+ if (holdsRole && !caller.owner) throw new BridgeError(403, "Only the owner can move the conductor.");
52378
+ const conductor = holdsRole ? await recordedConductor() : void 0;
52379
+ if (holdsRole && (!conductor || conductor.server !== target2.server || conductor.pane !== target2.pane)) {
52380
+ throw new BridgeError(409, "The conductor changed during the move; nothing was transferred.");
52381
+ }
52382
+ if (conductor && to.harness === "copilot") throw new BridgeError(400, "Copilot cannot run as a conductor.");
52230
52383
  const account = target2.source === "claude" ? this.deps.paneAccount?.(target2.server, pane) ?? DEFAULT_ACCOUNT : void 0;
52231
52384
  const sameHarness = to.harness === target2.source && (to.harness !== "claude" || (to.account ?? account) === account);
52232
52385
  if (sameHarness && !to.model && !to.effort) throw new BridgeError(400, "The session already runs there. Choose another harness, account, model or effort.");
@@ -52252,7 +52405,8 @@ var init_session_move = __esm({
52252
52405
  state: "handing-off",
52253
52406
  createdAt: at2,
52254
52407
  updatedAt: at2,
52255
- mode: data.mode,
52408
+ mode: conductor ? "new-chat" : data.mode,
52409
+ ...conductor ? { modeForced: "conductor" } : {},
52256
52410
  from: { target: target2, ...account ? { account } : {}, ...label2 ? { label: label2.slice(0, 200) } : {} },
52257
52411
  to,
52258
52412
  cwd,
@@ -52260,7 +52414,7 @@ var init_session_move = __esm({
52260
52414
  };
52261
52415
  await saveMove(record4);
52262
52416
  const key4 = `${target2.server}\0${target2.pane}`;
52263
- const work = this.run(record4, data.handoffTimeoutMs ?? DEFAULT_HANDOFF_MS).finally(() => this.running.delete(key4));
52417
+ const work = this.run(record4, data.handoffTimeoutMs ?? DEFAULT_HANDOFF_MS, conductor).finally(() => this.running.delete(key4));
52264
52418
  this.running.set(key4, work);
52265
52419
  return record4;
52266
52420
  }
@@ -52272,8 +52426,9 @@ var init_session_move = __esm({
52272
52426
  Object.assign(record4, change, { updatedAt: new Date(this.now).toISOString() });
52273
52427
  await saveMove(record4);
52274
52428
  }
52275
- async run(record4, handoffMs) {
52429
+ async run(record4, handoffMs, conductor) {
52276
52430
  const from = record4.from.target;
52431
+ let roleTransferred = false;
52277
52432
  try {
52278
52433
  const pane = findPane(await this.deps.snapshot(from.server), placeOf(from));
52279
52434
  const pids = pane ? (await this.deps.terminal.processes(from.server, from.pane).catch(() => void 0))?.foregroundPids ?? [] : [];
@@ -52294,7 +52449,7 @@ Continue the owner's goal above after checking the checkout and the latest agent
52294
52449
  ## Key files
52295
52450
 
52296
52451
  Open or changed files are named in the conversation above and the checked Git state below; open editor tabs are not available to the Hook.` : fallback2;
52297
- const document = handoffDocument(record4, body2, observedState(git9, processes), new Date(this.now).toISOString());
52452
+ const document = handoffDocument(record4, body2, observedState(git9, processes), new Date(this.now).toISOString(), !!conductor);
52298
52453
  const file4 = handoffPath(record4.id);
52299
52454
  const prompt = briefText(continuePrompt(document, file4));
52300
52455
  await writeLaunchBrief({ id: record4.id, text: prompt }, this.now, record4.from.label);
@@ -52305,12 +52460,55 @@ Open or changed files are named in the conversation above and the checked Git st
52305
52460
  ..."reason" in written ? { reason: written.reason.slice(0, 300) } : {},
52306
52461
  chars: document.length
52307
52462
  } });
52463
+ await this.checkPromotion(record4);
52308
52464
  if (record4.mode !== "new-chat") {
52309
52465
  const exit = await this.exit(record4);
52310
52466
  await this.update(record4, { state: "launching", exit });
52311
52467
  await this.deps.afterExit?.(from.server, from.pane).catch(() => void 0);
52312
52468
  }
52313
52469
  const launched = await this.relaunch(record4, prompt);
52470
+ await this.checkPromotion(record4);
52471
+ if (conductor) {
52472
+ try {
52473
+ if (launched.linkPending || !launched.target || !("session" in launched.target)) throw new Error("The new conductor conversation is not linked; the hand-over was not confirmed.");
52474
+ const confirmedTarget = launched.target;
52475
+ let accepted = false;
52476
+ for (const until = this.now + 3e4; this.now < until; await this.sleep(this.poll)) {
52477
+ const arrival = (await briefArrival(record4.id))?.accepted?.target;
52478
+ if (arrival && Object.keys(confirmedTarget).every((key4) => arrival[key4] === confirmedTarget[key4])) {
52479
+ accepted = true;
52480
+ break;
52481
+ }
52482
+ }
52483
+ if (!accepted) throw new Error("The new conductor's hand-off brief was not confirmed within 30 seconds.");
52484
+ const place = record4.paneTarget;
52485
+ const next = place && findPane(await this.deps.snapshot(place.server), place);
52486
+ if (!place || !runsAgent(next) || next.agent !== record4.to.harness) throw new Error("The new agent is no longer running in its launched pane.");
52487
+ if (!["idle", "working"].includes(String(next.agent_status))) throw new Error(`The new conductor is not ready (${String(next.agent_status)}); answer its startup dialog before retrying.`);
52488
+ if (typeof next.terminal_id !== "string" || !next.terminal_id) throw new Error("The new pane has no terminal identity for worker returns.");
52489
+ const origin = {
52490
+ server: place.server,
52491
+ workspace: place.workspace,
52492
+ tab: place.tab,
52493
+ pane: place.pane,
52494
+ agent: record4.to.harness,
52495
+ terminal: next.terminal_id
52496
+ };
52497
+ await transferConductor(
52498
+ conductor,
52499
+ place.server,
52500
+ next,
52501
+ launched.target && "session" in launched.target ? launched.target.session : void 0,
52502
+ (commit) => repointDispatchOrigins(conductor, origin, commit)
52503
+ );
52504
+ roleTransferred = true;
52505
+ const notice = await this.conductorNotice(record4, "The Hook confirmed the hand-over; you are now the conductor. Continue coordinating the owner's work and existing workers.", "confirmed");
52506
+ if (notice) record4.notice = notice;
52507
+ } catch (error62) {
52508
+ if (error62 instanceof BridgeError) throw error62;
52509
+ throw new Error(`Conductor role transfer failed. The old chat was left running. ${error62 instanceof Error ? error62.message : String(error62)}`);
52510
+ }
52511
+ }
52314
52512
  await this.update(record4, {
52315
52513
  state: "moved",
52316
52514
  movedAt: new Date(this.now).toISOString(),
@@ -52323,12 +52521,56 @@ Open or changed files are named in the conversation above and the checked Git st
52323
52521
  logger.info("move", `Moved ${from.source} in pane ${from.pane} to ${harnessName(record4.to)} (${launched.placement}); hand-off ${record4.handoff?.source}.`);
52324
52522
  } catch (error62) {
52325
52523
  const message = (error62 instanceof Error ? error62.message : String(error62)).replace(/[\x00-\x1f\x7f]+/g, " ");
52524
+ if (roleTransferred) {
52525
+ record4.state = "moved";
52526
+ record4.notice = `Conductor moved with worker routing, but saving move status failed: ${message}`.slice(0, 500);
52527
+ delete record4.error;
52528
+ landedMoves.set(recordFile(record4.id), record4);
52529
+ while (landedMoves.size > MAX_MOVES) landedMoves.delete(landedMoves.keys().next().value);
52530
+ await saveMove(record4).catch(() => void 0);
52531
+ logger.warn("move", record4.notice);
52532
+ return;
52533
+ }
52534
+ if (conductor && record4.paneTarget) {
52535
+ record4.notice = await this.conductorNotice(
52536
+ record4,
52537
+ "The conductor hand-over failed; you are not the conductor. The previous conductor keeps coordinating.",
52538
+ "failed"
52539
+ ) ?? "The new chat was told the conductor hand-over failed; it is not the conductor.";
52540
+ }
52326
52541
  const stopped = record4.exit !== void 0;
52327
52542
  const hint = stopped && record4.handoff ? ` The old agent has exited; start ${HARNESS_NAMES[record4.to.harness]} in the pane with the hand-off at ${record4.handoff.path}.` : "";
52328
52543
  await this.update(record4, { state: "failed", error: `${message}${hint}`.slice(0, 500) }).catch(() => void 0);
52329
52544
  logger.warn("move", `Moving pane ${from.pane} to ${record4.to.harness} failed: ${message}`);
52330
52545
  }
52331
52546
  }
52547
+ /** An ordinary move never acquires permission to stop a conductor merely
52548
+ * because the owner promoted its source while the hand-off was running. */
52549
+ async checkPromotion(record4) {
52550
+ if (record4.modeForced === "conductor") return;
52551
+ const current2 = await recordedConductor();
52552
+ if (current2?.server === record4.from.target.server && current2.pane === record4.from.target.pane) {
52553
+ throw new BridgeError(409, "The pane became the conductor during the move; nothing was changed.");
52554
+ }
52555
+ }
52556
+ /** Uses the same durable prompt path as the hand-off and its first brief. */
52557
+ async conductorNotice(record4, text5, outcome) {
52558
+ try {
52559
+ const target2 = targetSchema.safeParse(record4.target);
52560
+ if (target2.success) {
52561
+ const sent = await this.deps.deliver(target2.data, text5, `move-${record4.id}-conductor-${outcome}`);
52562
+ if (sent.state === "failed" || sent.ok !== true && sent.queued !== true || sent.delivered === false && sent.queued !== true) {
52563
+ throw new Error(String(sent.error ?? "delivery was not confirmed"));
52564
+ }
52565
+ } else if (record4.paneTarget) {
52566
+ await this.deps.terminal.prompt(record4.paneTarget.server, record4.paneTarget.pane, text5);
52567
+ return `The conductor hand-over ${outcome} notice was typed to the new pane; conversation delivery is unconfirmed.`;
52568
+ }
52569
+ return void 0;
52570
+ } catch (error62) {
52571
+ return `The conductor hand-over ${outcome}, but the new chat's notice could not be delivered: ${error62 instanceof Error ? error62.message : String(error62)}`.slice(0, 500);
52572
+ }
52573
+ }
52332
52574
  /** The agent's own hand-off, or why there is none. Fails only when the session itself went away. */
52333
52575
  async askForHandoff(record4, handoffMs) {
52334
52576
  const from = record4.from.target;
@@ -52386,12 +52628,15 @@ Open or changed files are named in the conversation above and the checked Git st
52386
52628
  };
52387
52629
  const pane = findPane(await this.deps.snapshot(from.server), placeOf(from));
52388
52630
  if (pane?.agent_status === "working") {
52631
+ await this.checkPromotion(record4);
52389
52632
  await this.deps.terminal.sendKeys(from.server, from.pane, ["esc"]).catch(() => void 0);
52390
52633
  await this.sleep(1e3);
52391
52634
  }
52635
+ await this.checkPromotion(record4);
52392
52636
  await this.deps.terminal.prompt(from.server, from.pane, EXIT_COMMANDS[from.source] ?? "/exit").catch(() => void 0);
52393
52637
  if (await gone(exitMs)) return "clean";
52394
52638
  for (let n7 = 0; n7 < 2; n7++) {
52639
+ await this.checkPromotion(record4);
52395
52640
  await this.deps.terminal.sendKeys(from.server, from.pane, ["ctrl+c"]).catch(() => void 0);
52396
52641
  await this.sleep(500);
52397
52642
  }
@@ -52400,6 +52645,7 @@ Open or changed files are named in the conversation above and the checked Git st
52400
52645
  const agent = foregroundPids2.filter((pid) => pid !== shellPid);
52401
52646
  const kill = this.deps.kill ?? ((pid, signal) => process.kill(pid, signal));
52402
52647
  for (const signal of ["SIGTERM", "SIGKILL"]) {
52648
+ await this.checkPromotion(record4);
52403
52649
  for (const pid of agent) {
52404
52650
  try {
52405
52651
  kill(pid, signal);
@@ -52418,7 +52664,7 @@ Open or changed files are named in the conversation above and the checked Git st
52418
52664
  if (!pane) throw new BridgeError(409, "The pane closed after the old agent exited.");
52419
52665
  const shellAccount = record4.from.account ?? DEFAULT_ACCOUNT;
52420
52666
  const account = record4.to.harness === "claude" ? record4.to.account ?? shellAccount : void 0;
52421
- const samePane2 = record4.mode !== "new-chat" && ((this.deps.envAtStart?.(from.server) ?? false) || record4.to.harness !== "claude" || account === shellAccount);
52667
+ const samePane3 = record4.mode !== "new-chat" && ((this.deps.envAtStart?.(from.server) ?? false) || record4.to.harness !== "claude" || account === shellAccount);
52422
52668
  const data = {
52423
52669
  kind: record4.to.harness,
52424
52670
  label: record4.from.label ?? HARNESS_NAMES[record4.to.harness],
@@ -52427,10 +52673,11 @@ Open or changed files are named in the conversation above and the checked Git st
52427
52673
  ...record4.to.effort ? { effort: record4.to.effort } : {},
52428
52674
  ...account ? { account } : {},
52429
52675
  brief: { id: record4.id, text: prompt },
52430
- ...samePane2 ? {} : { workspaceId: from.workspace }
52676
+ ...samePane3 ? {} : { workspaceId: from.workspace }
52431
52677
  };
52432
- const into = samePane2 ? { workspaceId: from.workspace, tabId: from.tab, paneId: from.pane } : void 0;
52433
- const launched = await this.deps.launch(from.server, data, { ...into ? { into } : {}, ...record4.dispatch ? { dispatchId: record4.dispatch } : {} });
52678
+ const into = samePane3 ? { workspaceId: from.workspace, tabId: from.tab, paneId: from.pane } : void 0;
52679
+ await this.checkPromotion(record4);
52680
+ const launched = await this.deps.launch(from.server, data, { ...into ? { into } : {}, ...record4.dispatch && record4.modeForced !== "conductor" ? { dispatchId: record4.dispatch } : {} });
52434
52681
  const paneTarget = targetSchema.omit({ session: true }).parse({
52435
52682
  server: from.server,
52436
52683
  workspace: launched.workspaceId,
@@ -52441,7 +52688,7 @@ Open or changed files are named in the conversation above and the checked Git st
52441
52688
  const launchedTarget = external_exports.union([targetSchema, startingTargetSchema]).safeParse(launched.target);
52442
52689
  await this.update(record4, {
52443
52690
  paneTarget,
52444
- placement: samePane2 ? "same-pane" : "adjacent-pane",
52691
+ placement: samePane3 ? "same-pane" : "adjacent-pane",
52445
52692
  ...launchedTarget.success ? { target: launchedTarget.data } : {}
52446
52693
  });
52447
52694
  if (launched.briefLaunched === false) {
@@ -52458,9 +52705,12 @@ Open or changed files are named in the conversation above and the checked Git st
52458
52705
  throw new Error(`${record4.mode === "new-chat" ? "New chat" : "Target"} started but did not receive the hand-off. The launched pane was left open. ${reason2}`);
52459
52706
  }
52460
52707
  }
52461
- if (!samePane2 && record4.mode !== "new-chat") await this.deps.terminal.closePane(from.server, from.pane).catch(() => void 0);
52708
+ if (!samePane3 && record4.mode !== "new-chat") {
52709
+ await this.checkPromotion(record4);
52710
+ await this.deps.terminal.closePane(from.server, from.pane).catch(() => void 0);
52711
+ }
52462
52712
  const to = account ? { ...record4.to, account } : record4.to;
52463
- return { to, placement: samePane2 ? "same-pane" : "adjacent-pane", ...await this.newTarget(record4, launched, record4.to.harness) };
52713
+ return { to, placement: samePane3 ? "same-pane" : "adjacent-pane", ...await this.newTarget(record4, launched, record4.to.harness) };
52464
52714
  }
52465
52715
  /** New chats remain open as linking while the harness establishes its conversation. */
52466
52716
  async newTarget(record4, launched, source) {
@@ -52569,7 +52819,7 @@ async function rpc(server, method, params = {}, signal, timeoutMs = 1e4) {
52569
52819
  return new Promise((resolve17, reject) => {
52570
52820
  const client = connect2(socket);
52571
52821
  const key4 = requestID();
52572
- let pending2 = Buffer.alloc(0);
52822
+ let pending3 = Buffer.alloc(0);
52573
52823
  const finish = (error62, result) => {
52574
52824
  signal?.removeEventListener("abort", abort);
52575
52825
  client.destroy();
@@ -52587,15 +52837,15 @@ async function rpc(server, method, params = {}, signal, timeoutMs = 1e4) {
52587
52837
  client.on("end", () => finish(new BridgeError(503, "Herdr closed the request before confirming it.")));
52588
52838
  client.on("connect", () => client.write(JSON.stringify({ id: key4, method, params }) + "\n"));
52589
52839
  client.on("data", (bytes) => {
52590
- pending2 = Buffer.concat([pending2, typeof bytes === "string" ? Buffer.from(bytes) : bytes]);
52591
- if (pending2.length > 4194304) {
52840
+ pending3 = Buffer.concat([pending3, typeof bytes === "string" ? Buffer.from(bytes) : bytes]);
52841
+ if (pending3.length > 4194304) {
52592
52842
  finish(new BridgeError(413, "Herdr response is too large."));
52593
52843
  return;
52594
52844
  }
52595
- const end = pending2.indexOf(10);
52845
+ const end = pending3.indexOf(10);
52596
52846
  if (end < 0) return;
52597
52847
  try {
52598
- const value2 = object2(JSON.parse(pending2.subarray(0, end).toString()));
52848
+ const value2 = object2(JSON.parse(pending3.subarray(0, end).toString()));
52599
52849
  if (value2.id !== key4) throw new Error("Mismatched response");
52600
52850
  if (value2.error) {
52601
52851
  const code = typeof object2(value2.error).code === "string" ? String(object2(value2.error).code).slice(0, 64) : void 0;
@@ -52646,8 +52896,8 @@ async function snapshot(server) {
52646
52896
  async function sharedSnapshot(server, maxAgeMs = SNAPSHOT_SHARE_MS) {
52647
52897
  const cached3 = sharedSnapshots.get(server);
52648
52898
  if (cached3 && Date.now() - cached3.at < maxAgeMs) return cached3.value;
52649
- const pending2 = inFlightSnapshots.get(server);
52650
- if (pending2) return pending2;
52899
+ const pending3 = inFlightSnapshots.get(server);
52900
+ if (pending3) return pending3;
52651
52901
  const value2 = snapshot(server).finally(() => {
52652
52902
  if (inFlightSnapshots.get(server) === value2) inFlightSnapshots.delete(server);
52653
52903
  });
@@ -54063,7 +54313,7 @@ var init_owner_inbox_sources = __esm({
54063
54313
  import { createHash as createHash24, randomUUID as randomUUID22 } from "node:crypto";
54064
54314
  import { lstat as lstat24, open as open16, readFile as readFile38, readdir as readdir14, unlink as unlink5 } from "node:fs/promises";
54065
54315
  import path93 from "node:path";
54066
- var queuedHandOffSchema, rowSchema, DAY3, HAND_OFF_RETENTION_MS, HAND_OFF_MAX_ROWS, settled2, samePane, HandOffQueue;
54316
+ var queuedHandOffSchema, rowSchema, DAY3, HAND_OFF_RETENTION_MS, HAND_OFF_MAX_ROWS, settled2, samePane2, HandOffQueue;
54067
54317
  var init_hand_off_queue = __esm({
54068
54318
  "src/bridge/hand-off-queue.ts"() {
54069
54319
  "use strict";
@@ -54091,7 +54341,7 @@ var init_hand_off_queue = __esm({
54091
54341
  HAND_OFF_RETENTION_MS = 7 * DAY3;
54092
54342
  HAND_OFF_MAX_ROWS = 512;
54093
54343
  settled2 = (row) => row.state !== "queued" && row.state !== "attempting";
54094
- samePane = (a, b) => ["server", "workspace", "tab", "pane", "source"].every((key4) => a[key4] === b[key4]);
54344
+ samePane2 = (a, b) => ["server", "workspace", "tab", "pane", "source"].every((key4) => a[key4] === b[key4]);
54095
54345
  HandOffQueue = class {
54096
54346
  constructor(options) {
54097
54347
  this.options = options;
@@ -54190,7 +54440,7 @@ var init_hand_off_queue = __esm({
54190
54440
  const data = queuedHandOffSchema.parse(input2), id2 = data.deliveryId ?? randomUUID22().replaceAll("-", "");
54191
54441
  const prior = await this.read(id2);
54192
54442
  if (prior) {
54193
- if (!samePane(prior.target, data.target) || prior.text !== data.text) throw new BridgeError(409, "This message id was already used for a different message.");
54443
+ if (!samePane2(prior.target, data.target) || prior.text !== data.text) throw new BridgeError(409, "This message id was already used for a different message.");
54194
54444
  return { ...this.reply(prior), replayed: true };
54195
54445
  }
54196
54446
  const row = { ...data, deliveryId: id2 };
@@ -54199,7 +54449,7 @@ var init_hand_off_queue = __esm({
54199
54449
  const at2 = new Date(this.now()).toISOString();
54200
54450
  Object.assign(row, { terminal: pane.terminal_id, state: "queued", createdAt: at2, updatedAt: at2 });
54201
54451
  await this.save(row);
54202
- const ahead = (await this.prune(await this.rows())).some((other) => other.deliveryId !== id2 && samePane(other.target, row.target) && other.state === "queued");
54452
+ const ahead = (await this.prune(await this.rows())).some((other) => other.deliveryId !== id2 && samePane2(other.target, row.target) && other.state === "queued");
54203
54453
  if (!ahead) await this.attempt(row, pane);
54204
54454
  return this.reply(row);
54205
54455
  });
@@ -54207,7 +54457,7 @@ var init_hand_off_queue = __esm({
54207
54457
  status(id2, target2) {
54208
54458
  return this.serial(async () => {
54209
54459
  const row = await this.read(id2);
54210
- if (!row || !samePane(row.target, target2)) throw new BridgeError(404, "No hand-off with this id and target.");
54460
+ if (!row || !samePane2(row.target, target2)) throw new BridgeError(404, "No hand-off with this id and target.");
54211
54461
  return this.reply(row);
54212
54462
  });
54213
54463
  }
@@ -54328,12 +54578,12 @@ var init_hand_off_queue = __esm({
54328
54578
  * A new hand-off cannot be accepted between the pending check and closure. */
54329
54579
  whenNoPending(target2, close) {
54330
54580
  return this.serial(async () => {
54331
- if ((await this.rows()).some((row) => samePane(row.target, target2) && ["queued", "attempting", "uncertain"].includes(row.state))) return { ok: true, closed: false };
54581
+ if ((await this.rows()).some((row) => samePane2(row.target, target2) && ["queued", "attempting", "uncertain"].includes(row.state))) return { ok: true, closed: false };
54332
54582
  return close();
54333
54583
  });
54334
54584
  }
54335
54585
  hasPending(target2) {
54336
- return this.serial(async () => (await this.rows()).some((row) => samePane(row.target, target2) && ["queued", "attempting", "uncertain"].includes(row.state)));
54586
+ return this.serial(async () => (await this.rows()).some((row) => samePane2(row.target, target2) && ["queued", "attempting", "uncertain"].includes(row.state)));
54337
54587
  }
54338
54588
  };
54339
54589
  }
@@ -55378,17 +55628,17 @@ function unknownHost(host) {
55378
55628
  }
55379
55629
  function checkRollup(items) {
55380
55630
  if (!Array.isArray(items) || !items.length) return null;
55381
- let pending2 = false;
55631
+ let pending3 = false;
55382
55632
  for (const raw of items) {
55383
55633
  const item = raw && typeof raw === "object" ? raw : {};
55384
55634
  const conclusion = String(item.conclusion ?? "").toUpperCase(), state = String(item.state ?? "").toUpperCase();
55385
55635
  const status = String(item.status ?? "").toUpperCase();
55386
55636
  if (["FAILURE", "TIMED_OUT", "CANCELLED", "ACTION_REQUIRED", "STARTUP_FAILURE"].includes(conclusion) || ["FAILURE", "ERROR"].includes(state)) return "failing";
55387
55637
  if (state && !status) {
55388
- if (state !== "SUCCESS") pending2 = true;
55389
- } else if (status !== "COMPLETED") pending2 = true;
55638
+ if (state !== "SUCCESS") pending3 = true;
55639
+ } else if (status !== "COMPLETED") pending3 = true;
55390
55640
  }
55391
- return pending2 ? "pending" : "passing";
55641
+ return pending3 ? "pending" : "passing";
55392
55642
  }
55393
55643
  function checkRuns(items) {
55394
55644
  if (!Array.isArray(items)) return [];
@@ -57229,6 +57479,7 @@ __export(scoped_gateway_exports, {
57229
57479
  GATEWAY_SCOPES: () => GATEWAY_SCOPES,
57230
57480
  SCOPED_COMMAND: () => SCOPED_COMMAND,
57231
57481
  SCOPE_KEY_COMMENT: () => SCOPE_KEY_COMMENT,
57482
+ admitPeerRequest: () => admitPeerRequest,
57232
57483
  admitScopedRequest: () => admitScopedRequest,
57233
57484
  isGatewayScope: () => isGatewayScope,
57234
57485
  scopedDispatch: () => scopedDispatch
@@ -57281,6 +57532,7 @@ function admitScopedRequest(scope, rawHead, rest = Buffer.alloc(0)) {
57281
57532
  const head = parseHead(rawHead);
57282
57533
  if ("ok" in head) return head;
57283
57534
  const rule2 = findRule(scope, head);
57535
+ if (!rule2 && head.path === "/v1/sessions/move") return refuse(403, "Only the owner can move the conductor.");
57284
57536
  if (!rule2) return refuse(403, `This key only permits ${DESCRIBE[scope]}.`);
57285
57537
  let target2 = head.path;
57286
57538
  if (rule2.query) {
@@ -57319,6 +57571,23 @@ Connection: close\r
57319
57571
  \r
57320
57572
  ${body2}` };
57321
57573
  }
57574
+ function admitPeerRequest(rawHead, rest = Buffer.alloc(0)) {
57575
+ const head = parseHead(rawHead);
57576
+ if ("ok" in head) return head;
57577
+ if (!["GET", "POST", "DELETE"].includes(head.method) || !head.path.startsWith("/v1/")) return refuse(403, "This key only permits Hook API requests.");
57578
+ if (head.contentLength > 8 * 1024 * 1024 || rest.length !== head.contentLength) return refuse(400, "Send one bounded request matching Content-Length.");
57579
+ if (rest.length && !head.json) return refuse(415, "Send Content-Type: application/json.");
57580
+ const body2 = rest.toString("utf8");
57581
+ const target2 = head.path + (head.query === null ? "" : `?${head.query}`);
57582
+ return { ok: true, request: `${head.method} ${target2} HTTP/1.1\r
57583
+ Host: phren.local\r
57584
+ X-Phren-Origin: peer\r
57585
+ Connection: close\r
57586
+ Content-Type: application/json\r
57587
+ Content-Length: ${Buffer.byteLength(body2)}\r
57588
+ \r
57589
+ ${body2}` };
57590
+ }
57322
57591
  function httpResponse(status, error62) {
57323
57592
  const body2 = JSON.stringify({ error: error62, code: status === 503 ? "hook-unavailable" : "scope-refused" });
57324
57593
  return `HTTP/1.1 ${status} ${REASONS[status] ?? "Bad Request"}\r
@@ -57330,7 +57599,7 @@ Content-Length: ${Buffer.byteLength(body2)}\r
57330
57599
  ${body2}`;
57331
57600
  }
57332
57601
  function readRequest(scope, input2) {
57333
- const bodyCap = Math.max(0, ...RULES[scope].map((rule2) => rule2.body?.max ?? 0));
57602
+ const bodyCap = scope === "peer" ? 8 * 1024 * 1024 : Math.max(0, ...RULES[scope].map((rule2) => rule2.body?.max ?? 0));
57334
57603
  return new Promise((resolve17) => {
57335
57604
  let buffer = Buffer.alloc(0), headEnd = -1, wanted = 0;
57336
57605
  const finish = (value2) => {
@@ -57364,10 +57633,10 @@ function readRequest(scope, input2) {
57364
57633
  });
57365
57634
  }
57366
57635
  async function scopedDispatch(scope, command, io) {
57367
- if (!isGatewayScope(scope)) throw new BridgeError(403, "Unknown key scope.");
57368
- if (command !== SCOPED_COMMAND) throw new BridgeError(403, `This SSH key only permits \`${SCOPED_COMMAND}\` with ${DESCRIBE[scope]}.`);
57636
+ if (scope !== "peer" && !isGatewayScope(scope)) throw new BridgeError(403, "Unknown key scope.");
57637
+ if (command !== SCOPED_COMMAND) throw new BridgeError(403, `This SSH key only permits \`${SCOPED_COMMAND}\` with ${scope === "peer" ? "Hook API requests" : DESCRIBE[scope]}.`);
57369
57638
  const read = await readRequest(scope, io.input);
57370
- const admission = "head" in read ? admitScopedRequest(scope, read.head, read.rest) : refuse(read.status, read.error);
57639
+ const admission = "head" in read ? scope === "peer" ? admitPeerRequest(read.head, read.rest) : admitScopedRequest(scope, read.head, read.rest) : refuse(read.status, read.error);
57371
57640
  if (!admission.ok) {
57372
57641
  await new Promise((done) => io.output.write(httpResponse(admission.status, admission.error), () => done()));
57373
57642
  return;
@@ -58285,16 +58554,16 @@ function openPaneClient(entry2, fetchImpl = fetch) {
58285
58554
  if (!response.ok || !response.body) throw new Error(`opencode GET /event failed with ${response.status}.`);
58286
58555
  const reader = response.body.getReader();
58287
58556
  const decoder = new TextDecoder();
58288
- let pending2 = "";
58557
+ let pending3 = "";
58289
58558
  try {
58290
58559
  for (; ; ) {
58291
58560
  const { value: value2, done } = await reader.read();
58292
58561
  if (done) return;
58293
- pending2 += decoder.decode(value2, { stream: true });
58562
+ pending3 += decoder.decode(value2, { stream: true });
58294
58563
  let boundary;
58295
- while ((boundary = pending2.indexOf("\n\n")) >= 0) {
58296
- const block = pending2.slice(0, boundary);
58297
- pending2 = pending2.slice(boundary + 2);
58564
+ while ((boundary = pending3.indexOf("\n\n")) >= 0) {
58565
+ const block = pending3.slice(0, boundary);
58566
+ pending3 = pending3.slice(boundary + 2);
58298
58567
  const data = block.split("\n").filter((row) => row.startsWith("data:")).map((row) => row.slice(5).trimStart()).join("\n");
58299
58568
  if (!data) continue;
58300
58569
  try {
@@ -59621,19 +59890,19 @@ var init_agent_hooks = __esm({
59621
59890
  }
59622
59891
  }
59623
59892
  approval(target2) {
59624
- const pending2 = [...this.pending.entries()].find(([, p]) => JSON.stringify(p.target) === JSON.stringify(target2));
59625
- if (pending2) return {
59626
- actionId: pending2[0],
59627
- toolName: pending2[1].tool,
59628
- title: pending2[1].choice?.title ?? pending2[1].title,
59629
- message: pending2[1].message,
59630
- request: pending2[1].request,
59631
- details: pending2[1].message,
59632
- terminalOnly: target2.source === "codex" && !pending2[1].choice && !pending2[1].appServer,
59633
- ...pending2[1].choice ? { choice: pending2[1].choice } : {},
59893
+ const pending3 = [...this.pending.entries()].find(([, p]) => JSON.stringify(p.target) === JSON.stringify(target2));
59894
+ if (pending3) return {
59895
+ actionId: pending3[0],
59896
+ toolName: pending3[1].tool,
59897
+ title: pending3[1].choice?.title ?? pending3[1].title,
59898
+ message: pending3[1].message,
59899
+ request: pending3[1].request,
59900
+ details: pending3[1].message,
59901
+ terminalOnly: target2.source === "codex" && !pending3[1].choice && !pending3[1].appServer,
59902
+ ...pending3[1].choice ? { choice: pending3[1].choice } : {},
59634
59903
  // An app-server request waits for as long as it takes: its card never runs out.
59635
- expiresAt: pending2[1].appServer ? new Date(Math.max(Date.parse(pending2[1].expiresAt), Date.now() + DIALOG_PUSH_MS)).toISOString() : pending2[1].expiresAt,
59636
- ...pending2[1].conductor ? { conductor: pending2[1].conductor } : {}
59904
+ expiresAt: pending3[1].appServer ? new Date(Math.max(Date.parse(pending3[1].expiresAt), Date.now() + DIALOG_PUSH_MS)).toISOString() : pending3[1].expiresAt,
59905
+ ...pending3[1].conductor ? { conductor: pending3[1].conductor } : {}
59637
59906
  };
59638
59907
  const own2 = target2.source === "opencode" ? this.opencodeApproval(target2) : void 0;
59639
59908
  if (own2) return own2;
@@ -59669,7 +59938,7 @@ var init_agent_hooks = __esm({
59669
59938
  }
59670
59939
  pendingPanes(server, state) {
59671
59940
  const panes2 = objects(state.panes);
59672
- const pending2 = new Set([...this.pending.values()].filter((p) => p.target.server === server && panes2.some((pane) => {
59941
+ const pending3 = new Set([...this.pending.values()].filter((p) => p.target.server === server && panes2.some((pane) => {
59673
59942
  if (pane.pane_id !== p.target.pane || pane.workspace_id !== p.target.workspace || pane.tab_id !== p.target.tab || pane.agent !== p.target.source) return false;
59674
59943
  const reported = object2(pane.agent_session);
59675
59944
  return reported.kind !== "id" || reported.agent === p.target.source && reported.value === p.target.session;
@@ -59678,26 +59947,26 @@ var init_agent_hooks = __esm({
59678
59947
  if (!entry2.choice || entry2.questions?.length || Date.now() - entry2.at > 9e5) continue;
59679
59948
  const target2 = JSON.parse(key4);
59680
59949
  if (target2.server !== server) continue;
59681
- if (panes2.some((pane) => pane.pane_id === target2.pane && pane.workspace_id === target2.workspace && pane.tab_id === target2.tab && pane.agent === target2.source && ["waiting", "blocked"].includes(String(pane.agent_status)))) pending2.add(target2.pane);
59950
+ if (panes2.some((pane) => pane.pane_id === target2.pane && pane.workspace_id === target2.workspace && pane.tab_id === target2.tab && pane.agent === target2.source && ["waiting", "blocked"].includes(String(pane.agent_status)))) pending3.add(target2.pane);
59682
59951
  }
59683
59952
  for (const pane of panes2) {
59684
59953
  if (pane.agent !== "opencode") continue;
59685
59954
  const reported = object2(pane.agent_session);
59686
59955
  if (reported.kind === "id" && reported.agent === "opencode" && typeof reported.value === "string" && opencodeRequest(reported.value)) {
59687
- pending2.add(String(pane.pane_id));
59956
+ pending3.add(String(pane.pane_id));
59688
59957
  }
59689
59958
  }
59690
59959
  const served = [...[...this.opencode.values()].filter((held) => held.served).map((held) => held.target), ...[...this.servedQuestions.values()].map((held) => held.target)];
59691
59960
  for (const at2 of served) {
59692
59961
  if (!at2 || at2.server !== server) continue;
59693
- if (panes2.some((pane) => pane.pane_id === at2.pane && pane.workspace_id === at2.workspace && pane.tab_id === at2.tab && pane.agent === "opencode")) pending2.add(at2.pane);
59962
+ if (panes2.some((pane) => pane.pane_id === at2.pane && pane.workspace_id === at2.workspace && pane.tab_id === at2.tab && pane.agent === "opencode")) pending3.add(at2.pane);
59694
59963
  }
59695
59964
  for (const held of this.opencode.values()) {
59696
59965
  const parent = held.target;
59697
59966
  if (!held.fanout || !parent || parent.server !== server) continue;
59698
- if (panes2.some((pane) => pane.pane_id === parent.pane && pane.workspace_id === parent.workspace && pane.tab_id === parent.tab) && this.fanoutHeld(parent).length) pending2.add(parent.pane);
59967
+ if (panes2.some((pane) => pane.pane_id === parent.pane && pane.workspace_id === parent.workspace && pane.tab_id === parent.tab) && this.fanoutHeld(parent).length) pending3.add(parent.pane);
59699
59968
  }
59700
- return pending2;
59969
+ return pending3;
59701
59970
  }
59702
59971
  /** Hands the owner's answer to the fan-out launcher waiting on the worker's session. */
59703
59972
  async answerFanout(id2, held, decision) {
@@ -59819,9 +60088,9 @@ var init_agent_hooks = __esm({
59819
60088
  await forwarded(decision);
59820
60089
  return;
59821
60090
  }
59822
- const pending2 = this.pending.get(linked.action);
59823
- if (pending2) {
59824
- await this.answer(pending2.target, linked.action, decision);
60091
+ const pending3 = this.pending.get(linked.action);
60092
+ if (pending3) {
60093
+ await this.answer(pending3.target, linked.action, decision);
59825
60094
  return;
59826
60095
  }
59827
60096
  if (await this.releasedHoldDialog(linked.action)) {
@@ -59971,8 +60240,8 @@ ${target2.source}`) ?? 0) > Date.now();
59971
60240
  const clip = (value2, max) => typeof value2 === "string" && value2 ? value2.slice(0, max) : void 0;
59972
60241
  const held = this.approval(target2);
59973
60242
  if (held) {
59974
- const actionId = String(held.actionId), pending2 = this.pending.get(actionId);
59975
- const pushed = pending2 ? this.pushedHolds.has(actionId) || !!pending2.appServer && this.push.available : this.push.available;
60243
+ const actionId = String(held.actionId), pending3 = this.pending.get(actionId);
60244
+ const pushed = pending3 ? this.pushedHolds.has(actionId) || !!pending3.appServer && this.push.available : this.push.available;
59976
60245
  const title3 = clip(held.title, 200), request11 = clip(held.request, 500), expiresAt = clip(held.expiresAt, 40);
59977
60246
  const conductor = held.conductor;
59978
60247
  return {
@@ -59980,7 +60249,7 @@ ${target2.source}`) ?? 0) > Date.now();
59980
60249
  tool: clip(held.toolName, 200) ?? "action",
59981
60250
  ...title3 ? { title: title3 } : {},
59982
60251
  ...request11 ? { request: request11 } : {},
59983
- ...pending2 ? { requestKind: pending2.requestKind } : {},
60252
+ ...pending3 ? { requestKind: pending3.requestKind } : {},
59984
60253
  ...expiresAt ? { expiresAt } : {},
59985
60254
  ...conductor ? { conductor } : {},
59986
60255
  ...pushed ? { pushed: true } : {}
@@ -60405,9 +60674,9 @@ ${await conductorBrief()}` : context3 } : {}));
60405
60674
  if (!delivered) {
60406
60675
  this.pushBindings.consume(binding);
60407
60676
  this.pushedHolds.delete(action);
60408
- const pending2 = this.pending.get(action);
60409
- if (!locallyWatched && pending2) {
60410
- clearTimeout(pending2.timer);
60677
+ const pending3 = this.pending.get(action);
60678
+ if (!locallyWatched && pending3) {
60679
+ clearTimeout(pending3.timer);
60411
60680
  this.pending.delete(action);
60412
60681
  res.end("{}");
60413
60682
  }
@@ -60463,9 +60732,9 @@ ${await conductorBrief()}` : context3 } : {}));
60463
60732
  this.sudo.close();
60464
60733
  void this.changes.close().catch(() => {
60465
60734
  });
60466
- for (const pending2 of this.pending.values()) {
60467
- clearTimeout(pending2.timer);
60468
- pending2.response.end("{}");
60735
+ for (const pending3 of this.pending.values()) {
60736
+ clearTimeout(pending3.timer);
60737
+ pending3.response.end("{}");
60469
60738
  }
60470
60739
  this.pending.clear();
60471
60740
  this.server?.close();
@@ -60495,7 +60764,7 @@ import path107 from "node:path";
60495
60764
  function readCodexModels(executable2 = codexExecutable()) {
60496
60765
  return new Promise((resolve17) => {
60497
60766
  const child = spawn11(executable2, ["app-server"], { cwd: homedir17(), stdio: ["pipe", "pipe", "ignore"] });
60498
- let pending2 = "", bytes = 0, initialized = false, done = false;
60767
+ let pending3 = "", bytes = 0, initialized = false, done = false;
60499
60768
  const finish = (result = []) => {
60500
60769
  if (done) return;
60501
60770
  done = true;
@@ -60524,11 +60793,11 @@ function readCodexModels(executable2 = codexExecutable()) {
60524
60793
  finish();
60525
60794
  return;
60526
60795
  }
60527
- pending2 += chunk;
60796
+ pending3 += chunk;
60528
60797
  let newline;
60529
- while (!done && (newline = pending2.indexOf("\n")) >= 0) {
60530
- const line = pending2.slice(0, newline);
60531
- pending2 = pending2.slice(newline + 1);
60798
+ while (!done && (newline = pending3.indexOf("\n")) >= 0) {
60799
+ const line = pending3.slice(0, newline);
60800
+ pending3 = pending3.slice(newline + 1);
60532
60801
  try {
60533
60802
  const response = object2(JSON.parse(line));
60534
60803
  if (response.id === 0 && !initialized) {
@@ -62529,16 +62798,16 @@ async function driveOpencode(child, o) {
62529
62798
  await call3("POST", `/permission/${encodeURIComponent(asked.id)}/reply`, decision === "approve" ? { reply: "once" } : decision === "always" ? { reply: "always" } : { reply: "reject", message: decision === "deny" ? DENIED_FEEDBACK : UNANSWERED_FEEDBACK });
62530
62799
  };
62531
62800
  const reader = events.body.getReader(), decoder = new TextDecoder();
62532
- let pending2 = "";
62801
+ let pending3 = "";
62533
62802
  const read = async () => {
62534
62803
  for (; ; ) {
62535
62804
  const { value: value2, done } = await reader.read();
62536
62805
  if (done) throw new Error("opencode closed its event stream.");
62537
- pending2 += decoder.decode(value2, { stream: true });
62806
+ pending3 += decoder.decode(value2, { stream: true });
62538
62807
  let boundary;
62539
- while ((boundary = pending2.indexOf("\n\n")) >= 0) {
62540
- const block = pending2.slice(0, boundary);
62541
- pending2 = pending2.slice(boundary + 2);
62808
+ while ((boundary = pending3.indexOf("\n\n")) >= 0) {
62809
+ const block = pending3.slice(0, boundary);
62810
+ pending3 = pending3.slice(boundary + 2);
62542
62811
  const data = block.split("\n").filter((row) => row.startsWith("data:")).map((row) => row.slice(5).trimStart()).join("\n");
62543
62812
  if (!data) continue;
62544
62813
  let event;
@@ -62835,7 +63104,7 @@ async function launch(options, reservation = createJob(options)) {
62835
63104
  stdio: ["pipe", "pipe", "pipe"],
62836
63105
  detached: process.platform !== "win32"
62837
63106
  });
62838
- let pending2 = "", stderr = "", cancelled = false;
63107
+ let pending3 = "", stderr = "", cancelled = false;
62839
63108
  let refused2;
62840
63109
  const watchdog = new LoopWatchdog();
62841
63110
  const kill = () => {
@@ -62858,11 +63127,11 @@ async function launch(options, reservation = createJob(options)) {
62858
63127
  };
62859
63128
  const events = (chunk) => {
62860
63129
  fs44.writeSync(out, typeof chunk === "string" ? chunk : chunk.toString("utf8"));
62861
- pending2 += chunk.toString();
63130
+ pending3 += chunk.toString();
62862
63131
  let newline;
62863
- while ((newline = pending2.indexOf("\n")) >= 0) {
62864
- const line = pending2.slice(0, newline);
62865
- pending2 = pending2.slice(newline + 1);
63132
+ while ((newline = pending3.indexOf("\n")) >= 0) {
63133
+ const line = pending3.slice(0, newline);
63134
+ pending3 = pending3.slice(newline + 1);
62866
63135
  try {
62867
63136
  const event = JSON.parse(line);
62868
63137
  watchdog.observe(event);
@@ -62871,7 +63140,7 @@ async function launch(options, reservation = createJob(options)) {
62871
63140
  } catch {
62872
63141
  }
62873
63142
  }
62874
- if (pending2.length > 1048576) pending2 = "";
63143
+ if (pending3.length > 1048576) pending3 = "";
62875
63144
  };
62876
63145
  if (!adapter.drive) child.stdout?.on("data", events);
62877
63146
  child.stderr?.on("data", (chunk) => {
@@ -63023,8 +63292,8 @@ var init_fanout_messages = __esm({
63023
63292
  const job = await this.selected(data.target, data.child);
63024
63293
  const directory = await this.messageDirectory(job);
63025
63294
  const message = { id: randomUUID27(), text: data.text, status: "queued", createdAt: (/* @__PURE__ */ new Date()).toISOString() };
63026
- const pending2 = (await this.records(job)).filter((row) => row.message.status === "queued");
63027
- if (pending2.length >= 32) throw new BridgeError(429, "This worker already has 32 queued messages.");
63295
+ const pending3 = (await this.records(job)).filter((row) => row.message.status === "queued");
63296
+ if (pending3.length >= 32) throw new BridgeError(429, "This worker already has 32 queued messages.");
63028
63297
  const file4 = path115.join(directory, `${message.createdAt.replace(/[:.]/g, "-")}-${message.id}.queued.json`);
63029
63298
  await atomic(file4, JSON.stringify(message));
63030
63299
  await this.drain(job);
@@ -63091,7 +63360,7 @@ var init_fanout_messages = __esm({
63091
63360
  return;
63092
63361
  }
63093
63362
  let launched = false;
63094
- let pending2;
63363
+ let pending3;
63095
63364
  let started;
63096
63365
  try {
63097
63366
  const fresh2 = (await this.jobs()).find((candidate) => candidate.directory === job.directory);
@@ -63099,7 +63368,7 @@ var init_fanout_messages = __esm({
63099
63368
  if (!fresh2.manifest.session || !["codex", "opencode", "claude"].includes(fresh2.manifest.provider)) return;
63100
63369
  const next = (await this.records(fresh2)).find((row) => row.message.status === "queued");
63101
63370
  if (!next) return;
63102
- pending2 = next;
63371
+ pending3 = next;
63103
63372
  if (!(await lstat32(fresh2.manifest.worktree)).isDirectory()) throw new BridgeError(409, "The worker's original worktree is unavailable.");
63104
63373
  for (const name of [fresh2.manifest.eventLog, "events.jsonl", "stderr.log", "final.txt", "exit.txt", "blocked.json", "prompt.txt"]) {
63105
63374
  const info = await lstat32(path115.join(fresh2.directory, name)).catch(() => void 0);
@@ -63121,7 +63390,7 @@ var init_fanout_messages = __esm({
63121
63390
  const message = { ...next.message, status: "running" };
63122
63391
  await atomic(next.file, JSON.stringify(message));
63123
63392
  await rename8(next.file, sentFile);
63124
- pending2 = { file: sentFile, message };
63393
+ pending3 = { file: sentFile, message };
63125
63394
  const now = (/* @__PURE__ */ new Date()).toISOString();
63126
63395
  const manifest = {
63127
63396
  ...fresh2.manifest,
@@ -63164,9 +63433,9 @@ var init_fanout_messages = __esm({
63164
63433
  }).catch(() => {
63165
63434
  });
63166
63435
  } catch (error62) {
63167
- if (!pending2) throw error62;
63168
- await atomic(pending2.file, JSON.stringify({ ...pending2.message, status: "failed" }));
63169
- if (pending2.file.endsWith(".queued.json")) await rename8(pending2.file, pending2.file.replace(/\.queued\.json$/, ".sent.json"));
63436
+ if (!pending3) throw error62;
63437
+ await atomic(pending3.file, JSON.stringify({ ...pending3.message, status: "failed" }));
63438
+ if (pending3.file.endsWith(".queued.json")) await rename8(pending3.file, pending3.file.replace(/\.queued\.json$/, ".sent.json"));
63170
63439
  if (started) await atomic(path115.join(job.directory, "manifest.json"), JSON.stringify({
63171
63440
  ...started,
63172
63441
  status: "failed",
@@ -63292,17 +63561,17 @@ function alignmentOf(raw) {
63292
63561
  }
63293
63562
  async function* timedLines(body2) {
63294
63563
  const decoder = new TextDecoder();
63295
- let pending2 = "";
63564
+ let pending3 = "";
63296
63565
  for await (const bytes of body2) {
63297
- pending2 += decoder.decode(bytes, { stream: true });
63298
- const lines = pending2.split("\n");
63299
- pending2 = lines.pop();
63566
+ pending3 += decoder.decode(bytes, { stream: true });
63567
+ const lines = pending3.split("\n");
63568
+ pending3 = lines.pop();
63300
63569
  for (const line of lines) {
63301
63570
  const out2 = timedLine(line);
63302
63571
  if (out2) yield out2;
63303
63572
  }
63304
63573
  }
63305
- const out = timedLine(pending2 + decoder.decode());
63574
+ const out = timedLine(pending3 + decoder.decode());
63306
63575
  if (out) yield out;
63307
63576
  }
63308
63577
  function timedLine(line) {
@@ -63856,7 +64125,7 @@ function relayTranscription(client, query, options = {}) {
63856
64125
  }
63857
64126
  const origin = options.origin ?? (await resolveSpeechRegion()).origin;
63858
64127
  const upstream = connect5(transcribeURL(query, origin), key4);
63859
- let pending2 = [], pendingBytes = 0, closed = false;
64128
+ let pending3 = [], pendingBytes = 0, closed = false;
63860
64129
  const finish = (code = 1e3, reason2 = "") => {
63861
64130
  if (closed) return;
63862
64131
  closed = true;
@@ -63897,13 +64166,13 @@ function relayTranscription(client, query, options = {}) {
63897
64166
  finish(1011);
63898
64167
  return;
63899
64168
  }
63900
- pending2.push(data);
64169
+ pending3.push(data);
63901
64170
  });
63902
64171
  client.on("close", () => finish());
63903
64172
  client.on("error", () => finish());
63904
64173
  upstream.on("open", () => {
63905
- for (const audio of pending2) upstream.send(chunk(audio));
63906
- pending2 = [];
64174
+ for (const audio of pending3) upstream.send(chunk(audio));
64175
+ pending3 = [];
63907
64176
  pendingBytes = 0;
63908
64177
  if (!closed) tell({ type: "ready" });
63909
64178
  });
@@ -64734,7 +65003,7 @@ function asyncQuestionReply(id2, questions, answers) {
64734
65003
  }
64735
65004
  async function pendingAsyncQuestions(file4, targetID) {
64736
65005
  return withTranscriptIndex(file4, async (handle, index2) => {
64737
- const replies = [], replied = /* @__PURE__ */ new Set(), acknowledged = /* @__PURE__ */ new Set(), resolved = /* @__PURE__ */ new Set(), seen = /* @__PURE__ */ new Set(), pending2 = [];
65006
+ const replies = [], replied = /* @__PURE__ */ new Set(), acknowledged = /* @__PURE__ */ new Set(), resolved = /* @__PURE__ */ new Set(), seen = /* @__PURE__ */ new Set(), pending3 = [];
64738
65007
  let bytes = 0;
64739
65008
  for await (const row of index2.rows(handle, index2.lines, Math.max(0, index2.lines - 1e4))) {
64740
65009
  if (!row.bytes || (bytes += row.bytes.length) > 8388608) throw new BridgeError(413, "The pending question history is too large to verify.");
@@ -64765,20 +65034,20 @@ async function pendingAsyncQuestions(file4, targetID) {
64765
65034
  if (!id2 || !acknowledged.has(id2)) continue;
64766
65035
  const questions = asyncQuestion(raw, id2);
64767
65036
  if (questions && !seen.has(id2) && !replied.has(id2) && !replies.some((reply) => answersQuestions(reply, questions))) {
64768
- pending2.push({ id: id2, questions });
64769
- if (pending2.length >= 64) throw new BridgeError(413, "Too many pending questions to verify.");
65037
+ pending3.push({ id: id2, questions });
65038
+ if (pending3.length >= 64) throw new BridgeError(413, "Too many pending questions to verify.");
64770
65039
  }
64771
65040
  if (questions) seen.add(id2);
64772
- if (targetID && questions && id2 === targetID) return pending2.filter((p2) => p2.id === targetID);
65041
+ if (targetID && questions && id2 === targetID) return pending3.filter((p2) => p2.id === targetID);
64773
65042
  }
64774
65043
  if (index2.lines > 1e4) throw new BridgeError(413, "The pending question history is too large to verify.");
64775
- return pending2.reverse();
65044
+ return pending3.reverse();
64776
65045
  });
64777
65046
  }
64778
65047
  async function pendingAsyncQuestion(file4, id2) {
64779
- const pending2 = (await pendingAsyncQuestions(file4, id2)).find((p) => p.id === id2);
64780
- if (!pending2) throw new BridgeError(409, "This question is no longer pending. Refresh the conversation.");
64781
- return pending2.questions;
65048
+ const pending3 = (await pendingAsyncQuestions(file4, id2)).find((p) => p.id === id2);
65049
+ if (!pending3) throw new BridgeError(409, "This question is no longer pending. Refresh the conversation.");
65050
+ return pending3.questions;
64782
65051
  }
64783
65052
  async function answerAttachments(session, data) {
64784
65053
  const requested = external_exports.array(external_exports.string().max(4096)).max(8).optional().parse(data.attachments) ?? [];
@@ -64918,19 +65187,19 @@ ${attachedFiles(paths)}` : answer2;
64918
65187
  if (Date.now() - (this.failedSnapshots.get(target2.session) ?? 0) < 5e3) throw new BridgeError(503, "Pending question history is unavailable.");
64919
65188
  const file4 = await transcriptPath("codex", target2.session);
64920
65189
  const cached3 = this.snapshots.get(target2.session);
64921
- let pending2 = cached3?.pending;
65190
+ let pending3 = cached3?.pending;
64922
65191
  if (!cached3 || Date.now() - cached3.at > 1e3) {
64923
65192
  const metadata = await stat26(file4), stamp2 = `${metadata.ino}:${metadata.size}:${metadata.mtimeMs}`;
64924
- pending2 = cached3?.stamp === stamp2 ? cached3.pending : await pendingAsyncQuestions(file4).catch((error62) => {
65193
+ pending3 = cached3?.stamp === stamp2 ? cached3.pending : await pendingAsyncQuestions(file4).catch((error62) => {
64925
65194
  if (this.failedSnapshots.size >= 64) this.failedSnapshots.delete(this.failedSnapshots.keys().next().value);
64926
65195
  this.failedSnapshots.set(target2.session, Date.now());
64927
65196
  throw error62;
64928
65197
  });
64929
65198
  this.failedSnapshots.delete(target2.session);
64930
65199
  if (this.snapshots.size >= 64) this.snapshots.delete(this.snapshots.keys().next().value);
64931
- this.snapshots.set(target2.session, { at: Date.now(), stamp: stamp2, pending: pending2 });
65200
+ this.snapshots.set(target2.session, { at: Date.now(), stamp: stamp2, pending: pending3 });
64932
65201
  }
64933
- return Promise.all((pending2 ?? []).map(async (p) => {
65202
+ return Promise.all((pending3 ?? []).map(async (p) => {
64934
65203
  const key4 = createHash30("sha256").update(JSON.stringify([target2.source, target2.session, p.id])).digest("hex");
64935
65204
  const submitted = await readFile49(path119.join(bridgeRoot(), "question-replies", key4), "utf8").then((value2) => value2 === "submitted").catch(() => false);
64936
65205
  return { toolUseId: p.id, isAsync: true, submitted, questions: asPrompt(p.questions) };
@@ -66049,6 +66318,16 @@ var init_canary = __esm({
66049
66318
  }
66050
66319
  });
66051
66320
 
66321
+ // src/bridge/request-origin.ts
66322
+ function ownerRequest(request10, data) {
66323
+ return request10.headers?.["x-phren-origin"] === void 0 && data.origin === void 0;
66324
+ }
66325
+ var init_request_origin = __esm({
66326
+ "src/bridge/request-origin.ts"() {
66327
+ "use strict";
66328
+ }
66329
+ });
66330
+
66052
66331
  // src/bridge/launch-worktree.ts
66053
66332
  import { execFile as execFile28 } from "node:child_process";
66054
66333
  import { mkdir as mkdir31, realpath as realpath20, rm as rm16, stat as stat28 } from "node:fs/promises";
@@ -67768,9 +68047,9 @@ async function candidateRepos(activity, env = process.env) {
67768
68047
  return root;
67769
68048
  };
67770
68049
  const activityDirectory = (event) => typeof event.directory === "string" && path130.isAbsolute(event.directory) ? event.directory : void 0;
67771
- const pending2 = [...new Set(activity.map(activityDirectory).filter((d) => !!d))];
67772
- await Promise.all(Array.from({ length: Math.min(8, pending2.length) }, async () => {
67773
- for (let directory = pending2.shift(); directory !== void 0; directory = pending2.shift()) await rootOf(directory);
68050
+ const pending3 = [...new Set(activity.map(activityDirectory).filter((d) => !!d))];
68051
+ await Promise.all(Array.from({ length: Math.min(8, pending3.length) }, async () => {
68052
+ for (let directory = pending3.shift(); directory !== void 0; directory = pending3.shift()) await rootOf(directory);
67774
68053
  }));
67775
68054
  for (const event of [...activity].reverse()) {
67776
68055
  const directory = activityDirectory(event);
@@ -68215,7 +68494,7 @@ async function refreshCitationFreshness(citations, opts) {
68215
68494
  for (const group of groups.values()) {
68216
68495
  const items = [...group.values()];
68217
68496
  for (let i = 0; i < items.length; i += 100) {
68218
- const batch = items.slice(i, i + 100).filter((item) => !pending.has(`${file4}:${item.key}`));
68497
+ const batch = items.slice(i, i + 100).filter((item) => !pending2.has(`${file4}:${item.key}`));
68219
68498
  const remaining = deadline - Date.now();
68220
68499
  if (remaining <= 0 || opts.signal?.aborted) {
68221
68500
  for (const item of items.slice(i)) if (!isChanged(entries2[item.key])) entries2[item.key] = { state: "unknown", checkedAt: (/* @__PURE__ */ new Date()).toISOString() };
@@ -68223,11 +68502,11 @@ async function refreshCitationFreshness(citations, opts) {
68223
68502
  }
68224
68503
  if (!batch.length) continue;
68225
68504
  const work = request9(batch, opts, remaining, entries2).then(() => save2(file4, entries2));
68226
- for (const item of batch) pending.set(`${file4}:${item.key}`, work);
68505
+ for (const item of batch) pending2.set(`${file4}:${item.key}`, work);
68227
68506
  try {
68228
68507
  await work;
68229
68508
  } finally {
68230
- for (const item of batch) pending.delete(`${file4}:${item.key}`);
68509
+ for (const item of batch) pending2.delete(`${file4}:${item.key}`);
68231
68510
  }
68232
68511
  }
68233
68512
  }
@@ -68241,7 +68520,7 @@ async function refreshCitationFreshness(citations, opts) {
68241
68520
  }
68242
68521
  return result;
68243
68522
  }
68244
- var MINUTE, GIT_TIMEOUT_MS, RETENTION, RESOLUTION_TTL, cacheMemo, isChanged, resolutionKey, pending, off;
68523
+ var MINUTE, GIT_TIMEOUT_MS, RETENTION, RESOLUTION_TTL, cacheMemo, isChanged, resolutionKey, pending2, off;
68245
68524
  var init_citation_freshness = __esm({
68246
68525
  "src/content/citation-freshness.ts"() {
68247
68526
  "use strict";
@@ -68255,7 +68534,7 @@ var init_citation_freshness = __esm({
68255
68534
  cacheMemo = /* @__PURE__ */ new Map();
68256
68535
  isChanged = (entry2) => !!entry2 && "state" in entry2 && entry2.state === "changed";
68257
68536
  resolutionKey = (citation, opts) => `repo:${citation.repo ?? ""}\0${citation.projectRemote ?? opts.projectRemote ?? ""}`;
68258
- pending = /* @__PURE__ */ new Map();
68537
+ pending2 = /* @__PURE__ */ new Map();
68259
68538
  off = () => process.env.PHREN_CITATION_FRESHNESS?.trim().toLowerCase() === "off";
68260
68539
  }
68261
68540
  });
@@ -74971,7 +75250,8 @@ function createRouteHandler(ctx) {
74971
75250
  } : void 0);
74972
75251
  } else if (url2.pathname === "/v1/sessions/move") {
74973
75252
  if (!ctx.mover) throw new BridgeError(503, "This Hook cannot move sessions.");
74974
- result = { ok: true, move: await ctx.mover.start(data) };
75253
+ const { origin: _origin, ...input2 } = data;
75254
+ result = { ok: true, move: await ctx.mover.start(input2, { owner: ownerRequest(request10, data) }) };
74975
75255
  } else if (url2.pathname === "/v1/sessions/rename") {
74976
75256
  result = await renameSession(selectedServer(url2), data);
74977
75257
  } else if (url2.pathname === "/v1/jobs/cleanup") {
@@ -75034,8 +75314,10 @@ function createRouteHandler(ctx) {
75034
75314
  if (data.origin !== void 0) throw new BridgeError(403, "Only the owner changes the release authority policy, from the phone or `phren authority` in their own terminal.");
75035
75315
  result = url2.pathname === "/v1/authority" ? { ok: true, authority: await setProjectAuthority(data, "phone") } : { ok: true, confirmation: await confirmAuthority(data, "phone") };
75036
75316
  } else if (url2.pathname === "/v1/conductor/make") {
75317
+ if (!ownerRequest(request10, data)) throw new BridgeError(403, "Only the owner can change the conductor.");
75037
75318
  result = await launches.run(async () => makeConductor(selectedServer(url2), data));
75038
75319
  } else if (url2.pathname === "/v1/conductor/stop") {
75320
+ if (!ownerRequest(request10, data)) throw new BridgeError(403, "Only the owner can change the conductor.");
75039
75321
  result = await launches.run(async () => stopConductor(data));
75040
75322
  } else if (url2.pathname === "/v1/sets/name") {
75041
75323
  result = await nameSet(data);
@@ -75079,6 +75361,7 @@ function createRouteHandler(ctx) {
75079
75361
  } else {
75080
75362
  if (url2.pathname === "/v1/workspaces/launch") {
75081
75363
  result = await launches.run(async () => {
75364
+ if (data.role === "conductor" && !ownerRequest(request10, data)) throw new BridgeError(403, "Only the owner can change the conductor.");
75082
75365
  if (data.role === "conductor" && !modules.has("conductor")) throw new BridgeError(404, disabledHint("conductor"));
75083
75366
  if (data.agentFolder === true && (data.role === "conductor" || data.project !== void 0 || data.cwd !== void 0 && data.cwd !== "" || data.worktree != null)) {
75084
75367
  throw new BridgeError(400, "An agent folder is for a projectless agent without cwd or worktree.");
@@ -75127,6 +75410,7 @@ var CHILD_ACTIVITY_CACHE_MS, OVERVIEW_ENRICH_BUDGET_MS, childActivityCache, capa
75127
75410
  var init_server_routes = __esm({
75128
75411
  "src/bridge/server-routes.ts"() {
75129
75412
  "use strict";
75413
+ init_request_origin();
75130
75414
  init_session_move();
75131
75415
  init_task_routes();
75132
75416
  init_owner_inbox_view();
@@ -75246,6 +75530,7 @@ var init_server_routes = __esm({
75246
75530
  launchPermissionMode: true,
75247
75531
  sessionMove: true,
75248
75532
  moveNewChat: true,
75533
+ moveConductor: true,
75249
75534
  projectMemory: true,
75250
75535
  fileWrite: true,
75251
75536
  fileSearch: true,
@@ -75729,12 +76014,12 @@ function transcriptStreams(ctx) {
75729
76014
  let awaitingTranscript = false, lastTranscriptLookup = 0;
75730
76015
  let initialPane;
75731
76016
  let busyAt = 0;
75732
- const pending2 = [];
76017
+ const pending3 = [];
75733
76018
  const stop = () => {
75734
76019
  abort.abort();
75735
76020
  clearInterval(timer);
75736
76021
  unwatch?.();
75737
- pending2.length = 0;
76022
+ pending3.length = 0;
75738
76023
  };
75739
76024
  client.once("close", stop);
75740
76025
  client.once("error", stop);
@@ -75762,7 +76047,7 @@ function transcriptStreams(ctx) {
75762
76047
  if (busy || !ready || abort.signal.aborted) return;
75763
76048
  busy = true;
75764
76049
  try {
75765
- if (first || pending2.length === 0) {
76050
+ if (first || pending3.length === 0) {
75766
76051
  const pane = first ? initialPane : await validateTarget(target2, false, false, SNAPSHOT_SHARE_MS);
75767
76052
  if (awaitingTranscript) await findTranscript();
75768
76053
  if (awaitingTranscript) {
@@ -75853,8 +76138,8 @@ function transcriptStreams(ctx) {
75853
76138
  }
75854
76139
  first = false;
75855
76140
  }
75856
- while (pending2.length && reader && !abort.signal.aborted) {
75857
- const before = pending2.shift();
76141
+ while (pending3.length && reader && !abort.signal.aborted) {
76142
+ const before = pending3.shift();
75858
76143
  await validateTarget(target2, false, false, SNAPSHOT_SHARE_MS);
75859
76144
  const page = await reader.read(before, abort.signal);
75860
76145
  send(client, { ...page, type: "older", ...conversation });
@@ -75866,7 +76151,7 @@ function transcriptStreams(ctx) {
75866
76151
  client.close(1011, reason2);
75867
76152
  } finally {
75868
76153
  busy = false;
75869
- if (pending2.length) void tick();
76154
+ if (pending3.length) void tick();
75870
76155
  }
75871
76156
  };
75872
76157
  client.on("message", (bytes) => {
@@ -75874,8 +76159,8 @@ function transcriptStreams(ctx) {
75874
76159
  const message = object2(JSON.parse(bytes.toString()));
75875
76160
  if (message.type !== "older" || url2.pathname !== "/v1/transcripts" || abort.signal.aborted) return;
75876
76161
  const before = external_exports.number().int().positive().parse(message.beforeLine);
75877
- if (pending2.length >= 8) throw new Error("History queue is full");
75878
- if (!pending2.includes(before)) pending2.push(before);
76162
+ if (pending3.length >= 8) throw new Error("History queue is full");
76163
+ if (!pending3.includes(before)) pending3.push(before);
75879
76164
  void tick();
75880
76165
  } catch {
75881
76166
  stop();
@@ -76966,7 +77251,7 @@ async function main() {
76966
77251
  return askpass2(args[1]);
76967
77252
  }
76968
77253
  const { runBridge: runBridge2 } = await Promise.resolve().then(() => (init_command(), command_exports));
76969
- return runBridge2(args, "0.3.50");
77254
+ return runBridge2(args, "0.3.51");
76970
77255
  }
76971
77256
  main().then((code) => {
76972
77257
  process.exitCode = code;