@staix/agent-hub 0.44.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 (100) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/README.md +3 -8
  3. package/docs/agent-notes/adapters.md +2 -2
  4. package/docs/agent-notes/daemon.md +1 -1
  5. package/docs/agent-notes/local-worker.md +1 -1
  6. package/docs/agent-notes/security-review.md +1 -1
  7. package/docs/agent-notes/tasks.md +3 -1
  8. package/docs/agent-notes/tests.md +3 -2
  9. package/docs/design/adapters.md +4 -2
  10. package/docs/design/agent-hub.md +1 -1
  11. package/docs/design/roadmap.md +75 -2
  12. package/docs/design/supervision.md +21 -1
  13. package/docs/design/task-board.md +30 -2
  14. package/docs/dogfood.md +13 -4
  15. package/docs/events.md +5 -1
  16. package/docs/influences.md +7 -0
  17. package/docs/memory.md +4 -4
  18. package/docs/operations.md +51 -18
  19. package/docs/quickstart.md +8 -2
  20. package/docs/research.md +16 -0
  21. package/docs/roadmap.json +4 -0
  22. package/docs/roadmap.md +9 -0
  23. package/docs/sdlc.md +15 -3
  24. package/docs/security.md +3 -3
  25. package/docs/verification/2026-11-19-claude-implementer-2.1.328.md +49 -0
  26. package/docs/verification/2026-11-20-claude-implementer-2.1.329.md +49 -0
  27. package/docs/verification/2026-11-20-sdlc-metrics-diagnosis.md +7 -0
  28. package/docs/verification/2026-11-21-0.45.0.md +69 -0
  29. package/docs/verification/2026-11-22-codex-0171-reviewer-isolation.md +47 -0
  30. package/docs/verified.json +32 -26
  31. package/package.json +2 -2
  32. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  33. package/plugins/agent-hub/kimi-hook.js +472 -229
  34. package/plugins/agent-hub/kimi-review-policy-worker.js +5 -5
  35. package/plugins/agent-hub/server.js +513 -258
  36. package/scripts/check-docs.mjs +9 -1
  37. package/src/adapters/acp.ts +11 -1
  38. package/src/adapters/compat.ts +3 -3
  39. package/src/adapters/definitions/builtin-metadata.ts +2 -2
  40. package/src/adapters/definitions/native-context.ts +10 -0
  41. package/src/adapters/jcode.ts +10 -0
  42. package/src/adapters/local-worker.ts +3 -2
  43. package/src/adapters/pi.ts +15 -4
  44. package/src/cli/console-state.ts +3 -1
  45. package/src/cli/help.ts +3 -1
  46. package/src/cli/identity.ts +2 -1
  47. package/src/cli/main.ts +11 -5
  48. package/src/cli/recovery-package.ts +16 -3
  49. package/src/cli/roadmap-write.ts +59 -0
  50. package/src/cli/roadmap.ts +81 -4
  51. package/src/cli/sdlc-output.ts +4 -0
  52. package/src/cli/upgrade-runtime.ts +10 -6
  53. package/src/hub/agent-mem-range.ts +43 -0
  54. package/src/hub/board.ts +102 -1
  55. package/src/hub/check-runner.ts +25 -1
  56. package/src/hub/config-apply.ts +4 -2
  57. package/src/hub/config-trust.ts +1 -1
  58. package/src/hub/context-window.ts +1 -1
  59. package/src/hub/cost-governance.ts +11 -7
  60. package/src/hub/daemon.ts +253 -30
  61. package/src/hub/dogfood-read.ts +4 -2
  62. package/src/hub/edit-guard.ts +100 -0
  63. package/src/hub/events.ts +79 -8
  64. package/src/hub/facts.ts +57 -4
  65. package/src/hub/hub-tools.ts +2 -0
  66. package/src/hub/lifecycle.ts +6 -1
  67. package/src/hub/log-rotation.ts +130 -0
  68. package/src/hub/memory-profile.ts +137 -21
  69. package/src/hub/no-writes.ts +1 -0
  70. package/src/hub/operational-authority.ts +3 -2
  71. package/src/hub/operational-settings.ts +2 -2
  72. package/src/hub/recovery-store.ts +49 -21
  73. package/src/hub/research-experiments.ts +132 -0
  74. package/src/hub/research-quality.ts +8 -2
  75. package/src/hub/research-record.ts +35 -0
  76. package/src/hub/research.ts +128 -28
  77. package/src/hub/roadmap-check.ts +65 -0
  78. package/src/hub/roadmap-decompose.ts +80 -0
  79. package/src/hub/roadmap-export.ts +27 -0
  80. package/src/hub/roadmap-sync.ts +97 -0
  81. package/src/hub/roadmap.ts +40 -0
  82. package/src/hub/sdlc-branch-ci.ts +128 -0
  83. package/src/hub/sdlc-merge.ts +6 -3
  84. package/src/hub/sdlc-metrics.ts +19 -5
  85. package/src/hub/sdlc.ts +73 -5
  86. package/src/hub/settings.ts +1 -0
  87. package/src/hub/snapshots.ts +13 -1
  88. package/src/hub/startup-event-seeds.ts +21 -15
  89. package/src/hub/startup-timing.ts +3 -1
  90. package/src/hub/supervision-proposals.ts +10 -2
  91. package/src/hub/supervision-rules.ts +26 -3
  92. package/src/hub/supervision.ts +7 -0
  93. package/src/hub/task-pr.ts +47 -0
  94. package/src/hub/task-worktree.ts +18 -11
  95. package/src/hub/tasks.ts +502 -34
  96. package/src/hub/usage-rollup.ts +35 -20
  97. package/src/local/tools.ts +13 -1
  98. package/src/memory/client.ts +3 -2
  99. package/src/pi/extension.ts +15 -3
  100. 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
  }
@@ -9149,7 +9160,7 @@ var init_shell_environment = () => {};
9149
9160
 
9150
9161
  // src/local/sandbox.ts
9151
9162
  import { spawn as spawn8, spawnSync as spawnSync3 } from "child_process";
9152
- 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";
9153
9164
  import { homedir as homedir4, tmpdir as tmpdir4 } from "os";
9154
9165
  import { dirname as dirname10, join as join15, resolve as resolve10 } from "path";
9155
9166
  function developerDir() {
@@ -9354,13 +9365,13 @@ async function probeCommand(argv, opts) {
9354
9365
  return { code: null, output: "error: probe command authority or environment unavailable", quiescent: true };
9355
9366
  }
9356
9367
  const own = realPath(mkdtempSync4(join15(proof.temporaryRoot, "command-")));
9357
- const created = lstatSync13(own);
9368
+ const created = lstatSync14(own);
9358
9369
  let removed = false;
9359
9370
  const dropOwn = () => {
9360
9371
  if (removed)
9361
9372
  return;
9362
9373
  proof.physical();
9363
- const current = lstatSync13(own);
9374
+ const current = lstatSync14(own);
9364
9375
  if (!current.isDirectory() || current.isSymbolicLink() || current.dev !== created.dev || current.ino !== created.ino || realPath(own) !== own)
9365
9376
  throw new Error("probe command temp ownership changed");
9366
9377
  rmdirSync2(own);
@@ -9473,7 +9484,7 @@ var init_text_projection = __esm(() => {
9473
9484
  });
9474
9485
 
9475
9486
  // src/local/doc-read.ts
9476
- import { lstatSync as lstatSync14 } from "fs";
9487
+ import { lstatSync as lstatSync15 } from "fs";
9477
9488
  import { extname } from "path";
9478
9489
  function docRead(file, shown, args, port, cwd) {
9479
9490
  const projections = port.projections();
@@ -9483,7 +9494,7 @@ function docRead(file, shown, args, port, cwd) {
9483
9494
  }
9484
9495
  let st;
9485
9496
  try {
9486
- st = lstatSync14(file);
9497
+ st = lstatSync15(file);
9487
9498
  } catch {
9488
9499
  return `error: ${shown} cannot be read`;
9489
9500
  }
@@ -9963,13 +9974,13 @@ var init_probe_errors = __esm(() => {
9963
9974
  });
9964
9975
 
9965
9976
  // src/local/probe-workspace.ts
9966
- 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";
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";
9967
9978
  import { dirname as dirname11, isAbsolute as isAbsolute6, join as join16 } from "path";
9968
9979
  function refused() {
9969
9980
  throw new Error("probe workspace source, role, path or resource proof is unavailable");
9970
9981
  }
9971
9982
  function directoryIdentity(file) {
9972
- const stat = lstatSync15(file);
9983
+ const stat = lstatSync16(file);
9973
9984
  if (!stat.isDirectory() || stat.isSymbolicLink() || realPath(file) !== file)
9974
9985
  refused();
9975
9986
  return { file, dev: stat.dev, ino: stat.ino };
@@ -9996,7 +10007,7 @@ function probeWorkspaceCurrent(workspace) {
9996
10007
  state.current();
9997
10008
  probeWorkspacePhysical(workspace);
9998
10009
  for (const entry of state.identities) {
9999
- const stat = lstatSync15(entry.file);
10010
+ const stat = lstatSync16(entry.file);
10000
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)
10001
10012
  refused();
10002
10013
  }
@@ -10024,7 +10035,7 @@ var init_probe_workspace = __esm(() => {
10024
10035
  });
10025
10036
 
10026
10037
  // src/local/tools.ts
10027
- import { lstatSync as lstatSync16, mkdirSync as mkdirSync9, readFileSync as readFileSync7, statSync as statSync4, writeFileSync as writeFileSync8 } from "fs";
10038
+ import { lstatSync as lstatSync17, mkdirSync as mkdirSync9, readFileSync as readFileSync7, statSync as statSync4, writeFileSync as writeFileSync8 } from "fs";
10028
10039
  import { dirname as dirname12, join as join17, relative as relative4, resolve as resolve11 } from "path";
10029
10040
  function probeCurrent(probe) {
10030
10041
  try {
@@ -10034,7 +10045,7 @@ function probeCurrent(probe) {
10034
10045
  }
10035
10046
  }
10036
10047
  function probeTargetIdentity(target) {
10037
- const stat = lstatSync16(target, { throwIfNoEntry: false });
10048
+ const stat = lstatSync17(target, { throwIfNoEntry: false });
10038
10049
  if (!stat)
10039
10050
  return;
10040
10051
  if (!stat.isFile())
@@ -10057,7 +10068,7 @@ function planProbeTool(name, rawArgs, ctx) {
10057
10068
  if (name === "write")
10058
10069
  maximum = Buffer.byteLength(String(value.content ?? ""), "utf8");
10059
10070
  else {
10060
- const stat = lstatSync16(target, { throwIfNoEntry: false });
10071
+ const stat = lstatSync17(target, { throwIfNoEntry: false });
10061
10072
  if (!stat || !stat.isFile())
10062
10073
  throw new ProbeToolRefusal("nonregular_target");
10063
10074
  maximum = Math.min(PROBE_WORKSPACE_LIMITS.fileBytes, stat.size + Buffer.byteLength(String(value.new ?? ""), "utf8"));
@@ -10134,7 +10145,7 @@ function guardPath(ctx, path, mode) {
10134
10145
  throw new Error(`${path} is on the secrets denylist`);
10135
10146
  }
10136
10147
  if (ctx.probe) {
10137
- const stat = lstatSync16(real, { throwIfNoEntry: false });
10148
+ const stat = lstatSync17(real, { throwIfNoEntry: false });
10138
10149
  if (stat && !stat.isFile() && !(mode === "read" && stat.isDirectory()))
10139
10150
  throw new ProbeToolRefusal("nonregular_target");
10140
10151
  if (stat?.isFile() && stat.nlink !== 1)
@@ -10146,7 +10157,7 @@ function guardPath(ctx, path, mode) {
10146
10157
  }
10147
10158
  if (mode === "write" && (isHubWritePath(rel) || inside && isHubWritePath(typed)))
10148
10159
  throw new Error(`${path} is not writable by the local worker`);
10149
- 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)
10150
10161
  throw new Error("hardlinked write target cannot be verified with data.readonly");
10151
10162
  if (mode === "write" && matchesPolicy(root, path, ctx.readOnly ?? []))
10152
10163
  throw new Error("target is protected by data.readonly");
@@ -10221,11 +10232,14 @@ async function runTool(name, rawArgs, ctx) {
10221
10232
  const file = guardPath(ctx, String(a.path), "read");
10222
10233
  if (statSync4(file).size > 5000000)
10223
10234
  return "error: file is larger than 5 MB; use bash (head, grep, sed -n) to look at parts of it";
10224
- const lines = readFileSync7(file, "utf8").split(`
10235
+ const bytes = readFileSync7(file);
10236
+ const lines = bytes.toString("utf8").split(`
10225
10237
  `);
10226
10238
  const from = Math.max(1, Number(a.offset) || 1);
10227
10239
  const out = lines.slice(from - 1, from - 1 + (Number(a.limit) || 2000)).map((l, i) => `${from + i} ${l}`).join(`
10228
10240
  `);
10241
+ ctx.editGuard?.read(file, bytes, a.offset === undefined && a.limit === undefined && out.split(`
10242
+ `).length === lines.length && out.length <= OUTPUT_CAP);
10229
10243
  return out.length > OUTPUT_CAP ? `${out.slice(0, OUTPUT_CAP)}
10230
10244
  (truncated: read again with offset/limit)` : out;
10231
10245
  }
@@ -10255,8 +10269,12 @@ ${preview(content)}`, "write", ctx.signal, file, undefined, String(a.path), a),
10255
10269
  if (guardPath(ctx, String(a.path), "write") !== approvedTarget)
10256
10270
  return formatProbeToolRefusal(new ProbeToolRefusal("target_changed"));
10257
10271
  }
10272
+ const unverified = ctx.editGuard?.write(file);
10258
10273
  mkdirSync9(dirname12(file), { recursive: true });
10259
10274
  writeFileSync8(file, content);
10275
+ try {
10276
+ ctx.editGuard?.written(file, unverified);
10277
+ } catch {}
10260
10278
  return `wrote ${a.path}`;
10261
10279
  }
10262
10280
  case "edit": {
@@ -10292,7 +10310,11 @@ ${preview(content)}`, "write", ctx.signal, file, undefined, String(a.path), a),
10292
10310
  if (guardPath(ctx, String(a.path), "write") !== approvedTarget || readFileSync7(file, "utf8") !== text)
10293
10311
  return formatProbeToolRefusal(new ProbeToolRefusal("target_changed"));
10294
10312
  }
10313
+ const unverified = ctx.editGuard?.write(file);
10295
10314
  writeFileSync8(file, replacement);
10315
+ try {
10316
+ ctx.editGuard?.written(file, unverified);
10317
+ } catch {}
10296
10318
  return `edited ${a.path}`;
10297
10319
  }
10298
10320
  case "bash": {
@@ -10321,7 +10343,11 @@ ${preview(content)}`, "write", ctx.signal, file, undefined, String(a.path), a),
10321
10343
  if (attempt)
10322
10344
  return "error: read-only shell proof remained unstable; no command was executed";
10323
10345
  }
10346
+ const observedShell = ctx.editGuard?.shell(command);
10324
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 {}
10325
10351
  try {
10326
10352
  ctx.onProcessExit?.(res.code);
10327
10353
  } catch {}
@@ -10374,7 +10400,7 @@ note: the sandbox does not let you move a branch, tag or HEAD, or stage inside a
10374
10400
  }
10375
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) => {
10376
10402
  try {
10377
- lstatSync16(p);
10403
+ lstatSync17(p);
10378
10404
  return true;
10379
10405
  } catch {
10380
10406
  return false;
@@ -10554,6 +10580,7 @@ var init_pi = __esm(() => {
10554
10580
  PiPeer = class PiPeer extends BasePeer {
10555
10581
  opts;
10556
10582
  preflight;
10583
+ sessionModel;
10557
10584
  hubNative = true;
10558
10585
  hubOwned = true;
10559
10586
  proc;
@@ -10779,6 +10806,9 @@ var init_pi = __esm(() => {
10779
10806
  const session = this.recoveryMetadata().sessionId;
10780
10807
  return typeof session === "string" ? session : undefined;
10781
10808
  }
10809
+ get verifiedRecordSession() {
10810
+ return this.verifiedOwner() ? this.nativeSession : undefined;
10811
+ }
10782
10812
  async captureResume() {
10783
10813
  if (this.state === "offline") {
10784
10814
  if (this.canReuseVerifiedEmptyResume())
@@ -10796,6 +10826,10 @@ var init_pi = __esm(() => {
10796
10826
  const snapshot = this.opts.mode === "headless" ? (await this.waitRpc("get_state", 15000)).data : await this.sendTui({ type: "get_session_state" });
10797
10827
  if (this.state !== "idle" || this.activeTools || snapshot?.sessionId !== this.sessionId || snapshot?.sessionFile !== this.sessionFile)
10798
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
+ }
10799
10833
  if (!this.observeSnapshotTitle(snapshot, titleRevisionBefore, titleEpochBefore))
10800
10834
  throw new Error("Pi source session title changed during capture; retry with a fresh native session snapshot");
10801
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;
@@ -11278,6 +11312,10 @@ var init_pi = __esm(() => {
11278
11312
  throw new Error("Pi roster return could not verify the current native session");
11279
11313
  if (lifecycle !== this.rosterLifecycleRevision)
11280
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
+ }
11281
11319
  this.observeSnapshotTitle(snapshot, titleRevisionBefore, titleEpochBefore);
11282
11320
  this.rosterDetached = false;
11283
11321
  this.hubPromptId = undefined;
@@ -11448,7 +11486,7 @@ var init_pi = __esm(() => {
11448
11486
  attempted = true;
11449
11487
  if (deliveryId)
11450
11488
  this.activeDeliveryIds.add(deliveryId);
11451
- const recordPrompt = this.opts.mode === "tui" ? "" : this.turnRecordPrompt("");
11489
+ const recordPrompt = this.turnRecordPrompt("");
11452
11490
  const message = [recordPrompt, envs.some((env) => env.private || remoteEnvelope(env)) ? undefined : this.opts.titlePreface?.(), renderDigest(envs, true)].filter(Boolean).join(`
11453
11491
  `);
11454
11492
  if (this.opts.mode === "tui") {
@@ -11558,6 +11596,11 @@ var init_pi = __esm(() => {
11558
11596
  return;
11559
11597
  }
11560
11598
  } catch {}
11599
+ } else {
11600
+ if (this.verifiedOwner() && this.sessionModel) {
11601
+ this.turnModel = { model: this.sessionModel, evidence: "session" };
11602
+ return;
11603
+ }
11561
11604
  }
11562
11605
  if (requested)
11563
11606
  this.turnModel = { model: requested, evidence: "configured" };
@@ -11583,9 +11626,11 @@ var init_pi = __esm(() => {
11583
11626
  const slash = model.indexOf("/");
11584
11627
  const provider = "agent-hub-local";
11585
11628
  const modelId = model;
11586
- if (this.opts.mode === "tui")
11629
+ if (this.opts.mode === "tui") {
11630
+ if (this.sessionModel !== modelId)
11631
+ this.sessionModel = undefined;
11587
11632
  await this.sendTui({ type: "set_model", provider, modelId });
11588
- else
11633
+ } else
11589
11634
  await this.sendRpc({ type: "set_model", provider, modelId });
11590
11635
  this.requestedModel = model;
11591
11636
  }
@@ -11668,6 +11713,7 @@ var init_pi = __esm(() => {
11668
11713
  this.opts.log?.(`[${this.id}] Pi session identity mismatch`);
11669
11714
  return;
11670
11715
  }
11716
+ this.sessionModel = stateModelId(event);
11671
11717
  this.titleRevision = -1;
11672
11718
  this.titleEpoch++;
11673
11719
  this.nativeTitleEpoch = typeof event.titleEpoch === "string" && event.titleEpoch ? event.titleEpoch : undefined;
@@ -11714,6 +11760,8 @@ var init_pi = __esm(() => {
11714
11760
  const generation = Number.isSafeInteger(event.generation) ? event.generation : this.budgetGeneration + 1;
11715
11761
  if (generation <= this.budgetGeneration)
11716
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" };
11717
11765
  this.modelStep = 0;
11718
11766
  this.ceilingUnsafe = false;
11719
11767
  this.turnObserved = false;
@@ -11744,6 +11792,14 @@ var init_pi = __esm(() => {
11744
11792
  }
11745
11793
  if (event.type === "activity" && this.state === "busy")
11746
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
+ }
11747
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)) {
11748
11804
  this.usageSeen.add(event.id);
11749
11805
  if (this.usageSeen.size > 1000)
@@ -12662,7 +12718,7 @@ var init_shipped_roles = __esm(() => {
12662
12718
 
12663
12719
  // src/hub/roles.ts
12664
12720
  import { createHash as createHash7 } from "crypto";
12665
- import { constants as constants7, closeSync as closeSync8, fstatSync as fstatSync7, lstatSync as lstatSync17, openSync as openSync8, readSync as readSync5, readdirSync as readdirSync3 } from "fs";
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";
12666
12722
  import { join as join19 } from "path";
12667
12723
  function parseRole(text, stem, layer) {
12668
12724
  if (Buffer.byteLength(text) > 8192 || text.includes("\r") || !ID.test(stem))
@@ -12744,7 +12800,7 @@ function loadRoleCatalog(cwd) {
12744
12800
  try {
12745
12801
  const config = join19(cwd, ".agenthub"), dir = join19(config, "roles");
12746
12802
  for (const path of [config, dir]) {
12747
- const stat = lstatSync17(path);
12803
+ const stat = lstatSync18(path);
12748
12804
  if (!stat.isDirectory() || stat.isSymbolicLink())
12749
12805
  throw new Error("unsafe role directory");
12750
12806
  }
@@ -13632,7 +13688,7 @@ var package_default;
13632
13688
  var init_package = __esm(() => {
13633
13689
  package_default = {
13634
13690
  name: "@staix/agent-hub",
13635
- version: "0.44.0",
13691
+ version: "0.45.0",
13636
13692
  description: "Native multi-agent hub: Claude Code, Codex, Kimi Code, Pi and local inference as peers in one project",
13637
13693
  license: "MIT",
13638
13694
  type: "module",
@@ -13649,7 +13705,7 @@ var init_package = __esm(() => {
13649
13705
  bun: ">=1.4.4"
13650
13706
  },
13651
13707
  dependencies: {
13652
- "@staix/agent-mem": "0.30.0"
13708
+ "@staix/agent-mem": ">=0.33.0 <1.0.0"
13653
13709
  },
13654
13710
  devDependencies: {
13655
13711
  "@modelcontextprotocol/sdk": "^1.27.1",
@@ -13766,6 +13822,12 @@ var init_host_executable = __esm(() => {
13766
13822
  init_project();
13767
13823
  });
13768
13824
 
13825
+ // src/hub/sdlc-branch-ci.ts
13826
+ var CAP2;
13827
+ var init_sdlc_branch_ci = __esm(() => {
13828
+ CAP2 = 256 * 1024;
13829
+ });
13830
+
13769
13831
  // src/hub/sdlc.ts
13770
13832
  var SDLC_STAGES, PLAYBOOK_STAGES, BASES2, STAGE_GATES, GATES;
13771
13833
  var init_sdlc = __esm(() => {
@@ -13780,6 +13842,7 @@ var init_sdlc = __esm(() => {
13780
13842
  init_workflow();
13781
13843
  init_child_process();
13782
13844
  init_host_executable();
13845
+ init_sdlc_branch_ci();
13783
13846
  SDLC_STAGES = ["spec", "plan", "implement", "review", "verify", "merge", "release"];
13784
13847
  PLAYBOOK_STAGES = ["intent", "spec", "plan", "build", "test", "review", "merge", "release", "maintain"];
13785
13848
  BASES2 = [...new Set([...SDLC_STAGES, ...PLAYBOOK_STAGES])];
@@ -13831,6 +13894,12 @@ var init_review_comments = __esm(() => {
13831
13894
  init_review_anchor();
13832
13895
  });
13833
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
+
13834
13903
  // node_modules/@staix/agent-mem/src/memory/screen.ts
13835
13904
  var SECRETS, looksSecret = (text) => SECRETS.some((re) => re.test(text));
13836
13905
  var init_screen = __esm(() => {
@@ -14523,11 +14592,45 @@ var init_capture = __esm(() => {
14523
14592
  });
14524
14593
 
14525
14594
  // node_modules/@staix/agent-mem/src/memory/style.ts
14526
- function style(color) {
14527
- 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;
14597
+ }
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
+ };
14528
14608
  }
14529
- var wrap = (on, open, close) => (text) => on ? `\x1B[${open}m${text}\x1B[${close}m` : text, PLAIN;
14609
+ var ESC, SGR_RESET, ROLE_SGR, MARKERS, PLAIN;
14530
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
+ });
14531
14634
  PLAIN = style(false);
14532
14635
  });
14533
14636
 
@@ -14627,6 +14730,7 @@ var init_reader_lease = __esm(() => {
14627
14730
  // node_modules/@staix/agent-mem/src/memory/store.ts
14628
14731
  var DEFAULT_TTL_MS, UNSETTLED_MS, DEFAULT_LEASE_MS, MIGRATION_BOOTSTRAP, curatedDepth, curatedPending;
14629
14732
  var init_store = __esm(() => {
14733
+ init_recap_scratch();
14630
14734
  init_brief_curated();
14631
14735
  init_curated_cache_state();
14632
14736
  init_sync_placement_guard();
@@ -14706,6 +14810,7 @@ var init_gc = __esm(() => {
14706
14810
 
14707
14811
  // node_modules/@staix/agent-mem/src/memory/curated-read.ts
14708
14812
  var init_curated_read = __esm(() => {
14813
+ init_recap_scratch();
14709
14814
  init_store();
14710
14815
  init_shard();
14711
14816
  });
@@ -14915,6 +15020,9 @@ var init_commands = __esm(() => {
14915
15020
  // node_modules/@staix/agent-mem/src/memory/shard-migration.ts
14916
15021
  var USER2;
14917
15022
  var init_shard_migration = __esm(() => {
15023
+ init_sync_placement_active();
15024
+ init_sync_placement_guard();
15025
+ init_sync_placement_format();
14918
15026
  init_bridge();
14919
15027
  init_generation();
14920
15028
  init_generation_index();
@@ -15158,6 +15266,11 @@ var init_hooks = __esm(() => {
15158
15266
  hookStartedAt = performance.now();
15159
15267
  });
15160
15268
 
15269
+ // node_modules/@staix/agent-mem/src/memory/native-roots.ts
15270
+ var init_native_roots = __esm(() => {
15271
+ init_platform();
15272
+ });
15273
+
15161
15274
  // node_modules/@staix/agent-mem/src/ingest-records.ts
15162
15275
  var init_ingest_records = __esm(() => {
15163
15276
  init_hook_record();
@@ -15168,6 +15281,7 @@ var MAX_BYTES8, DEFAULT_BYTES, MAX_CURSOR_BYTES, utf8, MAX_RECORD;
15168
15281
  var init_ingest = __esm(() => {
15169
15282
  init_capture();
15170
15283
  init_home();
15284
+ init_native_roots();
15171
15285
  init_platform();
15172
15286
  init_policy();
15173
15287
  init_config();
@@ -15226,10 +15340,15 @@ var init_curated_brief_cache = __esm(() => {
15226
15340
  init_store();
15227
15341
  });
15228
15342
 
15343
+ // node_modules/@staix/agent-mem/src/memory/review-targets.ts
15344
+ var init_review_targets = () => {};
15345
+
15229
15346
  // node_modules/@staix/agent-mem/src/memory/decay-review.ts
15230
15347
  var init_decay_review = __esm(() => {
15231
15348
  init_generation();
15232
15349
  init_candidates();
15350
+ init_candidates();
15351
+ init_review_targets();
15233
15352
  });
15234
15353
 
15235
15354
  // node_modules/@staix/agent-mem/src/memory/goal-promotion.ts
@@ -15811,6 +15930,7 @@ var init_sync_placement_writer_context = __esm(() => {
15811
15930
 
15812
15931
  // node_modules/@staix/agent-mem/src/index.ts
15813
15932
  var init_src = __esm(() => {
15933
+ init_platform();
15814
15934
  init_cli_attribution();
15815
15935
  init_search_fts();
15816
15936
  init_platform();
@@ -15861,6 +15981,7 @@ var init_src = __esm(() => {
15861
15981
  init_recall_staleness();
15862
15982
  init_intent_brief();
15863
15983
  init_plan_guard();
15984
+ init_review_targets();
15864
15985
  init_consolidate();
15865
15986
  init_record_candidates();
15866
15987
  init_consolidation_clusters();
@@ -15875,6 +15996,145 @@ var init_src = __esm(() => {
15875
15996
  init_sync_placement_journal();
15876
15997
  });
15877
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
+
15878
16138
  // src/hub/deliverables.ts
15879
16139
  var DELIVERABLE_LIMITS;
15880
16140
  var init_deliverables = __esm(() => {
@@ -15893,6 +16153,8 @@ var BODY2;
15893
16153
  var init_research_experiments = __esm(() => {
15894
16154
  init_src();
15895
16155
  init_packs();
16156
+ init_research2();
16157
+ init_events();
15896
16158
  init_research_runner();
15897
16159
  init_deliverables();
15898
16160
  BODY2 = 64 * 1024;
@@ -15910,12 +16172,13 @@ var init_planning = __esm(() => {
15910
16172
  });
15911
16173
 
15912
16174
  // src/hub/roadmap.ts
15913
- var MILESTONE_STATES, MILESTONE_HORIZONS, MILESTONE_LINK_KINDS, MILESTONE_LIMITS;
16175
+ var MILESTONE_STATES, MILESTONE_HORIZONS, MILESTONE_LINK_KINDS, MILESTONE_LIMITS, DECOMPOSE_LIMITS;
15914
16176
  var init_roadmap = __esm(() => {
15915
16177
  MILESTONE_STATES = ["proposed", "planned", "active", "done", "dropped"];
15916
16178
  MILESTONE_HORIZONS = ["now", "next", "later"];
15917
16179
  MILESTONE_LINK_KINDS = ["spec", "issue", "task", "release"];
15918
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 });
15919
16182
  });
15920
16183
 
15921
16184
  // src/hub/research-campaign.ts
@@ -15940,7 +16203,7 @@ var init_considered_findings = __esm(() => {
15940
16203
  });
15941
16204
 
15942
16205
  // src/hub/board.ts
15943
- 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;
15944
16207
  var init_board = __esm(() => {
15945
16208
  init_tool_refusal();
15946
16209
  init_guidance_variants();
@@ -15973,6 +16236,7 @@ var init_board = __esm(() => {
15973
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`;
15974
16237
  HOST_MERGE_ADOPTION = Symbol("host merge adoption");
15975
16238
  HOST_SPEC_ACCEPTANCE_CARRY = Symbol("host spec acceptance carry");
16239
+ HOST_ROADMAP_DRAFT = Symbol("host roadmap acceptance draft");
15976
16240
  EXECUTION_REFERENCE_SELECT = `SELECT
15977
16241
  CASE WHEN length(CAST(id AS BLOB))=64 THEN id END AS id,
15978
16242
  CASE WHEN length(CAST(project_id AS BLOB)) BETWEEN 1 AND 256 THEN project_id END AS project_id,
@@ -16310,7 +16574,7 @@ var init_config2 = __esm(() => {
16310
16574
  });
16311
16575
 
16312
16576
  // src/hub/routing.ts
16313
- import { join as join20, resolve as resolve13 } from "path";
16577
+ import { join as join21, resolve as resolve13 } from "path";
16314
16578
  function effectiveLocalRoute(defaultRoute, classRoute, classFixedModel) {
16315
16579
  return classRoute ?? (classFixedModel === undefined ? defaultRoute : undefined);
16316
16580
  }
@@ -16324,7 +16588,7 @@ var init_routing = __esm(() => {
16324
16588
  init_spec_read();
16325
16589
  init_config2();
16326
16590
  init_stage_fallback();
16327
- TEMPLATE = join20(import.meta.dir, "..", "..", "templates", "routing.toml");
16591
+ TEMPLATE = join21(import.meta.dir, "..", "..", "templates", "routing.toml");
16328
16592
  cache = new Map;
16329
16593
  });
16330
16594
 
@@ -18857,8 +19121,10 @@ var init_hub_tools = __esm(() => {
18857
19121
  TASK_TOOLS = [
18858
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.", {}),
18859
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.", {}),
18860
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 } }),
18861
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"]),
18862
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.", {
18863
19129
  op: { type: "string", enum: ["new", "edit", "link", "unlink", "order", "state", "accept", "reject"] },
18864
19130
  id: { type: "integer", minimum: 1 },
@@ -19502,7 +19768,7 @@ var init_local_worker = __esm(() => {
19502
19768
  }
19503
19769
  const taskToolName = name.replace(/^mcp__[^ ]+__/, "");
19504
19770
  const reviewNoteWrite = taskToolName === "hub_remember" || taskToolName === "hub_task_propose";
19505
- 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));
19506
19772
  const probe = this.probeSession;
19507
19773
  const running = probe ? (async () => {
19508
19774
  try {
@@ -19566,6 +19832,7 @@ var init_local_worker = __esm(() => {
19566
19832
  ...this.opts.tools.docRead ? { docRead: { ...this.opts.tools.docRead, pii } } : {},
19567
19833
  ...this.opts.tools.webFetch ? { webFetch: { ...this.opts.tools.webFetch, pii } } : {},
19568
19834
  cwd: this.opts.cwd,
19835
+ ...this.opts.tools.editGuard && !probe ? { editGuard: this.opts.tools.editGuard(task, () => !turnSignal.aborted && executionGeneration === this.turn) } : {},
19569
19836
  deny: this.opts.tools.deny,
19570
19837
  readOnly: this.opts.tools.readOnly,
19571
19838
  ...probe ? { probe: {
@@ -19921,12 +20188,12 @@ var init_launch2 = __esm(() => {
19921
20188
 
19922
20189
  // src/adapters/claude-task-sessions.ts
19923
20190
  import { randomUUID as randomUUID8 } from "crypto";
19924
- import { mkdirSync as mkdirSync11, readFileSync as readFileSync9 } from "fs";
19925
- import { dirname as dirname13 } from "path";
20191
+ import { mkdirSync as mkdirSync11, readFileSync as readFileSync10 } from "fs";
20192
+ import { dirname as dirname14 } from "path";
19926
20193
  function readState(file) {
19927
20194
  let text;
19928
20195
  try {
19929
- text = readFileSync9(file, "utf8");
20196
+ text = readFileSync10(file, "utf8");
19930
20197
  } catch (error) {
19931
20198
  if (error.code === "ENOENT")
19932
20199
  return { version: 1, sessions: {} };
@@ -19959,7 +20226,7 @@ class ClaudeTaskSessions {
19959
20226
  }
19960
20227
  write(sessions) {
19961
20228
  const next = { version: 1, sessions };
19962
- mkdirSync11(dirname13(this.file), { recursive: true, mode: 448 });
20229
+ mkdirSync11(dirname14(this.file), { recursive: true, mode: 448 });
19963
20230
  atomicPrivateJSON(this.file, next);
19964
20231
  this.state = next;
19965
20232
  }
@@ -20053,9 +20320,9 @@ __export(exports_claude_implementer, {
20053
20320
  ClaudeImplementerPeer: () => ClaudeImplementerPeer
20054
20321
  });
20055
20322
  import { randomUUID as randomUUID9 } from "crypto";
20056
- 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";
20057
20324
  import { tmpdir as tmpdir5 } from "os";
20058
- import { join as join21 } from "path";
20325
+ import { join as join22 } from "path";
20059
20326
  function provenVersion(binding) {
20060
20327
  return provenVersions.get(binding);
20061
20328
  }
@@ -20111,10 +20378,10 @@ function claudeImplementerArgs(turn, mcp, settings, prompt, model) {
20111
20378
  async function proveClaudeImplementer(peer, command) {
20112
20379
  const binary = Bun.which(command[0], { PATH: process.env.PATH }) ?? command[0];
20113
20380
  const fingerprint = () => {
20114
- const file = realPath(binary), stat = lstatSync18(file);
20381
+ const file = realPath(binary), stat = lstatSync19(file);
20115
20382
  return [file, stat.dev, stat.ino, stat.size, stat.mtimeMs, stat.ctimeMs].join(":");
20116
20383
  };
20117
- const binding = fingerprint(), home = mkdtempSync6(join21(tmpdir5(), "ahub-claude-proof-"));
20384
+ const binding = fingerprint(), home = mkdtempSync6(join22(tmpdir5(), "ahub-claude-proof-"));
20118
20385
  let version = "", timedOut = false;
20119
20386
  const child = new OwnedPrintChild({
20120
20387
  peer,
@@ -20123,7 +20390,7 @@ async function proveClaudeImplementer(peer, command) {
20123
20390
  cwd: home,
20124
20391
  input: "",
20125
20392
  envMode: "replace",
20126
- env: { PATH: process.env.PATH, HOME: home, CLAUDE_CONFIG_DIR: join21(home, ".claude") },
20393
+ env: { PATH: process.env.PATH, HOME: home, CLAUDE_CONFIG_DIR: join22(home, ".claude") },
20127
20394
  maxFrameBytes: 4096,
20128
20395
  maxOutputBytes: 4096,
20129
20396
  onLine: (line) => {
@@ -20159,7 +20426,7 @@ async function proveClaudeImplementer(peer, command) {
20159
20426
  } finally {
20160
20427
  clearTimeout(timer);
20161
20428
  await child.stop();
20162
- rmSync7(home, { recursive: true, force: true });
20429
+ rmSync8(home, { recursive: true, force: true });
20163
20430
  }
20164
20431
  }
20165
20432
  var provenVersions, ClaudeImplementerPeer;
@@ -20210,7 +20477,7 @@ var init_claude_implementer = __esm(() => {
20210
20477
  if (options.mode !== undefined && options.mode !== "ask" && options.mode !== "ask-when-needed")
20211
20478
  throw new Error("Claude implementer refuses unsupported permission mode");
20212
20479
  this.mode = options.mode ?? "ask";
20213
- this.sessions = new ClaudeTaskSessions(join21(options.stateDir, claudeStateFile("claude-task-sessions", id)));
20480
+ this.sessions = new ClaudeTaskSessions(join22(options.stateDir, claudeStateFile("claude-task-sessions", id)));
20214
20481
  }
20215
20482
  get permissionModeState() {
20216
20483
  return this.mode;
@@ -20379,9 +20646,9 @@ var init_claude_implementer = __esm(() => {
20379
20646
  this.observerSessionIdValue = turn.sessionId;
20380
20647
  this.currentInputContext = inputContext;
20381
20648
  this.options.beforeInput?.(inputContext, group.envs);
20382
- const launchId = randomUUID9(), directory = mkdtempSync6(join21(this.options.stateDir, "claude-child-")), settings = join21(directory, "settings.json");
20649
+ const launchId = randomUUID9(), directory = mkdtempSync6(join22(this.options.stateDir, "claude-child-")), settings = join22(directory, "settings.json");
20383
20650
  let launchFailureTrace;
20384
- this.cleanup = () => rmSync7(directory, { recursive: true, force: true });
20651
+ this.cleanup = () => rmSync8(directory, { recursive: true, force: true });
20385
20652
  writeFileSync9(settings, sessionSettings(undefined, { script: this.options.factsHook, stateDir: this.options.stateDir, purpose: "permission" }), { mode: 384, flag: "wx" });
20386
20653
  const env = {
20387
20654
  AGENTHUB_MODE: "tools",
@@ -20724,9 +20991,9 @@ var init_reviewer_variants = __esm(() => {
20724
20991
  });
20725
20992
 
20726
20993
  // src/adapters/agy/hooks.ts
20727
- 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";
20728
20995
  import { homedir as homedir5 } from "os";
20729
- import { isAbsolute as isAbsolute7, join as join22, relative as relative5 } from "path";
20996
+ import { isAbsolute as isAbsolute7, join as join23, relative as relative5 } from "path";
20730
20997
  import { createHash as createHash12 } from "crypto";
20731
20998
  function agyModel(value) {
20732
20999
  const model = safeModelLabel(value);
@@ -20781,19 +21048,19 @@ function readAgyTranscript(session, transcript, options) {
20781
21048
  if (!UUID2.test(session))
20782
21049
  return empty;
20783
21050
  const home = process.env.HOME ?? homedir5();
20784
- const candidates = ["antigravity-cli", "antigravity", "antigravity-ide"].map((surface) => join22(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"));
20785
21052
  if (!candidates.includes(transcript))
20786
21053
  return empty;
20787
21054
  let fd;
20788
21055
  try {
20789
21056
  let cursor = home;
20790
21057
  for (const name of relative5(home, transcript).split("/")) {
20791
- cursor = join22(cursor, name);
20792
- if (lstatSync19(cursor).isSymbolicLink())
21058
+ cursor = join23(cursor, name);
21059
+ if (lstatSync20(cursor).isSymbolicLink())
20793
21060
  return empty;
20794
21061
  }
20795
- fd = openSync10(transcript, constants9.O_RDONLY | constants9.O_NOFOLLOW);
20796
- const stat = fstatSync9(fd);
21062
+ fd = openSync12(transcript, constants9.O_RDONLY | constants9.O_NOFOLLOW);
21063
+ const stat = fstatSync11(fd);
20797
21064
  if (!stat.isFile() || stat.nlink !== 1)
20798
21065
  return empty;
20799
21066
  if (options?.unchanged && stat.size === options.unchanged.size && stat.mtimeMs === options.unchanged.mtimeMs)
@@ -20808,7 +21075,7 @@ function readAgyTranscript(session, transcript, options) {
20808
21075
  const buffer = Buffer.alloc(stat.size - from);
20809
21076
  let bytes = 0;
20810
21077
  while (bytes < buffer.length) {
20811
- const count = readSync7(fd, buffer, bytes, buffer.length - bytes, from + bytes);
21078
+ const count = readSync9(fd, buffer, bytes, buffer.length - bytes, from + bytes);
20812
21079
  if (!count)
20813
21080
  break;
20814
21081
  bytes += count;
@@ -20869,7 +21136,7 @@ function readAgyTranscript(session, transcript, options) {
20869
21136
  return empty;
20870
21137
  } finally {
20871
21138
  if (fd !== undefined)
20872
- closeSync10(fd);
21139
+ closeSync12(fd);
20873
21140
  }
20874
21141
  }
20875
21142
  var EVENTS2, UUID2, record6 = (value) => !!value && typeof value === "object" && !Array.isArray(value), AGY_FACTS_HOOK;
@@ -20947,8 +21214,8 @@ function builtinCliEntries(definitions) {
20947
21214
  return Object.freeze(definitions.flatMap((definition) => definition.cli.entry ? [Object.freeze({ ...definition.cli.entry, command: definition.cli.command })] : []));
20948
21215
  }
20949
21216
  // src/adapters/definitions/native-cli-entry-claude.ts
20950
- import { readFileSync as readFileSync10 } from "fs";
20951
- import { join as join23 } from "path";
21217
+ import { readFileSync as readFileSync11 } from "fs";
21218
+ import { join as join24 } from "path";
20952
21219
  import { randomUUID as randomUUID10 } from "crypto";
20953
21220
  async function runClaudeEntry(ctx) {
20954
21221
  const { args, cwd, stateDir, cliDir, unattendedEnv, projectConfig, fail } = ctx;
@@ -20999,17 +21266,17 @@ async function runClaudeEntry(ctx) {
20999
21266
  }
21000
21267
  }
21001
21268
  let original;
21002
- for (const file of [join23(executionCwd, ".claude", "settings.local.json"), join23(executionCwd, ".claude", "settings.json"), join23(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")]) {
21003
21270
  try {
21004
- original ??= JSON.parse(readFileSync10(file, "utf8")).statusLine;
21271
+ original ??= JSON.parse(readFileSync11(file, "utf8")).statusLine;
21005
21272
  } catch {}
21006
21273
  }
21007
- const facts = claudeObservationHooks(projectConfig(), { script: join23(cliDir, "facts-hook.ts"), stateDir });
21274
+ const facts = claudeObservationHooks(projectConfig(), { script: join24(cliDir, "facts-hook.ts"), stateDir });
21008
21275
  let previousLaunch;
21009
21276
  try {
21010
- previousLaunch = JSON.parse(readFileSync10(join23(stateDir, claudeStateFile("claude-launch", peer)), "utf8"));
21277
+ previousLaunch = JSON.parse(readFileSync11(join24(stateDir, claudeStateFile("claude-launch", peer)), "utf8"));
21011
21278
  } catch {}
21012
- const launch = buildLaunch("claude", args, { unattended: unattendedEnv, statusLine: { script: join23(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 } : {} });
21013
21280
  let result;
21014
21281
  try {
21015
21282
  let launchRecord;
@@ -21103,15 +21370,15 @@ var init_native_cli_entry_codex = () => {};
21103
21370
 
21104
21371
  // src/cli/kimi-plugin.ts
21105
21372
  import { randomUUID as randomUUID11 } from "crypto";
21106
- 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";
21107
- import { dirname as dirname14, isAbsolute as isAbsolute8, join as join24 } 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";
21108
21375
  function file(path, cap) {
21109
- const stat = lstatSync20(path, { throwIfNoEntry: false });
21376
+ const stat = lstatSync21(path, { throwIfNoEntry: false });
21110
21377
  if (!stat)
21111
21378
  return;
21112
21379
  if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > cap)
21113
21380
  throw new Error(`${path} must be a bounded regular file`);
21114
- return { stat, bytes: readFileSync11(path) };
21381
+ return { stat, bytes: readFileSync12(path) };
21115
21382
  }
21116
21383
  function parse2(value, name) {
21117
21384
  if (!value)
@@ -21126,28 +21393,28 @@ function parse2(value, name) {
21126
21393
  }
21127
21394
  }
21128
21395
  function atomic(path, bytes, before) {
21129
- const current = lstatSync20(path, { throwIfNoEntry: false });
21396
+ const current = lstatSync21(path, { throwIfNoEntry: false });
21130
21397
  if (before ? !current || current.dev !== before.dev || current.ino !== before.ino : current)
21131
21398
  throw new Error(`${path} changed before its managed write`);
21132
21399
  const temporary = `${path}.${randomUUID11()}.tmp`;
21133
21400
  let fd;
21134
21401
  try {
21135
- fd = openSync11(temporary, "wx", 384);
21402
+ fd = openSync13(temporary, "wx", 384);
21136
21403
  writeFileSync10(fd, bytes);
21137
- closeSync11(fd);
21404
+ closeSync13(fd);
21138
21405
  fd = undefined;
21139
- renameSync5(temporary, path);
21406
+ renameSync6(temporary, path);
21140
21407
  } finally {
21141
21408
  if (fd !== undefined)
21142
- closeSync11(fd);
21409
+ closeSync13(fd);
21143
21410
  try {
21144
21411
  unlinkSync4(temporary);
21145
21412
  } catch {}
21146
21413
  }
21147
21414
  }
21148
21415
  function removeFile(path, expected) {
21149
- const current = lstatSync20(path, { throwIfNoEntry: false });
21150
- 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))
21151
21418
  return;
21152
21419
  unlinkSync4(path);
21153
21420
  }
@@ -21177,7 +21444,7 @@ function plan2(options) {
21177
21444
  const hook = file(options.hookScript, MAX_HOOK);
21178
21445
  if (!hook)
21179
21446
  throw new Error("Kimi hook bundle is missing");
21180
- const root = join24(options.home, "plugins"), managed = join24(root, "managed", ID2), installed = join24(root, "installed.json");
21447
+ const root = join25(options.home, "plugins"), managed = join25(root, "managed", ID2), installed = join25(root, "installed.json");
21181
21448
  const installedBefore = file(installed, MAX_INSTALLED), document = parse2(installedBefore, installed);
21182
21449
  if (document && (document.version !== 1 || !Array.isArray(document.plugins)))
21183
21450
  throw new Error(`${installed} has an unsupported shape`);
@@ -21190,11 +21457,11 @@ function plan2(options) {
21190
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)) {
21191
21458
  throw new Error("Kimi's agent-hub plugin belongs to another launch or is disabled; it was not changed");
21192
21459
  }
21193
- const manifestBefore = file(join24(managed, "kimi.plugin.json"), MAX_INSTALLED), hookBefore = file(join24(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);
21194
21461
  const nextManifest = Buffer.from(`${JSON.stringify(manifest(), null, 2)}
21195
21462
  `);
21196
21463
  const now = new Date(options.now ?? Date.now()).toISOString();
21197
- 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);
21198
21465
  const nextRecord = {
21199
21466
  id: ID2,
21200
21467
  root: managed,
@@ -21203,7 +21470,7 @@ function plan2(options) {
21203
21470
  enabled: true,
21204
21471
  installedAt: typeof record?.installedAt === "string" ? record.installedAt : now,
21205
21472
  updatedAt: changed ? now : typeof record?.updatedAt === "string" ? record.updatedAt : now,
21206
- originalSource: dirname14(options.hookScript),
21473
+ originalSource: dirname15(options.hookScript),
21207
21474
  agentHubLaunch: options.launchId,
21208
21475
  agentHubOwner: record && record.agentHubLaunch === options.launchId && record.agentHubOwner ? record.agentHubOwner : ownerProof(options)
21209
21476
  };
@@ -21215,8 +21482,8 @@ function plan2(options) {
21215
21482
  ...record ? { record } : {},
21216
21483
  changed,
21217
21484
  targets: [
21218
- { path: join24(managed, "kimi.plugin.json"), next: nextManifest, ...manifestBefore ? { before: manifestBefore } : {} },
21219
- { path: join24(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 } : {} },
21220
21487
  { path: installed, next: Buffer.from(`${JSON.stringify(nextDocument, null, 2)}
21221
21488
  `), ...installedBefore ? { before: installedBefore } : {} }
21222
21489
  ]
@@ -21228,23 +21495,23 @@ function kimiPluginPreview(home, hookScript) {
21228
21495
  directory(home, false);
21229
21496
  if (!file(hookScript, MAX_HOOK))
21230
21497
  throw new Error("Kimi hook bundle is missing");
21231
- return { file: join24(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" };
21232
21499
  }
21233
21500
  function locked(options, run) {
21234
21501
  if (!isAbsolute8(options.home))
21235
21502
  throw new Error("Kimi home must be an absolute path");
21236
21503
  directory(options.home);
21237
- const path = join24(options.home, "agent-hub-plugin.lock");
21504
+ const path = join25(options.home, "agent-hub-plugin.lock");
21238
21505
  let fd;
21239
21506
  try {
21240
- fd = openSync11(path, "wx", 384);
21507
+ fd = openSync13(path, "wx", 384);
21241
21508
  } catch {
21242
21509
  throw new Error(`Another Kimi plugin replacement is active or left a stale lock; retry after it exits or inspect ${path}`);
21243
21510
  }
21244
21511
  try {
21245
21512
  return run();
21246
21513
  } finally {
21247
- closeSync11(fd);
21514
+ closeSync13(fd);
21248
21515
  unlinkSync4(path);
21249
21516
  }
21250
21517
  }
@@ -21253,7 +21520,7 @@ function ensureKimiPlugin(options) {
21253
21520
  const current = plan2(options);
21254
21521
  if (!current.changed)
21255
21522
  return { changed: false };
21256
- for (const path of [join24(options.home, "plugins"), join24(options.home, "plugins", "managed"), current.managed]) {
21523
+ for (const path of [join25(options.home, "plugins"), join25(options.home, "plugins", "managed"), current.managed]) {
21257
21524
  if (!directory(path, false))
21258
21525
  mkdirSync12(path, { mode: 448 });
21259
21526
  }
@@ -21278,15 +21545,15 @@ function cleanupKimiPlugin(options) {
21278
21545
  atomic(current.installed, Buffer.from(`${JSON.stringify(next, null, 2)}
21279
21546
  `), installedBefore?.stat);
21280
21547
  const [manifestTarget, hookTarget] = current.targets;
21281
- removeFile(join24(current.managed, "kimi.plugin.json"), manifestTarget.next);
21282
- removeFile(join24(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);
21283
21550
  try {
21284
21551
  rmdirSync4(current.managed);
21285
21552
  } catch {}
21286
21553
  });
21287
21554
  }
21288
21555
  var EVENTS3, ID2 = "agent-hub", MAX_INSTALLED, MAX_HOOK, object8 = (value) => !!value && typeof value === "object" && !Array.isArray(value), directory = (path, required = true) => {
21289
- const stat = lstatSync20(path, { throwIfNoEntry: false });
21556
+ const stat = lstatSync21(path, { throwIfNoEntry: false });
21290
21557
  if (stat && (!stat.isDirectory() || stat.isSymbolicLink()))
21291
21558
  throw new Error(`${path} must be a plain directory`);
21292
21559
  if (!stat && required)
@@ -21301,7 +21568,7 @@ var init_kimi_plugin = __esm(() => {
21301
21568
  });
21302
21569
 
21303
21570
  // src/adapters/definitions/native-cli-entry-kimi.ts
21304
- import { join as join25, resolve as resolve14 } from "path";
21571
+ import { join as join26, resolve as resolve14 } from "path";
21305
21572
  import { homedir as homedir6 } from "os";
21306
21573
  import { spawn as spawn10, spawnSync as spawnSync4 } from "child_process";
21307
21574
  import { mkdirSync as mkdirSync13 } from "fs";
@@ -21423,7 +21690,7 @@ async function runKimiEntry(ctx) {
21423
21690
  if (!gate.ok) {
21424
21691
  result = await runKimiTui(launch.cmd, launch.args, cwd, nativeEnv);
21425
21692
  } else {
21426
- const nativeHome = nativeEnv.KIMI_CODE_HOME ?? join25(nativeEnv.HOME ?? homedir6(), ".kimi-code");
21693
+ const nativeHome = nativeEnv.KIMI_CODE_HOME ?? join26(nativeEnv.HOME ?? homedir6(), ".kimi-code");
21427
21694
  let nativeLaunchId, completionEnv, plugin;
21428
21695
  try {
21429
21696
  mkdirSync13(nativeHome, { recursive: true, mode: 448 });
@@ -21432,7 +21699,7 @@ async function runKimiEntry(ctx) {
21432
21699
  throw new Error(native.error ?? "native hook launch was not admitted");
21433
21700
  nativeLaunchId = native.launchId;
21434
21701
  plugin = { home: nativeHome, hookScript: resolve14(serverBundle, "../kimi-hook.js"), launchId: native.launchId, replaceStale: true };
21435
- console.error(`Kimi TUI completion facts: installing a launch-scoped native plugin under ${join25(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`);
21436
21703
  ensureKimiPlugin(plugin);
21437
21704
  completionEnv = { ...nativeEnv, AGENTHUB_INSTANCE_ID: native.instanceId, AGENTHUB_LAUNCH_ID: native.launchId, AGENTHUB_HOOK_PURPOSE: "facts" };
21438
21705
  } catch (error) {
@@ -21443,7 +21710,7 @@ async function runKimiEntry(ctx) {
21443
21710
  try {
21444
21711
  cleanupKimiPlugin(plugin);
21445
21712
  } catch {
21446
- console.error(`Managed Kimi plugin cleanup refused: files or ownership changed; inspect ${join25(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`);
21447
21714
  }
21448
21715
  }
21449
21716
  if (completionEnv) {
@@ -21456,7 +21723,7 @@ async function runKimiEntry(ctx) {
21456
21723
  try {
21457
21724
  cleanupKimiPlugin(plugin);
21458
21725
  } catch {
21459
- console.error(`Managed Kimi plugin cleanup refused: files or ownership changed; inspect ${join25(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`);
21460
21727
  }
21461
21728
  }
21462
21729
  } else {
@@ -21824,8 +22091,8 @@ var init_native_cli_entry_jcode = __esm(() => {
21824
22091
  });
21825
22092
 
21826
22093
  // src/adapters/definitions/native-cli-preview-claude.ts
21827
- import { readFileSync as readFileSync12 } from "fs";
21828
- import { join as join26 } from "path";
22094
+ import { readFileSync as readFileSync13 } from "fs";
22095
+ import { join as join27 } from "path";
21829
22096
  function previewClaude(ctx) {
21830
22097
  const { args, cwd, stateDir, cliDir, unattended, config } = ctx;
21831
22098
  const { buildLaunch, claudeObservationHooks } = ctx.helpers;
@@ -21833,13 +22100,13 @@ function previewClaude(ctx) {
21833
22100
  let envNames = state.envNames;
21834
22101
  let launch;
21835
22102
  let original;
21836
- for (const file of [join26(cwd, ".claude/settings.local.json"), join26(cwd, ".claude/settings.json"), join26(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")]) {
21837
22104
  try {
21838
- original ??= JSON.parse(readFileSync12(file, "utf8")).statusLine;
22105
+ original ??= JSON.parse(readFileSync13(file, "utf8")).statusLine;
21839
22106
  } catch {}
21840
22107
  }
21841
- const facts = claudeObservationHooks(config, { script: join26(cliDir, "facts-hook.ts"), stateDir });
21842
- launch = buildLaunch("claude", args, { preview: true, unattended, statusLine: { script: join26(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 } : {} });
21843
22110
  const safeArgs = args.map((arg, i) => {
21844
22111
  if (args[i - 1] === "--settings")
21845
22112
  return "{}";
@@ -21850,7 +22117,7 @@ function previewClaude(ctx) {
21850
22117
  return publicArg(arg);
21851
22118
  });
21852
22119
  const publicLaunch = buildLaunch("claude", safeArgs, { preview: true, unattended, statusLine: {
21853
- script: join26(cliDir, "statusline-tee.ts"),
22120
+ script: join27(cliDir, "statusline-tee.ts"),
21854
22121
  stateDir,
21855
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 } : {} } } : {}
21856
22123
  }, facts });
@@ -21883,7 +22150,7 @@ function previewCodex(ctx) {
21883
22150
  var init_native_cli_preview_codex = () => {};
21884
22151
 
21885
22152
  // src/adapters/definitions/native-cli-preview-kimi.ts
21886
- import { join as join27 } from "path";
22153
+ import { join as join28 } from "path";
21887
22154
  import { homedir as homedir7 } from "os";
21888
22155
  function previewKimi(ctx) {
21889
22156
  const { args, cwd, stateDir, cliDir, config } = ctx;
@@ -21909,10 +22176,10 @@ function previewKimi(ctx) {
21909
22176
  const nativeEnv = nativeLaunchEnv("kimi", childEnv());
21910
22177
  envNames = Object.keys(nativeEnv).concat(["AGENTHUB_STATE_DIR", "AGENTHUB_PROJECT_DIR", "AGENTHUB_INSTANCE_ID", "AGENTHUB_LAUNCH_ID", "AGENTHUB_HOOK_PURPOSE"]);
21911
22178
  unresolved.push({ field: "nativeLaunchId", reason: "native completion facts bind to the launch admitted by the running hub" });
21912
- const home = nativeEnv.KIMI_CODE_HOME ?? join27(nativeEnv.HOME ?? homedir7(), ".kimi-code");
21913
- completionPlugin = kimiPluginPreview(home, join27(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"));
21914
22181
  }
21915
- const { file, action, changed, tracked } = kimiMcpPlan(cwd, stateDir, join27(cliDir, "../../plugins/agent-hub/server.js"), mode);
22182
+ const { file, action, changed, tracked } = kimiMcpPlan(cwd, stateDir, join28(cliDir, "../../plugins/agent-hub/server.js"), mode);
21916
22183
  kimiMetadata = { mode, mcp: { file, action, changed, tracked }, ...completionPlugin ? { completionPlugin } : {} };
21917
22184
  return finishPreview(ctx, launch, envNames, unresolved, kimiMetadata);
21918
22185
  }
@@ -21921,7 +22188,7 @@ var init_native_cli_preview_kimi = __esm(() => {
21921
22188
  });
21922
22189
 
21923
22190
  // src/adapters/definitions/native-cli-preview-pi.ts
21924
- import { join as join28, resolve as resolve16 } from "path";
22191
+ import { join as join29, resolve as resolve16 } from "path";
21925
22192
  function previewPi(ctx) {
21926
22193
  const { args, stateDir, cliDir, config } = ctx;
21927
22194
  const { relayModelIds, buildPiLaunch, startModeOf } = ctx.helpers;
@@ -21956,7 +22223,7 @@ function previewPi(ctx) {
21956
22223
  tools: [],
21957
22224
  preamble: REDACTED,
21958
22225
  maxSteps: config.pi.max_steps
21959
- }, {}, resolve16(join28(cliDir, "../pi/extension.ts")), UNRESOLVED, UNRESOLVED);
22226
+ }, {}, resolve16(join29(cliDir, "../pi/extension.ts")), UNRESOLVED, UNRESOLVED);
21960
22227
  launch = pi;
21961
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));
21962
22229
  if (mode === "tui")
@@ -22046,8 +22313,8 @@ var init_native_config_policy = __esm(() => {
22046
22313
  });
22047
22314
 
22048
22315
  // src/adapters/definitions/native-policy-aux.ts
22049
- import { closeSync as closeSync12, constants as constants10, fstatSync as fstatSync10, openSync as openSync12, readdirSync as readdirSync4, readFileSync as readFileSync13 } from "fs";
22050
- import { isAbsolute as isAbsolute9, join as join29, 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";
22051
22318
  function claudeCrashPlan(_meta) {
22052
22319
  return { how: "claude: the Claude Code plugin reconnects by itself while that session is still open" };
22053
22320
  }
@@ -22092,13 +22359,13 @@ function localCrashPlan(meta) {
22092
22359
  }
22093
22360
  function claudePlugins(root, cwd) {
22094
22361
  const enabled = new Map;
22095
- for (const file of [join29(root, "settings.json"), ...cwd ? [join29(cwd, ".claude", "settings.json"), join29(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")] : []]) {
22096
22363
  const map = json(file)?.enabledPlugins;
22097
22364
  if (map && typeof map === "object")
22098
22365
  for (const [key, on] of Object.entries(map))
22099
22366
  enabled.set(key, on === true);
22100
22367
  }
22101
- const installed = json(join29(root, "plugins", "installed_plugins.json"))?.plugins ?? {};
22368
+ const installed = json(join30(root, "plugins", "installed_plugins.json"))?.plugins ?? {};
22102
22369
  const out = [];
22103
22370
  for (const [key, on] of enabled) {
22104
22371
  if (!on)
@@ -22112,7 +22379,7 @@ function claudePlugins(root, cwd) {
22112
22379
  return out;
22113
22380
  }
22114
22381
  function codexPlugins(root) {
22115
- const config = text2(join29(root, "config.toml"));
22382
+ const config = text2(join30(root, "config.toml"));
22116
22383
  if (config === undefined)
22117
22384
  return [];
22118
22385
  const found = new Map, disabled = new Set;
@@ -22131,7 +22398,7 @@ function codexPlugins(root) {
22131
22398
  continue;
22132
22399
  let versions = [];
22133
22400
  try {
22134
- versions = readdirSync4(join29(root, "plugins", "cache", market, plugin));
22401
+ versions = readdirSync5(join30(root, "plugins", "cache", market, plugin));
22135
22402
  } catch {}
22136
22403
  out.push({ name, version: versions.length === 1 ? version2(versions[0]) : null });
22137
22404
  }
@@ -22151,16 +22418,16 @@ function absoluteContinuityPath(value) {
22151
22418
  var str3 = (value) => typeof value === "string" && value ? value : undefined, PLUGINS, CLAUDE_ONLY, text2 = (file) => {
22152
22419
  let fd;
22153
22420
  try {
22154
- fd = openSync12(file, constants10.O_RDONLY | constants10.O_NONBLOCK);
22155
- const st = fstatSync10(fd);
22421
+ fd = openSync14(file, constants10.O_RDONLY | constants10.O_NONBLOCK);
22422
+ const st = fstatSync12(fd);
22156
22423
  if (!st.isFile() || st.size > 1024 * 1024)
22157
22424
  return;
22158
- return readFileSync13(fd, "utf8");
22425
+ return readFileSync14(fd, "utf8");
22159
22426
  } catch {
22160
22427
  return;
22161
22428
  } finally {
22162
22429
  if (fd !== undefined)
22163
- closeSync12(fd);
22430
+ closeSync14(fd);
22164
22431
  }
22165
22432
  }, json = (file) => {
22166
22433
  try {
@@ -22169,7 +22436,7 @@ var str3 = (value) => typeof value === "string" && value ? value : undefined, PL
22169
22436
  } catch {
22170
22437
  return;
22171
22438
  }
22172
- }, version2 = (v) => typeof v === "string" && /^[0-9A-Za-z.+_-]{1,40}$/.test(v) ? v : null, claudePluginInventory = (ctx) => claudePlugins(ctx.env.CLAUDE_CONFIG_DIR?.trim() || join29(ctx.home, ".claude"), ctx.cwd), codexPluginInventory = (ctx) => codexPlugins(ctx.env.CODEX_HOME?.trim() || join29(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;
22173
22440
  var init_native_policy_aux = __esm(() => {
22174
22441
  PLUGINS = new Map([["claude-mem", "claude-mem"], ["ponytail", "ponytail"], ["open-code-review", "open-code-review"]]);
22175
22442
  CLAUDE_ONLY = new Map([["codex@openai-codex", "codex-plugin"]]);
@@ -22212,9 +22479,9 @@ var init_native_cli_launch_common = __esm(() => {
22212
22479
  });
22213
22480
 
22214
22481
  // src/adapters/definitions/native-cli-claude-launch.ts
22215
- 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";
22216
22483
  import { randomUUID as randomUUID12 } from "crypto";
22217
- import { resolve as resolve17, join as join30 } from "path";
22484
+ import { resolve as resolve17, join as join31 } from "path";
22218
22485
  function claudeChannel(userArgs) {
22219
22486
  const bundle = resolve17(import.meta.dir, "../../../plugins/agent-hub/server.js");
22220
22487
  for (let i = 0;i < userArgs.length; i++) {
@@ -22223,7 +22490,7 @@ function claudeChannel(userArgs) {
22223
22490
  if (!path)
22224
22491
  continue;
22225
22492
  try {
22226
- const server = JSON.parse(readFileSync14(resolve17(path), "utf8")).mcpServers?.["agent-hub"];
22493
+ const server = JSON.parse(readFileSync15(resolve17(path), "utf8")).mcpServers?.["agent-hub"];
22227
22494
  if (server?.command === "bun" && Array.isArray(server.args) && server.args.some((value) => typeof value === "string" && resolve17(value) === bundle))
22228
22495
  return "server:agent-hub";
22229
22496
  } catch {}
@@ -22247,7 +22514,7 @@ function claudeNativeLaunch(ctx) {
22247
22514
  throw new Error("--settings requires a JSON object or readable file so the hub permission hook can be installed");
22248
22515
  let caller;
22249
22516
  try {
22250
- caller = JSON.parse(value.trim().startsWith("{") ? value : readFileSync14(resolve17(value), "utf8"));
22517
+ caller = JSON.parse(value.trim().startsWith("{") ? value : readFileSync15(resolve17(value), "utf8"));
22251
22518
  if (!caller || typeof caller !== "object" || Array.isArray(caller))
22252
22519
  throw new Error("not an object");
22253
22520
  } catch {
@@ -22276,11 +22543,11 @@ function claudeNativeLaunch(ctx) {
22276
22543
  const stateDir = ctx.facts?.stateDir ?? ctx.statusLine?.stateDir;
22277
22544
  if (!stateDir)
22278
22545
  throw new Error("Claude session settings require the hub state directory");
22279
- const file = join30(stateDir, `claude-settings-${randomUUID12()}.json`);
22546
+ const file = join31(stateDir, `claude-settings-${randomUUID12()}.json`);
22280
22547
  try {
22281
22548
  mkdirSync14(stateDir, { recursive: true, mode: 448 });
22282
22549
  writeFileSync11(`${file}.tmp`, settingsArgs[1], { mode: 384, flag: "wx" });
22283
- renameSync6(`${file}.tmp`, file);
22550
+ renameSync7(`${file}.tmp`, file);
22284
22551
  } catch {
22285
22552
  try {
22286
22553
  unlinkSync5(`${file}.tmp`);
@@ -22332,44 +22599,20 @@ var init_native_cli_codex_launch = __esm(() => {
22332
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 });
22333
22600
  });
22334
22601
 
22335
- // src/hub/events.ts
22336
- import { appendFileSync, closeSync as closeSync13, existsSync as existsSync9, fstatSync as fstatSync11, openSync as openSync13, readFileSync as readFileSync15, readSync as readSync8 } from "fs";
22337
- function readEvents(file, since = 0) {
22338
- if (!existsSync9(file))
22339
- return [];
22340
- return readFileSync15(file, "utf8").split(`
22341
- `).flatMap((line) => {
22342
- const event = parseEventLine(line, since);
22343
- return event === undefined ? [] : [event];
22344
- });
22345
- }
22346
- function parseEventLine(line, since = 0) {
22347
- if (!line.trim())
22348
- return;
22349
- try {
22350
- const e = JSON.parse(line);
22351
- const measuredAt = e.type === "usage" && typeof e.measuredAt === "string" ? e.measuredAt : e.at;
22352
- return Date.parse(measuredAt) >= since ? e : undefined;
22353
- } catch {
22354
- return;
22355
- }
22356
- }
22357
- var init_events = () => {};
22358
-
22359
22602
  // src/cli/recovery-session-file.ts
22360
- import { statSync as statSync5 } from "fs";
22603
+ import { statSync as statSync6 } from "fs";
22361
22604
  import { homedir as homedir8 } from "os";
22362
- import { join as join31 } from "path";
22605
+ import { join as join32 } from "path";
22363
22606
  function checkedSessionPath(binding, kind) {
22364
22607
  if (kind === "rollout")
22365
- return join31(binding.launch.env.CODEX_HOME ?? join31(homedir8(), ".codex"), "sessions");
22366
- const config = binding.launch.env.CLAUDE_CONFIG_DIR ?? join31(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");
22367
22610
  const slug = binding.projectRoot.replace(/[^a-zA-Z0-9]/g, "-");
22368
- return join31(config, "projects", slug, `${binding.sessionId}.jsonl`);
22611
+ return join32(config, "projects", slug, `${binding.sessionId}.jsonl`);
22369
22612
  }
22370
22613
  function recordedFileState(file) {
22371
22614
  try {
22372
- return statSync5(file).isFile() ? "found" : "unknown";
22615
+ return statSync6(file).isFile() ? "found" : "unknown";
22373
22616
  } catch (error) {
22374
22617
  return error.code === "ENOENT" ? "missing" : "unknown";
22375
22618
  }
@@ -22377,11 +22620,11 @@ function recordedFileState(file) {
22377
22620
  var init_recovery_session_file = () => {};
22378
22621
 
22379
22622
  // src/adapters/definitions/native-recovery.ts
22380
- import { readdirSync as readdirSync5 } from "fs";
22381
- import { basename as basename5, join as join32 } from "path";
22623
+ import { readdirSync as readdirSync6 } from "fs";
22624
+ import { basename as basename6, join as join33 } from "path";
22382
22625
  var rolloutState = (binding) => {
22383
22626
  try {
22384
- 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));
22385
22628
  } catch (error) {
22386
22629
  return error.code === "ENOENT" ? false : "unknown";
22387
22630
  }
@@ -22402,7 +22645,7 @@ var init_native_recovery = __esm(() => {
22402
22645
  if (phase !== "plan")
22403
22646
  return false;
22404
22647
  let current, started = false, turned = false;
22405
- for (const e of readEvents(join32(stateDir, "events.jsonl"))) {
22648
+ for (const e of readEvents(join33(stateDir, "events.jsonl"))) {
22406
22649
  if (e.type === "native_thread" && e.peer === binding.peer) {
22407
22650
  current = e.thread;
22408
22651
  if (e.thread === binding.sessionId && e.fresh)
@@ -22479,9 +22722,9 @@ var init_native_recovery = __esm(() => {
22479
22722
  });
22480
22723
 
22481
22724
  // src/adapters/kimi-tui-facts.ts
22482
- 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";
22483
22726
  import { createHash as createHash13 } from "crypto";
22484
- import { basename as basename6, dirname as dirname15, isAbsolute as isAbsolute10, join as join33, relative as relative6 } from "path";
22727
+ import { basename as basename7, dirname as dirname16, isAbsolute as isAbsolute10, join as join34, relative as relative6 } from "path";
22485
22728
  import { homedir as homedir9 } from "os";
22486
22729
  function decodeKimiTuiHook(event, value) {
22487
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)
@@ -22490,8 +22733,8 @@ function decodeKimiTuiHook(event, value) {
22490
22733
  return;
22491
22734
  if (event === "TaskStarted" && (typeof value.task_id !== "string" || !TASK.test(value.task_id)))
22492
22735
  return;
22493
- const home = process.env.KIMI_CODE_HOME ?? join33(process.env.HOME ?? homedir9(), ".kimi-code");
22494
- const transcriptPath = value.agentHubTranscriptPath ?? join33(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");
22495
22738
  if (typeof transcriptPath !== "string" || !isAbsolute10(transcriptPath) || transcriptPath.length > 4096)
22496
22739
  return;
22497
22740
  const phase = { TurnStarted: "start", Stop: "stop", StopFailure: "stop", Interrupt: "stop", SessionEnd: "session", TaskStarted: "pre", Notification: "post" }[event];
@@ -22501,30 +22744,30 @@ function encodeKimiTuiHook() {
22501
22744
  return;
22502
22745
  }
22503
22746
  function readBytes(path, cap, tail = false) {
22504
- const link = lstatSync21(path);
22747
+ const link = lstatSync22(path);
22505
22748
  if (!link.isFile() || link.isSymbolicLink() || link.nlink !== 1)
22506
22749
  throw new Error("not a regular file");
22507
- const fd = openSync14(path, constants11.O_RDONLY | constants11.O_NOFOLLOW);
22750
+ const fd = openSync15(path, constants11.O_RDONLY | constants11.O_NOFOLLOW);
22508
22751
  try {
22509
- const stat = fstatSync12(fd);
22752
+ const stat = fstatSync13(fd);
22510
22753
  if (!stat.isFile() || stat.nlink !== 1 || !tail && stat.size > cap)
22511
22754
  throw new Error("invalid file");
22512
22755
  const length = Math.min(stat.size, cap), start = tail ? stat.size - length : 0;
22513
22756
  const bytes = Buffer.alloc(length);
22514
22757
  let offset = 0;
22515
22758
  while (offset < length) {
22516
- const count = readSync9(fd, bytes, offset, length - offset, start + offset);
22759
+ const count = readSync10(fd, bytes, offset, length - offset, start + offset);
22517
22760
  if (count <= 0)
22518
22761
  throw new Error("short read");
22519
22762
  offset += count;
22520
22763
  }
22521
22764
  return bytes;
22522
22765
  } finally {
22523
- closeSync14(fd);
22766
+ closeSync15(fd);
22524
22767
  }
22525
22768
  }
22526
22769
  function sessionDirectory(index, session) {
22527
- const home = dirname15(index), sessions = realPath(join33(home, "sessions"));
22770
+ const home = dirname16(index), sessions = realPath(join34(home, "sessions"));
22528
22771
  let listed;
22529
22772
  for (const line of readBytes(index, INDEX_CAP2).toString("utf8").split(`
22530
22773
  `)) {
@@ -22551,7 +22794,7 @@ function sessionDirectory(index, session) {
22551
22794
  }
22552
22795
  function taskInventory(agents) {
22553
22796
  let active = 0;
22554
- const names = readdirSync6(agents, { withFileTypes: true });
22797
+ const names = readdirSync7(agents, { withFileTypes: true });
22555
22798
  if (names.length > MAX_AGENTS2)
22556
22799
  throw new Error("too many agents");
22557
22800
  for (const entry of names) {
@@ -22559,19 +22802,19 @@ function taskInventory(agents) {
22559
22802
  continue;
22560
22803
  if (!entry.isDirectory())
22561
22804
  continue;
22562
- const tasks = join33(agents, entry.name, "tasks");
22563
- const dir = lstatSync21(tasks, { throwIfNoEntry: false });
22805
+ const tasks = join34(agents, entry.name, "tasks");
22806
+ const dir = lstatSync22(tasks, { throwIfNoEntry: false });
22564
22807
  if (!dir)
22565
22808
  continue;
22566
22809
  if (!dir.isDirectory() || dir.isSymbolicLink())
22567
22810
  throw new Error("invalid task directory");
22568
- const files = readdirSync6(tasks).filter((name) => name.endsWith(".json")).sort();
22811
+ const files = readdirSync7(tasks).filter((name) => name.endsWith(".json")).sort();
22569
22812
  if (files.length > MAX_TASKS)
22570
22813
  throw new Error("too many tasks");
22571
22814
  for (const name of files) {
22572
22815
  if (!TASK.test(name.slice(0, -5)))
22573
22816
  throw new Error("invalid task name");
22574
- const row = JSON.parse(readBytes(join33(tasks, name), TASK_CAP).toString("utf8"));
22817
+ const row = JSON.parse(readBytes(join34(tasks, name), TASK_CAP).toString("utf8"));
22575
22818
  if (!record7(row) || row.taskId !== name.slice(0, -5) || typeof row.status !== "string")
22576
22819
  throw new Error("invalid task");
22577
22820
  if (row.status === "running" && row.endedAt === null) {
@@ -22586,11 +22829,11 @@ function taskInventory(agents) {
22586
22829
  return active;
22587
22830
  }
22588
22831
  function readKimiTuiTranscript(session, index) {
22589
- if (!SESSION.test(session) || basename6(index) !== "session_index.jsonl" || !isAbsolute10(index))
22832
+ if (!SESSION.test(session) || basename7(index) !== "session_index.jsonl" || !isAbsolute10(index))
22590
22833
  return empty();
22591
22834
  try {
22592
22835
  const directory = sessionDirectory(index, session);
22593
- const wire = join33(directory, "agents", "main", "wire.jsonl");
22836
+ const wire = join34(directory, "agents", "main", "wire.jsonl");
22594
22837
  if (!inside3(directory, realPath(wire)))
22595
22838
  return empty();
22596
22839
  const bytes = readBytes(wire, WIRE_CAP, true);
@@ -22644,7 +22887,7 @@ function readKimiTuiTranscript(session, index) {
22644
22887
  }
22645
22888
  let background;
22646
22889
  try {
22647
- background = taskInventory(join33(directory, "agents"));
22890
+ background = taskInventory(join34(directory, "agents"));
22648
22891
  } catch {}
22649
22892
  return {
22650
22893
  factIds: [],
@@ -22901,7 +23144,7 @@ var init_builtin_metadata = __esm(() => {
22901
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 } },
22902
23145
  turnEnd: "adapter",
22903
23146
  settle: { signal: "agent-settled" },
22904
- 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 } },
22905
23148
  reporting: { tokensNotReported: true },
22906
23149
  configuration: { schema: piConfigSchema, routingSchema: piRoutingSchema, settings: PI_SETTINGS, restartReasons: PI_RESTART_REASONS, validateEffective: piEffectiveConfig },
22907
23150
  routing: { localAllowedRefusal: "local_allowed = false also excludes pi for this class", longContext: "backend-limit", preferredTier: true, handoffPriority: 0, trace: "backend", backendLabel: "pi" },
@@ -23033,7 +23276,7 @@ var init_native_cli_entry_qwen = __esm(() => {
23033
23276
  });
23034
23277
 
23035
23278
  // src/adapters/definitions/native-cli-preview-qwen.ts
23036
- import { join as join34 } from "path";
23279
+ import { join as join35 } from "path";
23037
23280
  function previewQwen(ctx) {
23038
23281
  const { tool, args, cwd, stateDir, cliDir, config } = ctx;
23039
23282
  const state = previewState(args, ctx.baseEnvNames), { unresolved, value } = state;
@@ -23063,7 +23306,7 @@ function previewQwen(ctx) {
23063
23306
  form: "headless",
23064
23307
  projectRoot: cwd,
23065
23308
  stateDir,
23066
- entrypoint: join34(cliDir, "main.js"),
23309
+ entrypoint: join35(cliDir, "main.js"),
23067
23310
  userArgs: [],
23068
23311
  unattended: false,
23069
23312
  env: {},
@@ -23160,7 +23403,7 @@ var init_qwen = __esm(() => {
23160
23403
  });
23161
23404
 
23162
23405
  // src/adapters/configured-acp.ts
23163
- import { basename as basename7 } from "path";
23406
+ import { basename as basename8 } from "path";
23164
23407
  import { types as types7 } from "util";
23165
23408
  function fields(raw, at) {
23166
23409
  if (!raw || typeof raw !== "object" || types7.isProxy(raw) || Array.isArray(raw) || ![Object.prototype, null].includes(Object.getPrototypeOf(raw)) || Object.getOwnPropertySymbols(raw).length)
@@ -23228,7 +23471,7 @@ function configuredAcpDefinitions(raw, builtinKinds) {
23228
23471
  return fail(`${at}.identity`, "unknown identity field");
23229
23472
  identity = { name: text4(value.name?.value, `${at}.identity.name`, 256), version: text4(value.version?.value, `${at}.identity.version`, 256) };
23230
23473
  }
23231
- 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";
23232
23475
  const noLeader = args.indexOf("--no-leader"), endOptions = args.indexOf("--");
23233
23476
  if (grokContract && (noLeader < 0 || endOptions >= 0 && noLeader > endOptions || args.some((arg) => arg.startsWith("--no-leader=")))) {
23234
23477
  return fail(`${at}.args`, "Grok requires explicit --no-leader before argv termination; valued opt-outs are unsupported");
@@ -23643,7 +23886,7 @@ import { relative as relative7, resolve as resolve19, isAbsolute as isAbsolute11
23643
23886
  // src/hub/control-client.ts
23644
23887
  init_project();
23645
23888
  import { readFileSync as readFileSync16 } from "fs";
23646
- import { join as join35, resolve as resolve18 } from "path";
23889
+ import { join as join36, resolve as resolve18 } from "path";
23647
23890
 
23648
23891
  // src/hub/tool-request.ts
23649
23892
  init_capabilities();
@@ -23851,8 +24094,8 @@ function controlProtocolWindow(descriptor) {
23851
24094
  }
23852
24095
  function readControl(stateDir) {
23853
24096
  try {
23854
- const status = JSON.parse(readFileSync16(join35(stateDir, "status.json"), "utf8"));
23855
- const token = readFileSync16(join35(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();
23856
24099
  if (!Number.isInteger(status.controlPort) || status.controlPort < 1 || status.controlPort > 65535 || !token)
23857
24100
  return;
23858
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;