@cydm/pie 4.3.5 → 4.3.7

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 (27) hide show
  1. package/dist/builtin/extensions/ask-user/index.js +4 -4
  2. package/dist/builtin/extensions/cron/index.js +7 -1
  3. package/dist/builtin/extensions/im-forward/index.js +101 -83
  4. package/dist/builtin/extensions/mcp-adapter/index.js +7 -1
  5. package/dist/builtin/extensions/memory/index.js +5 -5
  6. package/dist/builtin/extensions/pie-ipc/index.js +1 -1
  7. package/dist/builtin/extensions/pie-proc/index.js +3 -2
  8. package/dist/builtin/extensions/plan-mode/index.js +4 -4
  9. package/dist/builtin/extensions/subagent/index.js +5 -5
  10. package/dist/builtin/extensions/todo/index.js +4 -4
  11. package/dist/chunks/{chunk-J2LGVYH2.js → chunk-2SAFRLFJ.js} +28 -13
  12. package/dist/chunks/{chunk-JQRZLVPY.js → chunk-6JEYRAQM.js} +1898 -1692
  13. package/dist/chunks/{chunk-NCP264ZE.js → chunk-B4N5LJMD.js} +1 -1
  14. package/dist/chunks/{chunk-PFXSA2LK.js → chunk-BJ4XN5VX.js} +5 -5
  15. package/dist/chunks/{chunk-H5G55G3R.js → chunk-N3BWFAMZ.js} +11 -1
  16. package/dist/chunks/{chunk-QX6WS73C.js → chunk-VHKMWOG3.js} +1 -1
  17. package/dist/chunks/{chunk-PC6HUZAD.js → chunk-WZLO5V2X.js} +3 -3
  18. package/dist/chunks/{chunk-BK36Y35W.js → chunk-XMOWWL4B.js} +2 -2
  19. package/dist/chunks/{concierge-cli-MCHXTFBA.js → manager-cli-QNMCCIFG.js} +322 -44
  20. package/dist/chunks/{model-registry-YA6U366L.js → model-registry-NKE3BRSZ.js} +2 -2
  21. package/dist/chunks/{src-ODLT57PQ.js → src-46R5ZFOU.js} +2 -2
  22. package/dist/chunks/{src-VPMIQGEW.js → src-4EQ7PBEI.js} +3 -3
  23. package/dist/chunks/{src-XSLD2IQ2.js → src-BHIH4VLE.js} +1 -1
  24. package/dist/chunks/{src-AQ4H43UM.js → src-UVULNQOO.js} +4 -4
  25. package/dist/chunks/{test-stream-GIUD5JWS.js → test-stream-FC6ZRENI.js} +1 -1
  26. package/dist/cli.js +347 -208
  27. package/package.json +3 -3
@@ -1,10 +1,10 @@
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-PC6HUZAD.js";
5
- import "../../../chunks/chunk-BK36Y35W.js";
6
- import "../../../chunks/chunk-NCP264ZE.js";
7
- import "../../../chunks/chunk-JQRZLVPY.js";
4
+ } from "../../../chunks/chunk-WZLO5V2X.js";
5
+ import "../../../chunks/chunk-XMOWWL4B.js";
6
+ import "../../../chunks/chunk-B4N5LJMD.js";
7
+ import "../../../chunks/chunk-6JEYRAQM.js";
8
8
  import "../../../chunks/chunk-XXGYUYXI.js";
9
9
  import "../../../chunks/chunk-LZQXQOPJ.js";
10
10
 
@@ -496,7 +496,13 @@ function runWorker(job, signal, cli = process.argv[1], configDir) {
496
496
  return new Promise((resolve3, reject) => {
497
497
  const child = spawn(process.execPath, [path2.resolve(cli), "--json-events", "--session-id", job.sessionId, "--resume-required"], {
498
498
  cwd: job.cwd,
499
- env: { ...process.env, ...configDir ? { PIE_CODING_AGENT_DIR: configDir } : {}, PIE_CRON_ROLE: "worker" },
499
+ // R5-P2: a cron worker is an INDEPENDENT session — strip the manager
500
+ // identity/model quartet so it never inherits the manager's model or
501
+ // curated name (same boundary contract as pie-proc and the bash tool).
502
+ env: (() => {
503
+ const { PIE_DEFAULT_PROVIDER: _p, PIE_DEFAULT_MODEL: _m, PIE_MANAGER_BOOTSTRAP: _b, PIE_PROC_CURATED_NAME: _c, ...cleanEnv } = process.env;
504
+ return { ...cleanEnv, ...configDir ? { PIE_CODING_AGENT_DIR: configDir } : {}, PIE_CRON_ROLE: "worker" };
505
+ })(),
500
506
  stdio: ["pipe", "pipe", "pipe"],
501
507
  windowsHide: true
502
508
  });
@@ -27,7 +27,7 @@ import {
27
27
  truncateMarkdown,
28
28
  tryClaimConsumer,
29
29
  writeConfig
30
- } from "../../../chunks/chunk-H5G55G3R.js";
30
+ } from "../../../chunks/chunk-N3BWFAMZ.js";
31
31
  import {
32
32
  detectImageMime,
33
33
  readImageFormat
@@ -40,21 +40,22 @@ import "../../../chunks/chunk-LZQXQOPJ.js";
40
40
  // builtin/extensions/im-forward/runtime.ts
41
41
  import * as crypto from "node:crypto";
42
42
  import * as fs6 from "node:fs";
43
- import { basename } from "node:path";
43
+ import { basename, join as pathJoin, resolve as pathResolve } from "node:path";
44
+ import * as os2 from "node:os";
44
45
 
45
46
  // builtin/extensions/im-forward/address-book.ts
46
47
  import * as fs from "node:fs";
47
48
  import * as os from "node:os";
48
- import * as path2 from "node:path";
49
+ import * as path from "node:path";
49
50
  var MAX_ADDRESS_HEAD = 64;
50
51
  function addressBookRoot() {
51
52
  const raw = process.env.PIE_IPC_CONFIG_DIR;
52
53
  if (raw && raw.trim()) {
53
54
  const value = raw.trim();
54
- const expanded = value === "~" ? os.homedir() : value.startsWith("~/") ? path2.join(os.homedir(), value.slice(2)) : value;
55
- return path2.resolve(expanded);
55
+ const expanded = value === "~" ? os.homedir() : value.startsWith("~/") ? path.join(os.homedir(), value.slice(2)) : value;
56
+ return path.resolve(expanded);
56
57
  }
57
- return path2.resolve(resolveConfigDir());
58
+ return path.resolve(resolveConfigDir());
58
59
  }
59
60
  function pidAlive(pid) {
60
61
  if (!Number.isInteger(pid) || pid <= 0) return true;
@@ -70,7 +71,7 @@ function scanAddressBook() {
70
71
  let complete = true;
71
72
  let selfPublished;
72
73
  let dirExists = false;
73
- const dir = path2.join(addressBookRoot(), "run", "ipc");
74
+ const dir = path.join(addressBookRoot(), "run", "ipc");
74
75
  let entries;
75
76
  try {
76
77
  entries = fs.readdirSync(dir);
@@ -82,7 +83,7 @@ function scanAddressBook() {
82
83
  for (const [index, file] of entries.entries()) {
83
84
  if (!file.endsWith(".json")) continue;
84
85
  try {
85
- const status = JSON.parse(fs.readFileSync(path2.join(dir, file), "utf8"));
86
+ const status = JSON.parse(fs.readFileSync(path.join(dir, file), "utf8"));
86
87
  dirExists = true;
87
88
  const name = typeof status.sessionName === "string" ? status.sessionName.trim() : "";
88
89
  const pid = typeof status.pid === "number" ? status.pid : void 0;
@@ -142,7 +143,7 @@ function resolveAddress(text, ownLiveName, book) {
142
143
 
143
144
  // builtin/extensions/im-forward/thread-registry.ts
144
145
  import * as fs2 from "node:fs";
145
- import * as path3 from "node:path";
146
+ import * as path2 from "node:path";
146
147
  import { randomUUID } from "node:crypto";
147
148
  var SCHEMA = 1;
148
149
  var RUNTIME_ID = randomUUID();
@@ -151,7 +152,7 @@ function encodeThreadKey(input) {
151
152
  return Buffer.from(raw, "utf8").toString("base64url");
152
153
  }
153
154
  function threadsDir() {
154
- return path3.join(addressBookRoot(), "threads");
155
+ return path2.join(addressBookRoot(), "threads");
155
156
  }
156
157
  function pidAlive2(pid) {
157
158
  if (!Number.isInteger(pid) || pid <= 0) return true;
@@ -163,7 +164,7 @@ function pidAlive2(pid) {
163
164
  }
164
165
  }
165
166
  function ownerPath(threadKey) {
166
- return path3.join(threadsDir(), `${threadKey}.json`);
167
+ return path2.join(threadsDir(), `${threadKey}.json`);
167
168
  }
168
169
  function readOwner(threadKey) {
169
170
  const file = ownerPath(threadKey);
@@ -218,7 +219,7 @@ function decide(owner, threadKey, sessionId) {
218
219
  function writeNew(threadKey, sessionId) {
219
220
  const file = ownerPath(threadKey);
220
221
  const record = recordFor(threadKey, sessionId);
221
- const tmp = path3.join(threadsDir(), `.new-${randomUUID()}.json`);
222
+ const tmp = path2.join(threadsDir(), `.new-${randomUUID()}.json`);
222
223
  try {
223
224
  const fd = fs2.openSync(tmp, "wx", 384);
224
225
  try {
@@ -293,10 +294,10 @@ function claimThreadOwnership(input, sessionId) {
293
294
  }
294
295
  }
295
296
  function lockDirPath(threadKey) {
296
- return path3.join(threadsDir(), `${threadKey}.lock`);
297
+ return path2.join(threadsDir(), `${threadKey}.lock`);
297
298
  }
298
299
  function writeHolderEntry(dir, token) {
299
- fs2.writeFileSync(path3.join(dir, `held.${token}`), JSON.stringify({ version: 1, pid: process.pid, createdAt: Date.now() }), { mode: 384, flag: "wx" });
300
+ fs2.writeFileSync(path2.join(dir, `held.${token}`), JSON.stringify({ version: 1, pid: process.pid, createdAt: Date.now() }), { mode: 384, flag: "wx" });
300
301
  }
301
302
  function retireStaleLock(lock) {
302
303
  let entries;
@@ -318,7 +319,7 @@ function retireStaleLock(lock) {
318
319
  for (const name of holders) {
319
320
  let pid;
320
321
  try {
321
- const parsed = JSON.parse(fs2.readFileSync(path3.join(lock, name), "utf8"));
322
+ const parsed = JSON.parse(fs2.readFileSync(path2.join(lock, name), "utf8"));
322
323
  if (parsed?.version !== 1 || !Number.isInteger(parsed.pid) || parsed.pid <= 0) return false;
323
324
  pid = parsed.pid;
324
325
  } catch {
@@ -333,7 +334,7 @@ function retireStaleLock(lock) {
333
334
  }
334
335
  for (const name of holders) {
335
336
  try {
336
- fs2.unlinkSync(path3.join(lock, name));
337
+ fs2.unlinkSync(path2.join(lock, name));
337
338
  } catch (error) {
338
339
  if (error.code !== "ENOENT") return false;
339
340
  }
@@ -350,7 +351,7 @@ function acquireThreadLock(threadKey) {
350
351
  if (acquiredLocks.has(threadKey)) return { acquired: true };
351
352
  const lock = lockDirPath(threadKey);
352
353
  const token = randomUUID();
353
- const candidate = path3.join(threadsDir(), `lock.acquire.${token}`);
354
+ const candidate = path2.join(threadsDir(), `lock.acquire.${token}`);
354
355
  try {
355
356
  try {
356
357
  fs2.mkdirSync(candidate, { mode: 448 });
@@ -398,7 +399,7 @@ function releaseThreadLock(threadKey) {
398
399
  acquiredLocks.delete(threadKey);
399
400
  const lock = lockDirPath(threadKey);
400
401
  try {
401
- fs2.unlinkSync(path3.join(lock, `held.${token}`));
402
+ fs2.unlinkSync(path2.join(lock, `held.${token}`));
402
403
  } catch {
403
404
  }
404
405
  try {
@@ -426,10 +427,10 @@ function threadOwner(input) {
426
427
  // builtin/extensions/im-forward/event-dispatch.ts
427
428
  import * as net from "node:net";
428
429
  import * as fs3 from "node:fs";
429
- import * as path4 from "node:path";
430
+ import * as path3 from "node:path";
430
431
  import { createHmac, randomUUID as randomUUID2 } from "node:crypto";
431
432
  function discoveryDir() {
432
- return path4.join(addressBookRoot(), "run", "ipc");
433
+ return path3.join(addressBookRoot(), "run", "ipc");
433
434
  }
434
435
  function pidAlive3(pid) {
435
436
  if (!Number.isInteger(pid) || pid <= 0) return false;
@@ -451,7 +452,7 @@ function findOwnerInstance(sessionId) {
451
452
  for (const name of entries.slice(0, 256)) {
452
453
  if (!name.endsWith(".json")) continue;
453
454
  try {
454
- const parsed = JSON.parse(fs3.readFileSync(path4.join(discoveryDir(), name), "utf8"));
455
+ const parsed = JSON.parse(fs3.readFileSync(path3.join(discoveryDir(), name), "utf8"));
455
456
  if (parsed.instanceId === name.slice(0, -".json".length) && parsed.sessionId === sessionId && parsed.port && typeof parsed.secret === "string" && parsed.protocol === IPC_PROTOCOL_VERSION && pidAlive3(parsed.pid ?? 0)) {
456
457
  candidates.push({ file: parsed, startedAt: typeof parsed.startedAt === "number" ? parsed.startedAt : 0 });
457
458
  }
@@ -539,13 +540,13 @@ async function dispatchEventToSession(sessionId, eventText) {
539
540
 
540
541
  // builtin/extensions/im-forward/session-roots.ts
541
542
  import * as fs4 from "node:fs";
542
- import * as path5 from "node:path";
543
+ import * as path4 from "node:path";
543
544
  function rootsDir() {
544
- return path5.join(resolveConfigDir(), "im-forward", "roots");
545
+ return path4.join(resolveConfigDir(), "im-forward", "roots");
545
546
  }
546
547
  function rootPath(provider, messageId) {
547
548
  const safe = `${provider}:${messageId}`.replace(/[^a-zA-Z0-9._:-]/g, "_");
548
- return path5.join(rootsDir(), `${safe}.json`);
549
+ return path4.join(rootsDir(), `${safe}.json`);
549
550
  }
550
551
  function pidAlive4(pid) {
551
552
  if (!Number.isInteger(pid) || pid <= 0) return false;
@@ -582,13 +583,13 @@ function sessionRootOwner(provider, messageId) {
582
583
 
583
584
  // builtin/extensions/im-forward/session-anchors.ts
584
585
  import * as fs5 from "node:fs";
585
- import * as path6 from "node:path";
586
+ import * as path5 from "node:path";
586
587
  function anchorsDir() {
587
- return path6.join(addressBookRoot(), "im-forward", "anchors");
588
+ return path5.join(addressBookRoot(), "im-forward", "anchors");
588
589
  }
589
590
  function anchorPath(sessionId) {
590
591
  const safe = sessionId.replace(/[^a-zA-Z0-9._-]/g, "_");
591
- return path6.join(anchorsDir(), `${safe}.json`);
592
+ return path5.join(anchorsDir(), `${safe}.json`);
592
593
  }
593
594
  function loadPersistedAnchor(sessionId, identity) {
594
595
  try {
@@ -621,7 +622,7 @@ function savePersistedAnchor(sessionId, identity, anchor) {
621
622
  anchor
622
623
  };
623
624
  const target = anchorPath(sessionId);
624
- fs5.mkdirSync(path6.dirname(target), { recursive: true });
625
+ fs5.mkdirSync(path5.dirname(target), { recursive: true });
625
626
  fs5.writeFileSync(target, `${JSON.stringify(file)}
626
627
  `, "utf8");
627
628
  } catch {
@@ -667,10 +668,17 @@ function hashText(input) {
667
668
  }
668
669
  return Math.abs(hash).toString(36);
669
670
  }
671
+ function ipcDiscoveryRoot() {
672
+ const home = os2.homedir() || process.env.HOME || process.env.USERPROFILE || "/tmp";
673
+ const override = process.env.PIE_IPC_CONFIG_DIR;
674
+ const raw = override !== void 0 ? override : resolveConfigDir();
675
+ const configDir = process.platform === "win32" ? raw : pathResolve(raw === "~" ? home : raw.startsWith("~/") ? pathJoin(home, raw.slice(2)) : raw);
676
+ return pathJoin(configDir, "run", "ipc");
677
+ }
670
678
  function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
671
679
  const IM_INPUT_PREFIX = connection.sourcePrefix;
672
680
  const key = (id) => JSON.stringify([cfg.provider, id]);
673
- const isConcierge = cfg.unattended === true;
681
+ const isManager = cfg.unattended === true;
674
682
  const scopes = /* @__PURE__ */ new Set();
675
683
  let forwardingEnabled = cfg.enabled === true;
676
684
  let configurationFailed = false;
@@ -875,7 +883,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
875
883
  }
876
884
  ctx.on("terminal:input", (event) => {
877
885
  const text = event.text?.trim() ?? "";
878
- if (isConcierge && /^\[pie-ipc\][^\n]*says:\s*\n?\[ipc-done\] requestId=[a-zA-Z0-9:-]+ (?:outcome=\S+ )?user_assigned=true(?:\s|$)/.test(text) && currentSessionId) {
886
+ if (isManager && /^\[pie-ipc\][^\n]*says:\s*\n?\[ipc-done\] requestId=[a-zA-Z0-9:-]+ (?:outcome=\S+ )?user_assigned=true(?:\s|$)/.test(text) && currentSessionId) {
879
887
  const requestTag = /requestId=([a-zA-Z0-9:-]+)/.exec(text)?.[1] ?? "ipc-delivery";
880
888
  stampDeliveryDestination(`ipc-done:${requestTag}`);
881
889
  }
@@ -892,7 +900,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
892
900
  return { action: "continue" };
893
901
  });
894
902
  function outboundRoleAllows(attribution) {
895
- if (!isConcierge) return true;
903
+ if (!isManager) return true;
896
904
  if (attribution !== void 0) return true;
897
905
  pruneDeliveryDestinations();
898
906
  const scope = `s:${currentSessionId}:`;
@@ -933,7 +941,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
933
941
  return;
934
942
  }
935
943
  }
936
- if (inbound?.role === "user" && isConcierge && currentSessionId) {
944
+ if (inbound?.role === "user" && isManager && currentSessionId) {
937
945
  const userText = typeof inbound.content === "string" ? inbound.content : Array.isArray(inbound.content) ? inbound.content.map((block) => block && typeof block === "object" && typeof block.text === "string" ? block.text : "").join("") : "";
938
946
  const stampedWake = /^\[pie-ipc\][^\n]*says:\s*\n?\[(?:ipc-done|ipc-check|ipc-done-check)\] (?:No completion notification arrived for |The completion notification for )?requestId=[a-zA-Z0-9:-]+ (?:outcome=\S+ )?(?:\([^)]*\) )?user_assigned=true(?:\s|$)/;
939
947
  const wrappedNotify = stampedWake.exec(userText);
@@ -1016,7 +1024,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
1016
1024
  let sessionAnchorThreadId = sessionAnchor.threadId;
1017
1025
  let stakeFlightToken;
1018
1026
  const stakeWanted = () => {
1019
- if (isConcierge) return false;
1027
+ if (isManager) return false;
1020
1028
  const current = resolveSessionAnchor(sessionId);
1021
1029
  sessionAnchorThreadId = current.threadId;
1022
1030
  return !current.messageId || !current.threadId;
@@ -1033,7 +1041,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
1033
1041
  };
1034
1042
  const pinnedAnchor = replyTo ?? attributionAnchor;
1035
1043
  let stakeGuard = 8;
1036
- while (stakeGuard-- > 0 && !isConcierge) {
1044
+ while (stakeGuard-- > 0 && !isManager) {
1037
1045
  if (stakeFlightToken) break;
1038
1046
  const refreshed0 = resolveSessionAnchor(sessionId);
1039
1047
  if (refreshed0.threadId) {
@@ -1054,7 +1062,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
1054
1062
  sessionAnchorThreadId = refreshed.threadId;
1055
1063
  if (!pinnedAnchor && refreshed.messageId && !refreshed.threadId) anchor = refreshed.messageId;
1056
1064
  }
1057
- if (!isConcierge && !stakeFlightToken && !pinnedAnchor) {
1065
+ if (!isManager && !stakeFlightToken && !pinnedAnchor) {
1058
1066
  const last = resolveSessionAnchor(sessionId);
1059
1067
  if (!last.threadId) {
1060
1068
  ctx.log(`im-forward: topic stake unavailable for ${sessionId}; dropping forward (seq=${sequence})`);
@@ -1069,7 +1077,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
1069
1077
  token.release?.();
1070
1078
  anchorStakeFlights.delete(sessionId);
1071
1079
  };
1072
- let threadPlacement = attribution?.threadId ? { replyInThread: true } : !anchor && !isConcierge ? { replyInThread: true } : sessionAnchorThreadId ? { replyInThread: true, topicId: sessionAnchorThreadId } : { replyInThread: false };
1080
+ let threadPlacement = attribution?.threadId ? { replyInThread: true } : !anchor && !isManager ? { replyInThread: true } : sessionAnchorThreadId ? { replyInThread: true, topicId: sessionAnchorThreadId } : { replyInThread: false };
1073
1081
  const sendChunk = async (index) => {
1074
1082
  const key2 = chunkKey(baseKey, index);
1075
1083
  return providerCall(
@@ -1120,7 +1128,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
1120
1128
  return;
1121
1129
  }
1122
1130
  registerRoute(sent, sessionId);
1123
- const legacyUpgrade = !isConcierge && anchor !== void 0 && !sessionAnchor.threadId && sent.messageId !== anchor;
1131
+ const legacyUpgrade = !isManager && anchor !== void 0 && !sessionAnchor.threadId && sent.messageId !== anchor;
1124
1132
  const stakeNeeded = stakeFlightToken !== void 0;
1125
1133
  if (stakeNeeded) {
1126
1134
  try {
@@ -1192,18 +1200,18 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
1192
1200
  const files = collectFileReferences(
1193
1201
  text,
1194
1202
  ctx.cwd,
1195
- (path12) => {
1203
+ (path11) => {
1196
1204
  try {
1197
- const stat = fs6.statSync(path12);
1205
+ const stat = fs6.statSync(path11);
1198
1206
  return { isFile: stat.isFile(), size: stat.size };
1199
1207
  } catch {
1200
1208
  return null;
1201
1209
  }
1202
1210
  },
1203
1211
  {
1204
- canonicalize: (path12) => {
1212
+ canonicalize: (path11) => {
1205
1213
  try {
1206
- return fs6.realpathSync(path12);
1214
+ return fs6.realpathSync(path11);
1207
1215
  } catch {
1208
1216
  return null;
1209
1217
  }
@@ -1461,7 +1469,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
1461
1469
  return;
1462
1470
  }
1463
1471
  const unanchored = !meta.replyTo && !meta.threadId;
1464
- if (isConcierge && unanchored) {
1472
+ if (isManager && unanchored) {
1465
1473
  const residentRoute = {
1466
1474
  messageId: "",
1467
1475
  threadId: meta.threadId ?? null,
@@ -1495,7 +1503,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
1495
1503
  ctx.log(`im-forward: thread ownership unreadable for ${messageId}; dropping (fail closed)`);
1496
1504
  return;
1497
1505
  }
1498
- if (isConcierge && event.chatType === "group" && meta.threadId) {
1506
+ if (isManager && event.chatType === "group" && meta.threadId) {
1499
1507
  if (!scope.isCurrent()) {
1500
1508
  releaseInvalidatedEvent();
1501
1509
  return;
@@ -1505,7 +1513,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
1505
1513
  ctx.log(`im-forward: unowned-topic takeover lost the claim (${claim.reason}); ${messageId} dropped`);
1506
1514
  return;
1507
1515
  }
1508
- ctx.log(`im-forward: unowned group topic ${meta.threadId} taken by concierge (claimed)`);
1516
+ ctx.log(`im-forward: unowned group topic ${meta.threadId} taken by manager (claimed)`);
1509
1517
  await acceptRoutedMessage(
1510
1518
  { messageId: "", threadId: meta.threadId, sessionId, sentAt: Date.now() },
1511
1519
  event,
@@ -1746,14 +1754,14 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
1746
1754
  }
1747
1755
  let consumerStartupInFlight = false;
1748
1756
  function residentAliveSomewhere() {
1749
- if (isConcierge) return false;
1757
+ if (isManager) return false;
1750
1758
  try {
1751
- const dir = path.join(resolveConfigDir(), "run", "ipc");
1759
+ const dir = ipcDiscoveryRoot();
1752
1760
  const entries = fs6.readdirSync(dir);
1753
1761
  for (const name of entries) {
1754
1762
  if (!name.endsWith(".json")) continue;
1755
1763
  try {
1756
- const parsed = JSON.parse(fs6.readFileSync(path.join(dir, name), "utf8"));
1764
+ const parsed = JSON.parse(fs6.readFileSync(pathJoin(dir, name), "utf8"));
1757
1765
  const unattended = parsed.unattended === true;
1758
1766
  if (unattended && typeof parsed.pid === "number" && parsed.pid > 0) {
1759
1767
  try {
@@ -1785,22 +1793,32 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
1785
1793
  }
1786
1794
  function acquireClaimedSlot(binding) {
1787
1795
  if (consumerLock) return true;
1788
- if (!isConcierge && residentAliveSomewhere()) {
1796
+ if (!isManager && residentAliveSomewhere()) {
1789
1797
  ctx.log("im-forward: a live resident owns the feed class; standing down (dispatch mode)");
1790
1798
  return false;
1791
1799
  }
1792
- const claim = tryClaimConsumer(binding, `pie-${currentSessionId ?? "unknown"}`, () => {
1793
- ctx.log("im-forward: event-hub slot lost to another consumer; retiring ours");
1794
- consumerLock = void 0;
1795
- if (consumer || consumerRecovering) {
1796
- void stopGeneration(generation ?? { handle: null, installed: false, failed: false, retired: true }).catch(() => void 0);
1797
- consumer = null;
1798
- consumerRecovering = false;
1799
- consumerReady = false;
1800
- }
1801
- restartTimer = setTimeout(spawnConsumer, 15e3);
1802
- restartTimer.unref?.();
1803
- });
1800
+ const claim = tryClaimConsumer(
1801
+ binding,
1802
+ `pie-${currentSessionId ?? "unknown"}`,
1803
+ () => {
1804
+ ctx.log("im-forward: event-hub slot lost to another consumer; retiring ours");
1805
+ consumerLock = void 0;
1806
+ if (consumer || consumerRecovering) {
1807
+ void stopGeneration(generation ?? { handle: null, installed: false, failed: false, retired: true }).catch(() => void 0);
1808
+ consumer = null;
1809
+ consumerRecovering = false;
1810
+ consumerReady = false;
1811
+ }
1812
+ restartTimer = setTimeout(spawnConsumer, 15e3);
1813
+ restartTimer.unref?.();
1814
+ },
1815
+ // STAND-IN GAP FIX part 2 (dogfood 11-13): the claim-time gate alone was
1816
+ // not enough — a TUI that had ALREADY claimed kept the feed while a
1817
+ // resident started later. Every heartbeat (5s) re-checks: if a live
1818
+ // resident exists and we are not it, yield voluntarily. Managers never
1819
+ // yield (they ARE the resident; a false predicate would flap the feed).
1820
+ isManager ? void 0 : () => residentAliveSomewhere()
1821
+ );
1804
1822
  if (!claim) {
1805
1823
  ctx.log("im-forward: another consumer owns the event-hub slot; dispatch mode");
1806
1824
  return false;
@@ -2006,7 +2024,7 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
2006
2024
  // resident (this runtime, if unattended); anchored routing is
2007
2025
  // table-based and explicit addressing always works. Unconditional:
2008
2026
  // ownership is a capability axis, not route-table state.
2009
- cfg.unattended ? "- note: unanchored DM/@app messages bind to this resident session; reply/thread messages route to their referenced session." : "- note: interactive host \u2014 only reply/thread-attributed or explicitly addressed messages enter (unanchored messages belong to the resident concierge, if running)."
2027
+ cfg.unattended ? "- note: unanchored DM/@app messages bind to this resident session; reply/thread messages route to their referenced session." : "- note: interactive host \u2014 only reply/thread-attributed or explicitly addressed messages enter (unanchored messages belong to the resident manager, if running)."
2010
2028
  );
2011
2029
  if (lastSendError)
2012
2030
  lines.push(
@@ -2072,8 +2090,8 @@ Enable forwarding and start the connection? No test message will be sent. Saving
2072
2090
  // builtin/extensions/im-forward/providers/feishu/index.ts
2073
2091
  import { spawn as spawn4 } from "node:child_process";
2074
2092
  import * as fs9 from "node:fs";
2075
- import * as os2 from "node:os";
2076
- import * as path11 from "node:path";
2093
+ import * as os3 from "node:os";
2094
+ import * as path10 from "node:path";
2077
2095
 
2078
2096
  // builtin/extensions/im-forward/lark-cli.ts
2079
2097
  import { spawn as spawn2 } from "node:child_process";
@@ -2082,24 +2100,24 @@ import { StringDecoder as StringDecoder2 } from "node:string_decoder";
2082
2100
  // builtin/extensions/im-forward/launch.ts
2083
2101
  import { spawn } from "node:child_process";
2084
2102
  import * as fs7 from "node:fs";
2085
- import * as path7 from "node:path";
2103
+ import * as path6 from "node:path";
2086
2104
  import { StringDecoder } from "node:string_decoder";
2087
2105
  function resolveLaunchSpec(explicit, cwd = process.cwd(), platform = process.platform, env = process.env) {
2088
2106
  const windows = platform === "win32";
2089
- const candidates = explicit ? [path7.resolve(cwd, explicit)] : (env.PATH ?? "").split(windows ? ";" : ":").filter(Boolean).flatMap((dir) => (windows ? ["lark-cli.exe", "lark-cli.cmd"] : ["lark-cli"]).map((name) => path7.resolve(cwd, dir, name)));
2107
+ const candidates = explicit ? [path6.resolve(cwd, explicit)] : (env.PATH ?? "").split(windows ? ";" : ":").filter(Boolean).flatMap((dir) => (windows ? ["lark-cli.exe", "lark-cli.cmd"] : ["lark-cli"]).map((name) => path6.resolve(cwd, dir, name)));
2090
2108
  for (const candidate of candidates) {
2091
2109
  try {
2092
2110
  if (!fs7.statSync(candidate).isFile()) continue;
2093
- const ext = path7.extname(candidate).toLowerCase();
2111
+ const ext = path6.extname(candidate).toLowerCase();
2094
2112
  if (ext === ".js" || ext === ".mjs") return { command: process.execPath, prefix: [candidate] };
2095
2113
  if (windows && ext === ".cmd") {
2096
- const dir = path7.dirname(candidate);
2097
- for (const root of [path7.join(dir, "node_modules", "@larksuite", "cli"), path7.resolve(dir, "..", "@larksuite", "cli")]) {
2114
+ const dir = path6.dirname(candidate);
2115
+ for (const root of [path6.join(dir, "node_modules", "@larksuite", "cli"), path6.resolve(dir, "..", "@larksuite", "cli")]) {
2098
2116
  try {
2099
- const pkg = JSON.parse(fs7.readFileSync(path7.join(root, "package.json"), "utf8"));
2117
+ const pkg = JSON.parse(fs7.readFileSync(path6.join(root, "package.json"), "utf8"));
2100
2118
  const bin = typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.["lark-cli"];
2101
2119
  if (pkg.name !== "@larksuite/cli" || typeof bin !== "string" || bin.replace(/^\.\//, "") !== "scripts/run.js") continue;
2102
- const entry = path7.join(root, "scripts", "run.js");
2120
+ const entry = path6.join(root, "scripts", "run.js");
2103
2121
  if (fs7.statSync(entry).isFile()) return { command: process.execPath, prefix: [entry] };
2104
2122
  } catch {
2105
2123
  }
@@ -2163,7 +2181,7 @@ function stopOwnedTreeInner(child, signal) {
2163
2181
  }, 1500);
2164
2182
  try {
2165
2183
  const root = process.env.SystemRoot || process.env.windir || "C:\\Windows";
2166
- killer = spawn(path7.join(root, "System32", "taskkill.exe"), ["/PID", String(child.pid), "/T", "/F"], { shell: false, windowsHide: true, stdio: "ignore" });
2184
+ killer = spawn(path6.join(root, "System32", "taskkill.exe"), ["/PID", String(child.pid), "/T", "/F"], { shell: false, windowsHide: true, stdio: "ignore" });
2167
2185
  killer.on("error", () => finish(false));
2168
2186
  killer.on("exit", (code) => finish(code === 0));
2169
2187
  } catch {
@@ -2409,16 +2427,16 @@ function extractImageKey(content) {
2409
2427
 
2410
2428
  // builtin/extensions/im-forward/providers/feishu/setup.ts
2411
2429
  import * as fs8 from "node:fs";
2412
- import * as path10 from "node:path";
2430
+ import * as path9 from "node:path";
2413
2431
 
2414
2432
  // builtin/extensions/im-forward/browser.ts
2415
2433
  import { spawn as spawn3 } from "node:child_process";
2416
- import path8 from "node:path";
2434
+ import path7 from "node:path";
2417
2435
  var browserScript = "$ErrorActionPreference = 'Stop'; try { $reader = [System.IO.StreamReader]::new([Console]::OpenStandardInput(), [System.Text.Encoding]::UTF8); $url = $reader.ReadToEnd(); Start-Process -FilePath $url; exit 0 } catch { exit 1 }";
2418
2436
  function browserLaunch(platform = process.platform, root = process.env.SystemRoot || "C:\\Windows") {
2419
2437
  if (platform === "win32") {
2420
2438
  if (!/^[A-Za-z]:\\/.test(root) || /[\x00-\x1f]/.test(root)) return;
2421
- return { command: path8.win32.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), args: ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(browserScript, "utf16le").toString("base64")], stdin: true };
2439
+ return { command: path7.win32.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), args: ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(browserScript, "utf16le").toString("base64")], stdin: true };
2422
2440
  }
2423
2441
  if (platform === "darwin") return { command: "/usr/bin/open", args: ["--"], stdin: false };
2424
2442
  if (platform === "linux") return { command: "/usr/bin/xdg-open", args: [], stdin: false };
@@ -2477,23 +2495,23 @@ async function openBrowser(url, signal, seam = {}) {
2477
2495
  }
2478
2496
 
2479
2497
  // builtin/extensions/im-forward/existing-app-terminal.ts
2480
- import path9 from "node:path";
2498
+ import path8 from "node:path";
2481
2499
  var existingAppInnerScript = "$ErrorActionPreference = 'Stop'; try { $payload = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('__PAYLOAD__')) | ConvertFrom-Json; Set-Location -LiteralPath $payload.cwd; & $payload.command @($payload.args); $code = $LASTEXITCODE; if ($null -eq $code) { exit 1 }; exit $code } catch { Write-Host 'Official setup failed. Close this window and retry from Pie.'; exit 1 }";
2482
2500
  var existingAppOuterTemplate = "$ErrorActionPreference = 'Stop'; try { $inner = '" + existingAppInnerScript.replaceAll("'", "''") + "'; $encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($inner)); $child = Start-Process -FilePath (Join-Path $PSHOME 'powershell.exe') -WindowStyle Normal -Wait -PassThru -ArgumentList @('-NoLogo', '-NoProfile', '-EncodedCommand', $encoded); exit $child.ExitCode } catch { exit 1 }";
2483
2501
  function existingAppTerminal(binary, cwd, platform = process.platform, root = process.env.SystemRoot || "C:\\Windows") {
2484
2502
  if (platform !== "win32" || !/^[A-Za-z]:\\/.test(root) || /[\x00-\x1f]/.test(root)) return null;
2485
2503
  const payload = Buffer.from(JSON.stringify({ command: binary.command, args: [...binary.prefix, "config", "init", "--brand", "feishu"], cwd }), "utf8").toString("base64");
2486
2504
  const script = existingAppOuterTemplate.replace("__PAYLOAD__", payload);
2487
- return { command: path9.win32.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), prefix: ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")] };
2505
+ return { command: path8.win32.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), prefix: ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")] };
2488
2506
  }
2489
2507
 
2490
2508
  // builtin/extensions/im-forward/providers/feishu/setup.ts
2491
2509
  function findNpmCli() {
2492
- const dirs = [path10.dirname(process.execPath), ...(process.env.PATH ?? "").split(path10.delimiter)];
2493
- for (const dir of dirs) for (const root of [path10.join(dir, "node_modules", "npm"), path10.resolve(dir, "..", "lib", "node_modules", "npm")]) {
2510
+ const dirs = [path9.dirname(process.execPath), ...(process.env.PATH ?? "").split(path9.delimiter)];
2511
+ for (const dir of dirs) for (const root of [path9.join(dir, "node_modules", "npm"), path9.resolve(dir, "..", "lib", "node_modules", "npm")]) {
2494
2512
  try {
2495
- const pkg = JSON.parse(fs8.readFileSync(path10.join(root, "package.json"), "utf8"));
2496
- const entry = path10.join(root, "bin", "npm-cli.js");
2513
+ const pkg = JSON.parse(fs8.readFileSync(path9.join(root, "package.json"), "utf8"));
2514
+ const entry = path9.join(root, "bin", "npm-cli.js");
2497
2515
  if (pkg.name === "npm" && pkg.bin?.npm === "bin/npm-cli.js" && fs8.statSync(entry).isFile()) return { command: process.execPath, prefix: [entry] };
2498
2516
  } catch {
2499
2517
  }
@@ -3082,18 +3100,18 @@ function connect(binary, profile, targetKind = "chat") {
3082
3100
  return Array.isArray(data?.messages) ? data.messages.flatMap((message) => isRecord(message) && typeof message.message_id === "string" ? [message.message_id] : []) : null;
3083
3101
  },
3084
3102
  async downloadImage(messageId, image, index) {
3085
- const directory = fs9.mkdtempSync(path11.join(os2.tmpdir(), "pie-im-forward-"));
3103
+ const directory = fs9.mkdtempSync(path10.join(os3.tmpdir(), "pie-im-forward-"));
3086
3104
  const cleanup = () => fs9.rmSync(directory, { recursive: true, force: true });
3087
3105
  try {
3088
3106
  const name = `image-${index + 1}.png`;
3089
3107
  const result = await native(binary, profile ? ["im", "+messages-resources-download", "--as", "bot", "--message-id", messageId, "--file-key", image, "--type", "image", "--output", name, "--profile", profile] : ["im", "+messages-resources-download", "--as", "bot", "--message-id", messageId, "--file-key", image, "--type", "image", "--output", name], 3e4, directory, { signal: lifetime.signal });
3090
3108
  if (result.error || !parseLarkCliEnvelope(result.stdout).ok) throw new Error("Image download failed");
3091
- let target = path11.join(directory, name);
3109
+ let target = path10.join(directory, name);
3092
3110
  if (fs9.statSync(target).size > 10 * 1024 * 1024) throw new Error("Image exceeds 10 MiB");
3093
3111
  const detected = readImageFormat(target);
3094
3112
  if (detected.ext === ".bin") throw new Error("Unsupported image format");
3095
3113
  if (detected.ext !== ".png") {
3096
- const corrected = path11.join(directory, `image-${index + 1}${detected.ext}`);
3114
+ const corrected = path10.join(directory, `image-${index + 1}${detected.ext}`);
3097
3115
  fs9.renameSync(target, corrected);
3098
3116
  target = corrected;
3099
3117
  }
@@ -24708,7 +24708,13 @@ function toPrefixedName(server, tool) {
24708
24708
  return `${sanitizeName(server)}_${sanitizeName(tool)}`;
24709
24709
  }
24710
24710
  function buildEnv(definition) {
24711
- const base = definition.inheritEnv ? { ...process.env } : { ...getDefaultEnvironment() };
24711
+ const source = definition.inheritEnv ? { ...process.env } : { ...getDefaultEnvironment() };
24712
+ const { PIE_DEFAULT_PROVIDER, PIE_DEFAULT_MODEL, PIE_MANAGER_BOOTSTRAP, PIE_PROC_CURATED_NAME, ...rest } = source;
24713
+ void PIE_DEFAULT_PROVIDER;
24714
+ void PIE_DEFAULT_MODEL;
24715
+ void PIE_MANAGER_BOOTSTRAP;
24716
+ void PIE_PROC_CURATED_NAME;
24717
+ const base = rest;
24712
24718
  const merged = { ...base, ...definition.env };
24713
24719
  const clean = {};
24714
24720
  for (const [key, value] of Object.entries(merged)) {
@@ -3,7 +3,7 @@ import {
3
3
  distillWorkerLogPath,
4
4
  readDistillWorkerLog,
5
5
  spawnDistillWorker
6
- } from "../../../chunks/chunk-PFXSA2LK.js";
6
+ } from "../../../chunks/chunk-BJ4XN5VX.js";
7
7
  import {
8
8
  getConfigDir,
9
9
  getSettingsPath
@@ -19,10 +19,10 @@ import {
19
19
  saveAttestedEntry,
20
20
  searchMemory,
21
21
  todayKey
22
- } from "../../../chunks/chunk-PC6HUZAD.js";
23
- import "../../../chunks/chunk-BK36Y35W.js";
24
- import "../../../chunks/chunk-NCP264ZE.js";
25
- import "../../../chunks/chunk-JQRZLVPY.js";
22
+ } from "../../../chunks/chunk-WZLO5V2X.js";
23
+ import "../../../chunks/chunk-XMOWWL4B.js";
24
+ import "../../../chunks/chunk-B4N5LJMD.js";
25
+ import "../../../chunks/chunk-6JEYRAQM.js";
26
26
  import {
27
27
  Type
28
28
  } from "../../../chunks/chunk-XXGYUYXI.js";
@@ -25,7 +25,7 @@ import {
25
25
  takeDispatchFrame,
26
26
  wrapInboundText,
27
27
  wrappedMessageMarker
28
- } from "../../../chunks/chunk-H5G55G3R.js";
28
+ } from "../../../chunks/chunk-N3BWFAMZ.js";
29
29
  import {
30
30
  Type
31
31
  } from "../../../chunks/chunk-XXGYUYXI.js";
@@ -458,8 +458,9 @@ function pieProc(ctx) {
458
458
  const logFile = fs.openSync(path.join(logDir(), `${params.name}.jsonl`), "a");
459
459
  const args = params.kind === "resident" ? [...loaderArgs(), entry, "--json-events", "--idle", "--session-id", sessionId] : [...loaderArgs(), entry, "--session-id", sessionId];
460
460
  const inheritedIpcRoot = path.resolve(expandTilde(process.env.PIE_IPC_CONFIG_DIR ?? configDirRoot()));
461
+ const { PIE_DEFAULT_PROVIDER: _p, PIE_DEFAULT_MODEL: _m, PIE_MANAGER_BOOTSTRAP: _b, PIE_PROC_CURATED_NAME: _c, ...inheritedEnv } = process.env;
461
462
  const childEnv = {
462
- ...process.env,
463
+ ...inheritedEnv,
463
464
  PIE_CODING_AGENT_DIR: pieDir,
464
465
  PIE_IPC_CONFIG_DIR: inheritedIpcRoot,
465
466
  PIE_IPC_DISPLAY_NAME: params.kind === "resident" ? params.name : process.env.PIE_IPC_DISPLAY_NAME
@@ -576,7 +577,7 @@ function pieProc(ctx) {
576
577
  ctx.registerTool({
577
578
  name: "pie_proc",
578
579
  label: "Pie worker processes",
579
- description: "Controlled lifecycle for pie worker processes (concierge plan): spawn creates a bounded-shape pie worker \u2014 either a RESIDENT host (--json-events --idle, peer-addressable by worker name via ipc_send_notify) or a ONE-SHOT run (pie -p <task>, process exit is the completion). cwd must resolve inside the allowCwd roots configured in ~/.pie/pie-proc.json (symlinks resolved). Optional idle TTL retires idle RESIDENTS automatically (identity-verified; activity-aware). imForward accepts identity fields ONLY \u2014 executable selection is operator config. kill stops a worker gracefully (SIGTERM, bounded identity-verified escalation) and removes its generation; list shows workers with pid/session/cwd/liveness/last-active. Never use raw shell to start pie processes \u2014 this tool owns the audit trail, caps, and cleanup.",
580
+ description: "Controlled lifecycle for pie worker processes (manager plan): spawn creates a bounded-shape pie worker \u2014 either a RESIDENT host (--json-events --idle, peer-addressable by worker name via ipc_send_notify) or a ONE-SHOT run (pie -p <task>, process exit is the completion). cwd must resolve inside the allowCwd roots configured in ~/.pie/pie-proc.json (symlinks resolved). Optional idle TTL retires idle RESIDENTS automatically (identity-verified; activity-aware). imForward accepts identity fields ONLY \u2014 executable selection is operator config. kill stops a worker gracefully (SIGTERM, bounded identity-verified escalation) and removes its generation; list shows workers with pid/session/cwd/liveness/last-active. Never use raw shell to start pie processes \u2014 this tool owns the audit trail, caps, and cleanup.",
580
581
  parameters: Type.Object({
581
582
  action: Type.Union([Type.Literal("spawn"), Type.Literal("kill"), Type.Literal("list")], { description: "spawn | kill | list" }),
582
583
  name: Type.Optional(Type.String({ description: "Worker name ([a-z0-9-_], unique among alive workers)" })),