@cydm/pie 4.4.0 → 4.4.2

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 (41) 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 +2 -2
  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 +4 -3
  7. package/dist/builtin/extensions/im-forward/index.js +24 -5
  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 +11 -9
  11. package/dist/builtin/extensions/pie-ipc/index.js +270 -344
  12. package/dist/builtin/extensions/pie-proc/index.js +70 -7
  13. package/dist/builtin/extensions/plan-mode/index.js +6 -6
  14. package/dist/builtin/extensions/subagent/index.js +11 -9
  15. package/dist/builtin/extensions/todo/index.js +6 -6
  16. package/dist/builtin/skills/computer-use-axi/computer-use-axi-broker.js +1 -1
  17. package/dist/builtin/skills/computer-use-axi/computer-use-axi-runtime.js +1 -1
  18. package/dist/chunks/{auth-storage-3EGM3VTK.js → auth-storage-RABPRJ6T.js} +3 -3
  19. package/dist/chunks/chunk-7KLWHWZD.js +164 -0
  20. package/dist/chunks/{chunk-I7PBXG5Q.js → chunk-7LTQLJJF.js} +9 -6
  21. package/dist/chunks/{chunk-XXGYUYXI.js → chunk-BPSCGGVF.js} +1 -1
  22. package/dist/chunks/{chunk-VHKMWOG3.js → chunk-EQOI6RZV.js} +5 -3
  23. package/dist/chunks/{chunk-B4N5LJMD.js → chunk-IPLMGAML.js} +1 -1
  24. package/dist/chunks/{chunk-GY47MKCJ.js → chunk-IZDNZW3S.js} +8 -8
  25. package/dist/chunks/{chunk-AKXEZH7K.js → chunk-OFLKAWI4.js} +0 -7
  26. package/dist/chunks/{chunk-6DNYGVZP.js → chunk-OV7SLSHR.js} +4 -2
  27. package/dist/chunks/{chunk-6JEYRAQM.js → chunk-R7VO46EK.js} +2 -2
  28. package/dist/chunks/{chunk-LZQXQOPJ.js → chunk-RZGYXAJU.js} +12 -1
  29. package/dist/chunks/{chunk-ILUHTKF3.js → chunk-UCKOXAME.js} +61 -11
  30. package/dist/chunks/{chunk-XMOWWL4B.js → chunk-XO3NM7BB.js} +3 -3
  31. package/dist/chunks/{chunk-N5B5IGJ6.js → chunk-YNTIOWCD.js} +5 -5
  32. package/dist/chunks/{config-74AUVDLT.js → config-HF2PDLN5.js} +8 -4
  33. package/dist/chunks/{manager-cli-4Z6RZ7F4.js → manager-cli-BYCF4RKN.js} +5 -3
  34. package/dist/chunks/{model-registry-NKE3BRSZ.js → model-registry-7FNIUYPF.js} +5 -5
  35. package/dist/chunks/{src-V2M7FLWY.js → src-A5YI46OD.js} +6 -6
  36. package/dist/chunks/{src-4EQ7PBEI.js → src-OA3TP6DS.js} +5 -5
  37. package/dist/chunks/{src-46R5ZFOU.js → src-OVWRBWKU.js} +4 -4
  38. package/dist/chunks/{src-BHIH4VLE.js → src-TF2RAGRU.js} +3 -3
  39. package/dist/chunks/{test-stream-FC6ZRENI.js → test-stream-7YZDGBPO.js} +3 -3
  40. package/dist/cli.js +231 -49
  41. package/package.json +2 -2
@@ -2,10 +2,14 @@ import { createRequire as __createRequire } from "node:module"; const require =
2
2
  import {
3
3
  readProcessCommandLine
4
4
  } from "../../../chunks/chunk-X6LBWHK3.js";
5
+ import {
6
+ liveSessionHolder
7
+ } from "../../../chunks/chunk-7KLWHWZD.js";
8
+ import "../../../chunks/chunk-UCKOXAME.js";
5
9
  import {
6
10
  Type
7
- } from "../../../chunks/chunk-XXGYUYXI.js";
8
- import "../../../chunks/chunk-LZQXQOPJ.js";
11
+ } from "../../../chunks/chunk-BPSCGGVF.js";
12
+ import "../../../chunks/chunk-RZGYXAJU.js";
9
13
 
10
14
  // builtin/extensions/pie-proc/index.ts
11
15
  import { spawn } from "node:child_process";
@@ -15,6 +19,20 @@ import * as fs from "node:fs";
15
19
  import * as os from "node:os";
16
20
  import * as path from "node:path";
17
21
  var require_ = createRequire(import.meta.url);
22
+ function resolveOperatorSessionsDir() {
23
+ try {
24
+ const { getSessionsDir } = require_("../../../src/config.js");
25
+ return getSessionsDir();
26
+ } catch {
27
+ const override = process.env.PIE_SESSIONS_DIR;
28
+ if (override !== void 0 && override !== "") {
29
+ if (override === "~") return path.join(os.homedir(), ".pie", "sessions");
30
+ if (override.startsWith("~/")) return path.join(os.homedir(), override.slice(2));
31
+ if (path.isAbsolute(override)) return override;
32
+ }
33
+ return path.join(os.homedir(), ".pie", "sessions");
34
+ }
35
+ }
18
36
  var DEFAULT_CONFIG = { allowCwd: [], maxWorkers: 5, killGraceMs: 15e3, defaultTtlMs: 0 };
19
37
  var IM_FORWARD_ALLOWED_KEYS = /* @__PURE__ */ new Set(["enabled", "provider", "chatId", "openId", "allowUsers", "retryBackoffMs", "larkCliProfile"]);
20
38
  var ONESHOT_TASK_ENV = "PIE_PROC_ONESHOT_TASK";
@@ -160,9 +178,10 @@ function workerLiveness(record) {
160
178
  } catch {
161
179
  return "dead";
162
180
  }
181
+ const marker = record.launchToken ?? record.sessionId;
163
182
  const cmd = readProcessCommandLine(record.pid);
164
183
  if (cmd === void 0) return "unknown";
165
- return cmd.includes(record.sessionId) ? "alive" : "dead";
184
+ return cmd.includes(marker) ? "alive" : "dead";
166
185
  }
167
186
  function canonicalDir(dir) {
168
187
  const resolved = path.resolve(expandTilde(dir));
@@ -397,11 +416,36 @@ function pieProc(ctx) {
397
416
  if (params.kind === "oneshot" && params.task.startsWith("-")) throw new Error(`oneshot task must not start with "-" (got "${params.task.slice(0, 20)}\u2026")`);
398
417
  if (params.kind === "oneshot" && params.imForward) throw new Error("imForward applies to resident workers only");
399
418
  if (params.kind !== "resident" && params.ttlMs !== void 0) throw new Error("ttlMs applies to resident workers only");
419
+ if (params.kind !== "resident" && params.resumeSessionId) throw new Error("resumeSessionId applies to resident workers only");
400
420
  const canonicalCwd = cwdAllowedOrThrow(params.cwd, currentConfig().allowCwd);
401
421
  const entry = cliEntry();
402
422
  if (!entry) throw new Error("cannot resolve a trusted pie entry point (refusing to spawn)");
423
+ let resumeSessionId;
424
+ if (params.resumeSessionId) {
425
+ if (!/^[A-Za-z0-9][A-Za-z0-9-_]{5,63}$/.test(params.resumeSessionId)) throw new Error(`invalid resumeSessionId "${params.resumeSessionId}"`);
426
+ const globalSessionsDir = resolveOperatorSessionsDir();
427
+ const headPath = path.join(globalSessionsDir, params.resumeSessionId, "head.json");
428
+ let recordedCwd;
429
+ try {
430
+ const head = JSON.parse(fs.readFileSync(headPath, "utf8"));
431
+ recordedCwd = head.metadata?.cwd;
432
+ } catch {
433
+ throw new Error(`resumeSessionId "${params.resumeSessionId}" not found in the global session store (${globalSessionsDir})`);
434
+ }
435
+ if (typeof recordedCwd !== "string" || !recordedCwd) throw new Error(`session "${params.resumeSessionId}" has no recorded cwd; resume requires one`);
436
+ let canonicalRecorded = recordedCwd;
437
+ try {
438
+ canonicalRecorded = fs.realpathSync(recordedCwd);
439
+ } catch {
440
+ }
441
+ if (canonicalRecorded !== canonicalCwd) throw new Error(`resume cwd mismatch: session recorded "${recordedCwd}" but spawn cwd is "${params.cwd}" \u2014 resume in the session's own directory`);
442
+ const holder = liveSessionHolder(params.resumeSessionId);
443
+ if (holder) throw new Error(`session "${params.resumeSessionId}" is owned by a live host (pid ${holder.pid} ${holder.holder}); close it or resume another session`);
444
+ resumeSessionId = params.resumeSessionId;
445
+ }
403
446
  const generation = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
404
- const sessionId = `pie-proc-${params.name}-${generation}`;
447
+ const launchToken = `pie-proc-${params.name}-${generation}`;
448
+ const sessionId = resumeSessionId ?? launchToken;
405
449
  const imForward = sanitizeImForward(params.imForward);
406
450
  casRegistry((snap) => {
407
451
  const current = snap.workers;
@@ -437,6 +481,8 @@ function pieProc(ctx) {
437
481
  const reservation = {
438
482
  name: params.name,
439
483
  sessionId,
484
+ launchToken,
485
+ ...resumeSessionId ? { resumedFrom: resumeSessionId } : {},
440
486
  generation,
441
487
  pid: 0,
442
488
  cwd: "",
@@ -483,7 +529,19 @@ function pieProc(ctx) {
483
529
  }
484
530
  fs.mkdirSync(logDir(), { recursive: true });
485
531
  const logFile = fs.openSync(path.join(logDir(), `${params.name}.jsonl`), "a");
486
- const args = params.kind === "resident" ? [...loaderArgs(), entry, "--json-events", "--idle", "--session-id", sessionId] : [...loaderArgs(), entry, "--session-id", sessionId];
532
+ const args = params.kind === "resident" ? [
533
+ ...loaderArgs(),
534
+ entry,
535
+ "--json-events",
536
+ "--idle",
537
+ "--session-id",
538
+ sessionId,
539
+ // 4.4.1 resume: --resume-required makes a failed load a HARD exit
540
+ // (never silently mint a same-id empty session); --worker-token
541
+ // keeps argv liveness matching on the per-launch token even when
542
+ // --session-id carries a reusable business session id.
543
+ ...resumeSessionId ? ["--resume-required", "--worker-token", launchToken] : []
544
+ ] : [...loaderArgs(), entry, "--session-id", sessionId];
487
545
  const inheritedIpcRoot = path.resolve(expandTilde(process.env.PIE_IPC_CONFIG_DIR ?? configDirRoot()));
488
546
  const { PIE_DEFAULT_PROVIDER: _p, PIE_DEFAULT_MODEL: _m, PIE_MANAGER_BOOTSTRAP: _b, PIE_PROC_CURATED_NAME: _c, ...inheritedEnv } = process.env;
489
547
  const childEnv = {
@@ -493,6 +551,7 @@ function pieProc(ctx) {
493
551
  PIE_IPC_DISPLAY_NAME: params.kind === "resident" ? params.name : process.env.PIE_IPC_DISPLAY_NAME
494
552
  };
495
553
  if (params.kind === "oneshot") childEnv[ONESHOT_TASK_ENV] = params.task ?? "";
554
+ if (resumeSessionId) childEnv.PIE_SESSIONS_DIR = resolveOperatorSessionsDir();
496
555
  try {
497
556
  child = spawn(process.execPath, args, {
498
557
  cwd: canonicalCwd,
@@ -517,6 +576,8 @@ function pieProc(ctx) {
517
576
  const record = {
518
577
  name: params.name,
519
578
  sessionId,
579
+ launchToken,
580
+ ...resumeSessionId ? { resumedFrom: resumeSessionId } : {},
520
581
  generation,
521
582
  pid: child.pid,
522
583
  cwd: canonicalCwd,
@@ -618,7 +679,8 @@ function pieProc(ctx) {
618
679
  task: Type.Optional(Type.String({ description: "oneshot: the task prompt (non-empty, must not start with '-')" })),
619
680
  ttlMs: Type.Optional(Type.Number({ description: "spawn (resident only): idle TTL in ms (0 = never reap)", minimum: 0, maximum: 864e5 })),
620
681
  force: Type.Optional(Type.Boolean({ description: "kill: skip graceful SIGTERM" })),
621
- imForward: Type.Optional(Type.Union([Type.Literal("inherit"), Type.Record(Type.String(), Type.Unknown())], { description: "spawn (resident only): IM identity binding \u2014 'inherit' copies the operator's user-layer IM identity verbatim (recommended: open_ids are per-app, hand copies break silently), or an object of identity fields only (enabled/provider/chatId/openId/allowUsers/larkCliProfile/inherit)" }))
682
+ imForward: Type.Optional(Type.Union([Type.Literal("inherit"), Type.Record(Type.String(), Type.Unknown())], { description: "spawn (resident only): IM identity binding \u2014 'inherit' copies the operator's user-layer IM identity verbatim (recommended: open_ids are per-app, hand copies break silently), or an object of identity fields only (enabled/provider/chatId/openId/allowUsers/larkCliProfile/inherit)" })),
683
+ resumeSessionId: Type.Optional(Type.String({ description: "spawn (resident only): RESUME an existing business session instead of creating a new one. The session must exist in the global store (~/.pie/sessions), its recorded cwd must equal cwd, and no live host may own it. The worker keeps the session's context, IM topic anchors and model; its own config stays isolated. Use when the user wants an old session to CONTINUE its work (e.g. '\u8BA9 TBD \u7684\u90A3\u4E2A\u4F1A\u8BDD\u63A5\u7740\u67E5'), never for fresh tasks." }))
622
684
  }),
623
685
  risk: { riskClass: "process_lifecycle", requiresPermission: true, externalSideEffect: true, readsNetwork: false, writesNetwork: false, concurrencySafe: false },
624
686
  renderHint: { summary: (args) => `${String(args.action)}${args.name ? ` ${String(args.name)}` : ""}` },
@@ -652,7 +714,8 @@ function pieProc(ctx) {
652
714
  kind: args.kind ?? "resident",
653
715
  ttlMs: typeof args.ttlMs === "number" ? args.ttlMs : void 0,
654
716
  task: args.task,
655
- imForward: args.imForward
717
+ imForward: args.imForward,
718
+ resumeSessionId: args.resumeSessionId
656
719
  });
657
720
  }
658
721
  if (action === "kill") {
@@ -6,14 +6,14 @@ import {
6
6
  createPlanCapability,
7
7
  markCompletedPlanSteps,
8
8
  restoreExecutionState
9
- } from "../../../chunks/chunk-N5B5IGJ6.js";
10
- import "../../../chunks/chunk-XMOWWL4B.js";
11
- import "../../../chunks/chunk-B4N5LJMD.js";
12
- import "../../../chunks/chunk-6JEYRAQM.js";
9
+ } from "../../../chunks/chunk-YNTIOWCD.js";
10
+ import "../../../chunks/chunk-XO3NM7BB.js";
11
+ import "../../../chunks/chunk-IPLMGAML.js";
12
+ import "../../../chunks/chunk-R7VO46EK.js";
13
13
  import {
14
14
  Type
15
- } from "../../../chunks/chunk-XXGYUYXI.js";
16
- import "../../../chunks/chunk-LZQXQOPJ.js";
15
+ } from "../../../chunks/chunk-BPSCGGVF.js";
16
+ import "../../../chunks/chunk-RZGYXAJU.js";
17
17
 
18
18
  // builtin/extensions/plan-mode/index.ts
19
19
  import { randomUUID } from "node:crypto";
@@ -5,21 +5,22 @@ import {
5
5
  createCliRetryPolicy,
6
6
  formatTransportLifecycle,
7
7
  logTransportLifecycle
8
- } from "../../../chunks/chunk-I7PBXG5Q.js";
8
+ } from "../../../chunks/chunk-7LTQLJJF.js";
9
9
  import {
10
- getConfigDir
11
- } from "../../../chunks/chunk-ILUHTKF3.js";
10
+ getConfigDir,
11
+ init_config
12
+ } from "../../../chunks/chunk-UCKOXAME.js";
12
13
  import {
13
14
  SUBAGENT_SESSION_RECORD_VERSION,
14
15
  createPolicyEnforcedTools,
15
16
  createSharedFileSystemTools,
16
17
  createSubagentCapability
17
- } from "../../../chunks/chunk-N5B5IGJ6.js";
18
- import "../../../chunks/chunk-XMOWWL4B.js";
19
- import "../../../chunks/chunk-B4N5LJMD.js";
20
- import "../../../chunks/chunk-6JEYRAQM.js";
21
- import "../../../chunks/chunk-XXGYUYXI.js";
22
- import "../../../chunks/chunk-LZQXQOPJ.js";
18
+ } from "../../../chunks/chunk-YNTIOWCD.js";
19
+ import "../../../chunks/chunk-XO3NM7BB.js";
20
+ import "../../../chunks/chunk-IPLMGAML.js";
21
+ import "../../../chunks/chunk-R7VO46EK.js";
22
+ import "../../../chunks/chunk-BPSCGGVF.js";
23
+ import "../../../chunks/chunk-RZGYXAJU.js";
23
24
 
24
25
  // src/files/subagent-session-store.ts
25
26
  import { execFileSync } from "node:child_process";
@@ -380,6 +381,7 @@ function createSubagentSessionStore(sessionsDir, log, deps) {
380
381
  }
381
382
 
382
383
  // builtin/extensions/subagent/index.ts
384
+ init_config();
383
385
  import * as path2 from "path";
384
386
  function preserveModelResolution(r) {
385
387
  return r === void 0 ? void 0 : { ...r, model: r.model };
@@ -8,12 +8,12 @@ import {
8
8
  executeManageTodoList,
9
9
  executionStateToTodos,
10
10
  restoreExecutionState
11
- } from "../../../chunks/chunk-N5B5IGJ6.js";
12
- import "../../../chunks/chunk-XMOWWL4B.js";
13
- import "../../../chunks/chunk-B4N5LJMD.js";
14
- import "../../../chunks/chunk-6JEYRAQM.js";
15
- import "../../../chunks/chunk-XXGYUYXI.js";
16
- import "../../../chunks/chunk-LZQXQOPJ.js";
11
+ } from "../../../chunks/chunk-YNTIOWCD.js";
12
+ import "../../../chunks/chunk-XO3NM7BB.js";
13
+ import "../../../chunks/chunk-IPLMGAML.js";
14
+ import "../../../chunks/chunk-R7VO46EK.js";
15
+ import "../../../chunks/chunk-BPSCGGVF.js";
16
+ import "../../../chunks/chunk-RZGYXAJU.js";
17
17
 
18
18
  // builtin/extensions/todo/index.ts
19
19
  var EXECUTION_METADATA_KEY = "executionState";
@@ -4366,7 +4366,7 @@ import path from "node:path";
4366
4366
  // src/config.ts
4367
4367
  import { existsSync, mkdirSync, readFileSync, renameSync } from "fs";
4368
4368
  import { homedir } from "os";
4369
- import { dirname, join } from "path";
4369
+ import { dirname, isAbsolute, join } from "path";
4370
4370
  import { fileURLToPath } from "url";
4371
4371
  var __filename = fileURLToPath(import.meta.url);
4372
4372
  var __dirname = dirname(__filename);
@@ -41,7 +41,7 @@ import path from "node:path";
41
41
  // src/config.ts
42
42
  import { existsSync, mkdirSync, readFileSync, renameSync } from "fs";
43
43
  import { homedir } from "os";
44
- import { dirname, join } from "path";
44
+ import { dirname, isAbsolute, join } from "path";
45
45
  import { fileURLToPath } from "url";
46
46
  var __filename = fileURLToPath(import.meta.url);
47
47
  var __dirname = dirname(__filename);
@@ -3,9 +3,9 @@ import {
3
3
  AuthStorage,
4
4
  FileAuthStorageBackend,
5
5
  InMemoryAuthStorageBackend
6
- } from "./chunk-6DNYGVZP.js";
7
- import "./chunk-ILUHTKF3.js";
8
- import "./chunk-LZQXQOPJ.js";
6
+ } from "./chunk-OV7SLSHR.js";
7
+ import "./chunk-UCKOXAME.js";
8
+ import "./chunk-RZGYXAJU.js";
9
9
  export {
10
10
  AuthStorage,
11
11
  FileAuthStorageBackend,
@@ -0,0 +1,164 @@
1
+ import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
+ import {
3
+ config_exports,
4
+ init_config
5
+ } from "./chunk-UCKOXAME.js";
6
+ import {
7
+ __toCommonJS
8
+ } from "./chunk-RZGYXAJU.js";
9
+
10
+ // src/app/session-ownership.ts
11
+ import * as fs from "node:fs";
12
+ import * as os from "node:os";
13
+ import * as path from "node:path";
14
+ var STALE_MS = 2e4;
15
+ function sessionOwnersRoot() {
16
+ const store = process.env.PIE_SESSIONS_STORE_ROOT_FOR_OWNERS ?? sessionStoreRoot();
17
+ return path.join(store, "session-owners");
18
+ }
19
+ function sessionStoreRoot() {
20
+ try {
21
+ const { getSessionsDir } = (init_config(), __toCommonJS(config_exports));
22
+ return path.dirname(getSessionsDir());
23
+ } catch {
24
+ const storeOverride = process.env.PIE_SESSIONS_DIR;
25
+ if (storeOverride !== void 0 && storeOverride !== "") {
26
+ const expanded = storeOverride === "~" ? path.join(os.homedir(), "sessions") : storeOverride.startsWith("~/") ? path.join(os.homedir(), storeOverride.slice(2)) : storeOverride;
27
+ if (path.isAbsolute(expanded)) return path.dirname(expanded);
28
+ }
29
+ const agentDir = process.env.PIE_CODING_AGENT_DIR;
30
+ if (agentDir !== void 0 && agentDir !== "") {
31
+ if (agentDir === "~") return path.join(os.homedir(), ".pie");
32
+ if (agentDir.startsWith("~/")) return path.join(os.homedir(), agentDir.slice(2));
33
+ if (path.isAbsolute(agentDir)) return agentDir;
34
+ }
35
+ return path.join(os.homedir(), ".pie");
36
+ }
37
+ }
38
+ function lockPath(sessionId) {
39
+ const safe = sessionId.replace(/[^a-zA-Z0-9._-]/g, "_");
40
+ return path.join(sessionOwnersRoot(), `${safe}.lock`);
41
+ }
42
+ function pidAlive(pid) {
43
+ if (!Number.isInteger(pid) || pid <= 0) return false;
44
+ try {
45
+ process.kill(pid, 0);
46
+ return true;
47
+ } catch (error) {
48
+ return error.code === "EPERM";
49
+ }
50
+ }
51
+ function readLock(sessionId) {
52
+ try {
53
+ const parsed = JSON.parse(fs.readFileSync(lockPath(sessionId), "utf8"));
54
+ if (typeof parsed.pid === "number" && typeof parsed.holder === "string" && typeof parsed.heartbeatAt === "number" && typeof parsed.sessionId === "string") {
55
+ return { pid: parsed.pid, holder: parsed.holder, heartbeatAt: parsed.heartbeatAt, sessionId: parsed.sessionId };
56
+ }
57
+ return void 0;
58
+ } catch {
59
+ return void 0;
60
+ }
61
+ }
62
+ function sessionOwnerAlive(sessionId, now = Date.now()) {
63
+ const info = readLock(sessionId);
64
+ if (!info) return void 0;
65
+ if (!pidAlive(info.pid)) return void 0;
66
+ if (now - info.heartbeatAt >= STALE_MS) return void 0;
67
+ return info;
68
+ }
69
+ function claimSessionOwnership(sessionId, holder, onLost) {
70
+ const target = lockPath(sessionId);
71
+ const writeMine = () => {
72
+ fs.mkdirSync(path.dirname(target), { recursive: true, mode: 448 });
73
+ fs.writeFileSync(target, `${JSON.stringify({ pid: process.pid, holder, heartbeatAt: Date.now(), sessionId })}
74
+ `);
75
+ };
76
+ let existing;
77
+ try {
78
+ existing = readLock(sessionId);
79
+ } catch {
80
+ return { holder: { pid: -1, holder: "(unreadable lock)", heartbeatAt: Date.now(), sessionId } };
81
+ }
82
+ if (existing && pidAlive(existing.pid) && Date.now() - existing.heartbeatAt < STALE_MS) {
83
+ return { holder: existing };
84
+ }
85
+ if (existing) {
86
+ try {
87
+ fs.rmSync(target, { force: true });
88
+ } catch {
89
+ }
90
+ }
91
+ const tmp = `${target}.${process.pid}.${Date.now()}.tmp`;
92
+ try {
93
+ fs.mkdirSync(path.dirname(target), { recursive: true, mode: 448 });
94
+ fs.writeFileSync(tmp, `${JSON.stringify({ pid: process.pid, holder, heartbeatAt: Date.now(), sessionId })}
95
+ `);
96
+ try {
97
+ fs.linkSync(tmp, target);
98
+ fs.rmSync(tmp, { force: true });
99
+ } catch (error) {
100
+ fs.rmSync(tmp, { force: true });
101
+ if (error.code !== "EEXIST") throw error;
102
+ const winner = readLock(sessionId);
103
+ return { holder: winner ?? { pid: -1, holder: "(concurrent claim)", heartbeatAt: Date.now(), sessionId } };
104
+ }
105
+ const verified = readLock(sessionId);
106
+ if (!verified || verified.pid !== process.pid) {
107
+ return { holder: verified ?? { pid: -1, holder: "(takeover race lost)", heartbeatAt: Date.now(), sessionId } };
108
+ }
109
+ } catch {
110
+ return { holder: { pid: -1, holder: "(lock IO failed)", heartbeatAt: Date.now(), sessionId } };
111
+ }
112
+ let released = false;
113
+ let lost = false;
114
+ const heartbeatTimer = setInterval(() => {
115
+ if (released) return;
116
+ try {
117
+ const current = readLock(sessionId);
118
+ if (current && current.pid !== process.pid) {
119
+ if (!lost) {
120
+ lost = true;
121
+ try {
122
+ onLost?.("takeover");
123
+ } catch {
124
+ }
125
+ }
126
+ released = true;
127
+ clearInterval(heartbeatTimer);
128
+ return;
129
+ }
130
+ fs.writeFileSync(target, `${JSON.stringify({ pid: process.pid, holder, heartbeatAt: Date.now(), sessionId })}
131
+ `);
132
+ } catch {
133
+ }
134
+ }, 5e3);
135
+ heartbeatTimer.unref();
136
+ return {
137
+ handle: {
138
+ heartbeat: () => {
139
+ try {
140
+ writeMine();
141
+ } catch {
142
+ }
143
+ },
144
+ release: () => {
145
+ if (released) return;
146
+ released = true;
147
+ clearInterval(heartbeatTimer);
148
+ try {
149
+ const current = readLock(sessionId);
150
+ if (current && current.pid === process.pid) fs.rmSync(target, { force: true });
151
+ } catch {
152
+ }
153
+ }
154
+ }
155
+ };
156
+ }
157
+ function liveSessionHolder(sessionId) {
158
+ return sessionOwnerAlive(sessionId);
159
+ }
160
+
161
+ export {
162
+ claimSessionOwnership,
163
+ liveSessionHolder
164
+ };
@@ -1,8 +1,9 @@
1
1
  import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
2
  import {
3
3
  getBuiltinDir,
4
- getConfigDir
5
- } from "./chunk-ILUHTKF3.js";
4
+ getConfigDir,
5
+ init_config
6
+ } from "./chunk-UCKOXAME.js";
6
7
  import {
7
8
  classifyShellCommand,
8
9
  createSharedWebFetchTool,
@@ -10,18 +11,18 @@ import {
10
11
  createSharedWebSearchTool,
11
12
  defaultShellKindForPlatform,
12
13
  interpretShellExit
13
- } from "./chunk-N5B5IGJ6.js";
14
+ } from "./chunk-YNTIOWCD.js";
14
15
  import {
15
16
  requestInteraction
16
- } from "./chunk-XMOWWL4B.js";
17
+ } from "./chunk-XO3NM7BB.js";
17
18
  import {
18
19
  EMPTY_ASSISTANT_CONTENT_ERROR,
19
20
  OPENAI_COMPAT_PROTOCOL_ERROR_CODE,
20
21
  getLogger
21
- } from "./chunk-6JEYRAQM.js";
22
+ } from "./chunk-R7VO46EK.js";
22
23
  import {
23
24
  Type
24
- } from "./chunk-XXGYUYXI.js";
25
+ } from "./chunk-BPSCGGVF.js";
25
26
 
26
27
  // src/runtime/retry-policy.ts
27
28
  var TRANSIENT_NETWORK_ERROR_PATTERN = /sse stream aborted|sse stream closed before end|sse stream ended before response completed|responses stream ended without a terminal event|(?:read\s+)?ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|ECONNREFUSED|(?:read\s+|write\s+)?EPIPE|socket hang up|request timeout|websocket upgrade refused|websocket handshake|websocket connection failed|websocket transport failed|connection closed before opening|client network socket disconnected before secure TLS connection was established|connection.?error|connection.?refused|other side closed|fetch failed|upstream.?connect|reset before headers|terminated/i;
@@ -1411,6 +1412,7 @@ ${commandNonzeroHint}`;
1411
1412
  }
1412
1413
 
1413
1414
  // src/capabilities/rendered-page-reader.ts
1415
+ init_config();
1414
1416
  import { spawn as spawn2 } from "node:child_process";
1415
1417
  import { createRequire } from "node:module";
1416
1418
  import * as fs from "node:fs";
@@ -1615,6 +1617,7 @@ function createCliWebResearchHealthStore(configDir) {
1615
1617
  }
1616
1618
 
1617
1619
  // src/capabilities/index.ts
1620
+ init_config();
1618
1621
  function createCliHostCapabilities(cwd, options = {}) {
1619
1622
  const bashTool = createBashTool(cwd, options.getBashEnv ? { getEnv: options.getBashEnv } : void 0);
1620
1623
  const healthStore = createCliWebResearchHealthStore(options.configDir ?? getConfigDir());
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
2
  import {
3
3
  __export
4
- } from "./chunk-LZQXQOPJ.js";
4
+ } from "./chunk-RZGYXAJU.js";
5
5
 
6
6
  // ../../node_modules/@sinclair/typebox/build/esm/value/guard/guard.mjs
7
7
  function IsAsyncIterator(value) {
@@ -1,15 +1,17 @@
1
1
  import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
2
  import {
3
- getConfigDir
4
- } from "./chunk-ILUHTKF3.js";
3
+ getConfigDir,
4
+ init_config
5
+ } from "./chunk-UCKOXAME.js";
5
6
  import {
6
7
  MODEL_CLASS_FALLBACK_ORDER,
7
8
  modelSupportsToolPurpose,
8
9
  requiredCapabilityForToolPurpose,
9
10
  sortToolModelCandidatesByCapability
10
- } from "./chunk-6JEYRAQM.js";
11
+ } from "./chunk-R7VO46EK.js";
11
12
 
12
13
  // src/core/model-registry.ts
14
+ init_config();
13
15
  import * as fs from "fs";
14
16
  import * as path from "path";
15
17
  import { createHash, createHmac, randomBytes } from "node:crypto";
@@ -4,7 +4,7 @@ import {
4
4
  disposeModelTransports,
5
5
  streamSimple,
6
6
  validateToolArguments
7
- } from "./chunk-6JEYRAQM.js";
7
+ } from "./chunk-R7VO46EK.js";
8
8
 
9
9
  // ../../packages/agent-core/src/failure.ts
10
10
  function getAgentFailureMetadata(error) {
@@ -147,7 +147,7 @@ function pathContains(parent, child) {
147
147
  }
148
148
  async function readExcludeCwds() {
149
149
  try {
150
- const { getSettingsPath } = await import("./config-74AUVDLT.js");
150
+ const { getSettingsPath } = await import("./config-HF2PDLN5.js");
151
151
  const raw = JSON.parse(fs.readFileSync(getSettingsPath(), "utf8"));
152
152
  const list = raw?.extensions?.memory?.excludeCwds;
153
153
  if (!Array.isArray(list)) return [];
@@ -171,11 +171,11 @@ async function runDistillWorkerMain(memoryRoot, date, noExit = false) {
171
171
  let result;
172
172
  let ledger;
173
173
  try {
174
- const { ModelRegistry } = await import("./model-registry-NKE3BRSZ.js");
175
- const { AuthStorage } = await import("./auth-storage-3EGM3VTK.js");
176
- const { getSessionsDir } = await import("./config-74AUVDLT.js");
177
- const { FileSessionStore } = await import("./src-4EQ7PBEI.js");
178
- const { MemoryStore, runDistillation } = await import("./src-V2M7FLWY.js");
174
+ const { ModelRegistry } = await import("./model-registry-7FNIUYPF.js");
175
+ const { AuthStorage } = await import("./auth-storage-RABPRJ6T.js");
176
+ const { getSessionsDir } = await import("./config-HF2PDLN5.js");
177
+ const { FileSessionStore } = await import("./src-OA3TP6DS.js");
178
+ const { MemoryStore, runDistillation } = await import("./src-A5YI46OD.js");
179
179
  const store = new MemoryStore(memoryRoot);
180
180
  ledger = store;
181
181
  const registry = new ModelRegistry(AuthStorage.create());
@@ -190,7 +190,7 @@ async function runDistillWorkerMain(memoryRoot, date, noExit = false) {
190
190
  if (!resolved.model || !resolved.apiKey) {
191
191
  throw new Error(`no complete model/key pair for class ${modelClass}${resolved.fallbackReason ? `: ${resolved.fallbackReason}` : ""}`);
192
192
  }
193
- const { completeSimple } = await import("./src-BHIH4VLE.js");
193
+ const { completeSimple } = await import("./src-TF2RAGRU.js");
194
194
  const message = await withModelTimeout(
195
195
  completeSimple(
196
196
  resolved.model,
@@ -255,7 +255,7 @@ async function runDistillAuto(memoryRoot, days = 7, runner) {
255
255
  } catch {
256
256
  }
257
257
  };
258
- const { MemoryStore, todayKey } = await import("./src-V2M7FLWY.js");
258
+ const { MemoryStore, todayKey } = await import("./src-A5YI46OD.js");
259
259
  const store = new MemoryStore(memoryRoot);
260
260
  const today = todayKey(Date.now());
261
261
  const dates = [];
@@ -561,7 +561,6 @@ var MAX_STATUS_FILE_BYTES = 128 * 1024;
561
561
  var MAX_DISPLAY_NAME_CHARS = 64;
562
562
  var MAX_STATUS_TEXT_FIELD_CHARS = 4096;
563
563
  var MAX_BODY_CHARS = 8e3;
564
- var MAX_STATUS_BODY_CHARS = 2e3;
565
564
  var STATUS_FILE_STALE_MS = 12e4;
566
565
  var HEARTBEAT_INTERVAL_MS = 2e4;
567
566
  var DEFAULT_SEND_WAIT_MS = 12e4;
@@ -589,9 +588,6 @@ function peerLabel(instanceId, displayName) {
589
588
  return instanceId.length > 12 ? instanceId.slice(0, 12) : instanceId;
590
589
  }
591
590
  var ENVELOPE_KINDS = /* @__PURE__ */ new Set([
592
- "hello",
593
- "bye",
594
- "ping",
595
591
  "message",
596
592
  "ack",
597
593
  "result",
@@ -780,8 +776,6 @@ function parseStatusFile(raw) {
780
776
  if (typeof record.blockedSince === "number" && Number.isSafeInteger(record.blockedSince) && record.blockedSince >= 0) file.blockedSince = record.blockedSince;
781
777
  if (typeof record.turnStartedAt === "number" && Number.isSafeInteger(record.turnStartedAt) && record.turnStartedAt >= 0) file.turnStartedAt = record.turnStartedAt;
782
778
  if (typeof record.undeliveredInjections === "number" && Number.isFinite(record.undeliveredInjections)) file.undeliveredInjections = Math.min(100, Math.max(0, Math.floor(record.undeliveredInjections)));
783
- if (typeof record.lastBodyText === "string" && record.lastBodyText.length <= MAX_STATUS_TEXT_FIELD_CHARS && !/[\u0000-\u0008\u000b-\u001f\u007f]/.test(record.lastBodyText)) file.lastBodyText = record.lastBodyText;
784
- if (typeof record.lastBodyAt === "number" && Number.isSafeInteger(record.lastBodyAt) && record.lastBodyAt >= 0) file.lastBodyAt = record.lastBodyAt;
785
779
  if (typeof record.port === "number" && Number.isInteger(record.port) && record.port > 0 && record.port <= 65535) file.port = record.port;
786
780
  return file;
787
781
  }
@@ -1414,7 +1408,6 @@ export {
1414
1408
  IPC_PROTOCOL_VERSION,
1415
1409
  MAX_STATUS_FILE_BYTES,
1416
1410
  MAX_BODY_CHARS,
1417
- MAX_STATUS_BODY_CHARS,
1418
1411
  HEARTBEAT_INTERVAL_MS,
1419
1412
  DEFAULT_SEND_WAIT_MS,
1420
1413
  MAX_INBOX_MESSAGES,
@@ -1,9 +1,11 @@
1
1
  import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
2
  import {
3
- getConfigDir
4
- } from "./chunk-ILUHTKF3.js";
3
+ getConfigDir,
4
+ init_config
5
+ } from "./chunk-UCKOXAME.js";
5
6
 
6
7
  // src/core/auth-storage.ts
8
+ init_config();
7
9
  import * as fs from "fs";
8
10
  import * as path from "path";
9
11
  var AUTH_LOCK_WRITE_GRACE_MS = 1e3;
@@ -41,13 +41,13 @@ import {
41
41
  TypeSystemPolicy,
42
42
  Union,
43
43
  Unknown
44
- } from "./chunk-XXGYUYXI.js";
44
+ } from "./chunk-BPSCGGVF.js";
45
45
  import {
46
46
  __commonJS,
47
47
  __export,
48
48
  __require,
49
49
  __toESM
50
- } from "./chunk-LZQXQOPJ.js";
50
+ } from "./chunk-RZGYXAJU.js";
51
51
 
52
52
  // ../../node_modules/partial-json/dist/options.js
53
53
  var require_options = __commonJS({