@staix/agent-hub 0.43.0 → 0.45.0

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 (118) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/README.md +3 -8
  3. package/docs/agent-notes/adapters.md +2 -2
  4. package/docs/agent-notes/daemon.md +4 -4
  5. package/docs/agent-notes/local-worker.md +2 -1
  6. package/docs/agent-notes/security-review.md +1 -1
  7. package/docs/agent-notes/tasks.md +5 -2
  8. package/docs/agent-notes/tests.md +4 -3
  9. package/docs/design/adapters.md +4 -2
  10. package/docs/design/agent-hub-architecture.md +2 -0
  11. package/docs/design/agent-hub.md +1 -1
  12. package/docs/design/roadmap.md +75 -2
  13. package/docs/design/supervision.md +34 -2
  14. package/docs/design/task-board.md +36 -2
  15. package/docs/dogfood.md +20 -5
  16. package/docs/events.md +9 -3
  17. package/docs/influences.md +7 -0
  18. package/docs/memory.md +4 -4
  19. package/docs/operations.md +84 -31
  20. package/docs/quickstart.md +14 -2
  21. package/docs/research.md +18 -0
  22. package/docs/roadmap.json +4 -0
  23. package/docs/roadmap.md +9 -0
  24. package/docs/sdlc.md +19 -4
  25. package/docs/security.md +4 -4
  26. package/docs/verification/2026-11-11-supervision-pilot-1221.md +864 -0
  27. package/docs/verification/2026-11-19-0.44.0.md +60 -0
  28. package/docs/verification/2026-11-19-claude-implementer-2.1.328.md +49 -0
  29. package/docs/verification/2026-11-20-claude-implementer-2.1.329.md +49 -0
  30. package/docs/verification/2026-11-20-sdlc-metrics-diagnosis.md +7 -0
  31. package/docs/verification/2026-11-21-0.45.0.md +69 -0
  32. package/docs/verification/2026-11-22-codex-0171-reviewer-isolation.md +47 -0
  33. package/docs/verified.json +32 -26
  34. package/package.json +2 -2
  35. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  36. package/plugins/agent-hub/kimi-hook.js +585 -264
  37. package/plugins/agent-hub/kimi-review-policy-worker.js +5 -5
  38. package/plugins/agent-hub/server.js +629 -293
  39. package/scripts/check-docs.mjs +9 -1
  40. package/src/adapters/acp.ts +11 -1
  41. package/src/adapters/compat.ts +3 -3
  42. package/src/adapters/definitions/builtin-metadata.ts +2 -2
  43. package/src/adapters/definitions/native-context.ts +10 -0
  44. package/src/adapters/jcode.ts +10 -0
  45. package/src/adapters/local-worker.ts +3 -2
  46. package/src/adapters/pi.ts +15 -4
  47. package/src/cli/console-state.ts +3 -1
  48. package/src/cli/help.ts +3 -1
  49. package/src/cli/identity.ts +2 -1
  50. package/src/cli/main.ts +12 -6
  51. package/src/cli/output.ts +2 -2
  52. package/src/cli/recovery-package.ts +16 -3
  53. package/src/cli/roadmap-write.ts +59 -0
  54. package/src/cli/roadmap.ts +81 -4
  55. package/src/cli/sdlc-output.ts +11 -1
  56. package/src/cli/upgrade-runtime.ts +10 -6
  57. package/src/cli/upgrade.ts +9 -3
  58. package/src/hub/agent-mem-range.ts +43 -0
  59. package/src/hub/board.ts +116 -2
  60. package/src/hub/bus.ts +4 -0
  61. package/src/hub/check-runner.ts +25 -1
  62. package/src/hub/claude-shell-wrapper.ts +2 -1
  63. package/src/hub/config-apply.ts +4 -2
  64. package/src/hub/config-trust.ts +1 -1
  65. package/src/hub/context-window.ts +1 -1
  66. package/src/hub/control-write-trace.ts +39 -2
  67. package/src/hub/cost-governance.ts +11 -7
  68. package/src/hub/daemon.ts +318 -53
  69. package/src/hub/dogfood-read.ts +4 -2
  70. package/src/hub/edit-guard.ts +100 -0
  71. package/src/hub/events.ts +79 -8
  72. package/src/hub/facts.ts +85 -2
  73. package/src/hub/hub-tools.ts +3 -1
  74. package/src/hub/lifecycle.ts +6 -1
  75. package/src/hub/log-rotation.ts +130 -0
  76. package/src/hub/memory-profile.ts +137 -21
  77. package/src/hub/no-writes.ts +1 -0
  78. package/src/hub/operational-authority.ts +3 -2
  79. package/src/hub/operational-settings.ts +2 -2
  80. package/src/hub/quota-events.ts +40 -0
  81. package/src/hub/recovery-store.ts +70 -24
  82. package/src/hub/report.ts +1 -1
  83. package/src/hub/research-experiments.ts +132 -0
  84. package/src/hub/research-quality.ts +13 -3
  85. package/src/hub/research-record.ts +38 -2
  86. package/src/hub/research.ts +128 -28
  87. package/src/hub/restart.ts +49 -2
  88. package/src/hub/roadmap-check.ts +65 -0
  89. package/src/hub/roadmap-decompose.ts +80 -0
  90. package/src/hub/roadmap-export.ts +27 -0
  91. package/src/hub/roadmap-sync.ts +97 -0
  92. package/src/hub/roadmap.ts +40 -0
  93. package/src/hub/runtime-capture-prune.ts +9 -1
  94. package/src/hub/runtime-prune-health.ts +5 -1
  95. package/src/hub/sdlc-branch-ci.ts +128 -0
  96. package/src/hub/sdlc-merge.ts +12 -5
  97. package/src/hub/sdlc-metrics.ts +33 -10
  98. package/src/hub/sdlc.ts +90 -10
  99. package/src/hub/settings.ts +1 -0
  100. package/src/hub/snapshots.ts +56 -1
  101. package/src/hub/startup-event-seeds.ts +21 -15
  102. package/src/hub/startup-timing.ts +3 -1
  103. package/src/hub/supervision-proposals.ts +10 -2
  104. package/src/hub/supervision-rules.ts +27 -4
  105. package/src/hub/supervision.ts +7 -0
  106. package/src/hub/task-pr.ts +47 -0
  107. package/src/hub/task-shell-command.ts +124 -0
  108. package/src/hub/task-worktree.ts +18 -11
  109. package/src/hub/tasks.ts +617 -45
  110. package/src/hub/usage-rollup.ts +35 -20
  111. package/src/hub/worktree-shelf.ts +2 -1
  112. package/src/local/sandbox.ts +2 -1
  113. package/src/local/shell-environment.ts +6 -0
  114. package/src/local/tools.ts +13 -1
  115. package/src/memory/brief.ts +10 -1
  116. package/src/memory/client.ts +3 -2
  117. package/src/pi/extension.ts +15 -3
  118. package/src/pi/tool-receipts.ts +26 -0
@@ -122,7 +122,7 @@ function finishPreview(ctx, launch, envNames, unresolved, metadata, settings) {
122
122
  var REDACTED = "[redacted]", UNRESOLVED = "[unresolved]";
123
123
 
124
124
  // node_modules/@staix/agent-mem/src/memory/platform.ts
125
- import { realpathSync } from "fs";
125
+ import { lstatSync, realpathSync } from "fs";
126
126
  import { basename, dirname, join, resolve, sep } from "path";
127
127
  import { createRequire } from "module";
128
128
  import { createHash } from "crypto";
@@ -226,7 +226,7 @@ var init_git = __esm(() => {
226
226
  });
227
227
 
228
228
  // src/hub/project.ts
229
- import { existsSync, lstatSync, readFileSync } from "fs";
229
+ import { existsSync, lstatSync as lstatSync2, readFileSync } from "fs";
230
230
  import { homedir } from "os";
231
231
  import { dirname as dirname2, isAbsolute, join as join2, resolve as resolve2 } from "path";
232
232
  function gitRoot(dir) {
@@ -244,7 +244,7 @@ function projectRoot(cwd) {
244
244
  let dir;
245
245
  try {
246
246
  dir = canonicalPath(input);
247
- if (!lstatSync(dir).isDirectory())
247
+ if (!lstatSync2(dir).isDirectory())
248
248
  throw new Error(`${cwd} is not a directory`);
249
249
  } catch (error) {
250
250
  throw new Error(`cannot resolve project directory ${cwd}: ${error.message}`);
@@ -307,7 +307,7 @@ var init_project = __esm(() => {
307
307
  });
308
308
 
309
309
  // src/adapters/compat.ts
310
- import { closeSync, constants, fstatSync, lstatSync as lstatSync2, mkdirSync, openSync, readSync, renameSync, unlinkSync, writeFileSync } from "fs";
310
+ import { closeSync, constants, fstatSync, lstatSync as lstatSync3, mkdirSync, openSync, readSync, renameSync, unlinkSync, writeFileSync } from "fs";
311
311
  import { dirname as dirname3, join as join3 } from "path";
312
312
  function inLine(version, line) {
313
313
  const v = parts(version);
@@ -375,12 +375,12 @@ var init_compat = __esm(() => {
375
375
  },
376
376
  "claude-implementer": {
377
377
  label: "Claude headless implementer",
378
- verified: ["2.1.309", "2.1.310", "2.1.314", "2.1.316", "2.1.318", "2.1.319", "2.1.322", "2.1.323"],
378
+ verified: ["2.1.309", "2.1.310", "2.1.314", "2.1.316", "2.1.318", "2.1.319", "2.1.322", "2.1.323", "2.1.328", "2.1.329"],
379
379
  gate: "contract",
380
380
  probe: ["claude", "--version"],
381
381
  parse: (out) => plain(out.trim().replace(/ \(Claude Code\)$/, "")),
382
382
  trustNote: "The native prompt-tool transport and host-wrapper rewrite, environment isolation and replay contract have isolated receipts. No dontAsk/bypass fallback exists; another version's permission or rewrite behavior is unverified.",
383
- receipt: "docs/verification/2026-11-13-claude-implementer-2.1.323.md"
383
+ receipt: "docs/verification/2026-11-20-claude-implementer-2.1.329.md"
384
384
  },
385
385
  "codex-review": {
386
386
  label: "Codex reviewer (codex-cli)",
@@ -496,7 +496,7 @@ var init_same_directory = __esm(() => {
496
496
 
497
497
  // src/cli/agy-mcp.ts
498
498
  import { randomUUID } from "crypto";
499
- import { closeSync as closeSync2, fstatSync as fstatSync2, lstatSync as lstatSync3, mkdirSync as mkdirSync2, openSync as openSync2, readFileSync as readFileSync2, renameSync as renameSync2, rmdirSync, unlinkSync as unlinkSync2, writeFileSync as writeFileSync2 } from "fs";
499
+ import { closeSync as closeSync2, fstatSync as fstatSync2, lstatSync as lstatSync4, mkdirSync as mkdirSync2, openSync as openSync2, readFileSync as readFileSync2, renameSync as renameSync2, rmdirSync, unlinkSync as unlinkSync2, writeFileSync as writeFileSync2 } from "fs";
500
500
  import { isAbsolute as isAbsolute2, join as join4, resolve as resolve3 } from "path";
501
501
  import { isDeepStrictEqual } from "util";
502
502
  function object(value) {
@@ -550,13 +550,13 @@ function validateOptions(options) {
550
550
  return { root, peer };
551
551
  }
552
552
  function safeDirectory(path) {
553
- const stat = lstatSync3(path, { throwIfNoEntry: false });
553
+ const stat = lstatSync4(path, { throwIfNoEntry: false });
554
554
  if (stat && (!stat.isDirectory() || stat.isSymbolicLink()))
555
555
  throw new Error(`${path} must be a project directory, not a link`);
556
556
  return stat;
557
557
  }
558
558
  function safeFile(path) {
559
- const stat = lstatSync3(path, { throwIfNoEntry: false });
559
+ const stat = lstatSync4(path, { throwIfNoEntry: false });
560
560
  if (!stat)
561
561
  return;
562
562
  if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > MAX_CONFIG_BYTES)
@@ -741,7 +741,7 @@ function internalPlan(options) {
741
741
  return { file: pluginDir, tracked, changed, action: changed ? "create or update the managed agent-hub plugin" : "keep the managed agent-hub plugin", root, pluginDir, canonicalRoot, ...canonicalPluginDir ? { canonicalPluginDir } : {}, ...directories ? { directories } : {}, targets };
742
742
  }
743
743
  function identityMatches(path, before) {
744
- const now = lstatSync3(path, { throwIfNoEntry: false });
744
+ const now = lstatSync4(path, { throwIfNoEntry: false });
745
745
  return before ? !!now && now.dev === before.dev && now.ino === before.ino : !now;
746
746
  }
747
747
  function atomicWrite(path, bytes, expected, plan) {
@@ -760,7 +760,7 @@ function atomicWrite(path, bytes, expected, plan) {
760
760
  if (!identityMatches(path, expected))
761
761
  throw new Error(`${path} changed while the managed plugin was being written`);
762
762
  renameSync2(temporary, path);
763
- const stat = lstatSync3(path);
763
+ const stat = lstatSync4(path);
764
764
  if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1)
765
765
  throw new Error(`${path} changed while the managed plugin was written`);
766
766
  return { dev: stat.dev, ino: stat.ino };
@@ -768,7 +768,7 @@ function atomicWrite(path, bytes, expected, plan) {
768
768
  if (fd !== undefined)
769
769
  closeSync2(fd);
770
770
  try {
771
- const current = lstatSync3(temporary, { throwIfNoEntry: false });
771
+ const current = lstatSync4(temporary, { throwIfNoEntry: false });
772
772
  if (current && tempIdentity && current.dev === tempIdentity.dev && current.ino === tempIdentity.ino)
773
773
  unlinkSync2(temporary);
774
774
  } catch {}
@@ -777,7 +777,7 @@ function atomicWrite(path, bytes, expected, plan) {
777
777
  function rollback(plan, written, createdDirs) {
778
778
  for (const { target, own } of written.reverse()) {
779
779
  try {
780
- const now = lstatSync3(target.path, { throwIfNoEntry: false });
780
+ const now = lstatSync4(target.path, { throwIfNoEntry: false });
781
781
  if (!now || now.dev !== own.dev || now.ino !== own.ino)
782
782
  continue;
783
783
  if (target.current)
@@ -788,7 +788,7 @@ function rollback(plan, written, createdDirs) {
788
788
  }
789
789
  for (const { path, dev, ino } of createdDirs.reverse()) {
790
790
  try {
791
- const now = lstatSync3(path);
791
+ const now = lstatSync4(path);
792
792
  if (now.isDirectory() && !now.isSymbolicLink() && now.dev === dev && now.ino === ino)
793
793
  rmdirSync(path);
794
794
  } catch {}
@@ -844,7 +844,7 @@ function cleanupAgyMcp(options) {
844
844
  const deleted = [];
845
845
  try {
846
846
  for (const target of plan.targets) {
847
- const stat = lstatSync3(target.path);
847
+ const stat = lstatSync4(target.path);
848
848
  if (!target.stat || stat.dev !== target.stat.dev || stat.ino !== target.stat.ino)
849
849
  throw new Error(`${target.path} changed before agy plugin cleanup`);
850
850
  }
@@ -873,7 +873,7 @@ function cleanupAgyMcp(options) {
873
873
  } catch (error) {
874
874
  for (const item of deleted.reverse()) {
875
875
  try {
876
- const current = lstatSync3(item.path, { throwIfNoEntry: false });
876
+ const current = lstatSync4(item.path, { throwIfNoEntry: false });
877
877
  if (item.own) {
878
878
  if (current?.dev === item.own.dev && current.ino === item.own.ino)
879
879
  atomicWrite(item.path, item.bytes, current, plan);
@@ -2768,7 +2768,7 @@ var init_claude_print = __esm(() => {
2768
2768
  // src/adapters/codex-review-isolation.ts
2769
2769
  import { createHash as createHash2 } from "crypto";
2770
2770
  import { spawn as spawn3 } from "child_process";
2771
- import { existsSync as existsSync3, lstatSync as lstatSync4, mkdirSync as mkdirSync3, mkdtempSync, readFileSync as readFileSync3, rmSync, statSync, symlinkSync, writeFileSync as writeFileSync3 } from "fs";
2771
+ import { existsSync as existsSync3, lstatSync as lstatSync5, mkdirSync as mkdirSync3, mkdtempSync, readFileSync as readFileSync3, rmSync, statSync, symlinkSync, writeFileSync as writeFileSync3 } from "fs";
2772
2772
  import { createRequire as createRequire2 } from "module";
2773
2773
  import { homedir as homedir2, tmpdir } from "os";
2774
2774
  import { basename as basename2, delimiter, dirname as dirname5, isAbsolute as isAbsolute3, join as join5, relative, resolve as resolve5 } from "path";
@@ -2890,7 +2890,7 @@ function toml(value) {
2890
2890
  }
2891
2891
  function metadata(file) {
2892
2892
  try {
2893
- const link = lstatSync4(file), stat = statSync(file);
2893
+ const link = lstatSync5(file), stat = statSync(file);
2894
2894
  return [link.dev, link.ino, link.mtimeMs, stat.dev, stat.ino, stat.size, stat.mtimeMs, stat.ctimeMs].join(":");
2895
2895
  } catch (error) {
2896
2896
  if (error.code === "ENOENT")
@@ -2936,7 +2936,7 @@ function credentialCanonicalPath(lexical) {
2936
2936
  let ancestor = lexical;
2937
2937
  for (;; ) {
2938
2938
  try {
2939
- lstatSync4(ancestor);
2939
+ lstatSync5(ancestor);
2940
2940
  break;
2941
2941
  } catch (error) {
2942
2942
  if (error.code !== "ENOENT" || dirname5(ancestor) === ancestor)
@@ -3297,7 +3297,7 @@ var init_codex_review_isolation = __esm(() => {
3297
3297
  });
3298
3298
 
3299
3299
  // src/adapters/kimi-wire-usage.ts
3300
- import { closeSync as closeSync3, constants as constants2, fstatSync as fstatSync3, lstatSync as lstatSync5, openSync as openSync3, readSync as fsReadSync, readdirSync, statSync as statSync2 } from "fs";
3300
+ import { closeSync as closeSync3, constants as constants2, fstatSync as fstatSync3, lstatSync as lstatSync6, openSync as openSync3, readSync as fsReadSync, readdirSync, statSync as statSync2 } from "fs";
3301
3301
  import { createHash as createHash3 } from "crypto";
3302
3302
  import { join as join6, sep as sep2 } from "path";
3303
3303
  function kimiCountedTokens(row) {
@@ -3501,7 +3501,7 @@ class KimiWireReader {
3501
3501
  for (const name of names) {
3502
3502
  const path = join6(dir, "agents", name, "wire.jsonl");
3503
3503
  try {
3504
- lstatSync5(path);
3504
+ lstatSync6(path);
3505
3505
  } catch (error) {
3506
3506
  if (error.code === "ENOENT")
3507
3507
  continue;
@@ -4000,10 +4000,10 @@ var init_kimi_usage = __esm(() => {
4000
4000
 
4001
4001
  // src/adapters/kimi-review-policy.ts
4002
4002
  import { createHash as createHash4 } from "crypto";
4003
- import { lstatSync as lstatSync6, readFileSync as readFileSync4 } from "fs";
4003
+ import { lstatSync as lstatSync7, readFileSync as readFileSync4 } from "fs";
4004
4004
  import { dirname as dirname6, join as join7, resolve as resolve6 } from "path";
4005
4005
  function readKimiReviewFile(file, limit = 262144) {
4006
- const stat = lstatSync6(file);
4006
+ const stat = lstatSync7(file);
4007
4007
  if (!stat.isFile() || stat.size > limit)
4008
4008
  throw new Error("unsupported reviewer file");
4009
4009
  return readFileSync4(file, "utf8");
@@ -4016,7 +4016,7 @@ function assertCleanCwdAncestors(...candidates) {
4016
4016
  if (!seen.has(ancestor)) {
4017
4017
  seen.add(ancestor);
4018
4018
  for (const marker of [".git", ".kimi-code", "AGENTS.md"]) {
4019
- if (lstatSync6(join7(ancestor, marker), { throwIfNoEntry: false }) !== undefined) {
4019
+ if (lstatSync7(join7(ancestor, marker), { throwIfNoEntry: false }) !== undefined) {
4020
4020
  throw new Error("private cwd ancestor contains ambient configuration");
4021
4021
  }
4022
4022
  }
@@ -4052,7 +4052,7 @@ function projectKimiReviewPolicyBinding(binding) {
4052
4052
  function checkKimiReviewPolicy(binding) {
4053
4053
  try {
4054
4054
  assertCleanCwdAncestors(binding.lexicalCwd, binding.physicalCwd);
4055
- const now = lstatSync6(binding.executable), expected = binding.executableStat;
4055
+ const now = lstatSync7(binding.executable), expected = binding.executableStat;
4056
4056
  return realPath(binding.sourcePath) === binding.source && now.dev === expected.dev && now.ino === expected.ino && now.size === expected.size && now.mtimeMs === expected.mtimeMs && now.ctimeMs === expected.ctimeMs && kimiReviewFingerprint(readKimiReviewFile(binding.sourceConfig)) === binding.sourceConfigHash && binding.privateFiles.length === 3 && binding.privateFiles.every((file) => kimiReviewFingerprint(readKimiReviewFile(file.path, 2097152)) === file.hash) && binding.authTargets.length === 3 && ["credentials", "oauth", "device_id"].every((name, index) => realPath(join7(binding.source, name)) === binding.authTargets[index] && realPath(join7(binding.tool, name)) === binding.authTargets[index]);
4057
4057
  } catch {
4058
4058
  return false;
@@ -4192,7 +4192,7 @@ var init_kimi_review_policy_worker = __esm(() => {
4192
4192
 
4193
4193
  // src/adapters/kimi-review.ts
4194
4194
  import { spawn as spawn4 } from "child_process";
4195
- import { existsSync as existsSync4, lstatSync as lstatSync7, mkdirSync as mkdirSync4, mkdtempSync as mkdtempSync2, rmSync as rmSync2, symlinkSync as symlinkSync2, writeFileSync as writeFileSync4 } from "fs";
4195
+ import { existsSync as existsSync4, lstatSync as lstatSync8, mkdirSync as mkdirSync4, mkdtempSync as mkdtempSync2, rmSync as rmSync2, symlinkSync as symlinkSync2, writeFileSync as writeFileSync4 } from "fs";
4196
4196
  import { homedir as homedir3, tmpdir as tmpdir2 } from "os";
4197
4197
  import { basename as basename3, join as join8, resolve as resolve7 } from "path";
4198
4198
  function managedConfig(raw) {
@@ -4348,7 +4348,7 @@ async function prepareKimiReviewer(context, policyFactory = startKimiReviewPolic
4348
4348
  const sourcePath = process.env.KIMI_CODE_HOME ?? join8(process.env.HOME ?? homedir3(), ".kimi-code"), source = realPath(sourcePath);
4349
4349
  const sourceConfig = join8(source, "config.toml"), original = readKimiReviewFile(sourceConfig), selected = managedConfig(original);
4350
4350
  const sources = ["credentials", "oauth", "device_id"].map((name) => realPath(join8(source, name)));
4351
- if (!sources.every((file, index) => index < 2 ? lstatSync7(file).isDirectory() : lstatSync7(file).isFile()))
4351
+ if (!sources.every((file, index) => index < 2 ? lstatSync8(file).isDirectory() : lstatSync8(file).isFile()))
4352
4352
  throw new Error("native OAuth directories and device identity required");
4353
4353
  const mcp = mcpConfig(context);
4354
4354
  if (Buffer.byteLength(context.input ?? "") > 1048576)
@@ -4382,7 +4382,7 @@ ${context.input ?? "No review is active; startup self-check only."}
4382
4382
  const native = context.command ?? [Bun.which("kimi", { PATH: process.env.PATH }) ?? "kimi"];
4383
4383
  const executable = realPath(Bun.which(native[0], { PATH: process.env.PATH }) ?? resolve7(native[0]));
4384
4384
  const command = [executable, ...native.slice(1)];
4385
- const executableStat = lstatSync7(executable);
4385
+ const executableStat = lstatSync8(executable);
4386
4386
  const verdict = assessVersion("kimi-review", COMPAT["kimi-review"].parse(await version(command, cwd, env, context.signal)));
4387
4387
  if (!verdict.ok)
4388
4388
  throw new Error(verdict.reason);
@@ -4537,6 +4537,14 @@ function jcodeContextValue(value, sessionId, measuredAt) {
4537
4537
  const tokens = okay ? raw.used : null, window = okay ? raw.size : null;
4538
4538
  return { source: "jcode_usage_update", sessionId, measuredAt, tokens, window, used: tokens !== null && window !== null ? Math.min(1, tokens / window) : null };
4539
4539
  }
4540
+ function piContext(value, sessionId, measuredAt) {
4541
+ const raw = object4(value), parts = [raw.input, raw.cacheRead, raw.cacheWrite];
4542
+ const valid = parts.every((n) => Number.isSafeInteger(n) && n >= 0);
4543
+ const sum = valid ? parts.reduce((a, n) => a + n, 0) : null;
4544
+ const tokens = Number.isSafeInteger(sum) ? sum : null;
4545
+ const window = Number.isSafeInteger(raw.contextWindow) && raw.contextWindow > 0 ? raw.contextWindow : null;
4546
+ return { source: "pi_usage", sessionId, measuredAt, tokens, window, used: tokens !== null && window !== null ? Math.min(1, tokens / window) : null };
4547
+ }
4540
4548
  var nonnegative = (n) => typeof n === "number" && Number.isFinite(n) && n >= 0, positive = (n) => nonnegative(n) && n > 0, record2 = (v) => v !== null && typeof v === "object" && !Array.isArray(v), object4 = (v) => record2(v) ? v : {};
4541
4549
 
4542
4550
  // src/hub/context-window.ts
@@ -5044,7 +5052,7 @@ var init_acp = __esm(() => {
5044
5052
  init_model_token();
5045
5053
  init_acp_session_model();
5046
5054
  init_native_capabilities();
5047
- TOOL_CEILING_MS = 30 * 60000;
5055
+ TOOL_CEILING_MS = 60 * 60000;
5048
5056
  managedLaunches = new WeakMap;
5049
5057
  RpcTimeoutError = class RpcTimeoutError extends Error {
5050
5058
  };
@@ -5707,6 +5715,9 @@ ${renderDigest(envs, this.primed)}` : renderDigest(envs, this.primed) }] });
5707
5715
  this.touch(Math.min(this.watchdogMs, remaining));
5708
5716
  return;
5709
5717
  }
5718
+ try {
5719
+ this.opts.onToolCeiling?.({ ceilingMs: ceiling });
5720
+ } catch {}
5710
5721
  try {
5711
5722
  this.activityPrivate ||= this.opts.isPrivateTurn?.() === true;
5712
5723
  } catch {
@@ -7166,7 +7177,7 @@ __export(exports_jcode, {
7166
7177
  });
7167
7178
  import { spawn as spawn7, spawnSync as spawnSync2 } from "child_process";
7168
7179
  import { createConnection } from "net";
7169
- import { closeSync as closeSync4, constants as constants3, existsSync as existsSync5, fstatSync as fstatSync4, lstatSync as lstatSync8, mkdtempSync as mkdtempSync3, openSync as openSync4, readSync as readSync2, rmSync as rmSync3 } from "fs";
7180
+ import { closeSync as closeSync4, constants as constants3, existsSync as existsSync5, fstatSync as fstatSync4, lstatSync as lstatSync9, mkdtempSync as mkdtempSync3, openSync as openSync4, readSync as readSync2, rmSync as rmSync3 } from "fs";
7170
7181
  import { tmpdir as tmpdir3 } from "os";
7171
7182
  import { isAbsolute as isAbsolute4, join as join9 } from "path";
7172
7183
  function jcodeCommand(command, kind, socket, cwd, model, profile, provider, peer = "jcode") {
@@ -7211,12 +7222,12 @@ function jcodeTuiCommand(command, socket, sessionId, model, profile, provider) {
7211
7222
  function savedSession(home, id) {
7212
7223
  if (!/^[A-Za-z0-9_-]{1,128}$/.test(id))
7213
7224
  throw new Error("invalid native session identity");
7214
- const directory = join9(home, "sessions"), info = lstatSync8(directory, { throwIfNoEntry: false });
7225
+ const directory = join9(home, "sessions"), info = lstatSync9(directory, { throwIfNoEntry: false });
7215
7226
  if (!info)
7216
7227
  return false;
7217
7228
  if (!info.isDirectory() || info.isSymbolicLink())
7218
7229
  throw new Error("unsafe native session directory");
7219
- const file = join9(directory, `${id}.json`), entry = lstatSync8(file, { throwIfNoEntry: false });
7230
+ const file = join9(directory, `${id}.json`), entry = lstatSync9(file, { throwIfNoEntry: false });
7220
7231
  if (!entry)
7221
7232
  return false;
7222
7233
  if (!entry.isFile() || entry.isSymbolicLink())
@@ -7415,7 +7426,7 @@ var init_jcode = __esm(() => {
7415
7426
  ready.once("data", () => {
7416
7427
  clearTimeout(timer);
7417
7428
  server.off("exit", fail);
7418
- if (lstatSync8(this.socket, { throwIfNoEntry: false })?.isSocket())
7429
+ if (lstatSync9(this.socket, { throwIfNoEntry: false })?.isSocket())
7419
7430
  resolve();
7420
7431
  else
7421
7432
  reject(new Error("Jcode readiness has no private socket"));
@@ -7425,7 +7436,7 @@ var init_jcode = __esm(() => {
7425
7436
  if (!this.ending && this.server === server)
7426
7437
  this.stop("Jcode owned daemon disconnected").catch(() => {});
7427
7438
  });
7428
- const identity = lstatSync8(this.socket);
7439
+ const identity = lstatSync9(this.socket);
7429
7440
  this.socketIdentity = { dev: identity.dev, ino: identity.ino };
7430
7441
  await super.start();
7431
7442
  } catch (error) {
@@ -7499,7 +7510,7 @@ var init_jcode = __esm(() => {
7499
7510
  throw new Error(reason);
7500
7511
  };
7501
7512
  const sessionId = super.recoveryMetadata().sessionId;
7502
- const socket = lstatSync8(this.socket, { throwIfNoEntry: false });
7513
+ const socket = lstatSync9(this.socket, { throwIfNoEntry: false });
7503
7514
  if (this.state !== "busy")
7504
7515
  refuse(`jcode is ${this.state}`);
7505
7516
  if (this.ending || !this.server || this.server.exitCode !== null || this.server.signalCode !== null || !socket?.isSocket() || socket.dev !== this.socketIdentity?.dev || socket.ino !== this.socketIdentity.ino || typeof sessionId !== "string")
@@ -7512,7 +7523,7 @@ var init_jcode = __esm(() => {
7512
7523
  return "owned Jcode server changed before the steer was sent";
7513
7524
  if (super.recoveryMetadata().sessionId !== sessionId)
7514
7525
  return "jcode's session changed before the steer was sent";
7515
- const now = lstatSync8(this.socket, { throwIfNoEntry: false });
7526
+ const now = lstatSync9(this.socket, { throwIfNoEntry: false });
7516
7527
  if (!now?.isSocket() || now.dev !== identity?.dev || now.ino !== identity.ino)
7517
7528
  return "owned Jcode socket changed before the steer was sent";
7518
7529
  return;
@@ -7537,7 +7548,7 @@ var init_jcode = __esm(() => {
7537
7548
  }
7538
7549
  tuiLaunch(expected, options = {}) {
7539
7550
  const sessionId = super.recoveryMetadata().sessionId;
7540
- const socket = lstatSync8(this.socket, { throwIfNoEntry: false });
7551
+ const socket = lstatSync9(this.socket, { throwIfNoEntry: false });
7541
7552
  if (this.ending || !this.server || this.server.exitCode !== null || this.server.signalCode !== null || this.state === "offline")
7542
7553
  throw new JcodeTuiRefusal("server_not_running");
7543
7554
  if (!socket?.isSocket() || socket.dev !== this.socketIdentity?.dev || socket.ino !== this.socketIdentity.ino)
@@ -7578,7 +7589,7 @@ var exports_qwen_dual = {};
7578
7589
  __export(exports_qwen_dual, {
7579
7590
  QwenDualPeer: () => QwenDualPeer
7580
7591
  });
7581
- import { closeSync as closeSync5, constants as constants4, fstatSync as fstatSync5, lstatSync as lstatSync9, mkdirSync as mkdirSync5, openSync as openSync5, readSync as readSync3, realpathSync as realpathSync2, renameSync as renameSync3, writeFileSync as writeFileSync5, writeSync } from "fs";
7592
+ import { closeSync as closeSync5, constants as constants4, fstatSync as fstatSync5, lstatSync as lstatSync10, mkdirSync as mkdirSync5, openSync as openSync5, readSync as readSync3, realpathSync as realpathSync2, renameSync as renameSync3, writeFileSync as writeFileSync5, writeSync } from "fs";
7582
7593
  import { join as join10 } from "path";
7583
7594
  function qwenDualNamesStateDir(input, stateDir) {
7584
7595
  const needles = new Set([".agenthub/state", ".agenthub\\state", "qwen-dual", "input.jsonl", stateDir]);
@@ -7715,7 +7726,7 @@ var init_qwen_dual = __esm(() => {
7715
7726
  return { ...this.state_.sessionId ? { sessionId: this.state_.sessionId } : {}, launch: { mode: "tui" } };
7716
7727
  }
7717
7728
  ensureFile(path, create) {
7718
- const found = lstatSync9(path, { throwIfNoEntry: false });
7729
+ const found = lstatSync10(path, { throwIfNoEntry: false });
7719
7730
  if (!found) {
7720
7731
  if (!create)
7721
7732
  throw new Error("Qwen dual-output file is missing");
@@ -7780,7 +7791,7 @@ var init_qwen_dual = __esm(() => {
7780
7791
  }
7781
7792
  async start() {
7782
7793
  mkdirSync5(this.dir, { recursive: true, mode: 448 });
7783
- const dir = lstatSync9(this.dir);
7794
+ const dir = lstatSync10(this.dir);
7784
7795
  if (!dir.isDirectory() || dir.isSymbolicLink() || typeof process.getuid === "function" && dir.uid !== process.getuid() || (dir.mode & 63) !== 0)
7785
7796
  throw new Error("Qwen dual-output directory is not private to the person running the hub");
7786
7797
  this._launch = undefined;
@@ -7820,7 +7831,7 @@ var init_qwen_dual = __esm(() => {
7820
7831
  if (fenced && !this.freshBaselineAbsent) {
7821
7832
  this.sessionSeen = this.state_.sessionId !== undefined;
7822
7833
  this.primed = true;
7823
- this.denyCursor = lstatSync9(this.eventFile).size;
7834
+ this.denyCursor = lstatSync10(this.eventFile).size;
7824
7835
  this.setState("offline");
7825
7836
  try {
7826
7837
  this.opts.onNotice?.(`${this.id}: the hub could not verify that the old Qwen terminal is absent; inspect and end that terminal before running ahub qwen --mode tui again`);
@@ -7873,7 +7884,7 @@ var init_qwen_dual = __esm(() => {
7873
7884
  }
7874
7885
  prepareFreshEvents(fenced) {
7875
7886
  if (!fenced) {
7876
- const previous = lstatSync9(this.eventFile);
7887
+ const previous = lstatSync10(this.eventFile);
7877
7888
  if (previous.size > 0) {
7878
7889
  try {
7879
7890
  renameSync3(this.eventFile, join10(this.dir, "events.prev.jsonl"));
@@ -7886,7 +7897,7 @@ var init_qwen_dual = __esm(() => {
7886
7897
  let fd;
7887
7898
  let ready = false;
7888
7899
  try {
7889
- const previous = lstatSync9(this.eventFile);
7900
+ const previous = lstatSync10(this.eventFile);
7890
7901
  if (previous.size > 0)
7891
7902
  renameSync3(this.eventFile, join10(this.dir, "events.prev.jsonl"));
7892
7903
  this.ensureFile(this.eventFile, true);
@@ -8468,7 +8479,7 @@ ${text}`;
8468
8479
  this.discardReadProof();
8469
8480
  return;
8470
8481
  }
8471
- const current = fstatSync5(fd), named = lstatSync9(this.eventFile);
8482
+ const current = fstatSync5(fd), named = lstatSync10(this.eventFile);
8472
8483
  if (!current.isFile() || !named.isFile() || named.isSymbolicLink() || current.dev !== named.dev || current.ino !== named.ino || `${current.dev}:${current.ino}` !== candidate.source || this.freshInputPending && candidate.source !== this.freshRead?.source || current.size !== this.state_.offset || named.size !== current.size) {
8473
8484
  this.discardReadProof();
8474
8485
  return;
@@ -8706,7 +8717,7 @@ var init_recovery_error = __esm(() => {
8706
8717
  });
8707
8718
 
8708
8719
  // src/hub/recovery-store.ts
8709
- import { chmodSync, existsSync as existsSync6, linkSync, lstatSync as lstatSync10, mkdirSync as mkdirSync6, readFileSync as readFileSync5, renameSync as renameSync4, rmSync as rmSync4, writeFileSync as writeFileSync6 } from "fs";
8720
+ import { chmodSync, existsSync as existsSync6, linkSync, lstatSync as lstatSync11, mkdirSync as mkdirSync6, readFileSync as readFileSync5, renameSync as renameSync4, rmSync as rmSync4, writeFileSync as writeFileSync6 } from "fs";
8710
8721
  import { randomUUID as randomUUID4 } from "crypto";
8711
8722
  function atomicPrivateJSON(file, value) {
8712
8723
  const temporary = `${file}.${randomUUID4()}.tmp`;
@@ -8782,10 +8793,10 @@ var init_session = __esm(() => {
8782
8793
  });
8783
8794
 
8784
8795
  // src/hub/permission-mode.ts
8785
- import { lstatSync as lstatSync11 } from "fs";
8796
+ import { lstatSync as lstatSync12 } from "fs";
8786
8797
  function hardLinked(path) {
8787
8798
  try {
8788
- const st = lstatSync11(path);
8799
+ const st = lstatSync12(path);
8789
8800
  return st.isFile() && st.nlink > 1;
8790
8801
  } catch {
8791
8802
  return false;
@@ -8804,11 +8815,11 @@ var init_permission_mode = __esm(() => {
8804
8815
  });
8805
8816
 
8806
8817
  // src/hub/path-policy.ts
8807
- import { accessSync, constants as constants5, lstatSync as lstatSync12, opendirSync, readlinkSync, statSync as statSync3 } from "fs";
8818
+ import { accessSync, constants as constants5, lstatSync as lstatSync13, opendirSync, readlinkSync, statSync as statSync3 } from "fs";
8808
8819
  import { dirname as dirname8, isAbsolute as isAbsolute5, join as join13, relative as relative3, resolve as resolve9, sep as sep3 } from "path";
8809
8820
  function existing(path) {
8810
8821
  try {
8811
- lstatSync12(path);
8822
+ lstatSync13(path);
8812
8823
  return true;
8813
8824
  } catch (error) {
8814
8825
  if (error.code === "ENOENT")
@@ -8857,7 +8868,7 @@ function directAliasTarget(path) {
8857
8868
  return;
8858
8869
  ancestor = parent;
8859
8870
  }
8860
- if (!lstatSync12(ancestor).isSymbolicLink())
8871
+ if (!lstatSync13(ancestor).isSymbolicLink())
8861
8872
  return;
8862
8873
  target = resolve9(dirname8(ancestor), readlinkSync(ancestor), relative3(ancestor, target));
8863
8874
  }
@@ -9140,11 +9151,18 @@ var init_deny = __esm(() => {
9140
9151
  CONFIG_WORKTREE_NAME = [`^.*/${hfsFoldedName("config")}\\.[^/]*$`, `^.*/[^/]*${hfsFoldedName("worktree")}$`];
9141
9152
  });
9142
9153
 
9154
+ // src/local/shell-environment.ts
9155
+ import { join as join14 } from "path";
9156
+ function sandboxCommandEnvironment(base, own) {
9157
+ return { BUN_INSTALL_CACHE_DIR: join14(own, "bun-cache"), NPM_CONFIG_CACHE: join14(own, "npm-cache"), ...base, TMPDIR: `${own}/` };
9158
+ }
9159
+ var init_shell_environment = () => {};
9160
+
9143
9161
  // src/local/sandbox.ts
9144
9162
  import { spawn as spawn8, spawnSync as spawnSync3 } from "child_process";
9145
- import { existsSync as existsSync7, lstatSync as lstatSync13, mkdtempSync as mkdtempSync4, readdirSync as readdirSync2, rmdirSync as rmdirSync2, rmSync as rmSync5 } from "fs";
9163
+ import { existsSync as existsSync7, lstatSync as lstatSync14, mkdtempSync as mkdtempSync4, readdirSync as readdirSync2, rmdirSync as rmdirSync2, rmSync as rmSync5 } from "fs";
9146
9164
  import { homedir as homedir4, tmpdir as tmpdir4 } from "os";
9147
- import { dirname as dirname10, join as join14, resolve as resolve10 } from "path";
9165
+ import { dirname as dirname10, join as join15, resolve as resolve10 } from "path";
9148
9166
  function developerDir() {
9149
9167
  const out = spawnSync3("xcode-select", ["-p"], { encoding: "utf8" });
9150
9168
  let dir = out.status === 0 ? out.stdout.trim() : "";
@@ -9163,7 +9181,7 @@ function externalGitDirs(root) {
9163
9181
  }
9164
9182
  function worktreesRoot(root) {
9165
9183
  const out = memoryGitSync(["-C", root, "rev-parse", "--git-common-dir"], { encoding: "utf8" });
9166
- return out.status === 0 && out.stdout.trim() ? join14(resolve10(root, out.stdout.trim()), "worktrees") : undefined;
9184
+ return out.status === 0 && out.stdout.trim() ? join15(resolve10(root, out.stdout.trim()), "worktrees") : undefined;
9167
9185
  }
9168
9186
  function moduleGitDirs(root) {
9169
9187
  const out = memoryGitSync(["-C", root, "rev-parse", "--git-common-dir", "--absolute-git-dir"], { encoding: "utf8" });
@@ -9174,12 +9192,12 @@ function moduleGitDirs(root) {
9174
9192
  if (!commonRaw || !ownRaw)
9175
9193
  return [];
9176
9194
  const common = resolve10(root, commonRaw), own = resolve10(root, ownRaw);
9177
- const roots = new Set([join14(common, "modules"), join14(own, "modules")]);
9195
+ const roots = new Set([join15(common, "modules"), join15(own, "modules")]);
9178
9196
  try {
9179
- for (const e of readdirSync2(join14(common, "worktrees"), { withFileTypes: true })) {
9197
+ for (const e of readdirSync2(join15(common, "worktrees"), { withFileTypes: true })) {
9180
9198
  if (!e.isDirectory())
9181
9199
  continue;
9182
- const modules = join14(common, "worktrees", e.name, "modules");
9200
+ const modules = join15(common, "worktrees", e.name, "modules");
9183
9201
  if (existsSync7(modules))
9184
9202
  roots.add(modules);
9185
9203
  }
@@ -9203,7 +9221,7 @@ function moduleGitDirs(root) {
9203
9221
  }
9204
9222
  for (const e of entries)
9205
9223
  if (e.isDirectory())
9206
- walk(join14(dir, e.name), depth + 1);
9224
+ walk(join15(dir, e.name), depth + 1);
9207
9225
  };
9208
9226
  walk(modulesRoot, 0);
9209
9227
  const found = nesting >= MODULE_DEPTH ? [] : dirs;
@@ -9213,11 +9231,11 @@ function moduleGitDirs(root) {
9213
9231
  entries.add(p);
9214
9232
  trees.push({ root: modulesRoot, entries: [...entries], dirs: found });
9215
9233
  for (const d of found) {
9216
- tree(join14(d, "modules"), nesting + 1);
9234
+ tree(join15(d, "modules"), nesting + 1);
9217
9235
  try {
9218
- for (const e of readdirSync2(join14(d, "worktrees"), { withFileTypes: true })) {
9219
- if (e.isDirectory() && existsSync7(join14(d, "worktrees", e.name, "modules")))
9220
- tree(join14(d, "worktrees", e.name, "modules"), nesting + 1);
9236
+ for (const e of readdirSync2(join15(d, "worktrees"), { withFileTypes: true })) {
9237
+ if (e.isDirectory() && existsSync7(join15(d, "worktrees", e.name, "modules")))
9238
+ tree(join15(d, "worktrees", e.name, "modules"), nesting + 1);
9221
9239
  }
9222
9240
  } catch {}
9223
9241
  }
@@ -9228,14 +9246,14 @@ function moduleGitDirs(root) {
9228
9246
  }
9229
9247
  function profile(cwd, network, readAllow = [], deny = [], readOnly = []) {
9230
9248
  const home = homedir4();
9231
- const inHome = (p) => p.startsWith("~/") ? join14(home, p.slice(2)) : p;
9249
+ const inHome = (p) => p.startsWith("~/") ? join15(home, p.slice(2)) : p;
9232
9250
  const root = realPath(cwd);
9233
9251
  const gitDirs = externalGitDirs(root);
9234
9252
  const moduleGit = moduleGitDirs(root);
9235
9253
  const worktrees = worktreesRoot(root);
9236
9254
  const creds = [".ssh", ".aws", ".gnupg", ".config/gh", ".config/gcloud", ".kube", ".docker", ".netrc", ".npmrc", ".omniroute", ".claude", ".codex", ".kimi-code", "Library/Keychains"];
9237
9255
  const dev = developerDir();
9238
- const readable = [root, ...HOME_READABLE.map((p) => join14(home, p)), ...readAllow.map(inHome), ...gitDirs, ...dev ? [dev] : []];
9256
+ const readable = [root, ...HOME_READABLE.map((p) => join15(home, p)), ...readAllow.map(inHome), ...gitDirs, ...dev ? [dev] : []];
9239
9257
  const subpaths = (paths) => paths.map((p) => `(subpath ${q(p)})`).join(" ");
9240
9258
  const globals = (names) => names.map((n) => `(global-name ${q(n)})`).join(" ");
9241
9259
  const proxy = typeof network === "object" ? `(allow network-outbound (remote ip ${q(`localhost:${network.proxyPort}`)}))` : undefined;
@@ -9253,7 +9271,7 @@ function profile(cwd, network, readAllow = [], deny = [], readOnly = []) {
9253
9271
  '(allow file-ioctl (regex #"^/dev/"))',
9254
9272
  ...proxy ? [proxy] : network ? ["(allow network*)"] : []
9255
9273
  ];
9256
- const places = `${creds.map((c) => `(subpath ${q(join14(home, c))})`).join(" ")} ${denyRegexes(root, deny, false).join(" ")}`;
9274
+ const places = `${creds.map((c) => `(subpath ${q(join15(home, c))})`).join(" ")} ${denyRegexes(root, deny, false).join(" ")}`;
9257
9275
  return [
9258
9276
  "(version 1)",
9259
9277
  ...start,
@@ -9261,7 +9279,7 @@ function profile(cwd, network, readAllow = [], deny = [], readOnly = []) {
9261
9279
  ...readOnly.length ? ['(allow file-write* (literal "/dev/null"))'] : [`(allow file-write* (subpath ${q(root)}) (regex #"^/dev/") ${gitDirs.map((d) => `(subpath ${q(d)})`).join(" ")})`],
9262
9280
  `(deny file-write* ${hubWriteRegexes(root, gitDirs, moduleGit, worktrees).join(" ")})`,
9263
9281
  ...worktrees ? objectStoreRules(dirname10(worktrees)) : [],
9264
- `(deny file-read* file-write* ${creds.map((c) => `(subpath ${q(join14(home, c))})`).join(" ")})`,
9282
+ `(deny file-read* file-write* ${creds.map((c) => `(subpath ${q(join15(home, c))})`).join(" ")})`,
9265
9283
  `(deny file-read* file-write* ${denyRegexes(root, deny).join(" ")})`,
9266
9284
  ...network ? [`(allow file-read* ${CA_BUNDLES.map((p) => `(literal ${q(p)})`).join(" ")} (regex ${q("/certifi/cacert\\.pem$")}))`, `(deny file-read* file-write* ${places})`] : []
9267
9285
  ].join(`
@@ -9277,10 +9295,10 @@ function sandboxedExec(argv, opts) {
9277
9295
  if (opts.signal?.aborted)
9278
9296
  return Promise.resolve({ code: null, output: "error: command cancelled before execution" });
9279
9297
  return new Promise((resolve) => {
9280
- const own = realPath(mkdtempSync4(join14(tmpdir4(), "ahub-cmd-")));
9298
+ const own = realPath(mkdtempSync4(join15(tmpdir4(), "ahub-cmd-")));
9281
9299
  const sandbox = `${opts.profile}
9282
9300
  (allow file-read* ${opts.readOnlyData ? "" : "file-write* "}process-exec (subpath ${q(own)}))`;
9283
- const env = { PATH: process.env.PATH ?? "/usr/bin:/bin", HOME: homedir4(), LANG: process.env.LANG ?? "en_US.UTF-8", TERM: "dumb", ...opts.env, TMPDIR: `${own}/` };
9301
+ const env = sandboxCommandEnvironment({ PATH: process.env.PATH ?? "/usr/bin:/bin", HOME: homedir4(), LANG: process.env.LANG ?? "en_US.UTF-8", TERM: "dumb", ...opts.env }, own);
9284
9302
  const child = spawn8(SANDBOX_EXEC, ["-p", sandbox, ...argv], { cwd: opts.cwd, env, stdio: ["ignore", "pipe", "pipe"], detached: true });
9285
9303
  let output = "";
9286
9304
  let killRequested = false;
@@ -9346,14 +9364,14 @@ async function probeCommand(argv, opts) {
9346
9364
  } catch {
9347
9365
  return { code: null, output: "error: probe command authority or environment unavailable", quiescent: true };
9348
9366
  }
9349
- const own = realPath(mkdtempSync4(join14(proof.temporaryRoot, "command-")));
9350
- const created = lstatSync13(own);
9367
+ const own = realPath(mkdtempSync4(join15(proof.temporaryRoot, "command-")));
9368
+ const created = lstatSync14(own);
9351
9369
  let removed = false;
9352
9370
  const dropOwn = () => {
9353
9371
  if (removed)
9354
9372
  return;
9355
9373
  proof.physical();
9356
- const current = lstatSync13(own);
9374
+ const current = lstatSync14(own);
9357
9375
  if (!current.isDirectory() || current.isSymbolicLink() || current.dev !== created.dev || current.ino !== created.ino || realPath(own) !== own)
9358
9376
  throw new Error("probe command temp ownership changed");
9359
9377
  rmdirSync2(own);
@@ -9445,6 +9463,7 @@ var init_sandbox = __esm(() => {
9445
9463
  init_git();
9446
9464
  init_deny();
9447
9465
  init_child_process();
9466
+ init_shell_environment();
9448
9467
  q = sbplString;
9449
9468
  HOME_READABLE = [".bun", ".cargo", ".rustup", ".local", ".npm", ".cache", ".pyenv", ".nvm", ".deno", "go", ".gitconfig", ".config/git", "Library/Caches", ".volta", ".asdf", ".nodenv", ".rbenv", ".sdkman", "Library/Application Support/fnm", "Library/pnpm"];
9450
9469
  CA_BUNDLES = ["/private/etc/ssl/cert.pem", "/opt/homebrew/etc/ca-certificates/cert.pem", "/opt/homebrew/etc/openssl@3/cert.pem", "/usr/local/etc/ca-certificates/cert.pem", "/usr/local/etc/openssl@3/cert.pem"];
@@ -9465,7 +9484,7 @@ var init_text_projection = __esm(() => {
9465
9484
  });
9466
9485
 
9467
9486
  // src/local/doc-read.ts
9468
- import { lstatSync as lstatSync14 } from "fs";
9487
+ import { lstatSync as lstatSync15 } from "fs";
9469
9488
  import { extname } from "path";
9470
9489
  function docRead(file, shown, args, port, cwd) {
9471
9490
  const projections = port.projections();
@@ -9475,7 +9494,7 @@ function docRead(file, shown, args, port, cwd) {
9475
9494
  }
9476
9495
  let st;
9477
9496
  try {
9478
- st = lstatSync14(file);
9497
+ st = lstatSync15(file);
9479
9498
  } catch {
9480
9499
  return `error: ${shown} cannot be read`;
9481
9500
  }
@@ -9955,13 +9974,13 @@ var init_probe_errors = __esm(() => {
9955
9974
  });
9956
9975
 
9957
9976
  // src/local/probe-workspace.ts
9958
- import { chmodSync as chmodSync2, constants as constants6, closeSync as closeSync7, fstatSync as fstatSync6, lstatSync as lstatSync15, mkdirSync as mkdirSync8, mkdtempSync as mkdtempSync5, openSync as openSync7, opendirSync as opendirSync2, readSync as readSync4, rmSync as rmSync6, rmdirSync as rmdirSync3, unlinkSync as unlinkSync3, writeFileSync as writeFileSync7 } from "fs";
9959
- import { dirname as dirname11, isAbsolute as isAbsolute6, join as join15 } from "path";
9977
+ import { chmodSync as chmodSync2, constants as constants6, closeSync as closeSync7, fstatSync as fstatSync6, lstatSync as lstatSync16, mkdirSync as mkdirSync8, mkdtempSync as mkdtempSync5, openSync as openSync7, opendirSync as opendirSync2, readSync as readSync4, rmSync as rmSync6, rmdirSync as rmdirSync3, unlinkSync as unlinkSync3, writeFileSync as writeFileSync7 } from "fs";
9978
+ import { dirname as dirname11, isAbsolute as isAbsolute6, join as join16 } from "path";
9960
9979
  function refused() {
9961
9980
  throw new Error("probe workspace source, role, path or resource proof is unavailable");
9962
9981
  }
9963
9982
  function directoryIdentity(file) {
9964
- const stat = lstatSync15(file);
9983
+ const stat = lstatSync16(file);
9965
9984
  if (!stat.isDirectory() || stat.isSymbolicLink() || realPath(file) !== file)
9966
9985
  refused();
9967
9986
  return { file, dev: stat.dev, ino: stat.ino };
@@ -9988,7 +10007,7 @@ function probeWorkspaceCurrent(workspace) {
9988
10007
  state.current();
9989
10008
  probeWorkspacePhysical(workspace);
9990
10009
  for (const entry of state.identities) {
9991
- const stat = lstatSync15(entry.file);
10010
+ const stat = lstatSync16(entry.file);
9992
10011
  if (!stat.isFile() || stat.nlink !== 1 || stat.dev !== entry.dev || stat.ino !== entry.ino || stat.size !== entry.size || stat.mtimeMs !== entry.mtimeMs || stat.ctimeMs !== entry.ctimeMs)
9993
10012
  refused();
9994
10013
  }
@@ -10016,8 +10035,8 @@ var init_probe_workspace = __esm(() => {
10016
10035
  });
10017
10036
 
10018
10037
  // src/local/tools.ts
10019
- import { lstatSync as lstatSync16, mkdirSync as mkdirSync9, readFileSync as readFileSync7, statSync as statSync4, writeFileSync as writeFileSync8 } from "fs";
10020
- import { dirname as dirname12, join as join16, relative as relative4, resolve as resolve11 } from "path";
10038
+ import { lstatSync as lstatSync17, mkdirSync as mkdirSync9, readFileSync as readFileSync7, statSync as statSync4, writeFileSync as writeFileSync8 } from "fs";
10039
+ import { dirname as dirname12, join as join17, relative as relative4, resolve as resolve11 } from "path";
10021
10040
  function probeCurrent(probe) {
10022
10041
  try {
10023
10042
  probe.current();
@@ -10026,7 +10045,7 @@ function probeCurrent(probe) {
10026
10045
  }
10027
10046
  }
10028
10047
  function probeTargetIdentity(target) {
10029
- const stat = lstatSync16(target, { throwIfNoEntry: false });
10048
+ const stat = lstatSync17(target, { throwIfNoEntry: false });
10030
10049
  if (!stat)
10031
10050
  return;
10032
10051
  if (!stat.isFile())
@@ -10049,7 +10068,7 @@ function planProbeTool(name, rawArgs, ctx) {
10049
10068
  if (name === "write")
10050
10069
  maximum = Buffer.byteLength(String(value.content ?? ""), "utf8");
10051
10070
  else {
10052
- const stat = lstatSync16(target, { throwIfNoEntry: false });
10071
+ const stat = lstatSync17(target, { throwIfNoEntry: false });
10053
10072
  if (!stat || !stat.isFile())
10054
10073
  throw new ProbeToolRefusal("nonregular_target");
10055
10074
  maximum = Math.min(PROBE_WORKSPACE_LIMITS.fileBytes, stat.size + Buffer.byteLength(String(value.new ?? ""), "utf8"));
@@ -10112,7 +10131,7 @@ function guardPath(ctx, path, mode) {
10112
10131
  throw new ProbeToolRefusal("nonregular_target");
10113
10132
  throw new Error(`${path} goes through a dangling symlink`);
10114
10133
  }
10115
- const real = join16(realExisting, relative4(existing, abs));
10134
+ const real = join17(realExisting, relative4(existing, abs));
10116
10135
  const rel = relative4(root, real);
10117
10136
  if (rel.startsWith("..") || resolve11(root, rel) !== real) {
10118
10137
  if (ctx.probe)
@@ -10126,7 +10145,7 @@ function guardPath(ctx, path, mode) {
10126
10145
  throw new Error(`${path} is on the secrets denylist`);
10127
10146
  }
10128
10147
  if (ctx.probe) {
10129
- const stat = lstatSync16(real, { throwIfNoEntry: false });
10148
+ const stat = lstatSync17(real, { throwIfNoEntry: false });
10130
10149
  if (stat && !stat.isFile() && !(mode === "read" && stat.isDirectory()))
10131
10150
  throw new ProbeToolRefusal("nonregular_target");
10132
10151
  if (stat?.isFile() && stat.nlink !== 1)
@@ -10138,7 +10157,7 @@ function guardPath(ctx, path, mode) {
10138
10157
  }
10139
10158
  if (mode === "write" && (isHubWritePath(rel) || inside && isHubWritePath(typed)))
10140
10159
  throw new Error(`${path} is not writable by the local worker`);
10141
- if (mode === "write" && ctx.readOnly?.length && (lstatSync16(real, { throwIfNoEntry: false })?.nlink ?? 1) > 1)
10160
+ if (mode === "write" && ctx.readOnly?.length && (lstatSync17(real, { throwIfNoEntry: false })?.nlink ?? 1) > 1)
10142
10161
  throw new Error("hardlinked write target cannot be verified with data.readonly");
10143
10162
  if (mode === "write" && matchesPolicy(root, path, ctx.readOnly ?? []))
10144
10163
  throw new Error("target is protected by data.readonly");
@@ -10213,11 +10232,14 @@ async function runTool(name, rawArgs, ctx) {
10213
10232
  const file = guardPath(ctx, String(a.path), "read");
10214
10233
  if (statSync4(file).size > 5000000)
10215
10234
  return "error: file is larger than 5 MB; use bash (head, grep, sed -n) to look at parts of it";
10216
- const lines = readFileSync7(file, "utf8").split(`
10235
+ const bytes = readFileSync7(file);
10236
+ const lines = bytes.toString("utf8").split(`
10217
10237
  `);
10218
10238
  const from = Math.max(1, Number(a.offset) || 1);
10219
10239
  const out = lines.slice(from - 1, from - 1 + (Number(a.limit) || 2000)).map((l, i) => `${from + i} ${l}`).join(`
10220
10240
  `);
10241
+ ctx.editGuard?.read(file, bytes, a.offset === undefined && a.limit === undefined && out.split(`
10242
+ `).length === lines.length && out.length <= OUTPUT_CAP);
10221
10243
  return out.length > OUTPUT_CAP ? `${out.slice(0, OUTPUT_CAP)}
10222
10244
  (truncated: read again with offset/limit)` : out;
10223
10245
  }
@@ -10247,8 +10269,12 @@ ${preview(content)}`, "write", ctx.signal, file, undefined, String(a.path), a),
10247
10269
  if (guardPath(ctx, String(a.path), "write") !== approvedTarget)
10248
10270
  return formatProbeToolRefusal(new ProbeToolRefusal("target_changed"));
10249
10271
  }
10272
+ const unverified = ctx.editGuard?.write(file);
10250
10273
  mkdirSync9(dirname12(file), { recursive: true });
10251
10274
  writeFileSync8(file, content);
10275
+ try {
10276
+ ctx.editGuard?.written(file, unverified);
10277
+ } catch {}
10252
10278
  return `wrote ${a.path}`;
10253
10279
  }
10254
10280
  case "edit": {
@@ -10284,7 +10310,11 @@ ${preview(content)}`, "write", ctx.signal, file, undefined, String(a.path), a),
10284
10310
  if (guardPath(ctx, String(a.path), "write") !== approvedTarget || readFileSync7(file, "utf8") !== text)
10285
10311
  return formatProbeToolRefusal(new ProbeToolRefusal("target_changed"));
10286
10312
  }
10313
+ const unverified = ctx.editGuard?.write(file);
10287
10314
  writeFileSync8(file, replacement);
10315
+ try {
10316
+ ctx.editGuard?.written(file, unverified);
10317
+ } catch {}
10288
10318
  return `edited ${a.path}`;
10289
10319
  }
10290
10320
  case "bash": {
@@ -10313,7 +10343,11 @@ ${preview(content)}`, "write", ctx.signal, file, undefined, String(a.path), a),
10313
10343
  if (attempt)
10314
10344
  return "error: read-only shell proof remained unstable; no command was executed";
10315
10345
  }
10346
+ const observedShell = ctx.editGuard?.shell(command);
10316
10347
  const res = await sandboxedExec(["/bin/bash", "-c", command], { cwd: ctx.cwd, profile: ctx.sandboxProfile, readOnlyData: !!ctx.readOnly?.length, timeoutMs: (Number(a.timeout_s) || 120) * 1000, ...ctx.sandboxEnv ? { env: ctx.sandboxEnv } : {}, ...ctx.signal ? { signal: ctx.signal } : {} });
10348
+ try {
10349
+ observedShell?.();
10350
+ } catch {}
10317
10351
  try {
10318
10352
  ctx.onProcessExit?.(res.code);
10319
10353
  } catch {}
@@ -10366,7 +10400,7 @@ note: the sandbox does not let you move a branch, tag or HEAD, or stage inside a
10366
10400
  }
10367
10401
  var APPROVAL_EXPIRED_TEXT = "error: approval expired: no person answered; do not retry this call; hand the task off or stop", ApprovalWaitStop, approvalError = (picked, denied) => picked === true ? undefined : picked === "expired" ? APPROVAL_EXPIRED_TEXT : picked === "aborted" ? "error: approval withdrawn because the turn ended; no operation was executed" : denied, probeToolPlans, lexists = (p) => {
10368
10402
  try {
10369
- lstatSync16(p);
10403
+ lstatSync17(p);
10370
10404
  return true;
10371
10405
  } catch {
10372
10406
  return false;
@@ -10454,7 +10488,7 @@ __export(exports_pi, {
10454
10488
  });
10455
10489
  import { randomUUID as randomUUID5 } from "crypto";
10456
10490
  import { existsSync as existsSync8, mkdirSync as mkdirSync10 } from "fs";
10457
- import { join as join17, resolve as resolve12 } from "path";
10491
+ import { join as join18, resolve as resolve12 } from "path";
10458
10492
  import { spawn as spawn9 } from "child_process";
10459
10493
  function piVersionAsync(command, cwd, timeoutMs = 1e4) {
10460
10494
  const [bin, ...prefix] = command;
@@ -10546,6 +10580,7 @@ var init_pi = __esm(() => {
10546
10580
  PiPeer = class PiPeer extends BasePeer {
10547
10581
  opts;
10548
10582
  preflight;
10583
+ sessionModel;
10549
10584
  hubNative = true;
10550
10585
  hubOwned = true;
10551
10586
  proc;
@@ -10771,6 +10806,9 @@ var init_pi = __esm(() => {
10771
10806
  const session = this.recoveryMetadata().sessionId;
10772
10807
  return typeof session === "string" ? session : undefined;
10773
10808
  }
10809
+ get verifiedRecordSession() {
10810
+ return this.verifiedOwner() ? this.nativeSession : undefined;
10811
+ }
10774
10812
  async captureResume() {
10775
10813
  if (this.state === "offline") {
10776
10814
  if (this.canReuseVerifiedEmptyResume())
@@ -10788,6 +10826,10 @@ var init_pi = __esm(() => {
10788
10826
  const snapshot = this.opts.mode === "headless" ? (await this.waitRpc("get_state", 15000)).data : await this.sendTui({ type: "get_session_state" });
10789
10827
  if (this.state !== "idle" || this.activeTools || snapshot?.sessionId !== this.sessionId || snapshot?.sessionFile !== this.sessionFile)
10790
10828
  throw new Error("Pi source session changed during capture");
10829
+ if (this.opts.mode === "tui" && this.verifiedOwner() && this.sessionId) {
10830
+ this.sessionModel = stateModelId(snapshot);
10831
+ this.opts.onContext?.(snapshot.context, this.sessionId);
10832
+ }
10791
10833
  if (!this.observeSnapshotTitle(snapshot, titleRevisionBefore, titleEpochBefore))
10792
10834
  throw new Error("Pi source session title changed during capture; retry with a fresh native session snapshot");
10793
10835
  const empty = this.opts.mode === "headless" ? snapshot.messageCount === 0 && snapshot.pendingMessageCount === 0 && snapshot.isStreaming === false && snapshot.isCompacting !== true && !snapshot.sessionName : snapshot.empty === true && snapshot.idle === true;
@@ -11053,7 +11095,7 @@ var init_pi = __esm(() => {
11053
11095
  this.approvalStopReason = "";
11054
11096
  this.approvalAbortSent = false;
11055
11097
  mkdirSync10(this.opts.stateDir, { recursive: true });
11056
- const sessions = join17(this.opts.stateDir, "pi-sessions");
11098
+ const sessions = join18(this.opts.stateDir, "pi-sessions");
11057
11099
  mkdirSync10(sessions, { recursive: true, mode: 448 });
11058
11100
  if (this.opts.sessionFile) {
11059
11101
  try {
@@ -11116,7 +11158,7 @@ var init_pi = __esm(() => {
11116
11158
  return new Response("not found", { status: 404 });
11117
11159
  } });
11118
11160
  this.server = bridge;
11119
- const extension = resolve12(join17(import.meta.dir, "../pi/extension.ts"));
11161
+ const extension = resolve12(join18(import.meta.dir, "../pi/extension.ts"));
11120
11162
  const inherited = {};
11121
11163
  for (const key of ["PATH", "HOME", "USER", "SHELL", "TMPDIR", "TERM", "TERM_PROGRAM", "LANG", "LC_ALL", "LC_CTYPE", "NO_COLOR", "CODEX_HOME"])
11122
11164
  if (process.env[key])
@@ -11270,6 +11312,10 @@ var init_pi = __esm(() => {
11270
11312
  throw new Error("Pi roster return could not verify the current native session");
11271
11313
  if (lifecycle !== this.rosterLifecycleRevision)
11272
11314
  throw new Error("Pi native activity changed during roster return; retry with a fresh session snapshot");
11315
+ if (session) {
11316
+ this.sessionModel = stateModelId(snapshot);
11317
+ this.opts.onContext?.(snapshot.context, session);
11318
+ }
11273
11319
  this.observeSnapshotTitle(snapshot, titleRevisionBefore, titleEpochBefore);
11274
11320
  this.rosterDetached = false;
11275
11321
  this.hubPromptId = undefined;
@@ -11440,7 +11486,7 @@ var init_pi = __esm(() => {
11440
11486
  attempted = true;
11441
11487
  if (deliveryId)
11442
11488
  this.activeDeliveryIds.add(deliveryId);
11443
- const recordPrompt = this.opts.mode === "tui" ? "" : this.turnRecordPrompt("");
11489
+ const recordPrompt = this.turnRecordPrompt("");
11444
11490
  const message = [recordPrompt, envs.some((env) => env.private || remoteEnvelope(env)) ? undefined : this.opts.titlePreface?.(), renderDigest(envs, true)].filter(Boolean).join(`
11445
11491
  `);
11446
11492
  if (this.opts.mode === "tui") {
@@ -11550,6 +11596,11 @@ var init_pi = __esm(() => {
11550
11596
  return;
11551
11597
  }
11552
11598
  } catch {}
11599
+ } else {
11600
+ if (this.verifiedOwner() && this.sessionModel) {
11601
+ this.turnModel = { model: this.sessionModel, evidence: "session" };
11602
+ return;
11603
+ }
11553
11604
  }
11554
11605
  if (requested)
11555
11606
  this.turnModel = { model: requested, evidence: "configured" };
@@ -11575,9 +11626,11 @@ var init_pi = __esm(() => {
11575
11626
  const slash = model.indexOf("/");
11576
11627
  const provider = "agent-hub-local";
11577
11628
  const modelId = model;
11578
- if (this.opts.mode === "tui")
11629
+ if (this.opts.mode === "tui") {
11630
+ if (this.sessionModel !== modelId)
11631
+ this.sessionModel = undefined;
11579
11632
  await this.sendTui({ type: "set_model", provider, modelId });
11580
- else
11633
+ } else
11581
11634
  await this.sendRpc({ type: "set_model", provider, modelId });
11582
11635
  this.requestedModel = model;
11583
11636
  }
@@ -11660,6 +11713,7 @@ var init_pi = __esm(() => {
11660
11713
  this.opts.log?.(`[${this.id}] Pi session identity mismatch`);
11661
11714
  return;
11662
11715
  }
11716
+ this.sessionModel = stateModelId(event);
11663
11717
  this.titleRevision = -1;
11664
11718
  this.titleEpoch++;
11665
11719
  this.nativeTitleEpoch = typeof event.titleEpoch === "string" && event.titleEpoch ? event.titleEpoch : undefined;
@@ -11706,6 +11760,8 @@ var init_pi = __esm(() => {
11706
11760
  const generation = Number.isSafeInteger(event.generation) ? event.generation : this.budgetGeneration + 1;
11707
11761
  if (generation <= this.budgetGeneration)
11708
11762
  return;
11763
+ if (this.opts.mode === "tui" && this.sessionModel && this.verifiedOwner() && (event.sessionId === undefined || event.sessionId === this.sessionId))
11764
+ this.turnModel = { model: this.sessionModel, evidence: "session" };
11709
11765
  this.modelStep = 0;
11710
11766
  this.ceilingUnsafe = false;
11711
11767
  this.turnObserved = false;
@@ -11736,6 +11792,14 @@ var init_pi = __esm(() => {
11736
11792
  }
11737
11793
  if (event.type === "activity" && this.state === "busy")
11738
11794
  this.touch();
11795
+ if (event.type === "pi_model" && event.sessionId === this.sessionId && this.verifiedOwner() && this.sessionId) {
11796
+ this.sessionModel = stateModelId(event);
11797
+ this.opts.onContext?.(undefined, this.sessionId);
11798
+ }
11799
+ if (event.type === "pi_usage" && this.agentRunning && this.state === "busy" && event.sessionId === this.sessionId && event.generation === this.budgetGeneration && this.verifiedOwner() && this.sessionId) {
11800
+ this.sessionModel = stateModelId(event);
11801
+ this.opts.onContext?.(event.context, this.sessionId);
11802
+ }
11739
11803
  if (event.type === "tokens" && this.state === "busy" && typeof event.id === "string" && event.id.length <= 100 && Number.isSafeInteger(event.tokens) && event.tokens >= 0 && !this.usageSeen.has(event.id)) {
11740
11804
  this.usageSeen.add(event.id);
11741
11805
  if (this.usageSeen.size > 1000)
@@ -12654,8 +12718,8 @@ var init_shipped_roles = __esm(() => {
12654
12718
 
12655
12719
  // src/hub/roles.ts
12656
12720
  import { createHash as createHash7 } from "crypto";
12657
- import { constants as constants7, closeSync as closeSync8, fstatSync as fstatSync7, lstatSync as lstatSync17, openSync as openSync8, readSync as readSync5, readdirSync as readdirSync3 } from "fs";
12658
- import { join as join18 } from "path";
12721
+ import { constants as constants7, closeSync as closeSync8, fstatSync as fstatSync7, lstatSync as lstatSync18, openSync as openSync8, readSync as readSync5, readdirSync as readdirSync3 } from "fs";
12722
+ import { join as join19 } from "path";
12659
12723
  function parseRole(text, stem, layer) {
12660
12724
  if (Buffer.byteLength(text) > 8192 || text.includes("\r") || !ID.test(stem))
12661
12725
  throw new Error("invalid role size, encoding or file id");
@@ -12734,9 +12798,9 @@ function loadRoleCatalog(cwd) {
12734
12798
  if (!cwd)
12735
12799
  return { roles, errors };
12736
12800
  try {
12737
- const config = join18(cwd, ".agenthub"), dir = join18(config, "roles");
12801
+ const config = join19(cwd, ".agenthub"), dir = join19(config, "roles");
12738
12802
  for (const path of [config, dir]) {
12739
- const stat = lstatSync17(path);
12803
+ const stat = lstatSync18(path);
12740
12804
  if (!stat.isDirectory() || stat.isSymbolicLink())
12741
12805
  throw new Error("unsafe role directory");
12742
12806
  }
@@ -12746,7 +12810,7 @@ function loadRoleCatalog(cwd) {
12746
12810
  for (const file of files) {
12747
12811
  const id = file.slice(0, -3);
12748
12812
  try {
12749
- roles.set(id, parseRole(projectRole(join18(dir, file)), id, "project"));
12813
+ roles.set(id, parseRole(projectRole(join19(dir, file)), id, "project"));
12750
12814
  } catch {
12751
12815
  errors.push({ id: ID.test(id) ? id : "invalid-file-id", reason: "invalid or unsafe project role" });
12752
12816
  }
@@ -13193,6 +13257,7 @@ function controlWriteSpan(phase, fn) {
13193
13257
  }
13194
13258
  span.async = true;
13195
13259
  request.telemetry.recordSyncPrefix(span);
13260
+ request.telemetry.followSpan(span);
13196
13261
  return Promise.resolve(result).then((value) => {
13197
13262
  request.telemetry.finishSpan(span);
13198
13263
  return value;
@@ -13219,6 +13284,9 @@ class ControlWriteTelemetry {
13219
13284
  timer;
13220
13285
  nextSampleAt;
13221
13286
  lastNow = 0;
13287
+ hops = 0;
13288
+ turn = 0;
13289
+ turnPending = false;
13222
13290
  stopped = false;
13223
13291
  completedRequests = 0;
13224
13292
  expiredRequests = 0;
@@ -13269,6 +13337,7 @@ class ControlWriteTelemetry {
13269
13337
  phaseOrder: [],
13270
13338
  settled: false,
13271
13339
  privacySuppressed: false,
13340
+ hopsLeft: MAX_REQUEST_HOPS,
13272
13341
  logPrivacy: () => false
13273
13342
  };
13274
13343
  request.logPrivacy = () => !request.privacySuppressed && this.privateNow(request.privacyCurrent);
@@ -13386,7 +13455,14 @@ class ControlWriteTelemetry {
13386
13455
  };
13387
13456
  }
13388
13457
  beginSpan(request, phase) {
13389
- const span = { request, phase, startedAt: this.readNow(), async: false, finished: false, prefixRecorded: false };
13458
+ if (!this.turnPending && !this.stopped) {
13459
+ this.turnPending = true;
13460
+ setImmediate(() => {
13461
+ this.turn++;
13462
+ this.turnPending = false;
13463
+ }).unref?.();
13464
+ }
13465
+ const span = { request, phase, startedAt: this.readNow(), async: false, finished: false, prefixRecorded: false, turn: this.turn };
13390
13466
  if (this.spans.size >= this.maxActiveSpans) {
13391
13467
  this.droppedSpans++;
13392
13468
  return span;
@@ -13412,6 +13488,8 @@ class ControlWriteTelemetry {
13412
13488
  request.phases.set(span.phase, prior + durationMs);
13413
13489
  if (!span.async && !span.prefixRecorded)
13414
13490
  this.rememberSyncInterval(span, endedAt);
13491
+ else if (span.async && span.turn === this.turn && endedAt - span.startedAt >= MIN_SYNC_PREFIX_MS)
13492
+ this.rememberSyncInterval(span, endedAt);
13415
13493
  }
13416
13494
  recordSyncPrefix(span) {
13417
13495
  if (span.finished || span.prefixRecorded || span.request.settled)
@@ -13422,6 +13500,25 @@ class ControlWriteTelemetry {
13422
13500
  span.prefixRecorded = true;
13423
13501
  this.rememberSyncInterval(span, endedAt);
13424
13502
  }
13503
+ followedHops() {
13504
+ return this.hops;
13505
+ }
13506
+ followSpan(span) {
13507
+ let last = this.readNow();
13508
+ const hop = () => {
13509
+ const request = span.request;
13510
+ if (span.finished || request.settled || this.stopped || request.hopsLeft <= 0)
13511
+ return;
13512
+ request.hopsLeft--;
13513
+ this.hops++;
13514
+ const now = this.readNow();
13515
+ if (now - last >= MIN_SYNC_PREFIX_MS)
13516
+ this.rememberSyncInterval({ ...span, startedAt: last }, now);
13517
+ last = now;
13518
+ queueMicrotask(hop);
13519
+ };
13520
+ queueMicrotask(hop);
13521
+ }
13425
13522
  rememberSyncInterval(span, endedAt) {
13426
13523
  const request = span.request;
13427
13524
  this.recent.push({ kind: request.metadata.kind, ...request.metadata.task === undefined ? {} : { task: request.metadata.task }, phase: span.phase, startedAt: span.startedAt, endedAt, async: false, privacyCurrent: request.logPrivacy });
@@ -13542,7 +13639,7 @@ class ControlWriteTelemetry {
13542
13639
  return Math.round(bounded * 10) / 10;
13543
13640
  }
13544
13641
  }
13545
- var CONTROL_WRITE_KINDS, CONTROL_WRITE_PHASES, CONTROL_WRITE_SLOW_MS = 1000, CONTROL_WRITE_LOOP_DELAY_MS = 250, CONTROL_WRITE_SAMPLE_MS = 100, CONTROL_WRITE_MAX_LINE_BYTES = 2048, CONTROL_WRITE_MAX_DURATION_MS = 86400000, CONTROL_WRITE_REQUEST_MAX_AGE_MS, MAX_ACTIVE_REQUESTS = 128, MAX_ACTIVE_SPANS = 256, MAX_RECENT_SPANS = 512, MAX_LOOP_SPANS = 8, MIN_SYNC_PREFIX_MS = 10, MAX_EMITS_PER_MINUTE = 60, RATE_LIMIT_MS = 1000, currentTrace, OPERATIONS;
13642
+ var CONTROL_WRITE_KINDS, CONTROL_WRITE_PHASES, CONTROL_WRITE_SLOW_MS = 1000, CONTROL_WRITE_LOOP_DELAY_MS = 250, CONTROL_WRITE_SAMPLE_MS = 100, CONTROL_WRITE_MAX_LINE_BYTES = 2048, CONTROL_WRITE_MAX_DURATION_MS = 86400000, CONTROL_WRITE_REQUEST_MAX_AGE_MS, MAX_ACTIVE_REQUESTS = 128, MAX_ACTIVE_SPANS = 256, MAX_RECENT_SPANS = 512, MAX_LOOP_SPANS = 8, MIN_SYNC_PREFIX_MS = 10, MAX_REQUEST_HOPS = 16, MAX_EMITS_PER_MINUTE = 60, RATE_LIMIT_MS = 1000, currentTrace, OPERATIONS;
13546
13643
  var init_control_write_trace = __esm(() => {
13547
13644
  CONTROL_WRITE_KINDS = [
13548
13645
  "hub_task_propose",
@@ -13591,7 +13688,7 @@ var package_default;
13591
13688
  var init_package = __esm(() => {
13592
13689
  package_default = {
13593
13690
  name: "@staix/agent-hub",
13594
- version: "0.43.0",
13691
+ version: "0.45.0",
13595
13692
  description: "Native multi-agent hub: Claude Code, Codex, Kimi Code, Pi and local inference as peers in one project",
13596
13693
  license: "MIT",
13597
13694
  type: "module",
@@ -13608,7 +13705,7 @@ var init_package = __esm(() => {
13608
13705
  bun: ">=1.4.4"
13609
13706
  },
13610
13707
  dependencies: {
13611
- "@staix/agent-mem": "0.29.0"
13708
+ "@staix/agent-mem": ">=0.33.0 <1.0.0"
13612
13709
  },
13613
13710
  devDependencies: {
13614
13711
  "@modelcontextprotocol/sdk": "^1.27.1",
@@ -13656,12 +13753,13 @@ var init_db_schema = __esm(() => {
13656
13753
  });
13657
13754
 
13658
13755
  // src/hub/snapshots.ts
13659
- var HEAD_LOG_MAX_APPEND_BYTES;
13756
+ var SNAPSHOT_COOLDOWN_MS, HEAD_LOG_MAX_APPEND_BYTES;
13660
13757
  var init_snapshots = __esm(() => {
13661
13758
  init_db_schema();
13662
13759
  init_child_process();
13663
13760
  init_git();
13664
13761
  init_project();
13762
+ SNAPSHOT_COOLDOWN_MS = 10 * 60000;
13665
13763
  HEAD_LOG_MAX_APPEND_BYTES = 128 * 1024;
13666
13764
  });
13667
13765
 
@@ -13724,6 +13822,12 @@ var init_host_executable = __esm(() => {
13724
13822
  init_project();
13725
13823
  });
13726
13824
 
13825
+ // src/hub/sdlc-branch-ci.ts
13826
+ var CAP2;
13827
+ var init_sdlc_branch_ci = __esm(() => {
13828
+ CAP2 = 256 * 1024;
13829
+ });
13830
+
13727
13831
  // src/hub/sdlc.ts
13728
13832
  var SDLC_STAGES, PLAYBOOK_STAGES, BASES2, STAGE_GATES, GATES;
13729
13833
  var init_sdlc = __esm(() => {
@@ -13738,6 +13842,7 @@ var init_sdlc = __esm(() => {
13738
13842
  init_workflow();
13739
13843
  init_child_process();
13740
13844
  init_host_executable();
13845
+ init_sdlc_branch_ci();
13741
13846
  SDLC_STAGES = ["spec", "plan", "implement", "review", "verify", "merge", "release"];
13742
13847
  PLAYBOOK_STAGES = ["intent", "spec", "plan", "build", "test", "review", "merge", "release", "maintain"];
13743
13848
  BASES2 = [...new Set([...SDLC_STAGES, ...PLAYBOOK_STAGES])];
@@ -13789,6 +13894,12 @@ var init_review_comments = __esm(() => {
13789
13894
  init_review_anchor();
13790
13895
  });
13791
13896
 
13897
+ // node_modules/@staix/agent-mem/src/memory/recap-scratch.ts
13898
+ var RECAP_SCRATCH;
13899
+ var init_recap_scratch = __esm(() => {
13900
+ RECAP_SCRATCH = Symbol("recap scratch without search");
13901
+ });
13902
+
13792
13903
  // node_modules/@staix/agent-mem/src/memory/screen.ts
13793
13904
  var SECRETS, looksSecret = (text) => SECRETS.some((re) => re.test(text));
13794
13905
  var init_screen = __esm(() => {
@@ -13888,13 +13999,14 @@ var init_sync_placement_plan = __esm(() => {
13888
13999
  });
13889
14000
 
13890
14001
  // node_modules/@staix/agent-mem/src/memory/sync-placement-journal-format.ts
13891
- var PLACEMENT_JOURNAL_CHUNK_MAX_BYTES, PLACEMENT_JOURNAL_ROOT_MAX_BYTES;
14002
+ var PLACEMENT_JOURNAL_CHUNK_MAX_BYTES, PLACEMENT_JOURNAL_ROOT_MAX_BYTES, PLACEMENT_CHECKPOINT_COMMAND = "amem migrate --sync-placement --checkpoint", PLACEMENT_CHECKPOINT_PENDING_MESSAGE;
13892
14003
  var init_sync_placement_journal_format = __esm(() => {
13893
14004
  init_generation();
13894
14005
  init_policy();
13895
14006
  init_sync_placement_format();
13896
14007
  PLACEMENT_JOURNAL_CHUNK_MAX_BYTES = 64 * 1024;
13897
14008
  PLACEMENT_JOURNAL_ROOT_MAX_BYTES = 256 * 1024;
14009
+ PLACEMENT_CHECKPOINT_PENDING_MESSAGE = `A placement checkpoint is pending; placement effects are paused until it finishes. Run ${PLACEMENT_CHECKPOINT_COMMAND} --resume to complete its recorded bytes, or ${PLACEMENT_CHECKPOINT_COMMAND} --abandon if its commit line has not started.`;
13898
14010
  });
13899
14011
 
13900
14012
  // node_modules/@staix/agent-mem/src/memory/public-prune-view.ts
@@ -13930,7 +14042,6 @@ var init_mutation = __esm(() => {
13930
14042
  init_platform();
13931
14043
  mutations = new WeakMap;
13932
14044
  });
13933
-
13934
14045
  // node_modules/@staix/agent-mem/src/memory/sync-placement-bound.ts
13935
14046
  var PLACEMENT_SOURCE_MAX_BYTES;
13936
14047
  var init_sync_placement_bound = __esm(() => {
@@ -13967,16 +14078,45 @@ var init_sync_placement_writer_revision_format = __esm(() => {
13967
14078
  init_generation();
13968
14079
  init_sync_placement_writers();
13969
14080
  init_sync_placement_format();
14081
+ init_sync_placement_journal_format();
13970
14082
  WRITER_REVISION_MAX_BYTES = 512 * 1024;
13971
14083
  WRITER_COMMIT_MAX_BYTES = 64 * 1024;
13972
14084
  WRITER_RENEWAL_INTENT_MAX_BYTES = 1024 * 1024;
13973
14085
  });
13974
14086
 
14087
+ // node_modules/@staix/agent-mem/src/memory/sync-placement-checkpoint-format.ts
14088
+ var PLACEMENT_CHECKPOINT_LIMIT = 256, PLACEMENT_CHECKPOINT_PAGE_MAX_BYTES, PLACEMENT_CHECKPOINT_MANIFEST_MAX_BYTES, PLACEMENT_CHECKPOINT_COMMITS_MAX_BYTES, PLACEMENT_CHECKPOINT_INTENT_MAX_BYTES, PLACEMENT_CHECKPOINT_ARCHIVE_MAX_BYTES;
14089
+ var init_sync_placement_checkpoint_format = __esm(() => {
14090
+ init_generation();
14091
+ init_sync_placement_journal_format();
14092
+ init_sync_placement_writer_revision_format();
14093
+ PLACEMENT_CHECKPOINT_PAGE_MAX_BYTES = 64 * 1024;
14094
+ PLACEMENT_CHECKPOINT_MANIFEST_MAX_BYTES = 256 * 1024;
14095
+ PLACEMENT_CHECKPOINT_COMMITS_MAX_BYTES = PLACEMENT_CHECKPOINT_LIMIT * 1024;
14096
+ PLACEMENT_CHECKPOINT_INTENT_MAX_BYTES = 1024 * 1024;
14097
+ PLACEMENT_CHECKPOINT_ARCHIVE_MAX_BYTES = 8 * 1024 ** 3;
14098
+ });
14099
+
14100
+ // node_modules/@staix/agent-mem/src/memory/sync-placement-checkpoint-storage.ts
14101
+ var MEMBER_MAX_BYTES;
14102
+ var init_sync_placement_checkpoint_storage = __esm(() => {
14103
+ init_generation();
14104
+ init_platform();
14105
+ init_sync_placement_journal_format();
14106
+ init_sync_placement_checkpoint_format();
14107
+ init_sync_placement_writer_revision_format();
14108
+ init_sync_placement_journal_format();
14109
+ MEMBER_MAX_BYTES = 1024 * 1024;
14110
+ });
14111
+
13975
14112
  // node_modules/@staix/agent-mem/src/memory/sync-placement-writer-history.ts
13976
14113
  var init_sync_placement_writer_history = __esm(() => {
13977
14114
  init_generation();
13978
14115
  init_home_identity();
13979
14116
  init_platform();
14117
+ init_sync_placement_checkpoint_storage();
14118
+ init_sync_placement_checkpoint_format();
14119
+ init_sync_placement_journal_format();
13980
14120
  init_mutation();
13981
14121
  init_sync_placement_writer_revision_format();
13982
14122
  });
@@ -14020,6 +14160,8 @@ var init_sync_placement_journal_storage = __esm(() => {
14020
14160
  init_sync_placement_writer_history();
14021
14161
  init_sync_placement_batch_intent();
14022
14162
  init_formats();
14163
+ init_sync_placement_checkpoint_storage();
14164
+ init_sync_placement_checkpoint_format();
14023
14165
  inflight = new WeakSet;
14024
14166
  publicationDurability = new WeakMap;
14025
14167
  });
@@ -14450,11 +14592,45 @@ var init_capture = __esm(() => {
14450
14592
  });
14451
14593
 
14452
14594
  // node_modules/@staix/agent-mem/src/memory/style.ts
14453
- function style(color) {
14454
- return { color, ok: wrap(color, 32, 39), attention: wrap(color, 33, 39), error: wrap(color, 31, 39), dim: wrap(color, 2, 22), bold: wrap(color, 1, 22) };
14595
+ function paint(role, text, color) {
14596
+ return color && ROLE_SGR[role] ? `${ROLE_SGR[role]}${text}${SGR_RESET}` : text;
14455
14597
  }
14456
- var wrap = (on, open, close) => (text) => on ? `\x1B[${open}m${text}\x1B[${close}m` : text, PLAIN;
14598
+ function style(color, ascii = true) {
14599
+ return {
14600
+ color,
14601
+ ascii,
14602
+ ok: (text) => paint("success", text, color),
14603
+ attention: (text) => paint("warning", text, color),
14604
+ error: (text) => paint("error", text, color),
14605
+ dim: (text) => paint("hint", text, color),
14606
+ bold: (text) => paint("value", text, color)
14607
+ };
14608
+ }
14609
+ var ESC, SGR_RESET, ROLE_SGR, MARKERS, PLAIN;
14457
14610
  var init_style = __esm(() => {
14611
+ ESC = String.fromCharCode(27);
14612
+ SGR_RESET = `${ESC}[0m`;
14613
+ ROLE_SGR = Object.freeze({
14614
+ header: `${ESC}[1;34m`,
14615
+ section: `${ESC}[1;35m`,
14616
+ key: `${ESC}[34m`,
14617
+ value: "",
14618
+ success: `${ESC}[1;32m`,
14619
+ warning: `${ESC}[1;33m`,
14620
+ error: `${ESC}[1;31m`,
14621
+ hint: `${ESC}[90m`,
14622
+ accent: `${ESC}[36m`
14623
+ });
14624
+ MARKERS = Object.freeze({
14625
+ ok: { glyph: "\u2713", ascii: "ok", role: "success" },
14626
+ fail: { glyph: "\u2717", ascii: "x", role: "error" },
14627
+ warn: { glyph: "\u26A0", ascii: "!", role: "warning" },
14628
+ absent: { glyph: "-", ascii: "-", role: "hint" },
14629
+ unknown: { glyph: "?", ascii: "?", role: "hint" },
14630
+ pending: { glyph: "~", ascii: "~", role: "hint" },
14631
+ active: { glyph: "*", ascii: "*", role: "success" },
14632
+ next: { glyph: "\u2192", ascii: "->", role: "accent" }
14633
+ });
14458
14634
  PLAIN = style(false);
14459
14635
  });
14460
14636
 
@@ -14554,6 +14730,7 @@ var init_reader_lease = __esm(() => {
14554
14730
  // node_modules/@staix/agent-mem/src/memory/store.ts
14555
14731
  var DEFAULT_TTL_MS, UNSETTLED_MS, DEFAULT_LEASE_MS, MIGRATION_BOOTSTRAP, curatedDepth, curatedPending;
14556
14732
  var init_store = __esm(() => {
14733
+ init_recap_scratch();
14557
14734
  init_brief_curated();
14558
14735
  init_curated_cache_state();
14559
14736
  init_sync_placement_guard();
@@ -14595,11 +14772,16 @@ var init_catalog = __esm(() => {
14595
14772
  init_capture();
14596
14773
  init_store();
14597
14774
  init_lifecycle();
14775
+ init_sync_placement_guard();
14598
14776
  });
14599
14777
 
14778
+ // node_modules/@staix/agent-mem/src/hook-resources.ts
14779
+ var init_hook_resources = () => {};
14780
+
14600
14781
  // node_modules/@staix/agent-mem/src/memory/metrics.ts
14601
14782
  var METRICS_MAX_BYTES;
14602
14783
  var init_metrics = __esm(() => {
14784
+ init_hook_resources();
14603
14785
  METRICS_MAX_BYTES = 64 * 1024;
14604
14786
  });
14605
14787
 
@@ -14628,6 +14810,7 @@ var init_gc = __esm(() => {
14628
14810
 
14629
14811
  // node_modules/@staix/agent-mem/src/memory/curated-read.ts
14630
14812
  var init_curated_read = __esm(() => {
14813
+ init_recap_scratch();
14631
14814
  init_store();
14632
14815
  init_shard();
14633
14816
  });
@@ -14837,6 +15020,9 @@ var init_commands = __esm(() => {
14837
15020
  // node_modules/@staix/agent-mem/src/memory/shard-migration.ts
14838
15021
  var USER2;
14839
15022
  var init_shard_migration = __esm(() => {
15023
+ init_sync_placement_active();
15024
+ init_sync_placement_guard();
15025
+ init_sync_placement_format();
14840
15026
  init_bridge();
14841
15027
  init_generation();
14842
15028
  init_generation_index();
@@ -14952,6 +15138,7 @@ var init_mcp_memory = __esm(() => {
14952
15138
  init_capture();
14953
15139
  init_generation();
14954
15140
  init_home();
15141
+ init_metrics();
14955
15142
  init_platform();
14956
15143
  init_policy();
14957
15144
  init_config();
@@ -14980,9 +15167,6 @@ var init_record_instruction = __esm(() => {
14980
15167
  MAX_BYTES6 = 64 * 1024;
14981
15168
  });
14982
15169
 
14983
- // node_modules/@staix/agent-mem/src/hook-resources.ts
14984
- var init_hook_resources = () => {};
14985
-
14986
15170
  // node_modules/@staix/agent-mem/src/hook-git.ts
14987
15171
  var init_hook_git = __esm(() => {
14988
15172
  init_platform();
@@ -15082,6 +15266,11 @@ var init_hooks = __esm(() => {
15082
15266
  hookStartedAt = performance.now();
15083
15267
  });
15084
15268
 
15269
+ // node_modules/@staix/agent-mem/src/memory/native-roots.ts
15270
+ var init_native_roots = __esm(() => {
15271
+ init_platform();
15272
+ });
15273
+
15085
15274
  // node_modules/@staix/agent-mem/src/ingest-records.ts
15086
15275
  var init_ingest_records = __esm(() => {
15087
15276
  init_hook_record();
@@ -15092,6 +15281,7 @@ var MAX_BYTES8, DEFAULT_BYTES, MAX_CURSOR_BYTES, utf8, MAX_RECORD;
15092
15281
  var init_ingest = __esm(() => {
15093
15282
  init_capture();
15094
15283
  init_home();
15284
+ init_native_roots();
15095
15285
  init_platform();
15096
15286
  init_policy();
15097
15287
  init_config();
@@ -15150,10 +15340,15 @@ var init_curated_brief_cache = __esm(() => {
15150
15340
  init_store();
15151
15341
  });
15152
15342
 
15343
+ // node_modules/@staix/agent-mem/src/memory/review-targets.ts
15344
+ var init_review_targets = () => {};
15345
+
15153
15346
  // node_modules/@staix/agent-mem/src/memory/decay-review.ts
15154
15347
  var init_decay_review = __esm(() => {
15155
15348
  init_generation();
15156
15349
  init_candidates();
15350
+ init_candidates();
15351
+ init_review_targets();
15157
15352
  });
15158
15353
 
15159
15354
  // node_modules/@staix/agent-mem/src/memory/goal-promotion.ts
@@ -15282,7 +15477,9 @@ var init_sync_placement_effective_writers = __esm(() => {
15282
15477
  init_sync_placement_writer_revision_format();
15283
15478
  init_sync_placement_writer_roots();
15284
15479
  init_sync_placement_prerequisites();
15480
+ init_sync_placement_checkpoint_storage();
15285
15481
  });
15482
+
15286
15483
  // node_modules/@staix/agent-mem/src/memory/sync-placement-capture.ts
15287
15484
  var init_sync_placement_capture = __esm(() => {
15288
15485
  init_sync_placement_journal_format();
@@ -15733,6 +15930,7 @@ var init_sync_placement_writer_context = __esm(() => {
15733
15930
 
15734
15931
  // node_modules/@staix/agent-mem/src/index.ts
15735
15932
  var init_src = __esm(() => {
15933
+ init_platform();
15736
15934
  init_cli_attribution();
15737
15935
  init_search_fts();
15738
15936
  init_platform();
@@ -15783,6 +15981,7 @@ var init_src = __esm(() => {
15783
15981
  init_recall_staleness();
15784
15982
  init_intent_brief();
15785
15983
  init_plan_guard();
15984
+ init_review_targets();
15786
15985
  init_consolidate();
15787
15986
  init_record_candidates();
15788
15987
  init_consolidation_clusters();
@@ -15797,6 +15996,145 @@ var init_src = __esm(() => {
15797
15996
  init_sync_placement_journal();
15798
15997
  });
15799
15998
 
15999
+ // src/hub/log-rotation.ts
16000
+ import { appendFileSync, closeSync as closeSync10, copyFileSync, existsSync as existsSync9, fstatSync as fstatSync9, openSync as openSync10, readdirSync as readdirSync4, readSync as readSync7, renameSync as renameSync5, rmSync as rmSync7, statSync as statSync5, truncateSync } from "fs";
16001
+ import { basename as basename5, dirname as dirname13, join as join20 } from "path";
16002
+ function segmentsOf(file) {
16003
+ const dir = dirname13(file), prefix = `${basename5(file)}.`;
16004
+ let names;
16005
+ try {
16006
+ names = readdirSync4(dir);
16007
+ } catch {
16008
+ names = [];
16009
+ }
16010
+ const rotated = [];
16011
+ for (const name of names) {
16012
+ if (!name.startsWith(prefix))
16013
+ continue;
16014
+ const digits = /^(0|[1-9][0-9]{0,15})$/.exec(name.slice(prefix.length));
16015
+ if (!digits)
16016
+ continue;
16017
+ const path = join20(dir, name);
16018
+ try {
16019
+ const stat = statSync5(path);
16020
+ if (stat.isFile())
16021
+ rotated.push({ path, start: Number(digits[1]), size: stat.size, live: false });
16022
+ } catch {}
16023
+ }
16024
+ rotated.sort((a, b) => a.start - b.start);
16025
+ const last = rotated[rotated.length - 1];
16026
+ const start = last ? last.start + last.size : 0;
16027
+ try {
16028
+ const stat = statSync5(file);
16029
+ if (stat.isFile())
16030
+ rotated.push({ path: file, start, size: stat.size, live: true });
16031
+ } catch {}
16032
+ return rotated;
16033
+ }
16034
+ var EVENTS_SEGMENT_BYTES, HUB_LOG_SEGMENT_BYTES;
16035
+ var init_log_rotation = __esm(() => {
16036
+ EVENTS_SEGMENT_BYTES = 64 * 1024 * 1024;
16037
+ HUB_LOG_SEGMENT_BYTES = 16 * 1024 * 1024;
16038
+ });
16039
+
16040
+ // src/hub/events.ts
16041
+ import { appendFileSync as appendFileSync2, closeSync as closeSync11, existsSync as existsSync10, fstatSync as fstatSync10, openSync as openSync11, readFileSync as readFileSync9, readSync as readSync8 } from "fs";
16042
+ function readEvents(file, since = 0) {
16043
+ for (let attempt = 0;; attempt++) {
16044
+ const segments = segmentsOf(file), out = [];
16045
+ for (const segment of segments) {
16046
+ let text;
16047
+ try {
16048
+ text = readFileSync9(segment.path, "utf8");
16049
+ } catch {
16050
+ continue;
16051
+ }
16052
+ for (const line of text.split(`
16053
+ `)) {
16054
+ const event = parseEventLine(line, since);
16055
+ if (event !== undefined)
16056
+ out.push(event);
16057
+ }
16058
+ }
16059
+ const again = segmentsOf(file);
16060
+ if (attempt >= 3 || again.length === segments.length && again.every((segment, i) => segment.path === segments[i].path && segment.start === segments[i].start))
16061
+ return out;
16062
+ }
16063
+ }
16064
+ function parseEventLine(line, since = 0) {
16065
+ if (!line.trim())
16066
+ return;
16067
+ try {
16068
+ const e = JSON.parse(line);
16069
+ const measuredAt = e.type === "usage" && typeof e.measuredAt === "string" ? e.measuredAt : e.at;
16070
+ return Date.parse(measuredAt) >= since ? e : undefined;
16071
+ } catch {
16072
+ return;
16073
+ }
16074
+ }
16075
+ var init_events = __esm(() => {
16076
+ init_log_rotation();
16077
+ });
16078
+
16079
+ // src/hub/tooling.ts
16080
+ var identities;
16081
+ var init_tooling = __esm(() => {
16082
+ init_registry();
16083
+ init_project();
16084
+ identities = new Map;
16085
+ });
16086
+
16087
+ // src/hub/bench.ts
16088
+ var TASK_FIELDS, CLASSES3, HEAD;
16089
+ var init_bench = __esm(() => {
16090
+ init_project();
16091
+ init_process_signature();
16092
+ TASK_FIELDS = new Set(["id", "title", "detail", "class", "owner", "ref", "setup", "verify", "timeout_s"]);
16093
+ CLASSES3 = new Set(["plan", "implement", "bulk_edit", "test", "review", "summarize", "triage"]);
16094
+ HEAD = `${"".padEnd(28)} ${"attempts".padStart(8)} ${"pass".padStart(5)} ${"p/f/t/e".padStart(11)} ${"first pass".padStart(10)} ${"rework".padStart(6)} ${"tokens p50".padStart(10)} ${"wall p50".padStart(8)}`;
16095
+ });
16096
+
16097
+ // src/hub/research-memory.ts
16098
+ var UNKNOWN_MEMORY_FIGURES;
16099
+ var init_research_memory = __esm(() => {
16100
+ UNKNOWN_MEMORY_FIGURES = Object.freeze({ rendered: null, delivered: null, cited: null, failsExposed: null, failsCited: null, failRetrySignal: null });
16101
+ });
16102
+
16103
+ // src/hub/person-figures.ts
16104
+ var UNKNOWN_PERSON_FIGURES, ALLOW, DENY;
16105
+ var init_person_figures = __esm(() => {
16106
+ UNKNOWN_PERSON_FIGURES = Object.freeze({ permissions: null, questions: null, completions: null, cliRefusals: null, consoleConfirmations: null, latencyMs: null });
16107
+ ALLOW = new Set(["allow_once", "allow_always"]);
16108
+ DENY = new Set(["reject_once", "reject_always"]);
16109
+ });
16110
+
16111
+ // src/hub/cost-governance.ts
16112
+ var init_cost_governance = () => {};
16113
+
16114
+ // src/hub/research-record.ts
16115
+ var NO_EVIDENCE;
16116
+ var init_research_record = __esm(() => {
16117
+ init_cost_governance();
16118
+ init_db_schema();
16119
+ init_sdlc_metrics();
16120
+ NO_EVIDENCE = { tasks: new Map, board: false };
16121
+ });
16122
+
16123
+ // src/hub/research.ts
16124
+ var FAILED, TRACKED2;
16125
+ var init_research2 = __esm(() => {
16126
+ init_log_rotation();
16127
+ init_events();
16128
+ init_project();
16129
+ init_tooling();
16130
+ init_bench();
16131
+ init_research_memory();
16132
+ init_person_figures();
16133
+ init_research_record();
16134
+ FAILED = new Set(["regressed", "reverted", "incomplete", "wrong", "abandoned"]);
16135
+ TRACKED2 = new Set(["hub_start", "state", "tooling", "memory_brief", "task", "usage"]);
16136
+ });
16137
+
15800
16138
  // src/hub/deliverables.ts
15801
16139
  var DELIVERABLE_LIMITS;
15802
16140
  var init_deliverables = __esm(() => {
@@ -15815,6 +16153,8 @@ var BODY2;
15815
16153
  var init_research_experiments = __esm(() => {
15816
16154
  init_src();
15817
16155
  init_packs();
16156
+ init_research2();
16157
+ init_events();
15818
16158
  init_research_runner();
15819
16159
  init_deliverables();
15820
16160
  BODY2 = 64 * 1024;
@@ -15832,12 +16172,13 @@ var init_planning = __esm(() => {
15832
16172
  });
15833
16173
 
15834
16174
  // src/hub/roadmap.ts
15835
- var MILESTONE_STATES, MILESTONE_HORIZONS, MILESTONE_LINK_KINDS, MILESTONE_LIMITS;
16175
+ var MILESTONE_STATES, MILESTONE_HORIZONS, MILESTONE_LINK_KINDS, MILESTONE_LIMITS, DECOMPOSE_LIMITS;
15836
16176
  var init_roadmap = __esm(() => {
15837
16177
  MILESTONE_STATES = ["proposed", "planned", "active", "done", "dropped"];
15838
16178
  MILESTONE_HORIZONS = ["now", "next", "later"];
15839
16179
  MILESTONE_LINK_KINDS = ["spec", "issue", "task", "release"];
15840
16180
  MILESTONE_LIMITS = Object.freeze({ title: 300, outcome: 4000, spec: 160, issue: 300, actor: 64 });
16181
+ DECOMPOSE_LIMITS = Object.freeze({ parts: 8, title: 300, detail: 1200, cites: 16 });
15841
16182
  });
15842
16183
 
15843
16184
  // src/hub/research-campaign.ts
@@ -15862,7 +16203,7 @@ var init_considered_findings = __esm(() => {
15862
16203
  });
15863
16204
 
15864
16205
  // src/hub/board.ts
15865
- var SURVEY_STORE_BYTES, GUIDANCE_VARIANT_SELECT, HOST_MERGE_ADOPTION, HOST_SPEC_ACCEPTANCE_CARRY, EXECUTION_REFERENCE_SELECT, CLASSES2, SPEC_ACCEPTANCE_FIELD_BYTES, SPEC_ACCEPTANCE_TOTAL_BYTES, PLAN_KEYS, ALL_PLAN_KEYS, OUTCOMES_KEPT_MS;
16206
+ var SURVEY_STORE_BYTES, GUIDANCE_VARIANT_SELECT, HOST_MERGE_ADOPTION, HOST_SPEC_ACCEPTANCE_CARRY, HOST_ROADMAP_DRAFT, EXECUTION_REFERENCE_SELECT, CLASSES2, SPEC_ACCEPTANCE_FIELD_BYTES, SPEC_ACCEPTANCE_TOTAL_BYTES, PLAN_KEYS, ALL_PLAN_KEYS, OUTCOMES_KEPT_MS;
15866
16207
  var init_board = __esm(() => {
15867
16208
  init_tool_refusal();
15868
16209
  init_guidance_variants();
@@ -15895,6 +16236,7 @@ var init_board = __esm(() => {
15895
16236
  CASE WHEN withdrawn_by IS NULL OR typeof(withdrawn_by)='text' AND length(CAST(withdrawn_by AS BLOB))<=${EXECUTION_REFERENCE_LIMITS.id} THEN 1 ELSE 0 END AS valid_withdrawn_by`;
15896
16237
  HOST_MERGE_ADOPTION = Symbol("host merge adoption");
15897
16238
  HOST_SPEC_ACCEPTANCE_CARRY = Symbol("host spec acceptance carry");
16239
+ HOST_ROADMAP_DRAFT = Symbol("host roadmap acceptance draft");
15898
16240
  EXECUTION_REFERENCE_SELECT = `SELECT
15899
16241
  CASE WHEN length(CAST(id AS BLOB))=64 THEN id END AS id,
15900
16242
  CASE WHEN length(CAST(project_id AS BLOB)) BETWEEN 1 AND 256 THEN project_id END AS project_id,
@@ -16232,7 +16574,7 @@ var init_config2 = __esm(() => {
16232
16574
  });
16233
16575
 
16234
16576
  // src/hub/routing.ts
16235
- import { join as join19, resolve as resolve13 } from "path";
16577
+ import { join as join21, resolve as resolve13 } from "path";
16236
16578
  function effectiveLocalRoute(defaultRoute, classRoute, classFixedModel) {
16237
16579
  return classRoute ?? (classFixedModel === undefined ? defaultRoute : undefined);
16238
16580
  }
@@ -16246,7 +16588,7 @@ var init_routing = __esm(() => {
16246
16588
  init_spec_read();
16247
16589
  init_config2();
16248
16590
  init_stage_fallback();
16249
- TEMPLATE = join19(import.meta.dir, "..", "..", "templates", "routing.toml");
16591
+ TEMPLATE = join21(import.meta.dir, "..", "..", "templates", "routing.toml");
16250
16592
  cache = new Map;
16251
16593
  });
16252
16594
 
@@ -18779,8 +19121,10 @@ var init_hub_tools = __esm(() => {
18779
19121
  TASK_TOOLS = [
18780
19122
  tool2("hub_roadmap_list", "Read public milestones with computed task/issue/spec/train progress. Private work is a count only; unknown evidence stays unknown. Read only, with no GitHub or model call.", {}),
18781
19123
  tool2("hub_roadmap_show", "Read a milestone's public links, inherited membership and computed progress. Inspect this before editing and copy its current revision. Private tasks are counts only.", { id: { type: "integer", minimum: 1 } }, ["id"]),
19124
+ tool2("hub_roadmap_check", "Read roadmap drift findings and unknown evidence. Private tasks stay withheld; no writes are made.", {}),
18782
19125
  tool2("hub_roadmap_unplaced", "Read the open GitHub issues, open board tasks and active/draft specs that no live milestone places, each with why. Private tasks are a count only. partial: true means the GitHub read stopped early or a list was cut, so the lists are a lower bound; unavailable names evidence that could not be read. Read only: no write, no model call. Optional repo is owner/name.", { repo: { type: "string", maxLength: MILESTONE_LIMITS.issue } }),
18783
19126
  tool2("hub_roadmap_triage", "Ask the hub's model to suggest a milestone (or a new one) for unplaced work. Each suggestion cites the milestone and item words it matched and is saved as a pending model answer; nothing is linked until hub_roadmap_edit accept. Configured planner or unique conductor only. list: true reads the pending public suggestions without a model call and is open to any agent.", { repo: { type: "string", maxLength: MILESTONE_LIMITS.issue }, list: { type: "boolean" } }),
19127
+ tool2("hub_roadmap_decompose", "Ask the hub's model to decompose one milestone into parts, from its outcome, the specs it links and the issues it links. Each part cites linked ids and says whether it needs a spec issue or goes straight to a task; the answer is saved as a pending model answer and nothing is linked, intaken or published. Pass accept with one part's number to hold that part as an intake draft instead: it is linked to the milestone, carries the part's spec-issue or task kind, and is offered to nobody until the person releases it with ahub intake approve. Configured planner or unique conductor only. On refusal inspect hub_roadmap_show and correct the named input.", { id: { type: "integer", minimum: 1 }, accept: { type: "integer", minimum: 1 } }, ["id"]),
18784
19128
  tool2("hub_roadmap_edit", "Create or change a milestone. Configured planner or unique conductor only; done/dropped are person-only. new/edit take fields; edit also needs the current revision. Link kinds are spec/issue/task/release; issue refs are owner/repo#N. accept applies exactly one pending triage suggestion through link (creating its proposed milestone first); reject drops it. No GitHub write, task assignment or model call. On refusal inspect hub_roadmap_show and correct the named input.", {
18785
19129
  op: { type: "string", enum: ["new", "edit", "link", "unlink", "order", "state", "accept", "reject"] },
18786
19130
  id: { type: "integer", minimum: 1 },
@@ -18814,7 +19158,7 @@ var init_hub_tools = __esm(() => {
18814
19158
  tool2("hub_delivery_resolve", "Confirm completion or discard your own needs_review delivery using the revision shown by hub_inbox. Requires a reason. Never replays the delivery or changes task state; another peer's row and stale revisions are refused.", { delivery_id: { type: "string", minLength: 1, maxLength: 256 }, revision: { type: "integer", minimum: 0 }, action: { type: "string", enum: ["completed", "discard"] }, reason: { type: "string", minLength: 1, maxLength: 1000 } }, ["delivery_id", "revision", "action", "reason"]),
18815
19159
  tool2("hub_backlog_list", "Read public backlog cards with planning revisions. Configured planners only; PII remains a stub.", {}),
18816
19160
  tool2("hub_backlog_plan", "Plan an unpinned backlog item outside frozen releases with the revision you read and a bounded reason. Omit fields or give {} for a note-only revision. fields.sdlc accepts only repo/issue identity on unstarted backlog work; relinking clears old spec acceptance. A person's rank is retained. Actual dates cannot be set. fields.needsPerson (marking a leg only the person can run) is the person's: an agent that sends it, or plans a marked card, is refused.", { id: id2, revision: { type: "integer", minimum: 0 }, reason: { type: "string", maxLength: 1000 }, fields: { type: "object", properties: { sdlc: { type: "object", minProperties: 1, properties: { repo: { type: ["string", "null"], maxLength: 400 }, issue: { type: ["integer", "null"], minimum: 1 } }, additionalProperties: false }, rank: { type: ["integer", "null"], minimum: 0 }, priority: { type: ["integer", "null"], minimum: 0, maximum: 3 }, release: { type: ["integer", "null"], minimum: 1 }, plannedStart: { type: ["integer", "null"], minimum: 1 }, due: { type: ["integer", "null"], minimum: 1 }, deps: { type: "array", maxItems: 64, uniqueItems: true, items: { type: "integer", minimum: 1 } }, reserved: { type: ["string", "null"], minLength: 1, maxLength: 32 }, needsPerson: { type: "boolean" } }, additionalProperties: false } }, ["id", "revision", "reason"]),
18817
- tool2("hub_backlog_pull", "Reserve a WIP slot and pull ready unpinned backlog work into To Do at its current revision. Preserves person order/reservations and frozen scope; pending unowned work can be undone with hub_backlog_undo.", { id: id2, revision: { type: "integer", minimum: 0 }, reason: { type: "string", minLength: 1, maxLength: 1000 } }, ["id", "revision", "reason"]),
19161
+ tool2("hub_backlog_pull", "Configured planners only. Reserve a WIP slot and pull ready unpinned backlog work into To Do at its current revision. Preserves person order/reservations and frozen scope; pending unowned work can be undone with hub_backlog_undo.", { id: id2, revision: { type: "integer", minimum: 0 }, reason: { type: "string", minLength: 1, maxLength: 1000 } }, ["id", "revision", "reason"]),
18818
19162
  tool2("hub_backlog_split", "Split unstarted backlog work into two to eight staged parts. The original card retains integration/acceptance and depends on the children. Use after for existing prerequisite ids and afterParts for earlier zero-based part indexes. Latest unused unchanged children can be undone with hub_backlog_undo.", { id: id2, revision: { type: "integer", minimum: 0 }, reason: { type: "string", minLength: 1, maxLength: 1000 }, parts: { type: "array", minItems: 2, maxItems: 8, items: { type: "object", properties: { title: { type: "string", minLength: 1, maxLength: 300 }, detail: { type: "string", maxLength: 8000 }, class: str2, refs, plan, after: { type: "array", maxItems: 64, uniqueItems: true, items: { type: "integer", minimum: 1 } }, afterParts: { type: "array", maxItems: 8, uniqueItems: true, items: { type: "integer", minimum: 0 } } }, required: ["title"], additionalProperties: false } } }, ["id", "revision", "reason", "parts"]),
18819
19163
  tool2("hub_backlog_undo", "Undo your latest planning change at its current revision. Refuses intervening changes and another actor's edit.", { id: id2, revision: { type: "integer", minimum: 1 } }, ["id", "revision"]),
18820
19164
  tool2("hub_study_draft", "Store a research campaign contract as a DRAFT revision 1 on an approved parent task. Configured planners only; it creates no task, dispatches nothing and never approves (only the person approves, with ahub study approve). The contract is data: question, scope, exclusions, sourceIds, units, deliverableSections, stopPolicy and an optional budget.", { parentTaskId: id2, contract: { type: "object" } }, ["parentTaskId", "contract"]),
@@ -19424,7 +19768,7 @@ var init_local_worker = __esm(() => {
19424
19768
  }
19425
19769
  const taskToolName = name.replace(/^mcp__[^ ]+__/, "");
19426
19770
  const reviewNoteWrite = taskToolName === "hub_remember" || taskToolName === "hub_task_propose";
19427
- const toolRun = () => this.probeConfinement && !["read", "write", "edit"].includes(name) ? Promise.resolve(formatProbeToolRefusal(new ProbeToolRefusal("tool_unavailable"))) : reviewScope.excluded && reviewNoteWrite ? Promise.resolve("error: anchored review in this batch; save notes in a later turn") : (TASK_TOOL_NAMES.has(name) || CONDUCTOR_TOOL_NAMES.has(name)) && this.opts.taskTool ? this.opts.taskTool(name, safeParse(call.function.arguments), { pii: !!policy?.pii, signal: turnSignal }).catch((e) => `error: ${e.message}`) : runTool(name, call.function.arguments, ctx);
19771
+ const toolRun = () => this.probeConfinement && !["read", "write", "edit"].includes(name) ? Promise.resolve(formatProbeToolRefusal(new ProbeToolRefusal("tool_unavailable"))) : reviewScope.excluded && reviewNoteWrite ? Promise.resolve("error: anchored review in this batch; save notes in a later turn") : (TASK_TOOL_NAMES.has(name) || CONDUCTOR_TOOL_NAMES.has(name)) && this.opts.taskTool ? this.opts.taskTool(name, safeParse(call.function.arguments), { pii: !!policy?.pii, signal: turnSignal }).catch((e) => `error: ${e.message}`) : runTool(name, call.function.arguments, this.probeConfinement ? ctx : this.toolContext(envs, turnSignal, !!policy?.pii, reply, policy?.task));
19428
19772
  const probe = this.probeSession;
19429
19773
  const running = probe ? (async () => {
19430
19774
  try {
@@ -19488,6 +19832,7 @@ var init_local_worker = __esm(() => {
19488
19832
  ...this.opts.tools.docRead ? { docRead: { ...this.opts.tools.docRead, pii } } : {},
19489
19833
  ...this.opts.tools.webFetch ? { webFetch: { ...this.opts.tools.webFetch, pii } } : {},
19490
19834
  cwd: this.opts.cwd,
19835
+ ...this.opts.tools.editGuard && !probe ? { editGuard: this.opts.tools.editGuard(task, () => !turnSignal.aborted && executionGeneration === this.turn) } : {},
19491
19836
  deny: this.opts.tools.deny,
19492
19837
  readOnly: this.opts.tools.readOnly,
19493
19838
  ...probe ? { probe: {
@@ -19843,12 +20188,12 @@ var init_launch2 = __esm(() => {
19843
20188
 
19844
20189
  // src/adapters/claude-task-sessions.ts
19845
20190
  import { randomUUID as randomUUID8 } from "crypto";
19846
- import { mkdirSync as mkdirSync11, readFileSync as readFileSync9 } from "fs";
19847
- import { dirname as dirname13 } from "path";
20191
+ import { mkdirSync as mkdirSync11, readFileSync as readFileSync10 } from "fs";
20192
+ import { dirname as dirname14 } from "path";
19848
20193
  function readState(file) {
19849
20194
  let text;
19850
20195
  try {
19851
- text = readFileSync9(file, "utf8");
20196
+ text = readFileSync10(file, "utf8");
19852
20197
  } catch (error) {
19853
20198
  if (error.code === "ENOENT")
19854
20199
  return { version: 1, sessions: {} };
@@ -19881,7 +20226,7 @@ class ClaudeTaskSessions {
19881
20226
  }
19882
20227
  write(sessions) {
19883
20228
  const next = { version: 1, sessions };
19884
- mkdirSync11(dirname13(this.file), { recursive: true, mode: 448 });
20229
+ mkdirSync11(dirname14(this.file), { recursive: true, mode: 448 });
19885
20230
  atomicPrivateJSON(this.file, next);
19886
20231
  this.state = next;
19887
20232
  }
@@ -19975,9 +20320,9 @@ __export(exports_claude_implementer, {
19975
20320
  ClaudeImplementerPeer: () => ClaudeImplementerPeer
19976
20321
  });
19977
20322
  import { randomUUID as randomUUID9 } from "crypto";
19978
- import { lstatSync as lstatSync18, mkdtempSync as mkdtempSync6, rmSync as rmSync7, writeFileSync as writeFileSync9 } from "fs";
20323
+ import { lstatSync as lstatSync19, mkdtempSync as mkdtempSync6, rmSync as rmSync8, writeFileSync as writeFileSync9 } from "fs";
19979
20324
  import { tmpdir as tmpdir5 } from "os";
19980
- import { join as join20 } from "path";
20325
+ import { join as join22 } from "path";
19981
20326
  function provenVersion(binding) {
19982
20327
  return provenVersions.get(binding);
19983
20328
  }
@@ -20033,10 +20378,10 @@ function claudeImplementerArgs(turn, mcp, settings, prompt, model) {
20033
20378
  async function proveClaudeImplementer(peer, command) {
20034
20379
  const binary = Bun.which(command[0], { PATH: process.env.PATH }) ?? command[0];
20035
20380
  const fingerprint = () => {
20036
- const file = realPath(binary), stat = lstatSync18(file);
20381
+ const file = realPath(binary), stat = lstatSync19(file);
20037
20382
  return [file, stat.dev, stat.ino, stat.size, stat.mtimeMs, stat.ctimeMs].join(":");
20038
20383
  };
20039
- const binding = fingerprint(), home = mkdtempSync6(join20(tmpdir5(), "ahub-claude-proof-"));
20384
+ const binding = fingerprint(), home = mkdtempSync6(join22(tmpdir5(), "ahub-claude-proof-"));
20040
20385
  let version = "", timedOut = false;
20041
20386
  const child = new OwnedPrintChild({
20042
20387
  peer,
@@ -20045,7 +20390,7 @@ async function proveClaudeImplementer(peer, command) {
20045
20390
  cwd: home,
20046
20391
  input: "",
20047
20392
  envMode: "replace",
20048
- env: { PATH: process.env.PATH, HOME: home, CLAUDE_CONFIG_DIR: join20(home, ".claude") },
20393
+ env: { PATH: process.env.PATH, HOME: home, CLAUDE_CONFIG_DIR: join22(home, ".claude") },
20049
20394
  maxFrameBytes: 4096,
20050
20395
  maxOutputBytes: 4096,
20051
20396
  onLine: (line) => {
@@ -20081,7 +20426,7 @@ async function proveClaudeImplementer(peer, command) {
20081
20426
  } finally {
20082
20427
  clearTimeout(timer);
20083
20428
  await child.stop();
20084
- rmSync7(home, { recursive: true, force: true });
20429
+ rmSync8(home, { recursive: true, force: true });
20085
20430
  }
20086
20431
  }
20087
20432
  var provenVersions, ClaudeImplementerPeer;
@@ -20132,7 +20477,7 @@ var init_claude_implementer = __esm(() => {
20132
20477
  if (options.mode !== undefined && options.mode !== "ask" && options.mode !== "ask-when-needed")
20133
20478
  throw new Error("Claude implementer refuses unsupported permission mode");
20134
20479
  this.mode = options.mode ?? "ask";
20135
- this.sessions = new ClaudeTaskSessions(join20(options.stateDir, claudeStateFile("claude-task-sessions", id)));
20480
+ this.sessions = new ClaudeTaskSessions(join22(options.stateDir, claudeStateFile("claude-task-sessions", id)));
20136
20481
  }
20137
20482
  get permissionModeState() {
20138
20483
  return this.mode;
@@ -20301,9 +20646,9 @@ var init_claude_implementer = __esm(() => {
20301
20646
  this.observerSessionIdValue = turn.sessionId;
20302
20647
  this.currentInputContext = inputContext;
20303
20648
  this.options.beforeInput?.(inputContext, group.envs);
20304
- const launchId = randomUUID9(), directory = mkdtempSync6(join20(this.options.stateDir, "claude-child-")), settings = join20(directory, "settings.json");
20649
+ const launchId = randomUUID9(), directory = mkdtempSync6(join22(this.options.stateDir, "claude-child-")), settings = join22(directory, "settings.json");
20305
20650
  let launchFailureTrace;
20306
- this.cleanup = () => rmSync7(directory, { recursive: true, force: true });
20651
+ this.cleanup = () => rmSync8(directory, { recursive: true, force: true });
20307
20652
  writeFileSync9(settings, sessionSettings(undefined, { script: this.options.factsHook, stateDir: this.options.stateDir, purpose: "permission" }), { mode: 384, flag: "wx" });
20308
20653
  const env = {
20309
20654
  AGENTHUB_MODE: "tools",
@@ -20646,9 +20991,9 @@ var init_reviewer_variants = __esm(() => {
20646
20991
  });
20647
20992
 
20648
20993
  // src/adapters/agy/hooks.ts
20649
- import { closeSync as closeSync10, constants as constants9, fstatSync as fstatSync9, lstatSync as lstatSync19, openSync as openSync10, readSync as readSync7 } from "fs";
20994
+ import { closeSync as closeSync12, constants as constants9, fstatSync as fstatSync11, lstatSync as lstatSync20, openSync as openSync12, readSync as readSync9 } from "fs";
20650
20995
  import { homedir as homedir5 } from "os";
20651
- import { isAbsolute as isAbsolute7, join as join21, relative as relative5 } from "path";
20996
+ import { isAbsolute as isAbsolute7, join as join23, relative as relative5 } from "path";
20652
20997
  import { createHash as createHash12 } from "crypto";
20653
20998
  function agyModel(value) {
20654
20999
  const model = safeModelLabel(value);
@@ -20703,19 +21048,19 @@ function readAgyTranscript(session, transcript, options) {
20703
21048
  if (!UUID2.test(session))
20704
21049
  return empty;
20705
21050
  const home = process.env.HOME ?? homedir5();
20706
- const candidates = ["antigravity-cli", "antigravity", "antigravity-ide"].map((surface) => join21(home, ".gemini", surface, "brain", session, ".system_generated/logs/transcript_full.jsonl"));
21051
+ const candidates = ["antigravity-cli", "antigravity", "antigravity-ide"].map((surface) => join23(home, ".gemini", surface, "brain", session, ".system_generated/logs/transcript_full.jsonl"));
20707
21052
  if (!candidates.includes(transcript))
20708
21053
  return empty;
20709
21054
  let fd;
20710
21055
  try {
20711
21056
  let cursor = home;
20712
21057
  for (const name of relative5(home, transcript).split("/")) {
20713
- cursor = join21(cursor, name);
20714
- if (lstatSync19(cursor).isSymbolicLink())
21058
+ cursor = join23(cursor, name);
21059
+ if (lstatSync20(cursor).isSymbolicLink())
20715
21060
  return empty;
20716
21061
  }
20717
- fd = openSync10(transcript, constants9.O_RDONLY | constants9.O_NOFOLLOW);
20718
- const stat = fstatSync9(fd);
21062
+ fd = openSync12(transcript, constants9.O_RDONLY | constants9.O_NOFOLLOW);
21063
+ const stat = fstatSync11(fd);
20719
21064
  if (!stat.isFile() || stat.nlink !== 1)
20720
21065
  return empty;
20721
21066
  if (options?.unchanged && stat.size === options.unchanged.size && stat.mtimeMs === options.unchanged.mtimeMs)
@@ -20730,7 +21075,7 @@ function readAgyTranscript(session, transcript, options) {
20730
21075
  const buffer = Buffer.alloc(stat.size - from);
20731
21076
  let bytes = 0;
20732
21077
  while (bytes < buffer.length) {
20733
- const count = readSync7(fd, buffer, bytes, buffer.length - bytes, from + bytes);
21078
+ const count = readSync9(fd, buffer, bytes, buffer.length - bytes, from + bytes);
20734
21079
  if (!count)
20735
21080
  break;
20736
21081
  bytes += count;
@@ -20791,7 +21136,7 @@ function readAgyTranscript(session, transcript, options) {
20791
21136
  return empty;
20792
21137
  } finally {
20793
21138
  if (fd !== undefined)
20794
- closeSync10(fd);
21139
+ closeSync12(fd);
20795
21140
  }
20796
21141
  }
20797
21142
  var EVENTS2, UUID2, record6 = (value) => !!value && typeof value === "object" && !Array.isArray(value), AGY_FACTS_HOOK;
@@ -20869,8 +21214,8 @@ function builtinCliEntries(definitions) {
20869
21214
  return Object.freeze(definitions.flatMap((definition) => definition.cli.entry ? [Object.freeze({ ...definition.cli.entry, command: definition.cli.command })] : []));
20870
21215
  }
20871
21216
  // src/adapters/definitions/native-cli-entry-claude.ts
20872
- import { readFileSync as readFileSync10 } from "fs";
20873
- import { join as join22 } from "path";
21217
+ import { readFileSync as readFileSync11 } from "fs";
21218
+ import { join as join24 } from "path";
20874
21219
  import { randomUUID as randomUUID10 } from "crypto";
20875
21220
  async function runClaudeEntry(ctx) {
20876
21221
  const { args, cwd, stateDir, cliDir, unattendedEnv, projectConfig, fail } = ctx;
@@ -20921,17 +21266,17 @@ async function runClaudeEntry(ctx) {
20921
21266
  }
20922
21267
  }
20923
21268
  let original;
20924
- for (const file of [join22(executionCwd, ".claude", "settings.local.json"), join22(executionCwd, ".claude", "settings.json"), join22(process.env.HOME ?? "", ".claude", "settings.json")]) {
21269
+ for (const file of [join24(executionCwd, ".claude", "settings.local.json"), join24(executionCwd, ".claude", "settings.json"), join24(process.env.HOME ?? "", ".claude", "settings.json")]) {
20925
21270
  try {
20926
- original ??= JSON.parse(readFileSync10(file, "utf8")).statusLine;
21271
+ original ??= JSON.parse(readFileSync11(file, "utf8")).statusLine;
20927
21272
  } catch {}
20928
21273
  }
20929
- const facts = claudeObservationHooks(projectConfig(), { script: join22(cliDir, "facts-hook.ts"), stateDir });
21274
+ const facts = claudeObservationHooks(projectConfig(), { script: join24(cliDir, "facts-hook.ts"), stateDir });
20930
21275
  let previousLaunch;
20931
21276
  try {
20932
- previousLaunch = JSON.parse(readFileSync10(join22(stateDir, claudeStateFile("claude-launch", peer)), "utf8"));
21277
+ previousLaunch = JSON.parse(readFileSync11(join24(stateDir, claudeStateFile("claude-launch", peer)), "utf8"));
20933
21278
  } catch {}
20934
- const launch = buildLaunch("claude", args, { unattended: unattendedEnv, statusLine: { script: join22(cliDir, "statusline-tee.ts"), stateDir, ...original ? { original } : {} }, ...facts ? { facts } : {} });
21279
+ const launch = buildLaunch("claude", args, { unattended: unattendedEnv, statusLine: { script: join24(cliDir, "statusline-tee.ts"), stateDir, ...original ? { original } : {} }, ...facts ? { facts } : {} });
20935
21280
  let result;
20936
21281
  try {
20937
21282
  let launchRecord;
@@ -21025,15 +21370,15 @@ var init_native_cli_entry_codex = () => {};
21025
21370
 
21026
21371
  // src/cli/kimi-plugin.ts
21027
21372
  import { randomUUID as randomUUID11 } from "crypto";
21028
- import { closeSync as closeSync11, lstatSync as lstatSync20, mkdirSync as mkdirSync12, openSync as openSync11, readFileSync as readFileSync11, renameSync as renameSync5, rmdirSync as rmdirSync4, unlinkSync as unlinkSync4, writeFileSync as writeFileSync10 } from "fs";
21029
- import { dirname as dirname14, isAbsolute as isAbsolute8, join as join23 } from "path";
21373
+ import { closeSync as closeSync13, lstatSync as lstatSync21, mkdirSync as mkdirSync12, openSync as openSync13, readFileSync as readFileSync12, renameSync as renameSync6, rmdirSync as rmdirSync4, unlinkSync as unlinkSync4, writeFileSync as writeFileSync10 } from "fs";
21374
+ import { dirname as dirname15, isAbsolute as isAbsolute8, join as join25 } from "path";
21030
21375
  function file(path, cap) {
21031
- const stat = lstatSync20(path, { throwIfNoEntry: false });
21376
+ const stat = lstatSync21(path, { throwIfNoEntry: false });
21032
21377
  if (!stat)
21033
21378
  return;
21034
21379
  if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > cap)
21035
21380
  throw new Error(`${path} must be a bounded regular file`);
21036
- return { stat, bytes: readFileSync11(path) };
21381
+ return { stat, bytes: readFileSync12(path) };
21037
21382
  }
21038
21383
  function parse2(value, name) {
21039
21384
  if (!value)
@@ -21048,28 +21393,28 @@ function parse2(value, name) {
21048
21393
  }
21049
21394
  }
21050
21395
  function atomic(path, bytes, before) {
21051
- const current = lstatSync20(path, { throwIfNoEntry: false });
21396
+ const current = lstatSync21(path, { throwIfNoEntry: false });
21052
21397
  if (before ? !current || current.dev !== before.dev || current.ino !== before.ino : current)
21053
21398
  throw new Error(`${path} changed before its managed write`);
21054
21399
  const temporary = `${path}.${randomUUID11()}.tmp`;
21055
21400
  let fd;
21056
21401
  try {
21057
- fd = openSync11(temporary, "wx", 384);
21402
+ fd = openSync13(temporary, "wx", 384);
21058
21403
  writeFileSync10(fd, bytes);
21059
- closeSync11(fd);
21404
+ closeSync13(fd);
21060
21405
  fd = undefined;
21061
- renameSync5(temporary, path);
21406
+ renameSync6(temporary, path);
21062
21407
  } finally {
21063
21408
  if (fd !== undefined)
21064
- closeSync11(fd);
21409
+ closeSync13(fd);
21065
21410
  try {
21066
21411
  unlinkSync4(temporary);
21067
21412
  } catch {}
21068
21413
  }
21069
21414
  }
21070
21415
  function removeFile(path, expected) {
21071
- const current = lstatSync20(path, { throwIfNoEntry: false });
21072
- if (!current || !current.isFile() || current.isSymbolicLink() || current.nlink !== 1 || !readFileSync11(path).equals(expected))
21416
+ const current = lstatSync21(path, { throwIfNoEntry: false });
21417
+ if (!current || !current.isFile() || current.isSymbolicLink() || current.nlink !== 1 || !readFileSync12(path).equals(expected))
21073
21418
  return;
21074
21419
  unlinkSync4(path);
21075
21420
  }
@@ -21099,7 +21444,7 @@ function plan2(options) {
21099
21444
  const hook = file(options.hookScript, MAX_HOOK);
21100
21445
  if (!hook)
21101
21446
  throw new Error("Kimi hook bundle is missing");
21102
- const root = join23(options.home, "plugins"), managed = join23(root, "managed", ID2), installed = join23(root, "installed.json");
21447
+ const root = join25(options.home, "plugins"), managed = join25(root, "managed", ID2), installed = join25(root, "installed.json");
21103
21448
  const installedBefore = file(installed, MAX_INSTALLED), document = parse2(installedBefore, installed);
21104
21449
  if (document && (document.version !== 1 || !Array.isArray(document.plugins)))
21105
21450
  throw new Error(`${installed} has an unsupported shape`);
@@ -21112,11 +21457,11 @@ function plan2(options) {
21112
21457
  if (record && (record.root !== managed || record.source !== "local-path" || record.origin !== "custom" || record.enabled !== true || typeof record.originalSource !== "string" || record.agentHubLaunch !== options.launchId && options.replaceStale !== true)) {
21113
21458
  throw new Error("Kimi's agent-hub plugin belongs to another launch or is disabled; it was not changed");
21114
21459
  }
21115
- const manifestBefore = file(join23(managed, "kimi.plugin.json"), MAX_INSTALLED), hookBefore = file(join23(managed, "kimi-hook.js"), MAX_HOOK);
21460
+ const manifestBefore = file(join25(managed, "kimi.plugin.json"), MAX_INSTALLED), hookBefore = file(join25(managed, "kimi-hook.js"), MAX_HOOK);
21116
21461
  const nextManifest = Buffer.from(`${JSON.stringify(manifest(), null, 2)}
21117
21462
  `);
21118
21463
  const now = new Date(options.now ?? Date.now()).toISOString();
21119
- const changed = !record || record.agentHubLaunch !== options.launchId || !record.agentHubOwner || !manifestBefore?.bytes.equals(nextManifest) || !hookBefore?.bytes.equals(hook.bytes) || record.originalSource !== dirname14(options.hookScript);
21464
+ const changed = !record || record.agentHubLaunch !== options.launchId || !record.agentHubOwner || !manifestBefore?.bytes.equals(nextManifest) || !hookBefore?.bytes.equals(hook.bytes) || record.originalSource !== dirname15(options.hookScript);
21120
21465
  const nextRecord = {
21121
21466
  id: ID2,
21122
21467
  root: managed,
@@ -21125,7 +21470,7 @@ function plan2(options) {
21125
21470
  enabled: true,
21126
21471
  installedAt: typeof record?.installedAt === "string" ? record.installedAt : now,
21127
21472
  updatedAt: changed ? now : typeof record?.updatedAt === "string" ? record.updatedAt : now,
21128
- originalSource: dirname14(options.hookScript),
21473
+ originalSource: dirname15(options.hookScript),
21129
21474
  agentHubLaunch: options.launchId,
21130
21475
  agentHubOwner: record && record.agentHubLaunch === options.launchId && record.agentHubOwner ? record.agentHubOwner : ownerProof(options)
21131
21476
  };
@@ -21137,8 +21482,8 @@ function plan2(options) {
21137
21482
  ...record ? { record } : {},
21138
21483
  changed,
21139
21484
  targets: [
21140
- { path: join23(managed, "kimi.plugin.json"), next: nextManifest, ...manifestBefore ? { before: manifestBefore } : {} },
21141
- { path: join23(managed, "kimi-hook.js"), next: hook.bytes, ...hookBefore ? { before: hookBefore } : {} },
21485
+ { path: join25(managed, "kimi.plugin.json"), next: nextManifest, ...manifestBefore ? { before: manifestBefore } : {} },
21486
+ { path: join25(managed, "kimi-hook.js"), next: hook.bytes, ...hookBefore ? { before: hookBefore } : {} },
21142
21487
  { path: installed, next: Buffer.from(`${JSON.stringify(nextDocument, null, 2)}
21143
21488
  `), ...installedBefore ? { before: installedBefore } : {} }
21144
21489
  ]
@@ -21150,23 +21495,23 @@ function kimiPluginPreview(home, hookScript) {
21150
21495
  directory(home, false);
21151
21496
  if (!file(hookScript, MAX_HOOK))
21152
21497
  throw new Error("Kimi hook bundle is missing");
21153
- return { file: join23(home, "plugins", "managed", ID2), changed: true, action: "only after Kimi 2.5.2 is confirmed, install the launch-scoped completion plugin and remove it on exit; other versions keep the existing TUI with no plugin" };
21498
+ return { file: join25(home, "plugins", "managed", ID2), changed: true, action: "only after Kimi 2.5.2 is confirmed, install the launch-scoped completion plugin and remove it on exit; other versions keep the existing TUI with no plugin" };
21154
21499
  }
21155
21500
  function locked(options, run) {
21156
21501
  if (!isAbsolute8(options.home))
21157
21502
  throw new Error("Kimi home must be an absolute path");
21158
21503
  directory(options.home);
21159
- const path = join23(options.home, "agent-hub-plugin.lock");
21504
+ const path = join25(options.home, "agent-hub-plugin.lock");
21160
21505
  let fd;
21161
21506
  try {
21162
- fd = openSync11(path, "wx", 384);
21507
+ fd = openSync13(path, "wx", 384);
21163
21508
  } catch {
21164
21509
  throw new Error(`Another Kimi plugin replacement is active or left a stale lock; retry after it exits or inspect ${path}`);
21165
21510
  }
21166
21511
  try {
21167
21512
  return run();
21168
21513
  } finally {
21169
- closeSync11(fd);
21514
+ closeSync13(fd);
21170
21515
  unlinkSync4(path);
21171
21516
  }
21172
21517
  }
@@ -21175,7 +21520,7 @@ function ensureKimiPlugin(options) {
21175
21520
  const current = plan2(options);
21176
21521
  if (!current.changed)
21177
21522
  return { changed: false };
21178
- for (const path of [join23(options.home, "plugins"), join23(options.home, "plugins", "managed"), current.managed]) {
21523
+ for (const path of [join25(options.home, "plugins"), join25(options.home, "plugins", "managed"), current.managed]) {
21179
21524
  if (!directory(path, false))
21180
21525
  mkdirSync12(path, { mode: 448 });
21181
21526
  }
@@ -21200,15 +21545,15 @@ function cleanupKimiPlugin(options) {
21200
21545
  atomic(current.installed, Buffer.from(`${JSON.stringify(next, null, 2)}
21201
21546
  `), installedBefore?.stat);
21202
21547
  const [manifestTarget, hookTarget] = current.targets;
21203
- removeFile(join23(current.managed, "kimi.plugin.json"), manifestTarget.next);
21204
- removeFile(join23(current.managed, "kimi-hook.js"), hookTarget.next);
21548
+ removeFile(join25(current.managed, "kimi.plugin.json"), manifestTarget.next);
21549
+ removeFile(join25(current.managed, "kimi-hook.js"), hookTarget.next);
21205
21550
  try {
21206
21551
  rmdirSync4(current.managed);
21207
21552
  } catch {}
21208
21553
  });
21209
21554
  }
21210
21555
  var EVENTS3, ID2 = "agent-hub", MAX_INSTALLED, MAX_HOOK, object8 = (value) => !!value && typeof value === "object" && !Array.isArray(value), directory = (path, required = true) => {
21211
- const stat = lstatSync20(path, { throwIfNoEntry: false });
21556
+ const stat = lstatSync21(path, { throwIfNoEntry: false });
21212
21557
  if (stat && (!stat.isDirectory() || stat.isSymbolicLink()))
21213
21558
  throw new Error(`${path} must be a plain directory`);
21214
21559
  if (!stat && required)
@@ -21223,7 +21568,7 @@ var init_kimi_plugin = __esm(() => {
21223
21568
  });
21224
21569
 
21225
21570
  // src/adapters/definitions/native-cli-entry-kimi.ts
21226
- import { join as join24, resolve as resolve14 } from "path";
21571
+ import { join as join26, resolve as resolve14 } from "path";
21227
21572
  import { homedir as homedir6 } from "os";
21228
21573
  import { spawn as spawn10, spawnSync as spawnSync4 } from "child_process";
21229
21574
  import { mkdirSync as mkdirSync13 } from "fs";
@@ -21345,7 +21690,7 @@ async function runKimiEntry(ctx) {
21345
21690
  if (!gate.ok) {
21346
21691
  result = await runKimiTui(launch.cmd, launch.args, cwd, nativeEnv);
21347
21692
  } else {
21348
- const nativeHome = nativeEnv.KIMI_CODE_HOME ?? join24(nativeEnv.HOME ?? homedir6(), ".kimi-code");
21693
+ const nativeHome = nativeEnv.KIMI_CODE_HOME ?? join26(nativeEnv.HOME ?? homedir6(), ".kimi-code");
21349
21694
  let nativeLaunchId, completionEnv, plugin;
21350
21695
  try {
21351
21696
  mkdirSync13(nativeHome, { recursive: true, mode: 448 });
@@ -21354,7 +21699,7 @@ async function runKimiEntry(ctx) {
21354
21699
  throw new Error(native.error ?? "native hook launch was not admitted");
21355
21700
  nativeLaunchId = native.launchId;
21356
21701
  plugin = { home: nativeHome, hookScript: resolve14(serverBundle, "../kimi-hook.js"), launchId: native.launchId, replaceStale: true };
21357
- console.error(`Kimi TUI completion facts: installing a launch-scoped native plugin under ${join24(nativeHome, "plugins", "managed", "agent-hub")}; it will be removed after this TUI exits`);
21702
+ console.error(`Kimi TUI completion facts: installing a launch-scoped native plugin under ${join26(nativeHome, "plugins", "managed", "agent-hub")}; it will be removed after this TUI exits`);
21358
21703
  ensureKimiPlugin(plugin);
21359
21704
  completionEnv = { ...nativeEnv, AGENTHUB_INSTANCE_ID: native.instanceId, AGENTHUB_LAUNCH_ID: native.launchId, AGENTHUB_HOOK_PURPOSE: "facts" };
21360
21705
  } catch (error) {
@@ -21365,7 +21710,7 @@ async function runKimiEntry(ctx) {
21365
21710
  try {
21366
21711
  cleanupKimiPlugin(plugin);
21367
21712
  } catch {
21368
- console.error(`Managed Kimi plugin cleanup refused: files or ownership changed; inspect ${join24(nativeHome, "plugins", "managed", "agent-hub")} before removing it`);
21713
+ console.error(`Managed Kimi plugin cleanup refused: files or ownership changed; inspect ${join26(nativeHome, "plugins", "managed", "agent-hub")} before removing it`);
21369
21714
  }
21370
21715
  }
21371
21716
  if (completionEnv) {
@@ -21378,7 +21723,7 @@ async function runKimiEntry(ctx) {
21378
21723
  try {
21379
21724
  cleanupKimiPlugin(plugin);
21380
21725
  } catch {
21381
- console.error(`Managed Kimi plugin cleanup refused: files or ownership changed; inspect ${join24(nativeHome, "plugins", "managed", "agent-hub")} before removing it`);
21726
+ console.error(`Managed Kimi plugin cleanup refused: files or ownership changed; inspect ${join26(nativeHome, "plugins", "managed", "agent-hub")} before removing it`);
21382
21727
  }
21383
21728
  }
21384
21729
  } else {
@@ -21746,8 +22091,8 @@ var init_native_cli_entry_jcode = __esm(() => {
21746
22091
  });
21747
22092
 
21748
22093
  // src/adapters/definitions/native-cli-preview-claude.ts
21749
- import { readFileSync as readFileSync12 } from "fs";
21750
- import { join as join25 } from "path";
22094
+ import { readFileSync as readFileSync13 } from "fs";
22095
+ import { join as join27 } from "path";
21751
22096
  function previewClaude(ctx) {
21752
22097
  const { args, cwd, stateDir, cliDir, unattended, config } = ctx;
21753
22098
  const { buildLaunch, claudeObservationHooks } = ctx.helpers;
@@ -21755,13 +22100,13 @@ function previewClaude(ctx) {
21755
22100
  let envNames = state.envNames;
21756
22101
  let launch;
21757
22102
  let original;
21758
- for (const file of [join25(cwd, ".claude/settings.local.json"), join25(cwd, ".claude/settings.json"), join25(process.env.HOME ?? "", ".claude/settings.json")]) {
22103
+ for (const file of [join27(cwd, ".claude/settings.local.json"), join27(cwd, ".claude/settings.json"), join27(process.env.HOME ?? "", ".claude/settings.json")]) {
21759
22104
  try {
21760
- original ??= JSON.parse(readFileSync12(file, "utf8")).statusLine;
22105
+ original ??= JSON.parse(readFileSync13(file, "utf8")).statusLine;
21761
22106
  } catch {}
21762
22107
  }
21763
- const facts = claudeObservationHooks(config, { script: join25(cliDir, "facts-hook.ts"), stateDir });
21764
- launch = buildLaunch("claude", args, { preview: true, unattended, statusLine: { script: join25(cliDir, "statusline-tee.ts"), stateDir, ...original ? { original: { command: original.command ? REDACTED : "", ...typeof original.refreshInterval === "number" && Number.isFinite(original.refreshInterval) ? { refreshInterval: original.refreshInterval } : {}, ...typeof original.padding === "number" && Number.isFinite(original.padding) ? { padding: original.padding } : {} } } : {} }, ...facts ? { facts } : {} });
22108
+ const facts = claudeObservationHooks(config, { script: join27(cliDir, "facts-hook.ts"), stateDir });
22109
+ launch = buildLaunch("claude", args, { preview: true, unattended, statusLine: { script: join27(cliDir, "statusline-tee.ts"), stateDir, ...original ? { original: { command: original.command ? REDACTED : "", ...typeof original.refreshInterval === "number" && Number.isFinite(original.refreshInterval) ? { refreshInterval: original.refreshInterval } : {}, ...typeof original.padding === "number" && Number.isFinite(original.padding) ? { padding: original.padding } : {} } } : {} }, ...facts ? { facts } : {} });
21765
22110
  const safeArgs = args.map((arg, i) => {
21766
22111
  if (args[i - 1] === "--settings")
21767
22112
  return "{}";
@@ -21772,7 +22117,7 @@ function previewClaude(ctx) {
21772
22117
  return publicArg(arg);
21773
22118
  });
21774
22119
  const publicLaunch = buildLaunch("claude", safeArgs, { preview: true, unattended, statusLine: {
21775
- script: join25(cliDir, "statusline-tee.ts"),
22120
+ script: join27(cliDir, "statusline-tee.ts"),
21776
22121
  stateDir,
21777
22122
  ...original ? { original: { command: original.command ? REDACTED : "", ...typeof original.refreshInterval === "number" && Number.isFinite(original.refreshInterval) ? { refreshInterval: original.refreshInterval } : {}, ...typeof original.padding === "number" && Number.isFinite(original.padding) ? { padding: original.padding } : {} } } : {}
21778
22123
  }, facts });
@@ -21805,7 +22150,7 @@ function previewCodex(ctx) {
21805
22150
  var init_native_cli_preview_codex = () => {};
21806
22151
 
21807
22152
  // src/adapters/definitions/native-cli-preview-kimi.ts
21808
- import { join as join26 } from "path";
22153
+ import { join as join28 } from "path";
21809
22154
  import { homedir as homedir7 } from "os";
21810
22155
  function previewKimi(ctx) {
21811
22156
  const { args, cwd, stateDir, cliDir, config } = ctx;
@@ -21831,10 +22176,10 @@ function previewKimi(ctx) {
21831
22176
  const nativeEnv = nativeLaunchEnv("kimi", childEnv());
21832
22177
  envNames = Object.keys(nativeEnv).concat(["AGENTHUB_STATE_DIR", "AGENTHUB_PROJECT_DIR", "AGENTHUB_INSTANCE_ID", "AGENTHUB_LAUNCH_ID", "AGENTHUB_HOOK_PURPOSE"]);
21833
22178
  unresolved.push({ field: "nativeLaunchId", reason: "native completion facts bind to the launch admitted by the running hub" });
21834
- const home = nativeEnv.KIMI_CODE_HOME ?? join26(nativeEnv.HOME ?? homedir7(), ".kimi-code");
21835
- completionPlugin = kimiPluginPreview(home, join26(cliDir, "../../plugins/agent-hub/kimi-hook.js"));
22179
+ const home = nativeEnv.KIMI_CODE_HOME ?? join28(nativeEnv.HOME ?? homedir7(), ".kimi-code");
22180
+ completionPlugin = kimiPluginPreview(home, join28(cliDir, "../../plugins/agent-hub/kimi-hook.js"));
21836
22181
  }
21837
- const { file, action, changed, tracked } = kimiMcpPlan(cwd, stateDir, join26(cliDir, "../../plugins/agent-hub/server.js"), mode);
22182
+ const { file, action, changed, tracked } = kimiMcpPlan(cwd, stateDir, join28(cliDir, "../../plugins/agent-hub/server.js"), mode);
21838
22183
  kimiMetadata = { mode, mcp: { file, action, changed, tracked }, ...completionPlugin ? { completionPlugin } : {} };
21839
22184
  return finishPreview(ctx, launch, envNames, unresolved, kimiMetadata);
21840
22185
  }
@@ -21843,7 +22188,7 @@ var init_native_cli_preview_kimi = __esm(() => {
21843
22188
  });
21844
22189
 
21845
22190
  // src/adapters/definitions/native-cli-preview-pi.ts
21846
- import { join as join27, resolve as resolve16 } from "path";
22191
+ import { join as join29, resolve as resolve16 } from "path";
21847
22192
  function previewPi(ctx) {
21848
22193
  const { args, stateDir, cliDir, config } = ctx;
21849
22194
  const { relayModelIds, buildPiLaunch, startModeOf } = ctx.helpers;
@@ -21878,7 +22223,7 @@ function previewPi(ctx) {
21878
22223
  tools: [],
21879
22224
  preamble: REDACTED,
21880
22225
  maxSteps: config.pi.max_steps
21881
- }, {}, resolve16(join27(cliDir, "../pi/extension.ts")), UNRESOLVED, UNRESOLVED);
22226
+ }, {}, resolve16(join29(cliDir, "../pi/extension.ts")), UNRESOLVED, UNRESOLVED);
21882
22227
  launch = pi;
21883
22228
  envNames = Object.keys(pi.env).concat(["PATH", "HOME", "USER", "SHELL", "TMPDIR", "TERM", "TERM_PROGRAM", "LANG", "LC_ALL", "LC_CTYPE", "NO_COLOR", "CODEX_HOME"].filter((key) => process.env[key] !== undefined));
21884
22229
  if (mode === "tui")
@@ -21968,8 +22313,8 @@ var init_native_config_policy = __esm(() => {
21968
22313
  });
21969
22314
 
21970
22315
  // src/adapters/definitions/native-policy-aux.ts
21971
- import { closeSync as closeSync12, constants as constants10, fstatSync as fstatSync10, openSync as openSync12, readdirSync as readdirSync4, readFileSync as readFileSync13 } from "fs";
21972
- import { isAbsolute as isAbsolute9, join as join28, normalize } from "path";
22316
+ import { closeSync as closeSync14, constants as constants10, fstatSync as fstatSync12, openSync as openSync14, readdirSync as readdirSync5, readFileSync as readFileSync14 } from "fs";
22317
+ import { isAbsolute as isAbsolute9, join as join30, normalize } from "path";
21973
22318
  function claudeCrashPlan(_meta) {
21974
22319
  return { how: "claude: the Claude Code plugin reconnects by itself while that session is still open" };
21975
22320
  }
@@ -22014,13 +22359,13 @@ function localCrashPlan(meta) {
22014
22359
  }
22015
22360
  function claudePlugins(root, cwd) {
22016
22361
  const enabled = new Map;
22017
- for (const file of [join28(root, "settings.json"), ...cwd ? [join28(cwd, ".claude", "settings.json"), join28(cwd, ".claude", "settings.local.json")] : []]) {
22362
+ for (const file of [join30(root, "settings.json"), ...cwd ? [join30(cwd, ".claude", "settings.json"), join30(cwd, ".claude", "settings.local.json")] : []]) {
22018
22363
  const map = json(file)?.enabledPlugins;
22019
22364
  if (map && typeof map === "object")
22020
22365
  for (const [key, on] of Object.entries(map))
22021
22366
  enabled.set(key, on === true);
22022
22367
  }
22023
- const installed = json(join28(root, "plugins", "installed_plugins.json"))?.plugins ?? {};
22368
+ const installed = json(join30(root, "plugins", "installed_plugins.json"))?.plugins ?? {};
22024
22369
  const out = [];
22025
22370
  for (const [key, on] of enabled) {
22026
22371
  if (!on)
@@ -22034,7 +22379,7 @@ function claudePlugins(root, cwd) {
22034
22379
  return out;
22035
22380
  }
22036
22381
  function codexPlugins(root) {
22037
- const config = text2(join28(root, "config.toml"));
22382
+ const config = text2(join30(root, "config.toml"));
22038
22383
  if (config === undefined)
22039
22384
  return [];
22040
22385
  const found = new Map, disabled = new Set;
@@ -22053,7 +22398,7 @@ function codexPlugins(root) {
22053
22398
  continue;
22054
22399
  let versions = [];
22055
22400
  try {
22056
- versions = readdirSync4(join28(root, "plugins", "cache", market, plugin));
22401
+ versions = readdirSync5(join30(root, "plugins", "cache", market, plugin));
22057
22402
  } catch {}
22058
22403
  out.push({ name, version: versions.length === 1 ? version2(versions[0]) : null });
22059
22404
  }
@@ -22073,16 +22418,16 @@ function absoluteContinuityPath(value) {
22073
22418
  var str3 = (value) => typeof value === "string" && value ? value : undefined, PLUGINS, CLAUDE_ONLY, text2 = (file) => {
22074
22419
  let fd;
22075
22420
  try {
22076
- fd = openSync12(file, constants10.O_RDONLY | constants10.O_NONBLOCK);
22077
- const st = fstatSync10(fd);
22421
+ fd = openSync14(file, constants10.O_RDONLY | constants10.O_NONBLOCK);
22422
+ const st = fstatSync12(fd);
22078
22423
  if (!st.isFile() || st.size > 1024 * 1024)
22079
22424
  return;
22080
- return readFileSync13(fd, "utf8");
22425
+ return readFileSync14(fd, "utf8");
22081
22426
  } catch {
22082
22427
  return;
22083
22428
  } finally {
22084
22429
  if (fd !== undefined)
22085
- closeSync12(fd);
22430
+ closeSync14(fd);
22086
22431
  }
22087
22432
  }, json = (file) => {
22088
22433
  try {
@@ -22091,7 +22436,7 @@ var str3 = (value) => typeof value === "string" && value ? value : undefined, PL
22091
22436
  } catch {
22092
22437
  return;
22093
22438
  }
22094
- }, version2 = (v) => typeof v === "string" && /^[0-9A-Za-z.+_-]{1,40}$/.test(v) ? v : null, claudePluginInventory = (ctx) => claudePlugins(ctx.env.CLAUDE_CONFIG_DIR?.trim() || join28(ctx.home, ".claude"), ctx.cwd), codexPluginInventory = (ctx) => codexPlugins(ctx.env.CODEX_HOME?.trim() || join28(ctx.home, ".codex")), codexToolSemantic = (name, _command) => name.toLowerCase() === "filechange" ? "edit" : undefined;
22439
+ }, version2 = (v) => typeof v === "string" && /^[0-9A-Za-z.+_-]{1,40}$/.test(v) ? v : null, claudePluginInventory = (ctx) => claudePlugins(ctx.env.CLAUDE_CONFIG_DIR?.trim() || join30(ctx.home, ".claude"), ctx.cwd), codexPluginInventory = (ctx) => codexPlugins(ctx.env.CODEX_HOME?.trim() || join30(ctx.home, ".codex")), codexToolSemantic = (name, _command) => name.toLowerCase() === "filechange" ? "edit" : undefined;
22095
22440
  var init_native_policy_aux = __esm(() => {
22096
22441
  PLUGINS = new Map([["claude-mem", "claude-mem"], ["ponytail", "ponytail"], ["open-code-review", "open-code-review"]]);
22097
22442
  CLAUDE_ONLY = new Map([["codex@openai-codex", "codex-plugin"]]);
@@ -22134,9 +22479,9 @@ var init_native_cli_launch_common = __esm(() => {
22134
22479
  });
22135
22480
 
22136
22481
  // src/adapters/definitions/native-cli-claude-launch.ts
22137
- import { mkdirSync as mkdirSync14, writeFileSync as writeFileSync11, renameSync as renameSync6, unlinkSync as unlinkSync5, readFileSync as readFileSync14 } from "fs";
22482
+ import { mkdirSync as mkdirSync14, writeFileSync as writeFileSync11, renameSync as renameSync7, unlinkSync as unlinkSync5, readFileSync as readFileSync15 } from "fs";
22138
22483
  import { randomUUID as randomUUID12 } from "crypto";
22139
- import { resolve as resolve17, join as join29 } from "path";
22484
+ import { resolve as resolve17, join as join31 } from "path";
22140
22485
  function claudeChannel(userArgs) {
22141
22486
  const bundle = resolve17(import.meta.dir, "../../../plugins/agent-hub/server.js");
22142
22487
  for (let i = 0;i < userArgs.length; i++) {
@@ -22145,7 +22490,7 @@ function claudeChannel(userArgs) {
22145
22490
  if (!path)
22146
22491
  continue;
22147
22492
  try {
22148
- const server = JSON.parse(readFileSync14(resolve17(path), "utf8")).mcpServers?.["agent-hub"];
22493
+ const server = JSON.parse(readFileSync15(resolve17(path), "utf8")).mcpServers?.["agent-hub"];
22149
22494
  if (server?.command === "bun" && Array.isArray(server.args) && server.args.some((value) => typeof value === "string" && resolve17(value) === bundle))
22150
22495
  return "server:agent-hub";
22151
22496
  } catch {}
@@ -22169,7 +22514,7 @@ function claudeNativeLaunch(ctx) {
22169
22514
  throw new Error("--settings requires a JSON object or readable file so the hub permission hook can be installed");
22170
22515
  let caller;
22171
22516
  try {
22172
- caller = JSON.parse(value.trim().startsWith("{") ? value : readFileSync14(resolve17(value), "utf8"));
22517
+ caller = JSON.parse(value.trim().startsWith("{") ? value : readFileSync15(resolve17(value), "utf8"));
22173
22518
  if (!caller || typeof caller !== "object" || Array.isArray(caller))
22174
22519
  throw new Error("not an object");
22175
22520
  } catch {
@@ -22198,11 +22543,11 @@ function claudeNativeLaunch(ctx) {
22198
22543
  const stateDir = ctx.facts?.stateDir ?? ctx.statusLine?.stateDir;
22199
22544
  if (!stateDir)
22200
22545
  throw new Error("Claude session settings require the hub state directory");
22201
- const file = join29(stateDir, `claude-settings-${randomUUID12()}.json`);
22546
+ const file = join31(stateDir, `claude-settings-${randomUUID12()}.json`);
22202
22547
  try {
22203
22548
  mkdirSync14(stateDir, { recursive: true, mode: 448 });
22204
22549
  writeFileSync11(`${file}.tmp`, settingsArgs[1], { mode: 384, flag: "wx" });
22205
- renameSync6(`${file}.tmp`, file);
22550
+ renameSync7(`${file}.tmp`, file);
22206
22551
  } catch {
22207
22552
  try {
22208
22553
  unlinkSync5(`${file}.tmp`);
@@ -22254,44 +22599,20 @@ var init_native_cli_codex_launch = __esm(() => {
22254
22599
  CODEX_LAUNCH_POLICY = Object.freeze({ hubSwitches: Object.freeze(["--unattended", "--safe", "--new"]), ownedFlags: Object.freeze(["--remote", "--remote-auth-token-env", "--yolo", "--dangerously-bypass-approvals-and-sandbox"]), unattended: true, passthrough: true });
22255
22600
  });
22256
22601
 
22257
- // src/hub/events.ts
22258
- import { appendFileSync, closeSync as closeSync13, existsSync as existsSync9, fstatSync as fstatSync11, openSync as openSync13, readFileSync as readFileSync15, readSync as readSync8 } from "fs";
22259
- function readEvents(file, since = 0) {
22260
- if (!existsSync9(file))
22261
- return [];
22262
- return readFileSync15(file, "utf8").split(`
22263
- `).flatMap((line) => {
22264
- const event = parseEventLine(line, since);
22265
- return event === undefined ? [] : [event];
22266
- });
22267
- }
22268
- function parseEventLine(line, since = 0) {
22269
- if (!line.trim())
22270
- return;
22271
- try {
22272
- const e = JSON.parse(line);
22273
- const measuredAt = e.type === "usage" && typeof e.measuredAt === "string" ? e.measuredAt : e.at;
22274
- return Date.parse(measuredAt) >= since ? e : undefined;
22275
- } catch {
22276
- return;
22277
- }
22278
- }
22279
- var init_events = () => {};
22280
-
22281
22602
  // src/cli/recovery-session-file.ts
22282
- import { statSync as statSync5 } from "fs";
22603
+ import { statSync as statSync6 } from "fs";
22283
22604
  import { homedir as homedir8 } from "os";
22284
- import { join as join30 } from "path";
22605
+ import { join as join32 } from "path";
22285
22606
  function checkedSessionPath(binding, kind) {
22286
22607
  if (kind === "rollout")
22287
- return join30(binding.launch.env.CODEX_HOME ?? join30(homedir8(), ".codex"), "sessions");
22288
- const config = binding.launch.env.CLAUDE_CONFIG_DIR ?? join30(homedir8(), ".claude");
22608
+ return join32(binding.launch.env.CODEX_HOME ?? join32(homedir8(), ".codex"), "sessions");
22609
+ const config = binding.launch.env.CLAUDE_CONFIG_DIR ?? join32(homedir8(), ".claude");
22289
22610
  const slug = binding.projectRoot.replace(/[^a-zA-Z0-9]/g, "-");
22290
- return join30(config, "projects", slug, `${binding.sessionId}.jsonl`);
22611
+ return join32(config, "projects", slug, `${binding.sessionId}.jsonl`);
22291
22612
  }
22292
22613
  function recordedFileState(file) {
22293
22614
  try {
22294
- return statSync5(file).isFile() ? "found" : "unknown";
22615
+ return statSync6(file).isFile() ? "found" : "unknown";
22295
22616
  } catch (error) {
22296
22617
  return error.code === "ENOENT" ? "missing" : "unknown";
22297
22618
  }
@@ -22299,11 +22620,11 @@ function recordedFileState(file) {
22299
22620
  var init_recovery_session_file = () => {};
22300
22621
 
22301
22622
  // src/adapters/definitions/native-recovery.ts
22302
- import { readdirSync as readdirSync5 } from "fs";
22303
- import { basename as basename5, join as join31 } from "path";
22623
+ import { readdirSync as readdirSync6 } from "fs";
22624
+ import { basename as basename6, join as join33 } from "path";
22304
22625
  var rolloutState = (binding) => {
22305
22626
  try {
22306
- return readdirSync5(checkedSessionPath(binding, "rollout"), { recursive: true }).some((name) => String(name).endsWith(".jsonl") && basename5(String(name)).includes(binding.sessionId));
22627
+ return readdirSync6(checkedSessionPath(binding, "rollout"), { recursive: true }).some((name) => String(name).endsWith(".jsonl") && basename6(String(name)).includes(binding.sessionId));
22307
22628
  } catch (error) {
22308
22629
  return error.code === "ENOENT" ? false : "unknown";
22309
22630
  }
@@ -22324,7 +22645,7 @@ var init_native_recovery = __esm(() => {
22324
22645
  if (phase !== "plan")
22325
22646
  return false;
22326
22647
  let current, started = false, turned = false;
22327
- for (const e of readEvents(join31(stateDir, "events.jsonl"))) {
22648
+ for (const e of readEvents(join33(stateDir, "events.jsonl"))) {
22328
22649
  if (e.type === "native_thread" && e.peer === binding.peer) {
22329
22650
  current = e.thread;
22330
22651
  if (e.thread === binding.sessionId && e.fresh)
@@ -22401,9 +22722,9 @@ var init_native_recovery = __esm(() => {
22401
22722
  });
22402
22723
 
22403
22724
  // src/adapters/kimi-tui-facts.ts
22404
- import { closeSync as closeSync14, constants as constants11, fstatSync as fstatSync12, lstatSync as lstatSync21, openSync as openSync14, readSync as readSync9, readdirSync as readdirSync6 } from "fs";
22725
+ import { closeSync as closeSync15, constants as constants11, fstatSync as fstatSync13, lstatSync as lstatSync22, openSync as openSync15, readSync as readSync10, readdirSync as readdirSync7 } from "fs";
22405
22726
  import { createHash as createHash13 } from "crypto";
22406
- import { basename as basename6, dirname as dirname15, isAbsolute as isAbsolute10, join as join32, relative as relative6 } from "path";
22727
+ import { basename as basename7, dirname as dirname16, isAbsolute as isAbsolute10, join as join34, relative as relative6 } from "path";
22407
22728
  import { homedir as homedir9 } from "os";
22408
22729
  function decodeKimiTuiHook(event, value) {
22409
22730
  if (!EVENTS4.includes(event) || !record7(value) || value.hook_event_name !== event || value.client_type !== "kimi_code_cli" || typeof value.session_id !== "string" || !SESSION.test(value.session_id) || typeof value.cwd !== "string" || !isAbsolute10(value.cwd) || value.cwd.length > 4096)
@@ -22412,8 +22733,8 @@ function decodeKimiTuiHook(event, value) {
22412
22733
  return;
22413
22734
  if (event === "TaskStarted" && (typeof value.task_id !== "string" || !TASK.test(value.task_id)))
22414
22735
  return;
22415
- const home = process.env.KIMI_CODE_HOME ?? join32(process.env.HOME ?? homedir9(), ".kimi-code");
22416
- const transcriptPath = value.agentHubTranscriptPath ?? join32(home, "session_index.jsonl");
22736
+ const home = process.env.KIMI_CODE_HOME ?? join34(process.env.HOME ?? homedir9(), ".kimi-code");
22737
+ const transcriptPath = value.agentHubTranscriptPath ?? join34(home, "session_index.jsonl");
22417
22738
  if (typeof transcriptPath !== "string" || !isAbsolute10(transcriptPath) || transcriptPath.length > 4096)
22418
22739
  return;
22419
22740
  const phase = { TurnStarted: "start", Stop: "stop", StopFailure: "stop", Interrupt: "stop", SessionEnd: "session", TaskStarted: "pre", Notification: "post" }[event];
@@ -22423,30 +22744,30 @@ function encodeKimiTuiHook() {
22423
22744
  return;
22424
22745
  }
22425
22746
  function readBytes(path, cap, tail = false) {
22426
- const link = lstatSync21(path);
22747
+ const link = lstatSync22(path);
22427
22748
  if (!link.isFile() || link.isSymbolicLink() || link.nlink !== 1)
22428
22749
  throw new Error("not a regular file");
22429
- const fd = openSync14(path, constants11.O_RDONLY | constants11.O_NOFOLLOW);
22750
+ const fd = openSync15(path, constants11.O_RDONLY | constants11.O_NOFOLLOW);
22430
22751
  try {
22431
- const stat = fstatSync12(fd);
22752
+ const stat = fstatSync13(fd);
22432
22753
  if (!stat.isFile() || stat.nlink !== 1 || !tail && stat.size > cap)
22433
22754
  throw new Error("invalid file");
22434
22755
  const length = Math.min(stat.size, cap), start = tail ? stat.size - length : 0;
22435
22756
  const bytes = Buffer.alloc(length);
22436
22757
  let offset = 0;
22437
22758
  while (offset < length) {
22438
- const count = readSync9(fd, bytes, offset, length - offset, start + offset);
22759
+ const count = readSync10(fd, bytes, offset, length - offset, start + offset);
22439
22760
  if (count <= 0)
22440
22761
  throw new Error("short read");
22441
22762
  offset += count;
22442
22763
  }
22443
22764
  return bytes;
22444
22765
  } finally {
22445
- closeSync14(fd);
22766
+ closeSync15(fd);
22446
22767
  }
22447
22768
  }
22448
22769
  function sessionDirectory(index, session) {
22449
- const home = dirname15(index), sessions = realPath(join32(home, "sessions"));
22770
+ const home = dirname16(index), sessions = realPath(join34(home, "sessions"));
22450
22771
  let listed;
22451
22772
  for (const line of readBytes(index, INDEX_CAP2).toString("utf8").split(`
22452
22773
  `)) {
@@ -22473,7 +22794,7 @@ function sessionDirectory(index, session) {
22473
22794
  }
22474
22795
  function taskInventory(agents) {
22475
22796
  let active = 0;
22476
- const names = readdirSync6(agents, { withFileTypes: true });
22797
+ const names = readdirSync7(agents, { withFileTypes: true });
22477
22798
  if (names.length > MAX_AGENTS2)
22478
22799
  throw new Error("too many agents");
22479
22800
  for (const entry of names) {
@@ -22481,19 +22802,19 @@ function taskInventory(agents) {
22481
22802
  continue;
22482
22803
  if (!entry.isDirectory())
22483
22804
  continue;
22484
- const tasks = join32(agents, entry.name, "tasks");
22485
- const dir = lstatSync21(tasks, { throwIfNoEntry: false });
22805
+ const tasks = join34(agents, entry.name, "tasks");
22806
+ const dir = lstatSync22(tasks, { throwIfNoEntry: false });
22486
22807
  if (!dir)
22487
22808
  continue;
22488
22809
  if (!dir.isDirectory() || dir.isSymbolicLink())
22489
22810
  throw new Error("invalid task directory");
22490
- const files = readdirSync6(tasks).filter((name) => name.endsWith(".json")).sort();
22811
+ const files = readdirSync7(tasks).filter((name) => name.endsWith(".json")).sort();
22491
22812
  if (files.length > MAX_TASKS)
22492
22813
  throw new Error("too many tasks");
22493
22814
  for (const name of files) {
22494
22815
  if (!TASK.test(name.slice(0, -5)))
22495
22816
  throw new Error("invalid task name");
22496
- const row = JSON.parse(readBytes(join32(tasks, name), TASK_CAP).toString("utf8"));
22817
+ const row = JSON.parse(readBytes(join34(tasks, name), TASK_CAP).toString("utf8"));
22497
22818
  if (!record7(row) || row.taskId !== name.slice(0, -5) || typeof row.status !== "string")
22498
22819
  throw new Error("invalid task");
22499
22820
  if (row.status === "running" && row.endedAt === null) {
@@ -22508,11 +22829,11 @@ function taskInventory(agents) {
22508
22829
  return active;
22509
22830
  }
22510
22831
  function readKimiTuiTranscript(session, index) {
22511
- if (!SESSION.test(session) || basename6(index) !== "session_index.jsonl" || !isAbsolute10(index))
22832
+ if (!SESSION.test(session) || basename7(index) !== "session_index.jsonl" || !isAbsolute10(index))
22512
22833
  return empty();
22513
22834
  try {
22514
22835
  const directory = sessionDirectory(index, session);
22515
- const wire = join32(directory, "agents", "main", "wire.jsonl");
22836
+ const wire = join34(directory, "agents", "main", "wire.jsonl");
22516
22837
  if (!inside3(directory, realPath(wire)))
22517
22838
  return empty();
22518
22839
  const bytes = readBytes(wire, WIRE_CAP, true);
@@ -22566,7 +22887,7 @@ function readKimiTuiTranscript(session, index) {
22566
22887
  }
22567
22888
  let background;
22568
22889
  try {
22569
- background = taskInventory(join32(directory, "agents"));
22890
+ background = taskInventory(join34(directory, "agents"));
22570
22891
  } catch {}
22571
22892
  return {
22572
22893
  factIds: [],
@@ -22823,7 +23144,7 @@ var init_builtin_metadata = __esm(() => {
22823
23144
  session: { idField: "sessionId", currentId: sessionId("sessionId"), restoreOnStart: true, launchKind: "pi", launchRecord: true, ...PI_RECOVERY_SESSION, crashPlan: piCrashPlan, unrecordedTerminal: "tui", continuityBookmark: piRecoveryContinuity, continuity: { key: "pi", parse: parsePiContinuity } },
22824
23145
  turnEnd: "adapter",
22825
23146
  settle: { signal: "agent-settled" },
22826
- budget: { account: "pi", instrumented: true, noQuotaReason: "on-prem backends have no provider quota" },
23147
+ budget: { account: "pi", instrumented: true, noQuotaReason: "on-prem backends have no provider quota", context: { source: "pi_usage", read: piContext } },
22827
23148
  reporting: { tokensNotReported: true },
22828
23149
  configuration: { schema: piConfigSchema, routingSchema: piRoutingSchema, settings: PI_SETTINGS, restartReasons: PI_RESTART_REASONS, validateEffective: piEffectiveConfig },
22829
23150
  routing: { localAllowedRefusal: "local_allowed = false also excludes pi for this class", longContext: "backend-limit", preferredTier: true, handoffPriority: 0, trace: "backend", backendLabel: "pi" },
@@ -22955,7 +23276,7 @@ var init_native_cli_entry_qwen = __esm(() => {
22955
23276
  });
22956
23277
 
22957
23278
  // src/adapters/definitions/native-cli-preview-qwen.ts
22958
- import { join as join33 } from "path";
23279
+ import { join as join35 } from "path";
22959
23280
  function previewQwen(ctx) {
22960
23281
  const { tool, args, cwd, stateDir, cliDir, config } = ctx;
22961
23282
  const state = previewState(args, ctx.baseEnvNames), { unresolved, value } = state;
@@ -22985,7 +23306,7 @@ function previewQwen(ctx) {
22985
23306
  form: "headless",
22986
23307
  projectRoot: cwd,
22987
23308
  stateDir,
22988
- entrypoint: join33(cliDir, "main.js"),
23309
+ entrypoint: join35(cliDir, "main.js"),
22989
23310
  userArgs: [],
22990
23311
  unattended: false,
22991
23312
  env: {},
@@ -23082,7 +23403,7 @@ var init_qwen = __esm(() => {
23082
23403
  });
23083
23404
 
23084
23405
  // src/adapters/configured-acp.ts
23085
- import { basename as basename7 } from "path";
23406
+ import { basename as basename8 } from "path";
23086
23407
  import { types as types7 } from "util";
23087
23408
  function fields(raw, at) {
23088
23409
  if (!raw || typeof raw !== "object" || types7.isProxy(raw) || Array.isArray(raw) || ![Object.prototype, null].includes(Object.getPrototypeOf(raw)) || Object.getOwnPropertySymbols(raw).length)
@@ -23150,7 +23471,7 @@ function configuredAcpDefinitions(raw, builtinKinds) {
23150
23471
  return fail(`${at}.identity`, "unknown identity field");
23151
23472
  identity = { name: text4(value.name?.value, `${at}.identity.name`, 256), version: text4(value.version?.value, `${at}.identity.version`, 256) };
23152
23473
  }
23153
- const grokContract = kind === "grok" || /^grok(?:\.exe)?$/i.test(basename7(command)) || identity?.name.toLowerCase() === "grok";
23474
+ const grokContract = kind === "grok" || /^grok(?:\.exe)?$/i.test(basename8(command)) || identity?.name.toLowerCase() === "grok";
23154
23475
  const noLeader = args.indexOf("--no-leader"), endOptions = args.indexOf("--");
23155
23476
  if (grokContract && (noLeader < 0 || endOptions >= 0 && noLeader > endOptions || args.some((arg) => arg.startsWith("--no-leader=")))) {
23156
23477
  return fail(`${at}.args`, "Grok requires explicit --no-leader before argv termination; valued opt-outs are unsupported");
@@ -23565,7 +23886,7 @@ import { relative as relative7, resolve as resolve19, isAbsolute as isAbsolute11
23565
23886
  // src/hub/control-client.ts
23566
23887
  init_project();
23567
23888
  import { readFileSync as readFileSync16 } from "fs";
23568
- import { join as join34, resolve as resolve18 } from "path";
23889
+ import { join as join36, resolve as resolve18 } from "path";
23569
23890
 
23570
23891
  // src/hub/tool-request.ts
23571
23892
  init_capabilities();
@@ -23773,8 +24094,8 @@ function controlProtocolWindow(descriptor) {
23773
24094
  }
23774
24095
  function readControl(stateDir) {
23775
24096
  try {
23776
- const status = JSON.parse(readFileSync16(join34(stateDir, "status.json"), "utf8"));
23777
- const token = readFileSync16(join34(stateDir, "control-token"), "utf8").trim();
24097
+ const status = JSON.parse(readFileSync16(join36(stateDir, "status.json"), "utf8"));
24098
+ const token = readFileSync16(join36(stateDir, "control-token"), "utf8").trim();
23778
24099
  if (!Number.isInteger(status.controlPort) || status.controlPort < 1 || status.controlPort > 65535 || !token)
23779
24100
  return;
23780
24101
  const startModes = status.startModes && typeof status.startModes === "object" && !Array.isArray(status.startModes) ? Object.fromEntries(Object.entries(status.startModes).filter((entry) => entry[1] === "tui" || entry[1] === "headless")) : undefined;