@cydm/pie 4.4.2 → 4.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/builtin/extensions/ask-user/index.js +6 -6
  2. package/dist/builtin/extensions/changelog/index.js +1 -1
  3. package/dist/builtin/extensions/cron/index.js +55 -7
  4. package/dist/builtin/extensions/document-attachments/index.js +1 -1
  5. package/dist/builtin/extensions/herdr-agent-state/index.js +1 -1
  6. package/dist/builtin/extensions/im-forward/README.md +3 -1
  7. package/dist/builtin/extensions/im-forward/index.js +98 -41
  8. package/dist/builtin/extensions/init/index.js +1 -1
  9. package/dist/builtin/extensions/mcp-adapter/index.js +2 -2
  10. package/dist/builtin/extensions/memory/index.js +9 -11
  11. package/dist/builtin/extensions/pie-ipc/index.js +45 -18
  12. package/dist/builtin/extensions/pie-proc/index.js +18 -12
  13. package/dist/builtin/extensions/plan-mode/index.js +6 -6
  14. package/dist/builtin/extensions/subagent/index.js +9 -11
  15. package/dist/builtin/extensions/todo/index.js +6 -6
  16. package/dist/builtin/skills/chrome-devtools-axi/SKILL.md +24 -1
  17. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-bridge.js +86 -21
  18. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-cli.js +6 -1
  19. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-runtime.js +1 -1
  20. package/dist/builtin/skills/chrome-devtools-axi/{cli-CHC7XYFU.js → cli-NLPMVDGG.js} +32 -4
  21. package/dist/builtin/skills/computer-use-axi/computer-use-axi-broker.js +220 -22
  22. package/dist/chunks/{auth-storage-RABPRJ6T.js → auth-storage-C3FZMT7J.js} +3 -3
  23. package/dist/chunks/{chunk-R7VO46EK.js → chunk-3W3SXVPB.js} +5 -4
  24. package/dist/chunks/{chunk-IPLMGAML.js → chunk-5KI4Y4LA.js} +1 -1
  25. package/dist/chunks/{chunk-YNTIOWCD.js → chunk-BLDI2GRF.js} +5 -5
  26. package/dist/chunks/{chunk-UCKOXAME.js → chunk-CBDQJMUI.js} +9 -44
  27. package/dist/chunks/chunk-CGSFBWOM.js +100 -0
  28. package/dist/chunks/{chunk-OFLKAWI4.js → chunk-JMKLTTZQ.js} +89 -100
  29. package/dist/chunks/{chunk-7LTQLJJF.js → chunk-LAJXWOKS.js} +15 -10
  30. package/dist/chunks/{chunk-RZGYXAJU.js → chunk-LZQXQOPJ.js} +1 -12
  31. package/dist/chunks/{chunk-EQOI6RZV.js → chunk-NHV2CALB.js} +3 -5
  32. package/dist/chunks/{chunk-OV7SLSHR.js → chunk-SW2E33UL.js} +2 -4
  33. package/dist/chunks/{chunk-BPSCGGVF.js → chunk-XXGYUYXI.js} +1 -1
  34. package/dist/chunks/{chunk-XO3NM7BB.js → chunk-Y3I2UV5Y.js} +3 -3
  35. package/dist/chunks/{chunk-IZDNZW3S.js → chunk-Z2FKA2ZH.js} +8 -8
  36. package/dist/chunks/chunk-ZPJ3BNQB.js +126 -0
  37. package/dist/chunks/{config-HF2PDLN5.js → config-4EOI5NOU.js} +2 -4
  38. package/dist/chunks/{manager-cli-BYCF4RKN.js → manager-cli-WEHNUV5T.js} +3 -5
  39. package/dist/chunks/{model-registry-7FNIUYPF.js → model-registry-3XAHXXTA.js} +5 -5
  40. package/dist/chunks/{src-OVWRBWKU.js → src-B44QWSGM.js} +4 -4
  41. package/dist/chunks/{src-A5YI46OD.js → src-CLE5ILN4.js} +6 -6
  42. package/dist/chunks/{src-OA3TP6DS.js → src-EGXFJ3WA.js} +5 -5
  43. package/dist/chunks/{src-TF2RAGRU.js → src-Q7LU27C2.js} +3 -3
  44. package/dist/chunks/{test-stream-7YZDGBPO.js → test-stream-OR3EJBNF.js} +3 -3
  45. package/dist/cli.js +128 -132
  46. package/package.json +3 -3
  47. package/dist/chunks/chunk-7KLWHWZD.js +0 -164
@@ -1,12 +1,12 @@
1
1
  import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
2
  import {
3
3
  createAskUserCapability
4
- } from "../../../chunks/chunk-YNTIOWCD.js";
5
- import "../../../chunks/chunk-XO3NM7BB.js";
6
- import "../../../chunks/chunk-IPLMGAML.js";
7
- import "../../../chunks/chunk-R7VO46EK.js";
8
- import "../../../chunks/chunk-BPSCGGVF.js";
9
- import "../../../chunks/chunk-RZGYXAJU.js";
4
+ } from "../../../chunks/chunk-BLDI2GRF.js";
5
+ import "../../../chunks/chunk-Y3I2UV5Y.js";
6
+ import "../../../chunks/chunk-5KI4Y4LA.js";
7
+ import "../../../chunks/chunk-3W3SXVPB.js";
8
+ import "../../../chunks/chunk-XXGYUYXI.js";
9
+ import "../../../chunks/chunk-LZQXQOPJ.js";
10
10
 
11
11
  // builtin/extensions/ask-user/index.ts
12
12
  function askUserExtension(ctx) {
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
- import "../../../chunks/chunk-RZGYXAJU.js";
2
+ import "../../../chunks/chunk-LZQXQOPJ.js";
3
3
 
4
4
  // builtin/extensions/changelog/index.ts
5
5
  import * as fs from "node:fs";
@@ -1,8 +1,8 @@
1
1
  import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
2
  import {
3
3
  Type
4
- } from "../../../chunks/chunk-BPSCGGVF.js";
5
- import "../../../chunks/chunk-RZGYXAJU.js";
4
+ } from "../../../chunks/chunk-XXGYUYXI.js";
5
+ import "../../../chunks/chunk-LZQXQOPJ.js";
6
6
 
7
7
  // builtin/extensions/cron/index.ts
8
8
  import * as path4 from "node:path";
@@ -311,6 +311,8 @@ var Store = class {
311
311
  validateState(s) {
312
312
  if (s.version !== 1 || !Array.isArray(s.jobs) || !s.owners || typeof s.owners !== "object") throw new Error("invalid cron state; manual recovery required");
313
313
  if (Array.isArray(s.owners) || s.jobs.length > 100 || Object.keys(s.owners).length > 1e3) throw new Error("cron state exceeds record limit");
314
+ if (s.managedEnabled !== void 0 && (!s.managedEnabled || typeof s.managedEnabled !== "object" || Array.isArray(s.managedEnabled) || Object.keys(s.managedEnabled).length > 100 || Object.entries(s.managedEnabled).some(([key, value]) => !this.validManagedKey(key) || typeof value !== "boolean")))
315
+ throw new Error("invalid managed schedule intent; manual recovery required");
314
316
  const ids = /* @__PURE__ */ new Set();
315
317
  for (const j of s.jobs) {
316
318
  if (!j || typeof j.id !== "string" || ids.has(j.id) || typeof j.sessionId !== "string" || !j.sessionId || j.sessionId.length > 256 || typeof j.cwd !== "string" || !path.isAbsolute(j.cwd) || typeof j.prompt !== "string" || !j.prompt.trim() || j.prompt.length > 16e3 || typeof j.enabled !== "boolean" || !["ready", "running", "blocked"].includes(j.state) || j.remaining !== void 0 && (!Number.isSafeInteger(j.remaining) || j.remaining < 0 || j.remaining > 1e3) || j.next !== null && !Number.isSafeInteger(j.next) || j.authorization !== void 0 && !["dialog", "yolo", "unattended"].includes(j.authorization) || j.retriedOnce !== void 0 && typeof j.retriedOnce !== "boolean" || j.noticedError !== void 0 && typeof j.noticedError !== "string") throw new Error("invalid cron job; manual recovery required");
@@ -393,6 +395,37 @@ var Store = class {
393
395
  * replaced: removing its reservation would let another execution start
394
396
  * while the original worker is still alive (single-outstanding invariant). */
395
397
  addProcess(command, managedBy, cwd, schedule, now = Date.now(), opts) {
398
+ return this.registerProcess(command, managedBy, cwd, schedule, now, opts);
399
+ }
400
+ /** Default registration never replaces an existing record, including paused/blocked. */
401
+ ensureProcess(command, managedBy, cwd, schedule, now = Date.now()) {
402
+ return this.registerProcess(command, managedBy, cwd, schedule, now, { onlyIfAbsent: true });
403
+ }
404
+ /** Opt-out and removal share the state writer mutex with on/default registration. */
405
+ disableProcess(managedBy) {
406
+ this.disabledMarker(managedBy);
407
+ const removed = this.transaction((s) => {
408
+ const existing = s.jobs.find((j) => j.sessionId === PROCESS_SESSION_ID && parseProcessCommand(j)?.managedBy === managedBy);
409
+ if (existing?.state === "running") throw new Error("managed job is currently running; try again after it finishes");
410
+ s.managedEnabled = { ...s.managedEnabled, [managedBy]: false };
411
+ s.jobs = s.jobs.filter((j) => j !== existing);
412
+ return !!existing;
413
+ });
414
+ try {
415
+ fs.writeFileSync(this.disabledMarker(managedBy), (/* @__PURE__ */ new Date()).toISOString(), { mode: 384 });
416
+ } catch {
417
+ }
418
+ return removed;
419
+ }
420
+ validManagedKey(key) {
421
+ return /^[a-zA-Z0-9_-]{1,64}$/.test(key) && !["__proto__", "constructor", "prototype"].includes(key);
422
+ }
423
+ disabledMarker(managedBy) {
424
+ if (!this.validManagedKey(managedBy)) throw new Error("invalid managed marker identity");
425
+ return path.join(this.dir, `${managedBy}-disabled`);
426
+ }
427
+ registerProcess(command, managedBy, cwd, schedule, now, opts) {
428
+ this.disabledMarker(managedBy);
396
429
  const validated = validateSchedule(schedule), next = nextTime(validated, now);
397
430
  if (next === null) throw new Error("at must be in the future");
398
431
  const count = validated.count;
@@ -411,8 +444,10 @@ var Store = class {
411
444
  if (command.some((part) => part.includes("\0"))) throw new Error("process command arguments must not contain NUL bytes");
412
445
  if (probe.prompt.length > 16e3) throw new Error("process command exceeds the 16000-character job budget");
413
446
  const job = { ...probe };
414
- return this.transaction((s) => {
447
+ const registered = this.transaction((s) => {
415
448
  const existing = s.jobs.find((j) => j.sessionId === PROCESS_SESSION_ID && parseProcessCommand(j)?.managedBy === managedBy);
449
+ const intent = s.managedEnabled && Object.hasOwn(s.managedEnabled, managedBy) ? s.managedEnabled[managedBy] : void 0;
450
+ if (opts?.onlyIfAbsent && (existing || intent === false || intent === void 0 && fs.existsSync(this.disabledMarker(managedBy)))) return void 0;
416
451
  if (existing?.state === "running") throw new Error("managed job is currently running; try again after it finishes");
417
452
  if (!opts?.forceReplace) {
418
453
  if (existing?.state === "blocked") throw new Error("managed job is blocked; resume or recover it explicitly instead of re-registering");
@@ -423,8 +458,16 @@ var Store = class {
423
458
  s.jobs = s.jobs.filter((j) => j !== existing);
424
459
  if (s.jobs.length >= 100) throw new Error("maximum 100 jobs");
425
460
  s.jobs.push(job);
461
+ if (opts?.forceReplace) s.managedEnabled = { ...s.managedEnabled, [managedBy]: true };
426
462
  return job;
427
463
  });
464
+ if (registered && opts?.forceReplace) {
465
+ try {
466
+ fs.rmSync(this.disabledMarker(managedBy), { force: true });
467
+ } catch {
468
+ }
469
+ }
470
+ return registered;
428
471
  }
429
472
  /** Find the managed process job for a manager identity, if present. */
430
473
  findProcess(managedBy) {
@@ -855,13 +898,12 @@ var Runtime = class {
855
898
  try {
856
899
  const existing = this.store.findProcess("memory");
857
900
  if (existing) return;
858
- if (fs3.existsSync(path3.join(this.store.dir, "memory-disabled"))) return;
859
901
  const { managedMemoryCommand: managedMemoryCommand2, localTimeToCronUtc: localTimeToCronUtc2 } = await import("./index.js");
860
902
  const command = managedMemoryCommand2();
861
903
  const cronSpec = localTimeToCronUtc2("03:00");
862
904
  if ("error" in cronSpec) throw new Error(cronSpec.error);
863
- this.store.addProcess(command, "memory", process.cwd(), cronSpec);
864
- this.ctx.log("cron: registered the default daily memory distillation (03:00)");
905
+ if (this.store.ensureProcess(command, "memory", process.cwd(), cronSpec))
906
+ this.ctx.log("cron: registered the default daily memory distillation (03:00)");
865
907
  } catch (error) {
866
908
  const message = String(error instanceof Error ? error.message : error);
867
909
  if (/managed job is (blocked|paused|currently running)/.test(message)) return;
@@ -1429,7 +1471,13 @@ function localTimeToCronUtc(time) {
1429
1471
  function managedMemoryCommand() {
1430
1472
  const entry = process.argv[1] ? path4.resolve(process.argv[1]) : path4.join(configPath(), "..", "cli.js");
1431
1473
  const resolved = fs4.existsSync(entry) ? entry : path4.join(configPath(), "cli.js");
1432
- const loaderArgs = process.execArgv.filter((a) => a.startsWith("--import") || a.startsWith("--loader"));
1474
+ const loaderArgs = [];
1475
+ for (let i = 0; i < process.execArgv.length; i++) {
1476
+ const arg = process.execArgv[i];
1477
+ if (/^--(?:import|loader|experimental-loader)=/.test(arg)) loaderArgs.push(arg);
1478
+ else if (/^--(?:import|loader|experimental-loader)$/.test(arg) && i + 1 < process.execArgv.length)
1479
+ loaderArgs.push(arg, process.execArgv[++i]);
1480
+ }
1433
1481
  return [process.execPath, ...loaderArgs, resolved, "memory", "distill", "--worker", "--auto", "--memory-root", path4.join(configPath(), "memory")];
1434
1482
  }
1435
1483
  function cron(ctx) {
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
- import "../../../chunks/chunk-RZGYXAJU.js";
2
+ import "../../../chunks/chunk-LZQXQOPJ.js";
3
3
 
4
4
  // builtin/extensions/document-attachments/index.ts
5
5
  import * as fs from "node:fs";
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
- import "../../../chunks/chunk-RZGYXAJU.js";
2
+ import "../../../chunks/chunk-LZQXQOPJ.js";
3
3
 
4
4
  // builtin/extensions/herdr-agent-state/index.ts
5
5
  import { spawn } from "node:child_process";
@@ -22,7 +22,7 @@ otherwise it toggles the desired enabled flag. Replies/thread posts associated
22
22
  with this process's forwarded messages enter their originating live session.
23
23
  COLD-START note: replaced 11-08 by the user routing design — an UNANCHORED message (a true DM root: no explicit address, no replyTo, no threadId) binds to the UNATTENDED RESIDENT host (json-events --idle, the concierge) statelessly, for the resident's whole life; interactive/embedded hosts never claim unanchored messages. A message that REPLIED to something or sits in a THREAD whose attribution fails to resolve is NOT unanchored — it drops on every host (no ack reaction is the user-visible signal). A retry chain never re-binds across a session switch (released for redelivery instead).
24
24
 
25
- EXPLICIT ADDRESSING (`<session name>: body`) is exclusive: the address space is the set of session names advertised by LIVE local sessions in the pie-ipc discovery directory (`<PIE_IPC_CONFIG_DIR ?? agent dir>/run/ipc`), scanned per candidate message (no negative cache). A name owned by another live session is dropped here; a name advertised by two live sessions, or an address-shaped message while the book is unreadable, drops too (ambiguous → nobody acts). Without pie-ipc running, no foreign names are known, so exclusivity degrades to own-name-only — pie-ipc is the local session registry.
25
+ EXPLICIT ADDRESSING (`<session name>: body`) is exclusive: the address space is the set of session names advertised by LIVE local sessions in the pie-ipc discovery directory (`<PIE_IPC_CONFIG_DIR ?? agent dir>/run/ipc`), scanned per candidate message (no negative cache). The unique consumer forwards a foreign explicit address to its unique live session owner over IPC, before thread routing; non-consumer hosts do not re-dispatch it. Targets must advertise the same active IM app binding. A name advertised by two live sessions, or an address-shaped message while the book is unreadable, drops (ambiguous → nobody acts). Without pie-ipc running, no foreign names are known, so exclusivity degrades to own-name-only — pie-ipc is the local session registry.
26
26
 
27
27
  Feishu (Lark) is the only implemented platform. The wizard always shows a generic
28
28
  platform picker with implemented platforms and Cancel, before provider setup. See [Feishu setup and transport](providers/feishu/README.md).
@@ -81,6 +81,8 @@ lark-cli daemon automatically; the warning gives the operator the explicit
81
81
  `event stop --force` recovery command. Optional card/menu consumers respawn
82
82
  on bounded backoff, reset only at their ready marker; dead children are removed.
83
83
 
84
+ Only an explicitly identified manager advertising the same active IM app binding suppresses stand-in acquisition; ordinary unattended workers (including oneself) and managers on another app never do. Binding changes publish immediately through IPC discovery, not only at its heartbeat. Consumer ownership is generation-checked under a short directory mutex; heartbeat age is diagnostic, never permission to steal from a live PID. Provider shutdown must complete before release; see [ownership and upgrade rules](../../../../../docs/ownership-locks.md).
85
+
84
86
  On a machine where a resident holds the consumer slot, non-holder runtimes
85
87
  operate in dispatch mode: they never spawn a consumer and receive events over
86
88
  pie-ipc. For such runtimes the tag answers a delivery question, not a
@@ -20,6 +20,7 @@ import {
20
20
  readLiveConfig,
21
21
  readLiveEnabled,
22
22
  registerDispatchReceiver,
23
+ registerImBinding,
23
24
  registerTurnImDriver,
24
25
  resolveAddress,
25
26
  resolveConfig,
@@ -31,12 +32,13 @@ import {
31
32
  truncateMarkdown,
32
33
  tryClaimConsumer,
33
34
  writeConfig
34
- } from "../../../chunks/chunk-OFLKAWI4.js";
35
+ } from "../../../chunks/chunk-JMKLTTZQ.js";
35
36
  import {
36
37
  detectImageMime,
37
38
  readImageFormat
38
39
  } from "../../../chunks/chunk-F7EBZTZO.js";
39
- import "../../../chunks/chunk-RZGYXAJU.js";
40
+ import "../../../chunks/chunk-ZPJ3BNQB.js";
41
+ import "../../../chunks/chunk-LZQXQOPJ.js";
40
42
 
41
43
  // builtin/extensions/im-forward/runtime.ts
42
44
  import * as crypto from "node:crypto";
@@ -525,6 +527,34 @@ function findOwnerInstance(sessionId) {
525
527
  candidates.sort((a, b) => b.startedAt - a.startedAt);
526
528
  return candidates[0].file;
527
529
  }
530
+ function findNamedOwnerInstance(name, binding) {
531
+ let entries;
532
+ try {
533
+ entries = fs3.readdirSync(discoveryDir()).filter((entry) => entry.endsWith(".json"));
534
+ } catch {
535
+ return void 0;
536
+ }
537
+ if (entries.length > 256) return void 0;
538
+ const matches = [];
539
+ for (const entry of entries) {
540
+ try {
541
+ const peer = JSON.parse(fs3.readFileSync(path4.join(discoveryDir(), entry), "utf8"));
542
+ if (peer.sessionName?.trim() !== name || !pidAlive2(peer.pid)) continue;
543
+ matches.push(peer);
544
+ } catch {
545
+ return void 0;
546
+ }
547
+ }
548
+ if (matches.length !== 1) return void 0;
549
+ const owner = matches[0];
550
+ if (owner.imBinding !== binding || owner.protocol !== IPC_PROTOCOL_VERSION || !/^pie-[a-z0-9]{12}$/.test(owner.instanceId) || !entries.includes(`${owner.instanceId}.json`) || typeof owner.sessionId !== "string" || !owner.sessionId || !Number.isInteger(owner.port) || !owner.port || owner.port < 1 || owner.port > 65535 || typeof owner.secret !== "string") return void 0;
551
+ return owner;
552
+ }
553
+ async function dispatchEventToName(name, binding, eventText) {
554
+ const owner = findNamedOwnerInstance(name, binding);
555
+ if (!owner?.port || !owner.secret) return void 0;
556
+ return await deliverOnce(owner.port, owner.secret, eventText, owner.sessionId, owner.instanceId) ? owner.instanceId : void 0;
557
+ }
528
558
  var SYNTHETIC_SENDER = (() => {
529
559
  const hex = randomUUID2().replace(/-/g, "");
530
560
  return `pie-${hex.slice(0, 12)}`;
@@ -742,6 +772,26 @@ function ipcDiscoveryRoot2() {
742
772
  const configDir = process.platform === "win32" ? raw : pathResolve(raw === "~" ? home : raw.startsWith("~/") ? pathJoin(home, raw.slice(2)) : raw);
743
773
  return pathJoin(configDir, "run", "ipc");
744
774
  }
775
+ function liveManagerForBinding(binding) {
776
+ try {
777
+ for (const file of fs6.readdirSync(ipcDiscoveryRoot2())) {
778
+ if (!file.endsWith(".json")) continue;
779
+ try {
780
+ const peer = JSON.parse(fs6.readFileSync(pathJoin(ipcDiscoveryRoot2(), file), "utf8"));
781
+ if (peer.pid === process.pid || peer.isManager !== true || peer.imBinding !== binding || !Number.isInteger(peer.pid) || !peer.pid || peer.pid <= 0) continue;
782
+ try {
783
+ process.kill(peer.pid, 0);
784
+ return true;
785
+ } catch (error) {
786
+ if (error.code !== "ESRCH") return true;
787
+ }
788
+ } catch {
789
+ }
790
+ }
791
+ } catch {
792
+ }
793
+ return false;
794
+ }
745
795
  async function applyModelControl(peerRef, model) {
746
796
  const net2 = await import("node:net");
747
797
  let target;
@@ -749,7 +799,7 @@ async function applyModelControl(peerRef, model) {
749
799
  const dir = ipcDiscoveryRoot2();
750
800
  for (const file of fs6.readdirSync(dir).filter((f) => f.endsWith(".json"))) {
751
801
  const parsed = JSON.parse(fs6.readFileSync(join7(dir, file), "utf8"));
752
- if (!parsed.port || !parsed.secret || typeof parsed.pid !== "number" || !parsed.instanceId) continue;
802
+ if (!parsed.port || !parsed.secret || typeof parsed.pid !== "number" || !parsed.instanceId || typeof parsed.sessionId !== "string" || !parsed.sessionId) continue;
753
803
  const match = parsed.instanceId === peerRef || parsed.instanceId.startsWith(peerRef) || parsed.displayName === peerRef;
754
804
  if (!match) continue;
755
805
  try {
@@ -757,7 +807,7 @@ async function applyModelControl(peerRef, model) {
757
807
  } catch {
758
808
  continue;
759
809
  }
760
- target = { port: parsed.port, secret: parsed.secret, instanceId: parsed.instanceId };
810
+ target = { port: parsed.port, secret: parsed.secret, instanceId: parsed.instanceId, sessionId: parsed.sessionId };
761
811
  break;
762
812
  }
763
813
  } catch {
@@ -769,6 +819,7 @@ async function applyModelControl(peerRef, model) {
769
819
  from: "pie-panel0000000",
770
820
  to: target.instanceId,
771
821
  kind: "control",
822
+ sessionId: target.sessionId,
772
823
  createdAt: Date.now(),
773
824
  text: JSON.stringify({ control: "model.set", payload: { model } })
774
825
  }, target.secret);
@@ -1761,7 +1812,14 @@ ${result.spec.body}`, `panel-${event.event_id}`);
1761
1812
  }
1762
1813
  const address = resolveInboundAddress(event.text);
1763
1814
  if (address.kind === "other") {
1764
- ctx.log(`im-forward: message addressed to "${address.name}" (another live session); ignoring here`);
1815
+ if (consumerLock) {
1816
+ const epoch2 = inputEpoch;
1817
+ const session = currentSessionId;
1818
+ const payload = `${DISPATCH_PREFIX} ${JSON.stringify({ v: 1, binding: bindingKey(), event })}`;
1819
+ if (terminated || suspended || !isForwardingEnabled() || inputEpoch !== epoch2 || currentSessionId !== session) return;
1820
+ const owner2 = await dispatchEventToName(address.name, bindingKey(), payload);
1821
+ ctx.log(owner2 ? `im-forward: explicit address "${address.name}" dispatched to ${owner2}` : `im-forward: explicit address "${address.name}" has no deliverable unique owner`);
1822
+ }
1765
1823
  return;
1766
1824
  }
1767
1825
  if (address.kind === "ambiguous") {
@@ -2088,12 +2146,15 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
2088
2146
  function stopGeneration(gen) {
2089
2147
  if (gen.startup) clearTimeout(gen.startup);
2090
2148
  return gen.stopping ??= Promise.resolve().then(() => gen.handle?.stop()).catch(() => {
2149
+ gen.stopFailed = true;
2091
2150
  ctx.log(`im-forward: ${cfg.provider} consumer stop failed`);
2092
2151
  }).then(() => {
2093
2152
  gen.retired = true;
2094
2153
  });
2095
2154
  }
2096
2155
  let consumerLock;
2156
+ let consumerSlotRetiring = false;
2157
+ let releaseImBinding;
2097
2158
  let resolvedBindingKey;
2098
2159
  function bindingKey() {
2099
2160
  return resolvedBindingKey ?? `${cfg.provider}:${cfg.appId ?? (cfg.profile ? `profile:${cfg.profile}` : cfg.targetId)}`;
@@ -2115,28 +2176,7 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
2115
2176
  }
2116
2177
  let consumerStartupInFlight = false;
2117
2178
  function residentAliveSomewhere() {
2118
- if (isManager) return false;
2119
- try {
2120
- const dir = ipcDiscoveryRoot2();
2121
- const entries = fs6.readdirSync(dir);
2122
- for (const name of entries) {
2123
- if (!name.endsWith(".json")) continue;
2124
- try {
2125
- const parsed = JSON.parse(fs6.readFileSync(pathJoin(dir, name), "utf8"));
2126
- const unattended = parsed.unattended === true;
2127
- if (unattended && typeof parsed.pid === "number" && parsed.pid > 0) {
2128
- try {
2129
- process.kill(parsed.pid, 0);
2130
- return true;
2131
- } catch {
2132
- }
2133
- }
2134
- } catch {
2135
- }
2136
- }
2137
- } catch {
2138
- }
2139
- return false;
2179
+ return !isManager && liveManagerForBinding(bindingKey());
2140
2180
  }
2141
2181
  function needsCanonicalResolution() {
2142
2182
  return !resolvedBindingKey && !cfg.appId && !!cfg.profile && connection.canonicalAppId !== void 0;
@@ -2153,6 +2193,7 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
2153
2193
  return resolved ? acquireClaimedSlot(resolved) : false;
2154
2194
  }
2155
2195
  function acquireClaimedSlot(binding) {
2196
+ if (!releaseImBinding) releaseImBinding = registerImBinding(binding);
2156
2197
  if (consumerLock) return true;
2157
2198
  if (!isManager && residentAliveSomewhere()) {
2158
2199
  if (!dispatchMode) {
@@ -2166,17 +2207,26 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
2166
2207
  const claim = tryClaimConsumer(
2167
2208
  binding,
2168
2209
  `pie-${currentSessionId ?? "unknown"}`,
2169
- () => {
2170
- ctx.log("im-forward: event-hub slot lost to another consumer; retiring ours");
2210
+ async () => {
2211
+ consumerSlotRetiring = true;
2212
+ ctx.log("im-forward: retiring event-hub consumer before releasing slot");
2213
+ if (restartTimer) clearTimeout(restartTimer);
2214
+ const retiringGeneration = generation;
2215
+ if (retiringGeneration) {
2216
+ await stopGeneration(retiringGeneration);
2217
+ if (retiringGeneration.stopFailed) throw new Error("Consumer stop failed; retaining slot");
2218
+ }
2219
+ consumer = null;
2220
+ consumerRecovering = false;
2221
+ consumerReady = false;
2171
2222
  consumerLock = void 0;
2172
- if (consumer || consumerRecovering) {
2173
- void stopGeneration(generation ?? { handle: null, installed: false, failed: false, retired: true }).catch(() => void 0);
2174
- consumer = null;
2175
- consumerRecovering = false;
2176
- consumerReady = false;
2223
+ if (!terminated) {
2224
+ restartTimer = setTimeout(() => {
2225
+ consumerSlotRetiring = false;
2226
+ void spawnConsumer();
2227
+ }, 15e3);
2228
+ restartTimer.unref?.();
2177
2229
  }
2178
- restartTimer = setTimeout(spawnConsumer, 15e3);
2179
- restartTimer.unref?.();
2180
2230
  },
2181
2231
  // STAND-IN GAP FIX part 2 (dogfood 11-13): the claim-time gate alone was
2182
2232
  // not enough — a TUI that had ALREADY claimed kept the feed while a
@@ -2206,14 +2256,14 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
2206
2256
  async function spawnConsumer() {
2207
2257
  restartTimer = void 0;
2208
2258
  restartDueAt = void 0;
2209
- if (terminated || suspended || consumer || consumerRecovering) return;
2259
+ if (terminated || suspended || consumerSlotRetiring || generation?.stopFailed || consumer || consumerRecovering) return;
2210
2260
  if (needsCanonicalResolution()) {
2211
2261
  if (consumerStartupInFlight) return;
2212
2262
  consumerStartupInFlight = true;
2213
2263
  let key2;
2214
2264
  try {
2215
2265
  key2 = await resolveBindingKey();
2216
- if (terminated || suspended || consumer || consumerRecovering) return;
2266
+ if (terminated || suspended || consumerSlotRetiring || generation?.stopFailed || consumer || consumerRecovering) return;
2217
2267
  } finally {
2218
2268
  consumerStartupInFlight = false;
2219
2269
  }
@@ -2247,7 +2297,7 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
2247
2297
  const recover = () => {
2248
2298
  if (!gen.installed) return;
2249
2299
  void stopGeneration(gen).then(() => {
2250
- if (generation !== gen) return;
2300
+ if (generation !== gen || gen.stopFailed || consumerSlotRetiring) return;
2251
2301
  consumer = null;
2252
2302
  consumerRecovering = false;
2253
2303
  if (terminated || suspended) return;
@@ -2325,6 +2375,8 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
2325
2375
  };
2326
2376
  inputEpoch++;
2327
2377
  suspended = true;
2378
+ releaseImBinding?.();
2379
+ releaseImBinding = void 0;
2328
2380
  const gen = generation;
2329
2381
  if (restartTimer) {
2330
2382
  suspendedRestartInMs = restartDueAt !== void 0 ? Math.max(0, restartDueAt - Date.now()) : 0;
@@ -2366,12 +2418,13 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
2366
2418
  ctx.registerCleanup?.(async () => {
2367
2419
  inputEpoch++;
2368
2420
  terminated = true;
2421
+ releaseImBinding?.();
2422
+ releaseImBinding = void 0;
2369
2423
  clearInterval(busHealthTimer);
2370
2424
  clearInterval(dispatchTagTimer);
2371
2425
  registerDispatchReceiver(void 0);
2372
2426
  registerTurnImDriver(void 0);
2373
- consumerLock?.release();
2374
- consumerLock = void 0;
2427
+ consumerSlotRetiring = true;
2375
2428
  const resources = [...scopes];
2376
2429
  scopes.clear();
2377
2430
  for (const { timer } of retryTimers.values()) clearTimeout(timer);
@@ -2388,6 +2441,10 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
2388
2441
  Promise.resolve().then(() => connection.dispose?.()),
2389
2442
  generation ? stopGeneration(generation) : Promise.resolve()
2390
2443
  ]);
2444
+ if (!generation?.stopFailed && !results.some((result) => result.status === "rejected")) {
2445
+ consumerLock?.release();
2446
+ consumerLock = void 0;
2447
+ }
2391
2448
  consumer = null;
2392
2449
  if (results.some((result) => result.status === "rejected"))
2393
2450
  ctx.log(`im-forward: ${cfg.provider} resource cleanup failed`);
@@ -2,7 +2,7 @@ import { createRequire as __createRequire } from "node:module"; const require =
2
2
  import {
3
3
  resolveCliProjectRoot
4
4
  } from "../../../chunks/chunk-WLFOBECN.js";
5
- import "../../../chunks/chunk-RZGYXAJU.js";
5
+ import "../../../chunks/chunk-LZQXQOPJ.js";
6
6
 
7
7
  // builtin/extensions/init/index.ts
8
8
  import fs from "node:fs";
@@ -1,13 +1,13 @@
1
1
  import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
2
  import {
3
3
  Type
4
- } from "../../../chunks/chunk-BPSCGGVF.js";
4
+ } from "../../../chunks/chunk-XXGYUYXI.js";
5
5
  import {
6
6
  __commonJS,
7
7
  __export,
8
8
  __require,
9
9
  __toESM
10
- } from "../../../chunks/chunk-RZGYXAJU.js";
10
+ } from "../../../chunks/chunk-LZQXQOPJ.js";
11
11
 
12
12
  // ../../node_modules/isexe/windows.js
13
13
  var require_windows = __commonJS({
@@ -3,12 +3,11 @@ import {
3
3
  distillWorkerLogPath,
4
4
  readDistillWorkerLog,
5
5
  spawnDistillWorker
6
- } from "../../../chunks/chunk-IZDNZW3S.js";
6
+ } from "../../../chunks/chunk-Z2FKA2ZH.js";
7
7
  import {
8
8
  getConfigDir,
9
- getSettingsPath,
10
- init_config
11
- } from "../../../chunks/chunk-UCKOXAME.js";
9
+ getSettingsPath
10
+ } from "../../../chunks/chunk-CBDQJMUI.js";
12
11
  import {
13
12
  DEFAULT_MEMORY_INJECTION_BUDGET,
14
13
  MemoryStore,
@@ -20,19 +19,18 @@ import {
20
19
  saveAttestedEntry,
21
20
  searchMemory,
22
21
  todayKey
23
- } from "../../../chunks/chunk-YNTIOWCD.js";
24
- import "../../../chunks/chunk-XO3NM7BB.js";
25
- import "../../../chunks/chunk-IPLMGAML.js";
26
- import "../../../chunks/chunk-R7VO46EK.js";
22
+ } from "../../../chunks/chunk-BLDI2GRF.js";
23
+ import "../../../chunks/chunk-Y3I2UV5Y.js";
24
+ import "../../../chunks/chunk-5KI4Y4LA.js";
25
+ import "../../../chunks/chunk-3W3SXVPB.js";
27
26
  import {
28
27
  Type
29
- } from "../../../chunks/chunk-BPSCGGVF.js";
30
- import "../../../chunks/chunk-RZGYXAJU.js";
28
+ } from "../../../chunks/chunk-XXGYUYXI.js";
29
+ import "../../../chunks/chunk-LZQXQOPJ.js";
31
30
 
32
31
  // builtin/extensions/memory/index.ts
33
32
  import * as fs from "node:fs";
34
33
  import * as path from "node:path";
35
- init_config();
36
34
  function yesterdayKey() {
37
35
  const probe = /* @__PURE__ */ new Date();
38
36
  probe.setDate(probe.getDate() - 1);