tenjin-cli 0.1.0-alpha.27 → 0.1.0-alpha.29

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 (148) hide show
  1. package/README.md +18 -26
  2. package/dist/alive-3J3CHOQP.js +21 -0
  3. package/dist/{chunk-XVYATBKD.js → chunk-25GGN553.js} +897 -522
  4. package/dist/chunk-25GGN553.js.map +1 -0
  5. package/dist/{chunk-B2L53TMK.js → chunk-2SNUOHAT.js} +28 -23
  6. package/dist/chunk-2SNUOHAT.js.map +1 -0
  7. package/dist/{chunk-5NEHH2E5.js → chunk-3FY5HG7R.js} +86 -19
  8. package/dist/chunk-3FY5HG7R.js.map +1 -0
  9. package/dist/{chunk-YQOQ6XEI.js → chunk-4FYMDRD3.js} +51 -41
  10. package/dist/chunk-4FYMDRD3.js.map +1 -0
  11. package/dist/chunk-6W5GYG3W.js +128 -0
  12. package/dist/chunk-6W5GYG3W.js.map +1 -0
  13. package/dist/{chunk-G4AM2SOL.js → chunk-AMEUXNJT.js} +4 -8
  14. package/dist/{chunk-G4AM2SOL.js.map → chunk-AMEUXNJT.js.map} +1 -1
  15. package/dist/chunk-EWLU46J6.js +100 -0
  16. package/dist/chunk-EWLU46J6.js.map +1 -0
  17. package/dist/chunk-LRCJ2IZ5.js +115 -0
  18. package/dist/{chunk-HC3QEZKT.js.map → chunk-LRCJ2IZ5.js.map} +1 -1
  19. package/dist/{chunk-X7I343ZY.js → chunk-LX5OT4TQ.js} +3 -3
  20. package/dist/{chunk-X7I343ZY.js.map → chunk-LX5OT4TQ.js.map} +1 -1
  21. package/dist/{chunk-DATCR7AU.js → chunk-MG3G644T.js} +5 -7
  22. package/dist/{chunk-DATCR7AU.js.map → chunk-MG3G644T.js.map} +1 -1
  23. package/dist/{chunk-BOAI23CX.js → chunk-MOG7PB3A.js} +21 -15
  24. package/dist/chunk-MOG7PB3A.js.map +1 -0
  25. package/dist/{chunk-GU4GGKYP.js → chunk-MRUPDSUM.js} +14 -59
  26. package/dist/chunk-MRUPDSUM.js.map +1 -0
  27. package/dist/{chunk-AWKQSKUL.js → chunk-OOSRB3OF.js} +2 -2
  28. package/dist/{chunk-PZ5N6BAL.js → chunk-ORWL5BSN.js} +5 -4
  29. package/dist/chunk-ORWL5BSN.js.map +1 -0
  30. package/dist/chunk-P4LVLFO4.js +29 -0
  31. package/dist/chunk-P4LVLFO4.js.map +1 -0
  32. package/dist/{chunk-VXIBZ6W5.js → chunk-QTGUDCIR.js} +5 -5
  33. package/dist/{chunk-YKM2ZTA2.js → chunk-R4AO7GC2.js} +462 -105
  34. package/dist/chunk-R4AO7GC2.js.map +1 -0
  35. package/dist/{chunk-OHZYNZSD.js → chunk-RJEPZMYY.js} +12 -8
  36. package/dist/chunk-RJEPZMYY.js.map +1 -0
  37. package/dist/chunk-SBL4THYT.js +2074 -0
  38. package/dist/chunk-SBL4THYT.js.map +1 -0
  39. package/dist/{chunk-VNNXAYJE.js → chunk-SFEQGENI.js} +2 -2
  40. package/dist/{chunk-K6AXXYCG.js → chunk-SJLTEINJ.js} +10 -2
  41. package/dist/{chunk-K6AXXYCG.js.map → chunk-SJLTEINJ.js.map} +1 -1
  42. package/dist/{chunk-5FGO6TYT.js → chunk-TROZ6HL4.js} +3 -5
  43. package/dist/{chunk-5FGO6TYT.js.map → chunk-TROZ6HL4.js.map} +1 -1
  44. package/dist/{chunk-SKQQOEWH.js → chunk-USOLCBKC.js} +6 -8
  45. package/dist/{chunk-SKQQOEWH.js.map → chunk-USOLCBKC.js.map} +1 -1
  46. package/dist/{chunk-64SE3QC5.js → chunk-VKQXVCZR.js} +54 -5
  47. package/dist/chunk-VKQXVCZR.js.map +1 -0
  48. package/dist/{chunk-VIOUZW7Z.js → chunk-VVAHFCX2.js} +209 -37
  49. package/dist/chunk-VVAHFCX2.js.map +1 -0
  50. package/dist/{chunk-4L7KMA7P.js → chunk-WM7TJEBP.js} +8 -10
  51. package/dist/{chunk-4L7KMA7P.js.map → chunk-WM7TJEBP.js.map} +1 -1
  52. package/dist/{chunk-2TYQD22Q.js → chunk-XDYKZRLN.js} +23 -16
  53. package/dist/chunk-XDYKZRLN.js.map +1 -0
  54. package/dist/{chunk-LAIZ2AQA.js → chunk-XJQ6CH7X.js} +3 -2
  55. package/dist/{chunk-O7CUHHYU.js → chunk-ZQNGTLOC.js} +8 -10
  56. package/dist/{chunk-O7CUHHYU.js.map → chunk-ZQNGTLOC.js.map} +1 -1
  57. package/dist/{cli-6JNIPZQ6.js → cli-JPTDHGRX.js} +58 -52
  58. package/dist/{cli-6JNIPZQ6.js.map → cli-JPTDHGRX.js.map} +1 -1
  59. package/dist/{config-G75YT6NC.js → config-YYKDH2TH.js} +12 -15
  60. package/dist/{doctor-3GMDOW4Y.js → doctor-SSTXGCHX.js} +298 -269
  61. package/dist/doctor-SSTXGCHX.js.map +1 -0
  62. package/dist/{fund-3IPR5YRJ.js → fund-QWVWRVDK.js} +95 -43
  63. package/dist/{fund-3IPR5YRJ.js.map → fund-QWVWRVDK.js.map} +1 -1
  64. package/dist/hook-command-VWJXRT7H.js +31 -0
  65. package/dist/hosts/claude/.claude-plugin/marketplace.json +19 -0
  66. package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +14 -0
  67. package/dist/hosts/claude/tenjin/.mcp.json +12 -0
  68. package/dist/hosts/claude/tenjin/hooks/hooks.json +221 -0
  69. package/dist/index.js +13 -4
  70. package/dist/index.js.map +1 -1
  71. package/dist/install-2GXXD4DK.js +51 -0
  72. package/dist/{install-identity-PM4AGFFX.js → install-identity-FK3YF227.js} +7 -9
  73. package/dist/{install-wallet-6756NOB5.js → install-wallet-TC22U52X.js} +21 -17
  74. package/dist/{install-wallet-6756NOB5.js.map → install-wallet-TC22U52X.js.map} +1 -1
  75. package/dist/{mcp-33FAAZ7F.js → mcp-42H2F4NY.js} +2128 -372
  76. package/dist/mcp-42H2F4NY.js.map +1 -0
  77. package/dist/package-6DJA3Y2O.js +37 -0
  78. package/dist/{paths-MUXHUOCM.js → paths-POPTXJO6.js} +6 -2
  79. package/dist/{pay-XOYR4PCH.js → pay-LSDJBIAZ.js} +20 -18
  80. package/dist/payments-SPECLBRQ.js +105 -0
  81. package/dist/payments-SPECLBRQ.js.map +1 -0
  82. package/dist/{send-CVGNOQW3.js → send-MHAOLPK3.js} +13 -17
  83. package/dist/{send-CVGNOQW3.js.map → send-MHAOLPK3.js.map} +1 -1
  84. package/dist/status-O2RWLPS5.js +114 -0
  85. package/dist/status-O2RWLPS5.js.map +1 -0
  86. package/dist/{status-line-3IQKGRUH.js → status-line-45TVCRM3.js} +7 -9
  87. package/dist/{status-line-3IQKGRUH.js.map → status-line-45TVCRM3.js.map} +1 -1
  88. package/dist/uninstall-VOK2Z5M4.js +146 -0
  89. package/dist/uninstall-VOK2Z5M4.js.map +1 -0
  90. package/dist/update-FGP3HNLD.js +33 -0
  91. package/dist/update-FGP3HNLD.js.map +1 -0
  92. package/dist/{wallet-B3FVHNTS.js → wallet-DA7OFNEW.js} +18 -14
  93. package/dist/wallet-DA7OFNEW.js.map +1 -0
  94. package/docs/agent-permissions.md +35 -22
  95. package/docs/safety-model.md +3 -1
  96. package/package.json +2 -2
  97. package/dist/chunk-2TYQD22Q.js.map +0 -1
  98. package/dist/chunk-5NEHH2E5.js.map +0 -1
  99. package/dist/chunk-64SE3QC5.js.map +0 -1
  100. package/dist/chunk-6ZSGER3A.js +0 -52
  101. package/dist/chunk-6ZSGER3A.js.map +0 -1
  102. package/dist/chunk-B2L53TMK.js.map +0 -1
  103. package/dist/chunk-BOAI23CX.js.map +0 -1
  104. package/dist/chunk-DSNXKUXI.js +0 -172
  105. package/dist/chunk-DSNXKUXI.js.map +0 -1
  106. package/dist/chunk-GU4GGKYP.js.map +0 -1
  107. package/dist/chunk-H2L33M7F.js +0 -944
  108. package/dist/chunk-H2L33M7F.js.map +0 -1
  109. package/dist/chunk-HC3QEZKT.js +0 -87
  110. package/dist/chunk-JLEF5WHM.js +0 -132
  111. package/dist/chunk-JLEF5WHM.js.map +0 -1
  112. package/dist/chunk-MAQUL5BD.js +0 -99
  113. package/dist/chunk-MAQUL5BD.js.map +0 -1
  114. package/dist/chunk-OHZYNZSD.js.map +0 -1
  115. package/dist/chunk-PY7MQUKP.js +0 -755
  116. package/dist/chunk-PY7MQUKP.js.map +0 -1
  117. package/dist/chunk-PZ5N6BAL.js.map +0 -1
  118. package/dist/chunk-TGLKKLQG.js +0 -11
  119. package/dist/chunk-TGLKKLQG.js.map +0 -1
  120. package/dist/chunk-VIOUZW7Z.js.map +0 -1
  121. package/dist/chunk-XVYATBKD.js.map +0 -1
  122. package/dist/chunk-YKM2ZTA2.js.map +0 -1
  123. package/dist/chunk-YQOQ6XEI.js.map +0 -1
  124. package/dist/doctor-3GMDOW4Y.js.map +0 -1
  125. package/dist/hook-command-ZXX4FT4N.js +0 -32
  126. package/dist/install-6OROTYHZ.js +0 -72
  127. package/dist/mcp-33FAAZ7F.js.map +0 -1
  128. package/dist/payments-UTQDBO7H.js +0 -48
  129. package/dist/payments-UTQDBO7H.js.map +0 -1
  130. package/dist/status-NACN4DGX.js +0 -72
  131. package/dist/status-NACN4DGX.js.map +0 -1
  132. package/dist/status-line-wiring-QXBOOY2T.js +0 -31
  133. package/dist/uninstall-NYFKSYW4.js +0 -175
  134. package/dist/uninstall-NYFKSYW4.js.map +0 -1
  135. package/dist/update-RJDA5ZY3.js +0 -442
  136. package/dist/update-RJDA5ZY3.js.map +0 -1
  137. /package/dist/{config-G75YT6NC.js.map → alive-3J3CHOQP.js.map} +0 -0
  138. /package/dist/{chunk-AWKQSKUL.js.map → chunk-OOSRB3OF.js.map} +0 -0
  139. /package/dist/{chunk-VXIBZ6W5.js.map → chunk-QTGUDCIR.js.map} +0 -0
  140. /package/dist/{chunk-VNNXAYJE.js.map → chunk-SFEQGENI.js.map} +0 -0
  141. /package/dist/{chunk-LAIZ2AQA.js.map → chunk-XJQ6CH7X.js.map} +0 -0
  142. /package/dist/{hook-command-ZXX4FT4N.js.map → config-YYKDH2TH.js.map} +0 -0
  143. /package/dist/{install-6OROTYHZ.js.map → hook-command-VWJXRT7H.js.map} +0 -0
  144. /package/dist/{install-identity-PM4AGFFX.js.map → install-2GXXD4DK.js.map} +0 -0
  145. /package/dist/{paths-MUXHUOCM.js.map → install-identity-FK3YF227.js.map} +0 -0
  146. /package/dist/{pay-XOYR4PCH.js.map → package-6DJA3Y2O.js.map} +0 -0
  147. /package/dist/{status-line-wiring-QXBOOY2T.js.map → paths-POPTXJO6.js.map} +0 -0
  148. /package/dist/{wallet-B3FVHNTS.js.map → pay-LSDJBIAZ.js.map} +0 -0
@@ -3,26 +3,72 @@ import {
3
3
  HOOK_TOOL
4
4
  } from "./chunk-AKWGE6JQ.js";
5
5
  import {
6
- MCP_SERVER_NAME
7
- } from "./chunk-TGLKKLQG.js";
6
+ LEGACY_MCP_SERVER_NAME,
7
+ ROUTER_DEFAULTS
8
+ } from "./chunk-EWLU46J6.js";
8
9
  import {
9
- package_default
10
- } from "./chunk-HC3QEZKT.js";
10
+ modeGatedPointer
11
+ } from "./chunk-A36LQPHV.js";
11
12
  import {
13
+ confirmChoice
14
+ } from "./chunk-P7LABKCW.js";
15
+ import {
16
+ LockTimeoutError,
17
+ withFileLock
18
+ } from "./chunk-MEFB5KHA.js";
19
+ import {
20
+ style
21
+ } from "./chunk-TROZ6HL4.js";
22
+ import {
23
+ projectRouterPath,
24
+ readProjectRouterFile,
25
+ routerSettings
26
+ } from "./chunk-MG3G644T.js";
27
+ import {
28
+ hasCode
29
+ } from "./chunk-2I4QTOLB.js";
30
+ import {
31
+ isTeamShelfOrigin,
32
+ loadProjectConfig
33
+ } from "./chunk-AMEUXNJT.js";
34
+ import {
35
+ CONFIG_KEYS,
12
36
  CliError,
37
+ EXPERIMENTAL_CONFIG_KEYS,
13
38
  HARNESSES,
39
+ HOOKS_CONFIG_KEYS,
40
+ LOOP_CONFIG_KEYS,
41
+ PRODUCTION_ORIGIN,
42
+ PUBLISH_CONFIG_KEYS,
43
+ PublishModeSchema,
44
+ RETIRED_PAYMENT_GUIDANCE,
45
+ ROUTER_CONFIG_KEYS,
46
+ ROUTER_CONTEXTS,
47
+ RawConfigSchema,
48
+ SEND_MAX_UNSET,
49
+ TEAM_CONFIG_KEYS,
50
+ UPDATE_CONFIG_KEYS,
51
+ isSameDeployment,
52
+ loadRawConfig,
53
+ parseAckServerWarnings,
54
+ parseLoopValue,
55
+ parsePublicFallbackFlag,
56
+ parseUpdateModeFlag,
57
+ parseUsdToAtomic,
58
+ resolveSettings,
59
+ retiredPaymentKeys,
60
+ toMoney,
14
61
  writeFileAtomic
15
- } from "./chunk-JLEF5WHM.js";
62
+ } from "./chunk-VVAHFCX2.js";
16
63
  import {
17
- daemonBundlePath,
18
- daemonLogPath,
19
- daemonPidPath,
20
- daemonSpawnPath,
21
- daemonTokenPath,
22
- hooksDir,
23
- shimBundlePath,
24
- vitestReporterPath
25
- } from "./chunk-K6AXXYCG.js";
64
+ configPath,
65
+ hooksDir
66
+ } from "./chunk-SJLTEINJ.js";
67
+
68
+ // src/commands/config.ts
69
+ import { mkdir as mkdir2 } from "node:fs/promises";
70
+ import { homedir } from "node:os";
71
+ import { dirname as dirname3 } from "node:path";
26
72
 
27
73
  // src/lib/harness-permissions.ts
28
74
  import { chmod, lstat, mkdir, readFile, realpath, stat as stat2 } from "node:fs/promises";
@@ -42,13 +88,9 @@ var AGENT_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
42
88
 
43
89
  // src/hooks/constants.ts
44
90
  var HARNESS_MS = 5e3;
45
- var SPAWN_MS = 500;
46
- var HEALTH_MS = 200;
47
- var SPAWN_BACKOFF_MS = 6e4;
48
91
  var MAX_BODY_BYTES = 4 * 1024 * 1024;
49
92
  var LOG_TRUNCATE_BYTES = 5 * 1024 * 1024;
50
93
  var CONTEXT_MAX = 1e4;
51
- var STOP_GRACE_MS = 3e3;
52
94
 
53
95
  // src/lib/codex-trust.ts
54
96
  import { spawn } from "node:child_process";
@@ -259,8 +301,8 @@ async function trustCodexHooks(home, keys, ownedBy, opts = {}) {
259
301
  }
260
302
  async function readCodexTrust(home, keys, opts = {}) {
261
303
  const env = opts.env ?? process.env;
262
- const configPath = codexConfigPath(home, env);
263
- const base = { configPath, trusted: 0, expected: keys.length };
304
+ const configPath2 = codexConfigPath(home, env);
305
+ const base = { configPath: configPath2, trusted: 0, expected: keys.length };
264
306
  if (keys.length === 0) return { ...base, state: "unknown", source: "none" };
265
307
  const list = await (opts.listHooks ?? ((h, e) => listHooksViaAppServer(h, e, opts.timeoutMs ?? PROBE_MS)))(home, env);
266
308
  if (list !== null) {
@@ -893,33 +935,115 @@ async function inspectAllowlistAt(declaredPath, rules, list = "allow") {
893
935
  const alreadyPresent = rules.filter((rule) => present.has(rule));
894
936
  return { path, raw, settings, permissions, allow, added, alreadyPresent: [...alreadyPresent] };
895
937
  }
896
- async function appendAllowlistRules(declaredPath, rules, list = "allow") {
897
- const found = await inspectAllowlistAt(declaredPath, rules, list);
898
- if ("result" in found) {
899
- const result = found.result;
900
- return {
901
- path: result.path ?? declaredPath,
902
- added: [],
903
- alreadyPresent: [],
904
- ...result.skipped !== void 0 ? { skipped: result.skipped } : {},
905
- ...result.warning !== void 0 ? { warning: result.warning } : {}
906
- };
938
+
939
+ // src/lib/skill-wiring.ts
940
+ import { existsSync, statSync } from "node:fs";
941
+ import { constants, open } from "node:fs/promises";
942
+ import { delimiter, join as join6 } from "node:path";
943
+
944
+ // src/lib/skills-source.ts
945
+ import { dirname as dirname2, join as join5 } from "node:path";
946
+ var SKILL_NAMES = ["tenjin-search", "tenjin-publish", "tenjin"];
947
+ var RETIRED_SKILL_NAMES = ["tenjin-pay"];
948
+ var PACKAGED_SKILL_NAMES = [...SKILL_NAMES];
949
+ var SHIPPED_SKILL_FILES = {
950
+ "tenjin-search": ["SKILL.md", "references/permissions.md"],
951
+ "tenjin-publish": ["SKILL.md", "references/maintain.md"],
952
+ tenjin: ["SKILL.md"],
953
+ "tenjin-pay": ["SKILL.md"]
954
+ };
955
+ var SENTINEL = join5("tenjin", "SKILL.md");
956
+
957
+ // src/lib/skill-wiring.ts
958
+ var CLI_SKILL_NAMES = [
959
+ "tenjin-search",
960
+ "tenjin-publish"
961
+ ];
962
+ function skillsDirsFor(home) {
963
+ return [join6(home, ".claude", "skills"), join6(home, ".agents", "skills")];
964
+ }
965
+ function harnessTargetDir(home, harness) {
966
+ if (harness === "claude") return join6(home, ".claude", "skills");
967
+ return join6(home, ".agents", "skills");
968
+ }
969
+ function harnessFlagFor(home, dir) {
970
+ if (dir === join6(home, ".claude", "skills")) return "claude";
971
+ return "codex";
972
+ }
973
+ function harnessDetectedBy(home, harness, which) {
974
+ const reasons = [];
975
+ if (existsSync(join6(home, `.${harness}`))) reasons.push("home-dir");
976
+ if (which(harness)) reasons.push("binary");
977
+ return reasons;
978
+ }
979
+ function detectHarnesses(home, which) {
980
+ return {
981
+ claude: harnessDetectedBy(home, "claude", which).length > 0,
982
+ codex: harnessDetectedBy(home, "codex", which).length > 0
983
+ };
984
+ }
985
+ function harnessReads(home, dir, present) {
986
+ if (harnessFlagFor(home, dir) === "claude") return present.claude;
987
+ return present.codex;
988
+ }
989
+ function harnessRequested(home, dir, requested) {
990
+ return requested.some((h) => harnessTargetDir(home, h) === dir);
991
+ }
992
+ function harnessInPlay(home, dir, present, requested) {
993
+ if (requested.length > 0) return harnessRequested(home, dir, requested);
994
+ return harnessReads(home, dir, present);
995
+ }
996
+ function onPath(bin, env) {
997
+ const raw = env.PATH ?? "";
998
+ const exts = process.platform === "win32" ? ["", ...(env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM").split(";").filter((e) => e.length > 0)] : [""];
999
+ for (const part of raw.split(delimiter)) {
1000
+ if (part.length === 0) continue;
1001
+ for (const ext of exts) {
1002
+ if (isFile(join6(part, bin + ext))) return true;
1003
+ }
907
1004
  }
908
- const { path, raw, settings, permissions, allow, added, alreadyPresent } = found;
909
- if (added.length === 0) return { path, added: [], alreadyPresent };
910
- const next = { ...settings, permissions: { ...permissions, [list]: [...allow, ...added] } };
911
- const current = await readFile(path, "utf8").catch(() => null);
912
- if (current !== raw) {
913
- return {
914
- path,
915
- added: [],
916
- alreadyPresent,
917
- skipped: "changed-since-read",
918
- warning: `${path} changed while it was being updated, so nothing was written. Re-run \`tenjin install\`.`
919
- };
1005
+ return false;
1006
+ }
1007
+ function isFile(p) {
1008
+ try {
1009
+ return statSync(p).isFile();
1010
+ } catch {
1011
+ return false;
1012
+ }
1013
+ }
1014
+ async function readSkillFile(path) {
1015
+ let handle;
1016
+ try {
1017
+ handle = await open(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));
1018
+ } catch (err) {
1019
+ if (hasCode(err, "ENOENT")) return { kind: "absent" };
1020
+ return { kind: "unreadable", err };
1021
+ }
1022
+ try {
1023
+ if (!(await handle.stat()).isFile()) return { kind: "not-regular" };
1024
+ return { kind: "ok", bytes: await handle.readFile() };
1025
+ } catch (err) {
1026
+ return { kind: "unreadable", err };
1027
+ } finally {
1028
+ await handle.close().catch(() => void 0);
920
1029
  }
921
- await writeSettings(path, next);
922
- return { path, added, alreadyPresent };
1030
+ }
1031
+ function skillFrontmatterName(skillMd) {
1032
+ const frontmatter = extractFrontmatter(skillMd);
1033
+ if (frontmatter === null) return null;
1034
+ for (const line of frontmatter) {
1035
+ const m = /^name:\s*(.+?)\s*$/.exec(line);
1036
+ if (m !== null) return (m[1] ?? "").replace(/^["']|["']$/g, "");
1037
+ }
1038
+ return null;
1039
+ }
1040
+ function extractFrontmatter(text) {
1041
+ const lines = text.replace(/^\uFEFF/, "").split(/\r?\n/);
1042
+ const open2 = lines.findIndex((l) => l.trim().length > 0);
1043
+ if (open2 === -1 || lines[open2]?.trim() !== "---") return null;
1044
+ const end = lines.findIndex((l, i) => i > open2 && l.trim() === "---");
1045
+ if (end === -1) return null;
1046
+ return lines.slice(open2 + 1, end);
923
1047
  }
924
1048
 
925
1049
  // src/adapters/claude.ts
@@ -1139,308 +1263,17 @@ var ADAPTERS = {
1139
1263
  // src/lib/harness-hooks.ts
1140
1264
  import { chmod as chmod2, lstat as lstat2, readFile as readFile2, realpath as realpath2, stat as stat3 } from "node:fs/promises";
1141
1265
  import { resolve } from "node:path";
1142
-
1143
- // src/daemon/control.ts
1144
- import { randomBytes } from "node:crypto";
1145
- import { copyFileSync, existsSync as existsSync2, mkdirSync as mkdirSync2, renameSync, rmSync, writeFileSync as writeFileSync2 } from "node:fs";
1146
- import { dirname as dirname2, join as join5 } from "node:path";
1147
- import { fileURLToPath } from "node:url";
1148
-
1149
- // src/hooks/shim.ts
1150
- import { spawn as spawn2 } from "node:child_process";
1151
- import {
1152
- appendFileSync,
1153
- closeSync,
1154
- existsSync,
1155
- mkdirSync,
1156
- openSync,
1157
- readFileSync,
1158
- statSync,
1159
- unlinkSync,
1160
- writeFileSync
1161
- } from "node:fs";
1162
- function missingRoutes(h, required) {
1163
- const served = new Set(Array.isArray(h.harnesses) ? h.harnesses : []);
1164
- return required.filter((harness) => !served.has(harness));
1165
- }
1166
- function readPid(dataDir2) {
1167
- try {
1168
- const raw = JSON.parse(readFileSync(daemonPidPath(dataDir2), "utf8"));
1169
- if (typeof raw.pid === "number" && typeof raw.port === "number" && typeof raw.started_at === "number" && typeof raw.data_dir === "string") {
1170
- return { pid: raw.pid, port: raw.port, started_at: raw.started_at, data_dir: raw.data_dir };
1171
- }
1172
- return null;
1173
- } catch {
1174
- return null;
1175
- }
1176
- }
1177
- function readToken(dataDir2) {
1178
- try {
1179
- const t = readFileSync(daemonTokenPath(dataDir2), "utf8").trim();
1180
- return t.length > 0 ? t : null;
1181
- } catch {
1182
- return null;
1183
- }
1184
- }
1185
- async function health(port, timeoutMs = HEALTH_MS) {
1186
- try {
1187
- const res = await fetch(`http://127.0.0.1:${port}/health`, {
1188
- signal: AbortSignal.timeout(timeoutMs)
1189
- });
1190
- if (!res.ok) return null;
1191
- const body = await res.json();
1192
- if (typeof body.pid !== "number" || typeof body.data_dir !== "string") return null;
1193
- return body;
1194
- } catch {
1195
- return null;
1196
- }
1197
- }
1198
- function daemonEnv(dataDir2, env = process.env) {
1199
- const keep = [
1200
- "PATH",
1201
- "HOME",
1202
- "USERPROFILE",
1203
- "TMPDIR",
1204
- "TEMP",
1205
- "TMP",
1206
- "HTTP_PROXY",
1207
- "HTTPS_PROXY",
1208
- "NO_PROXY",
1209
- "http_proxy",
1210
- "https_proxy",
1211
- "no_proxy"
1212
- ];
1213
- const out = {};
1214
- for (const k of keep) if (env[k] !== void 0) out[k] = env[k];
1215
- out.TENJIN_DATA_DIR = dataDir2;
1216
- return out;
1217
- }
1218
- function inBackoff(dataDir2, now = Date.now()) {
1219
- try {
1220
- return now - statSync(daemonSpawnPath(dataDir2)).mtimeMs < SPAWN_BACKOFF_MS;
1221
- } catch {
1222
- return false;
1223
- }
1224
- }
1225
- function spawnDaemon(dataDir2, env = process.env) {
1226
- mkdirSync(dataDir2, { recursive: true, mode: 448 });
1227
- writeFileSync(daemonSpawnPath(dataDir2), "");
1228
- const log = openSync(daemonLogPath(dataDir2), "a");
1229
- try {
1230
- const child = spawn2(process.execPath, [daemonBundlePath(dataDir2)], {
1231
- detached: true,
1232
- stdio: ["ignore", log, log],
1233
- env: daemonEnv(dataDir2, env),
1234
- // Never the hook's cwd: a detached daemon would pin a project worktree.
1235
- cwd: dataDir2,
1236
- windowsHide: true
1237
- });
1238
- child.unref();
1239
- } finally {
1240
- closeSync(log);
1241
- }
1242
- }
1243
- function sleep(ms) {
1244
- return new Promise((r) => setTimeout(r, ms));
1245
- }
1246
- async function ensureDaemon(dataDir2, opts = {}) {
1247
- const now = opts.now ?? (() => Date.now());
1248
- const pid = readPid(dataDir2);
1249
- if (pid !== null) {
1250
- const h = await health(pid.port);
1251
- if (h !== null && h.data_dir === dataDir2) return { ok: true, health: h, spawned: false };
1252
- }
1253
- if (!existsSync(daemonBundlePath(dataDir2)))
1254
- return { ok: false, reason: "no bundle; run `tenjin daemon start`" };
1255
- if (inBackoff(dataDir2, now())) return { ok: false, reason: "spawn backoff" };
1256
- try {
1257
- spawnDaemon(dataDir2, opts.env);
1258
- } catch (err) {
1259
- return {
1260
- ok: false,
1261
- reason: `spawn failed: ${err instanceof Error ? err.message : String(err)}`
1262
- };
1263
- }
1264
- const budget = opts.spawnMs ?? SPAWN_MS;
1265
- const until = now() + budget;
1266
- const settled = async () => {
1267
- const fresh = readPid(dataDir2);
1268
- if (fresh === null || pid !== null && fresh.started_at === pid.started_at) return null;
1269
- const h = await health(fresh.port);
1270
- return h !== null && h.data_dir === dataDir2 ? h : null;
1271
- };
1272
- const won = (h) => {
1273
- try {
1274
- unlinkSync(daemonSpawnPath(dataDir2));
1275
- } catch {
1276
- }
1277
- return { ok: true, health: h, spawned: true };
1278
- };
1279
- while (now() < until) {
1280
- await sleep(20);
1281
- const h = await settled();
1282
- if (h !== null) return won(h);
1283
- }
1284
- const late = await settled();
1285
- if (late !== null) return won(late);
1286
- return { ok: false, reason: `spawned but not healthy within ${budget} ms` };
1287
- }
1288
-
1289
- // src/daemon/control.ts
1290
- var INSTALL_SPAWN_MS = 5e3;
1291
- var BUNDLES = {
1292
- "tenjin-daemon.mjs": daemonBundlePath,
1293
- "tenjin-shim.mjs": shimBundlePath,
1294
- "tenjin-vitest-reporter.mjs": vitestReporterPath
1295
- };
1296
- function defaultBundleDir() {
1297
- return dirname2(fileURLToPath(import.meta.url));
1298
- }
1299
- function installDaemonFiles(dataDir2, bundleDir) {
1300
- const written = [];
1301
- mkdirSync2(hooksDir(dataDir2), { recursive: true, mode: 448 });
1302
- for (const [name, target] of Object.entries(BUNDLES)) {
1303
- const src = join5(bundleDir, name);
1304
- if (!existsSync2(src)) {
1305
- throw new CliError("INTERNAL", `Daemon bundle missing: ${src}`, {
1306
- fix: `Reinstall tenjin-cli; the package ships dist/${Object.keys(BUNDLES).join(", dist/")}.`
1307
- });
1308
- }
1309
- const dest = target(dataDir2);
1310
- const staged = `${dest}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
1311
- copyFileSync(src, staged);
1312
- renameSync(staged, dest);
1313
- written.push(dest);
1314
- }
1315
- if (readToken(dataDir2) === null) {
1316
- writeFileSync2(daemonTokenPath(dataDir2), randomBytes(32).toString("hex"), { mode: 384 });
1317
- written.push(daemonTokenPath(dataDir2));
1318
- }
1319
- return { written };
1320
- }
1321
- function alive(pid, kill) {
1322
- try {
1323
- kill(pid, 0);
1324
- return true;
1325
- } catch {
1326
- return false;
1327
- }
1328
- }
1329
- async function stopDaemon(dataDir2, deps = {}) {
1330
- const kill = deps.kill ?? ((pid, sig) => process.kill(pid, sig));
1331
- const sleep2 = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
1332
- const now = deps.now ?? (() => Date.now());
1333
- const rec = readPid(dataDir2);
1334
- if (rec === null || !alive(rec.pid, kill)) {
1335
- if (rec !== null) rmSync(daemonPidPath(dataDir2), { force: true });
1336
- return { state: "not-running" };
1337
- }
1338
- const h = await health(rec.port);
1339
- if (h !== null && (h.pid !== rec.pid || h.data_dir !== dataDir2)) {
1340
- rmSync(daemonPidPath(dataDir2), { force: true });
1341
- return { state: "not-running" };
1342
- }
1343
- if (h === null) return { state: "unconfirmed", pid: rec.pid };
1344
- kill(rec.pid, "SIGTERM");
1345
- const until = now() + STOP_GRACE_MS;
1346
- while (now() < until) {
1347
- await sleep2(50);
1348
- if (!alive(rec.pid, kill)) return { state: "stopped", pid: rec.pid };
1349
- }
1350
- try {
1351
- kill(rec.pid, "SIGKILL");
1352
- } catch {
1353
- }
1354
- rmSync(daemonPidPath(dataDir2), { force: true });
1355
- return { state: "killed", pid: rec.pid };
1356
- }
1357
- async function startDaemon(dataDir2, deps = {}) {
1358
- const { written } = installDaemonFiles(dataDir2, deps.bundleDir ?? defaultBundleDir());
1359
- const rec = readPid(dataDir2);
1360
- const running = rec === null ? null : await health(rec.port);
1361
- let replaced = null;
1362
- let reason;
1363
- let short = [];
1364
- let unconfirmed = null;
1365
- if (running !== null && running.data_dir === dataDir2) {
1366
- short = missingRoutes(running, deps.requires ?? []);
1367
- const stale = running.version !== package_default.version ? "older-build" : short.length > 0 ? "missing-routes" : void 0;
1368
- if (stale !== void 0) {
1369
- const stopped = await stopDaemon(dataDir2, deps);
1370
- if (stopped.state === "stopped" || stopped.state === "killed") {
1371
- replaced = rec;
1372
- reason = stale;
1373
- } else if (stopped.state === "unconfirmed") unconfirmed = stopped.pid ?? null;
1374
- }
1375
- }
1376
- const ensured = await ensureDaemon(dataDir2, {
1377
- ...deps.env ? { env: deps.env } : {},
1378
- spawnMs: deps.spawnMs ?? INSTALL_SPAWN_MS,
1379
- ...deps.now ? { now: deps.now } : {}
1380
- });
1381
- if (!ensured.ok) {
1382
- throw new CliError("INTERNAL", `Daemon did not start: ${ensured.reason}`, {
1383
- fix: `Read ${join5(dataDir2, "daemon.log")}; if it names a port conflict, set \`tenjin config set loop.port <n>\`.`
1384
- });
1385
- }
1386
- const stillShort = missingRoutes(ensured.health, deps.requires ?? []);
1387
- if (stillShort.length > 0) {
1388
- throw new CliError(
1389
- "INTERNAL",
1390
- `The daemon on 127.0.0.1:${ensured.health.port} (v${ensured.health.version}) has no route for ${stillShort.join(", ")}, so its hook entries would answer 404.`,
1391
- { fix: "Run `tenjin daemon stop`, then re-run `tenjin install`." }
1392
- );
1393
- }
1394
- return {
1395
- health: ensured.health,
1396
- spawned: ensured.spawned,
1397
- replaced,
1398
- ...reason !== void 0 ? { replacedReason: reason } : {},
1399
- ...reason === "missing-routes" ? { missingRoutes: short } : {},
1400
- unconfirmed,
1401
- written
1402
- };
1403
- }
1404
-
1405
- // src/lib/harness-hooks.ts
1406
1266
  var OUR_HOOK_FILES = ["tenjin-daemon.mjs", "tenjin-shim.mjs"];
1407
1267
  var OUR_HOOK_COMMAND = "tenjin hook ";
1408
1268
  var LOOP_URL_RE = new RegExp(`^http://127\\.0\\.0\\.1:\\d+/hook/(?:${HARNESSES.join("|")})$`);
1409
1269
  var HOOK_TIMEOUT_SECONDS = HARNESS_MS / 1e3;
1410
- function skip2(reason, args) {
1411
- return {
1412
- harness: args.harness,
1413
- ...args.path !== void 0 ? { path: args.path } : {},
1414
- ...args.hooksDir !== void 0 ? { hooksDir: args.hooksDir } : {},
1415
- entries: 0,
1416
- wrote: false,
1417
- skipped: reason,
1418
- ...args.warning !== void 0 ? { warning: args.warning } : {},
1419
- ...args.fix !== void 0 ? { fix: args.fix } : {}
1420
- };
1421
- }
1422
- function fixFor2(reason) {
1423
- switch (reason) {
1424
- case "declined":
1425
- case "dry-run":
1426
- return "Wire them with `tenjin install`.";
1427
- case "daemon-down":
1428
- return "Run `tenjin daemon start`, then re-run `tenjin install`.";
1429
- case "changed-since-read":
1430
- return "Another process changed the file mid-run; re-run `tenjin install`.";
1431
- case "unwritable":
1432
- return "The daemon, its bundles and the skills are already in place; only the hooks file could not be written. Fix its permissions (or its directory\u2019s), then re-run `tenjin install`.";
1433
- default:
1434
- return "Fix the reported file, then re-run `tenjin install`.";
1435
- }
1436
- }
1437
1270
  function isPlainObject2(value) {
1438
1271
  return typeof value === "object" && value !== null && !Array.isArray(value);
1439
1272
  }
1440
1273
  function ownsHandler(handler, dataDir2) {
1441
1274
  if (!isPlainObject2(handler)) return false;
1442
1275
  if (handler.type === "mcp_tool") {
1443
- return handler.server === MCP_SERVER_NAME && handler.tool === HOOK_TOOL;
1276
+ return handler.server === LEGACY_MCP_SERVER_NAME && handler.tool === HOOK_TOOL;
1444
1277
  }
1445
1278
  const url = handler.url;
1446
1279
  if (typeof url === "string" && LOOP_URL_RE.test(url)) return true;
@@ -1456,29 +1289,6 @@ function ownsHookEntry(entry, dataDir2) {
1456
1289
  if (!Array.isArray(handlers)) return false;
1457
1290
  return handlers.some((h) => ownsHandler(h, dataDir2));
1458
1291
  }
1459
- function pruneOurHandlers(entry, dataDir2) {
1460
- if (!isPlainObject2(entry)) return entry;
1461
- const handlers = entry.hooks;
1462
- if (!Array.isArray(handlers)) return entry;
1463
- const kept = handlers.filter((h) => !ownsHandler(h, dataDir2));
1464
- if (kept.length === handlers.length) return entry;
1465
- return kept.length === 0 ? null : { ...entry, hooks: kept };
1466
- }
1467
- function pruneHooks(hooks, dataDir2) {
1468
- const next = {};
1469
- const removed = [];
1470
- for (const [event, value] of Object.entries(hooks)) {
1471
- if (!Array.isArray(value)) {
1472
- next[event] = value;
1473
- continue;
1474
- }
1475
- const kept = value.map((e) => pruneOurHandlers(e, dataDir2)).filter((e) => e !== null);
1476
- if (kept.length !== value.length) removed.push(event);
1477
- const emptiedByUs = kept.length === 0 && value.length > 0;
1478
- if (!emptiedByUs) next[event] = kept;
1479
- }
1480
- return { next, removed };
1481
- }
1482
1292
  async function inspectHooksFile(declaredPath) {
1483
1293
  const entry = await lstat2(declaredPath).catch(() => null);
1484
1294
  let path = declaredPath;
@@ -1594,195 +1404,760 @@ async function registeredHooks(adapter, homeDir, dataDir2, env = process.env) {
1594
1404
  }
1595
1405
  return out;
1596
1406
  }
1597
- async function writeHooks(opts) {
1598
- const { adapter, homeDir, dataDir: dataDir2 } = opts;
1599
- const env = opts.env ?? process.env;
1600
- const harness = adapter.id;
1601
- const dir = hooksDir(dataDir2);
1602
- const declaredPath = opts.settingsPath ?? adapter.registrar.configPath(homeDir, env);
1603
- const steps = adapter.registrar.activation?.(declaredPath);
1604
- const activation = steps !== void 0 ? { activation: steps } : {};
1605
- if (opts.plan !== void 0) return writePlainEntries(opts, opts.plan, declaredPath, activation);
1606
- let started;
1607
- try {
1608
- started = await (opts.start ?? startDaemon)(dataDir2, {
1609
- ...opts.bundleDir !== void 0 ? { bundleDir: opts.bundleDir } : {},
1610
- // The entries this call is about to write all post to this harness's
1611
- // route, so a running daemon that has no such route is replaced before
1612
- // they name it, whatever its version says (tenjin-agent#342).
1613
- requires: [harness]
1614
- });
1615
- } catch (err) {
1616
- return skip2("daemon-down", {
1617
- harness,
1618
- path: declaredPath,
1619
- hooksDir: dir,
1620
- warning: `${err instanceof Error ? err.message : String(err)}; no hook entry was written, so nothing points at a daemon that is not there.`,
1621
- fix: fixFor2("daemon-down")
1622
- });
1407
+
1408
+ // src/lib/harness-presence.ts
1409
+ async function installedHarnessInPlay(adapter, home, dataDir2, options = {}) {
1410
+ const env = options.env ?? process.env;
1411
+ const which = options.which ?? ((bin) => onPath(bin, env));
1412
+ if (harnessInPlay(
1413
+ home,
1414
+ harnessTargetDir(home, adapter.id),
1415
+ detectHarnesses(home, which),
1416
+ options.requested ?? []
1417
+ )) {
1418
+ return true;
1419
+ }
1420
+ return (await registeredHooks(adapter, home, dataDir2, env)).entries > 0;
1421
+ }
1422
+
1423
+ // src/commands/config.ts
1424
+ var SHELF_KEYS = /* @__PURE__ */ new Set([
1425
+ "allowlistCreators",
1426
+ "publicShelfUrl",
1427
+ "shelfBypassSecret",
1428
+ "evalCohort",
1429
+ ...PUBLISH_CONFIG_KEYS,
1430
+ ...HOOKS_CONFIG_KEYS,
1431
+ ...LOOP_CONFIG_KEYS,
1432
+ ...TEAM_CONFIG_KEYS
1433
+ ]);
1434
+ var KEY_WIDTH = Math.max(
1435
+ ...[...CONFIG_KEYS, ...UPDATE_CONFIG_KEYS, ...ROUTER_CONFIG_KEYS, ...EXPERIMENTAL_CONFIG_KEYS].filter((key) => !SHELF_KEYS.has(key)).map((key) => key.length)
1436
+ );
1437
+ var KEY_DESCRIPTIONS = {
1438
+ maxAutoSpend: "automatic router limit per call",
1439
+ sessionBudget: "automatic router daily limit: 0 blocks automatic spend, none removes the ceiling",
1440
+ sendMaxAmount: "hard cap per tenjin wallet send; unset = send refuses until set, 0 disables send, none = uncapped; never bypassed by --yes",
1441
+ allowlistCreators: "only auto-pay these creators (empty = any)",
1442
+ baseUrl: "Tenjin API base URL the router asks",
1443
+ publicShelfUrl: "the public marketplace, consume-only: the second shelf a team-mode search falls through to",
1444
+ shelfBypassSecret: "the team shelf's Vercel protection-bypass secret; setting it is what turns team mode on (printed as set/unset)",
1445
+ rpcUrl: "Base RPC endpoint for balance reads",
1446
+ evalCohort: "opt in to the search evaluation cohort",
1447
+ bazaarRegistries: "x402 registries used to verify direct-payment listings",
1448
+ "publish.mode": "review=always ask, auto=ask on findings, full-auto=only hard blocks stop it",
1449
+ "publish.defaultPrice": "price used when none is given",
1450
+ "publish.ackServerWarnings": "whether a yes covers the MARKETPLACE scan's warn findings: mode=only the ones an earlier render already showed you (full-auto still acks), on=any of them, off=never",
1451
+ "hooks.prompt": "answer the prompt you just typed with what the shelves already know",
1452
+ "hooks.web-search": "ask Tenjin before the agent runs a WebSearch",
1453
+ "hooks.web-fetch": "ask Tenjin before the agent fetches a page",
1454
+ "hooks.subagent": "ask Tenjin with a subagent work order (the most sensitive payload any hook sees) and hand the answer to the child at its start",
1455
+ "hooks.failure": "answer a failing command with the fix this machine or a shelf already has",
1456
+ "hooks.publish": "the turn-end ask to publish what this turn settled, spoken to you and to each subagent at its own end",
1457
+ "hooks.primer": "one-paragraph search-first primer at session start",
1458
+ "update.mode": "nudge=report a newer version (stderr line, JSON envelope, hook output), off=neither report nor ask npm",
1459
+ "loop.human_wait_ms": "ms a hook fire may take when a human is waiting on it (prompt, Stop, SessionStart)",
1460
+ "loop.tool_wait_ms": "ms a hook fire may take when a tool call is waiting on it",
1461
+ "loop.idle_exit_min": "minutes without a hook fire before the loop daemon exits",
1462
+ "loop.port": "the loop daemon's loopback port; null derives one from the data dir (set only when doctor reports a foreign listener)",
1463
+ "team.publicFallback": "on=a team-shelf miss falls through to the public marketplace, off=team-only (public-only lookup stages are dropped)",
1464
+ "router.enabled": "false stops every router hook and the request tool; --project sets it for this repository, --project --local for you alone in it",
1465
+ "router.context": "session=a hook packet carries up to six prior messages, turn=the current turn only; --project and --local as for router.enabled",
1466
+ "experimental.bazaar": "EXPERIMENTAL. on=the router may also suggest unreviewed sellers from Coinbase's open x402 Bazaar, off=curated services and Tenjin's reviewed list only"
1467
+ };
1468
+ var EXPERIMENTAL_BAZAAR_WARNING = "Experimental: the router may now also suggest sellers from Coinbase's open x402 Bazaar. They are unreviewed third parties, Tenjin has not checked them, matches can be noisy, prices can vary with the input, and payments are real, under your spend limits. To find them, short snippets of your prompts are sent to Coinbase's public Bazaar search. Tenjin's reviewed list stays on either way. Turn this off with `tenjin config set experimental.bazaar off`.";
1469
+ function isExperimentalKey(key) {
1470
+ return EXPERIMENTAL_CONFIG_KEYS.includes(key);
1471
+ }
1472
+ function isLoopKey(key) {
1473
+ return LOOP_CONFIG_KEYS.includes(key);
1474
+ }
1475
+ function isTeamKey(key) {
1476
+ return TEAM_CONFIG_KEYS.includes(key);
1477
+ }
1478
+ function isRouterKey(key) {
1479
+ return ROUTER_CONFIG_KEYS.includes(key);
1480
+ }
1481
+ function renderRouterSetting(key, settings) {
1482
+ const { value, source, path } = key === "router.enabled" ? settings.enabled : settings.context;
1483
+ return { value, source, ...path !== void 0 ? { path } : {} };
1484
+ }
1485
+ async function resolveRouterFromContext(ctx) {
1486
+ return routerSettings({ cwd: process.cwd(), dataDir: ctx.dataDir });
1487
+ }
1488
+ function renderLoopSetting(key, settings) {
1489
+ const field = key.slice("loop.".length);
1490
+ const { value, source } = settings.loop[field];
1491
+ return { value: value === null ? "null" : String(value), source };
1492
+ }
1493
+ function isPublishKey(key) {
1494
+ return PUBLISH_CONFIG_KEYS.includes(key);
1495
+ }
1496
+ function isHooksKey(key) {
1497
+ return HOOKS_CONFIG_KEYS.includes(key);
1498
+ }
1499
+ function isUpdateKey(key) {
1500
+ return UPDATE_CONFIG_KEYS.includes(key);
1501
+ }
1502
+ async function runConfigList(ctx) {
1503
+ const settings = await resolveFromContext(ctx);
1504
+ const data = {};
1505
+ const humanLines = [];
1506
+ const show = (key, line) => {
1507
+ if (!SHELF_KEYS.has(key)) humanLines.push(line);
1508
+ };
1509
+ for (const key of CONFIG_KEYS) {
1510
+ const entry = renderSetting(key, settings[key].value, settings[key].source);
1511
+ data[key] = entry;
1512
+ show(key, describedLine(key, entry));
1513
+ }
1514
+ for (const key of PUBLISH_CONFIG_KEYS) {
1515
+ const entry = renderPublishSetting(key, settings);
1516
+ data[key] = entry;
1517
+ show(key, describedLine(key, entry, downgradeNote(key, settings)));
1518
+ }
1519
+ for (const key of HOOKS_CONFIG_KEYS) {
1520
+ const entry = renderHooksSetting(key, settings);
1521
+ data[key] = entry;
1522
+ show(key, describedLine(key, entry));
1523
+ }
1524
+ for (const key of UPDATE_CONFIG_KEYS) {
1525
+ const entry = {
1526
+ value: settings.updateMode.value,
1527
+ source: settings.updateMode.source
1528
+ };
1529
+ data[key] = entry;
1530
+ show(key, describedLine(key, entry));
1531
+ }
1532
+ for (const key of LOOP_CONFIG_KEYS) {
1533
+ const entry = renderLoopSetting(key, settings);
1534
+ data[key] = entry;
1535
+ show(key, describedLine(key, entry));
1536
+ }
1537
+ for (const key of TEAM_CONFIG_KEYS) {
1538
+ const entry = {
1539
+ value: settings.teamPublicFallback.value,
1540
+ source: settings.teamPublicFallback.source
1541
+ };
1542
+ data[key] = entry;
1543
+ show(key, describedLine(key, entry));
1544
+ }
1545
+ const router = await resolveRouterFromContext(ctx);
1546
+ for (const key of ROUTER_CONFIG_KEYS) {
1547
+ const entry = renderRouterSetting(key, router);
1548
+ data[key] = entry;
1549
+ show(key, describedLine(key, entry));
1550
+ }
1551
+ for (const key of EXPERIMENTAL_CONFIG_KEYS) {
1552
+ const entry = {
1553
+ value: settings.experimentalBazaar.value,
1554
+ source: settings.experimentalBazaar.source
1555
+ };
1556
+ data[key] = entry;
1557
+ show(key, describedLine(key, entry));
1558
+ }
1559
+ return { data, humanLines };
1560
+ }
1561
+ async function runConfigGet({ key }, ctx) {
1562
+ if (isPublishKey(key)) {
1563
+ const settings2 = await resolveFromContext(ctx);
1564
+ const entry2 = renderPublishSetting(key, settings2);
1565
+ return {
1566
+ data: { key, ...entry2 },
1567
+ humanLines: [withNote(formatLine(key, entry2), downgradeNote(key, settings2))]
1568
+ };
1569
+ }
1570
+ if (isHooksKey(key)) {
1571
+ const entry2 = renderHooksSetting(key, await resolveFromContext(ctx));
1572
+ return { data: { key, ...entry2 }, humanLines: [formatLine(key, entry2)] };
1573
+ }
1574
+ if (isUpdateKey(key)) {
1575
+ const { updateMode } = await resolveFromContext(ctx);
1576
+ const entry2 = { value: updateMode.value, source: updateMode.source };
1577
+ return { data: { key, ...entry2 }, humanLines: [formatLine(key, entry2)] };
1578
+ }
1579
+ if (isLoopKey(key)) {
1580
+ const entry2 = renderLoopSetting(key, await resolveFromContext(ctx));
1581
+ return { data: { key, ...entry2 }, humanLines: [formatLine(key, entry2)] };
1623
1582
  }
1624
- const pid = readPid(dataDir2);
1625
- const token = readToken(dataDir2);
1626
- if (pid === null || token === null) {
1627
- return skip2("daemon-down", {
1628
- harness,
1629
- path: declaredPath,
1630
- hooksDir: dir,
1631
- warning: `The daemon answered but left no ${pid === null ? "daemon.pid" : "daemon.token"} under ${dataDir2}, so no hook entry could name it.`,
1632
- fix: fixFor2("daemon-down")
1583
+ if (isTeamKey(key)) {
1584
+ const { teamPublicFallback } = await resolveFromContext(ctx);
1585
+ const entry2 = {
1586
+ value: teamPublicFallback.value,
1587
+ source: teamPublicFallback.source
1588
+ };
1589
+ return { data: { key, ...entry2 }, humanLines: [formatLine(key, entry2)] };
1590
+ }
1591
+ if (isRouterKey(key)) {
1592
+ const entry2 = renderRouterSetting(key, await resolveRouterFromContext(ctx));
1593
+ return { data: { key, ...entry2 }, humanLines: [formatLine(key, entry2)] };
1594
+ }
1595
+ if (isExperimentalKey(key)) {
1596
+ const { experimentalBazaar } = await resolveFromContext(ctx);
1597
+ const entry2 = {
1598
+ value: experimentalBazaar.value,
1599
+ source: experimentalBazaar.source
1600
+ };
1601
+ return { data: { key, ...entry2 }, humanLines: [formatLine(key, entry2)] };
1602
+ }
1603
+ const configKey = assertKey(key);
1604
+ const settings = await resolveFromContext(ctx);
1605
+ const entry = renderSetting(configKey, settings[configKey].value, settings[configKey].source);
1606
+ return { data: { key: configKey, ...entry }, humanLines: [formatLine(configKey, entry)] };
1607
+ }
1608
+ async function runConfigSet({
1609
+ key,
1610
+ value,
1611
+ project,
1612
+ local
1613
+ }, ctx, deps = {}) {
1614
+ if (local === true && project !== true) {
1615
+ throw new CliError("USAGE", "--local names the personal project file, so it needs --project", {
1616
+ fix: `Run \`tenjin config set --project --local ${key} ${value}\`.`
1633
1617
  });
1634
1618
  }
1635
- const url = `http://127.0.0.1:${pid.port}/hook/${harness}`;
1636
- const found = await inspectHooksFile(declaredPath);
1637
- if ("refusal" in found) {
1638
- return skip2(found.refusal.reason, {
1639
- harness,
1640
- path: found.refusal.path,
1641
- hooksDir: dir,
1642
- warning: found.refusal.message,
1643
- fix: fixFor2(found.refusal.reason)
1619
+ if (isRouterKey(key)) {
1620
+ return setRouterKey(key, value, ctx, project === true ? { local: local === true } : void 0);
1621
+ }
1622
+ if (project === true) {
1623
+ throw new CliError("USAGE", `${key} is not a project key`, {
1624
+ fix: `--project applies to ${ROUTER_CONFIG_KEYS.join(" and ")} only; drop it to set ${key} for this machine.`
1644
1625
  });
1645
1626
  }
1646
- const { path, raw, settings, hooks } = found;
1647
- const plan = adapter.registrar.plan({
1648
- url,
1649
- token,
1650
- shimPath: shimBundlePath(dataDir2),
1651
- timeoutSeconds: HOOK_TIMEOUT_SECONDS
1652
- });
1653
- const planned = /* @__PURE__ */ new Map();
1654
- for (const item of plan) {
1655
- if (!isPlainObject2(item) || typeof item.event !== "string") continue;
1656
- const { event, ...entry } = item;
1657
- const list = planned.get(event) ?? [];
1658
- list.push(entry);
1659
- planned.set(event, list);
1660
- }
1661
- const nextHooks = pruneHooks(hooks, dataDir2).next;
1662
- for (const [event, mine] of planned) {
1663
- const kept = nextHooks[event];
1664
- nextHooks[event] = Array.isArray(kept) ? [...kept, ...mine] : mine;
1665
- }
1666
- const next = `${JSON.stringify({ ...settings, hooks: nextHooks }, null, 2)}
1667
- `;
1668
- const carriesUrl = JSON.stringify(plan).includes(url);
1669
- const result = {
1670
- harness,
1671
- path,
1672
- hooksDir: dir,
1673
- entries: plan.length,
1674
- wrote: next !== raw,
1675
- daemon: { pid: started.health.pid, port: pid.port, version: started.health.version },
1676
- ...carriesUrl ? { url } : {},
1677
- ...activation
1627
+ if (isPublishKey(key)) return setPublishKey(key, value, ctx, deps);
1628
+ if (isHooksKey(key)) return setHooksKey(key, value, ctx);
1629
+ if (isUpdateKey(key)) return setUpdateKey(key, value, ctx);
1630
+ if (isLoopKey(key)) return setLoopKey(key, value, ctx);
1631
+ if (isTeamKey(key)) return setTeamKey(key, value, ctx);
1632
+ if (isExperimentalKey(key)) return setExperimentalKey(key, value, ctx);
1633
+ const configKey = assertKey(key);
1634
+ const stored = parseValue(configKey, value);
1635
+ await persist(ctx.dataDir, (existing) => ({ ...existing, [configKey]: stored }));
1636
+ const entry = renderSetting(configKey, stored, "file");
1637
+ const warning = await halfWiredTeamShelf(configKey, ctx.dataDir);
1638
+ return {
1639
+ data: { key: configKey, ...entry, ...warning !== void 0 ? { warning } : {} },
1640
+ humanLines: [formatLine(configKey, entry), ...warning !== void 0 ? [warning] : []]
1678
1641
  };
1679
- if (next === raw) {
1680
- await tightenFile(path);
1681
- return result;
1642
+ }
1643
+ async function halfWiredTeamShelf(configKey, dataDir2) {
1644
+ if (configKey !== "shelfBypassSecret" && configKey !== "baseUrl" && configKey !== "publicShelfUrl") {
1645
+ return void 0;
1646
+ }
1647
+ const config = await loadRawConfig(dataDir2).catch(() => void 0);
1648
+ if (config === void 0) return void 0;
1649
+ const s = resolveSettings({ config, flags: {}, env: {} });
1650
+ if (s.shelfBypassSecret.value.length === 0) return void 0;
1651
+ const baseUrl = s.baseUrl.value;
1652
+ if (isTeamShelfOrigin(new URL(baseUrl).origin, s.publicShelfUrl.value)) return void 0;
1653
+ const isProduction = isSameDeployment(new URL(baseUrl).origin, PRODUCTION_ORIGIN);
1654
+ const cause = isProduction ? `baseUrl is the public marketplace (${baseUrl})` : `baseUrl and publicShelfUrl are the same shelf (${baseUrl})`;
1655
+ const fix = isProduction ? "Point baseUrl at the team deployment to finish team mode: `tenjin config set baseUrl <team shelf url>`." : `A team shelf must differ from the shelf it falls through to: \`tenjin config set publicShelfUrl ${PRODUCTION_ORIGIN}\`.`;
1656
+ return `Warning: shelfBypassSecret is set, but ${cause}, so this machine stays in PUBLIC mode \u2014 publishes go to the marketplace with the scan\u2019s warn tier and the confirm cascade on. ` + fix;
1657
+ }
1658
+ async function setPublishKey(key, value, ctx, deps) {
1659
+ const entry = key === "publish.mode" ? { value: parsePublishMode(value), source: "file" } : key === "publish.ackServerWarnings" ? { value: parseAckServerWarnings(value, key), source: "file" } : { value: toMoney(parseUsdToAtomic(value)), source: "file" };
1660
+ const subkey = key === "publish.mode" ? "mode" : key === "publish.ackServerWarnings" ? "ackServerWarnings" : "defaultPrice";
1661
+ const stored = key === "publish.defaultPrice" ? entry.value.atomic : entry.value;
1662
+ const persistEntry = async () => persist(ctx.dataDir, (existing) => ({
1663
+ ...existing,
1664
+ publish: { ...existing.publish, [subkey]: stored }
1665
+ }));
1666
+ const humanLines = [formatLine(key, entry)];
1667
+ if (key !== "publish.mode") {
1668
+ await persistEntry();
1669
+ return { data: { key, ...entry }, humanLines };
1670
+ }
1671
+ const allowlist = await syncPublishRule(entry.value, ctx, deps);
1672
+ const failure = grantSyncFailure(allowlist);
1673
+ if (failure !== void 0) {
1674
+ throw new CliError(
1675
+ "REFUSED",
1676
+ `publish.mode was not changed because the ${failure.harness} grant could not be updated: ${failure.reason}`,
1677
+ {
1678
+ fix: failure.fix ?? `Fix the permissions for ${failure.path}, then re-run \`tenjin config set publish.mode ${entry.value}\`.`,
1679
+ details: { key, value: entry.value, allowlist }
1680
+ }
1681
+ );
1682
1682
  }
1683
- if (await readFile2(path, "utf8").catch(() => null) !== raw) {
1684
- return skip2("changed-since-read", {
1685
- harness,
1686
- path,
1687
- hooksDir: dir,
1688
- warning: `${path} changed while it was being updated, so no hooks were registered. Re-run \`tenjin install\`.`,
1689
- fix: fixFor2("changed-since-read")
1683
+ await persistEntry();
1684
+ return {
1685
+ data: { key, ...entry, allowlist },
1686
+ humanLines: [...humanLines, ...allowlistLines(allowlist)]
1687
+ };
1688
+ }
1689
+ function grantSyncFailure(sync) {
1690
+ for (const [harness, result] of Object.entries(sync.byHarness)) {
1691
+ if ("error" in result && result.error !== void 0) {
1692
+ return { harness, path: result.path, reason: result.error };
1693
+ }
1694
+ if ("warning" in result && result.warning !== void 0) {
1695
+ return {
1696
+ harness,
1697
+ path: result.path ?? "(unknown path)",
1698
+ reason: result.warning,
1699
+ ...result.fix !== void 0 ? { fix: result.fix } : {}
1700
+ };
1701
+ }
1702
+ }
1703
+ return void 0;
1704
+ }
1705
+ function publishRuleQuestion(mode, pending, harnesses) {
1706
+ const gated = new Set(MODE_GATED_RULES);
1707
+ const others = pending.filter((rule) => !gated.has(rule)).length;
1708
+ const also = others > 0 ? ` Also adds the ${others} command-grant rule(s) \`tenjin install\` writes.` : "";
1709
+ const targets = harnesses.map(
1710
+ (harness) => harness === "claude" ? "Claude Code" : harness === "codex" ? "Codex" : harness
1711
+ ).join(" and ");
1712
+ return `publish.mode ${mode} is unattended only if ${targets} carries the matching grant for ${MODE_GATED_RULES.join(" and ")}. Update the ${targets} grant now?${also}`;
1713
+ }
1714
+ async function syncPublishRule(mode, ctx, deps) {
1715
+ const home = deps.homeDir ?? homedir();
1716
+ const nothing = { byHarness: {} };
1717
+ const write = async () => {
1718
+ const result = await (deps.wireAllowlist ?? wireFreeVerbAllowlist)(home, mode);
1719
+ if (result.skipped !== void 0) {
1720
+ return {
1721
+ byHarness: { claude: result },
1722
+ skipped: "unwritable",
1723
+ ...result.fix !== void 0 ? { pointer: result.fix } : {}
1724
+ };
1725
+ }
1726
+ return { byHarness: { claude: result } };
1727
+ };
1728
+ const adapters = deps.adapters ?? ADAPTERS;
1729
+ const env = deps.env ?? process.env;
1730
+ const which = deps.which ?? ((bin) => onPath(bin, env));
1731
+ const requested = await loadRawConfig(ctx.dataDir).then((config) => config.install?.harness ?? []).catch(() => []);
1732
+ const inPlay = deps.harnessesInPlay ?? (await Promise.all(
1733
+ Object.values(adapters).map(async (adapter) => ({
1734
+ adapter,
1735
+ selected: await installedHarnessInPlay(adapter, home, ctx.dataDir, {
1736
+ env,
1737
+ which,
1738
+ requested
1739
+ })
1740
+ }))
1741
+ )).filter((entry) => entry.selected).map((entry) => entry.adapter.id);
1742
+ const selectedAdapters = inPlay.map((harness) => adapters[harness]);
1743
+ const isClaude = inPlay.includes("claude");
1744
+ const withOtherGrants = async (sync) => {
1745
+ const byHarness = { ...sync.byHarness };
1746
+ for (const adapter of selectedAdapters) {
1747
+ if (adapter.id === "claude" || adapter.registrar.grant === void 0) continue;
1748
+ const result = await adapter.registrar.grant.write(home, mode, env);
1749
+ byHarness[adapter.id] = result;
1750
+ }
1751
+ return { ...sync, byHarness };
1752
+ };
1753
+ if (selectedAdapters.every((adapter) => adapter.registrar.grant === void 0)) {
1754
+ return { ...nothing, skipped: "not-claude" };
1755
+ }
1756
+ const probe = isClaude ? await (deps.inspectAllowlist ?? inspectFreeVerbRules)(home, mode) : { pending: [] };
1757
+ const gated = new Set(MODE_GATED_RULES);
1758
+ const missing = (probe.pending ?? []).filter((r) => gated.has(r));
1759
+ const pointer = modeGatedPointer(mode, missing) ?? void 0;
1760
+ if (mode === "review") {
1761
+ const retracted = isClaude ? await (deps.retractModeGated ?? retractModeGatedRules)(home) : void 0;
1762
+ if (retracted?.skipped !== void 0) {
1763
+ return {
1764
+ ...nothing,
1765
+ skipped: "unwritable",
1766
+ ...retracted.fix !== void 0 ? { pointer: retracted.fix } : {}
1767
+ };
1768
+ }
1769
+ return await withOtherGrants({
1770
+ byHarness: retracted === void 0 ? {} : { claude: retracted }
1690
1771
  });
1691
1772
  }
1773
+ if (probe.satisfied !== void 0 && selectedAdapters.length === 1 && isClaude) return nothing;
1774
+ const canPrompt = ctx.flags.json === true ? false : deps.isInteractive ?? Boolean(process.stdin.isTTY);
1775
+ if (!canPrompt) {
1776
+ return { ...nothing, skipped: "no-tty", ...pointer ? { pointer } : {} };
1777
+ }
1778
+ const confirm = deps.confirmRule ?? ((label) => confirmChoice(label, true));
1779
+ const grantable = selectedAdapters.filter((adapter) => adapter.registrar.grant !== void 0).map((adapter) => adapter.id);
1780
+ if (!await confirm(publishRuleQuestion(mode, probe.pending ?? [], grantable))) {
1781
+ return { ...nothing, skipped: "declined", ...pointer ? { pointer } : {} };
1782
+ }
1783
+ return await withOtherGrants(isClaude ? await write() : nothing);
1784
+ }
1785
+ function allowlistLines(sync) {
1786
+ const lines = [];
1787
+ const claude = sync.byHarness.claude;
1788
+ if ((claude?.added.length ?? 0) > 0) {
1789
+ lines.push(`Added ${claude?.added.length ?? 0} harness rule(s) to your allowlist.`);
1790
+ }
1791
+ if ((claude?.removed.length ?? 0) > 0) {
1792
+ lines.push(`Removed ${claude?.removed.join(", ")} from your allowlist.`);
1793
+ }
1794
+ const grant = sync.byHarness.codex;
1795
+ if (grant !== void 0 && grant.error === void 0 && grant.wrote) {
1796
+ lines.push(
1797
+ `Codex now allows ${grant.granted.length} tenjin command prefix(es) in ${grant.path}.`
1798
+ );
1799
+ }
1800
+ if (grant?.error !== void 0) {
1801
+ lines.push(`Codex's grant at ${grant.path} could not be updated (${grant.error}).`);
1802
+ }
1803
+ if (sync.pointer !== void 0) lines.push(sync.pointer);
1804
+ return lines;
1805
+ }
1806
+ async function setHooksKey(key, value, ctx) {
1807
+ const arm = key.slice("hooks.".length);
1808
+ const parsed = parseBoolean(value);
1809
+ await persistHookArm(ctx.dataDir, arm, parsed);
1810
+ const entry = { value: parsed, source: "file" };
1811
+ return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };
1812
+ }
1813
+ async function setUpdateKey(key, value, ctx) {
1814
+ const parsed = parseUpdateModeFlag(value, key);
1815
+ await persist(ctx.dataDir, (existing) => ({
1816
+ ...existing,
1817
+ update: { ...existing.update, mode: parsed }
1818
+ }));
1819
+ const entry = { value: parsed, source: "file" };
1820
+ return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };
1821
+ }
1822
+ async function setLoopKey(key, value, ctx) {
1823
+ const parsed = parseLoopValue(key, value);
1824
+ const field = key.slice("loop.".length);
1825
+ await persist(ctx.dataDir, (existing) => ({
1826
+ ...existing,
1827
+ loop: { ...existing.loop, [field]: parsed }
1828
+ }));
1829
+ const entry = {
1830
+ value: parsed === null ? "null" : String(parsed),
1831
+ source: "file"
1832
+ };
1833
+ return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };
1834
+ }
1835
+ async function setTeamKey(key, value, ctx) {
1836
+ const parsed = parsePublicFallbackFlag(value, key);
1837
+ await persist(ctx.dataDir, (existing) => ({
1838
+ ...existing,
1839
+ team: { ...existing.team, publicFallback: parsed }
1840
+ }));
1841
+ const entry = { value: parsed, source: "file" };
1842
+ return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };
1843
+ }
1844
+ async function setExperimentalKey(key, value, ctx) {
1845
+ const parsed = parsePublicFallbackFlag(value, key);
1846
+ await persist(ctx.dataDir, (existing) => ({
1847
+ ...existing,
1848
+ experimental: { ...existing.experimental, bazaar: parsed }
1849
+ }));
1850
+ const entry = { value: parsed, source: "file" };
1851
+ const warning = parsed === "on" ? EXPERIMENTAL_BAZAAR_WARNING : void 0;
1852
+ return {
1853
+ data: { key, ...entry, ...warning !== void 0 ? { warning } : {} },
1854
+ humanLines: [formatLine(key, entry), ...warning !== void 0 ? [warning] : []]
1855
+ };
1856
+ }
1857
+ async function setRouterKey(key, value, ctx, project) {
1858
+ const field = key === "router.enabled" ? "enabled" : "context";
1859
+ const parsed = field === "enabled" ? parseBoolean(value) : parseRouterContext(value);
1860
+ let written;
1861
+ if (project === void 0) {
1862
+ await persist(ctx.dataDir, (existing) => ({
1863
+ ...existing,
1864
+ router: { ...existing.router, [field]: parsed }
1865
+ }));
1866
+ written = { value: parsed, source: "file", path: configPath(ctx.dataDir) };
1867
+ } else {
1868
+ const path = await projectRouterPath({ cwd: process.cwd(), local: project.local });
1869
+ await persistProjectRouter(path, field, parsed);
1870
+ written = { value: parsed, source: project.local ? "local" : "project", path };
1871
+ }
1872
+ const effective = renderRouterSetting(key, await resolveRouterFromContext(ctx));
1873
+ const humanLines = [formatLine(key, written)];
1874
+ if (effective.value !== written.value) {
1875
+ humanLines.push(
1876
+ `Still ${String(effective.value)} here: ${effective.path ?? "the default"} is tighter, and a nearer file can only tighten an outer one.`
1877
+ );
1878
+ }
1879
+ if (project?.local === true) {
1880
+ humanLines.push("Keep .tenjin/config.local.json out of git: add it to .gitignore.");
1881
+ }
1882
+ return { data: { key, ...written, effective }, humanLines };
1883
+ }
1884
+ function parseRouterContext(value) {
1885
+ const found = ROUTER_CONTEXTS.find((context) => context === value);
1886
+ if (found !== void 0) return found;
1887
+ throw new CliError("USAGE", `Invalid router.context: ${JSON.stringify(value)}`, {
1888
+ fix: 'Use "session" or "turn".'
1889
+ });
1890
+ }
1891
+ async function persistProjectRouter(path, field, value) {
1892
+ await mkdir2(dirname3(path), { recursive: true, mode: 493 });
1893
+ const lockPath = `${path}.lock`;
1692
1894
  try {
1693
- await writeFileAtomic(path, next, { mode: 384 });
1895
+ await withFileLock(lockPath, () => mergeProjectRouter(path, field, value));
1694
1896
  } catch (err) {
1695
- return skip2("unwritable", {
1696
- harness,
1697
- path,
1698
- hooksDir: dir,
1699
- warning: `${path} could not be written (${err instanceof Error ? err.message : String(err)}); no hook entry was registered.`,
1700
- fix: fixFor2("unwritable")
1701
- });
1897
+ if (err instanceof LockTimeoutError) {
1898
+ throw new CliError("INTERNAL", err.message, {
1899
+ fix: `If no other tenjin process is running, remove ${lockPath} and retry.`,
1900
+ cause: err
1901
+ });
1902
+ }
1903
+ throw err;
1702
1904
  }
1905
+ }
1906
+ async function mergeProjectRouter(path, field, value) {
1907
+ const existing = await readProjectRouterFile(path);
1908
+ const block = existing?.json.router;
1909
+ const next = {
1910
+ ...existing?.json ?? {},
1911
+ router: { ...block !== void 0 ? block : {}, [field]: value }
1912
+ };
1913
+ await writeFileAtomic(path, `${JSON.stringify(next, null, 2)}
1914
+ `, {
1915
+ mode: 420,
1916
+ dirMode: 493
1917
+ });
1918
+ }
1919
+ function parsePublishMode(value) {
1920
+ const parsed = PublishModeSchema.safeParse(value);
1921
+ if (parsed.success) return parsed.data;
1922
+ throw new CliError("USAGE", `Invalid publish mode: ${JSON.stringify(value)}`, {
1923
+ fix: 'Use "review", "auto", or "full-auto".'
1924
+ });
1925
+ }
1926
+ async function persistHookArm(dir, arm, value) {
1927
+ await persist(dir, (existing) => ({
1928
+ ...existing,
1929
+ hooks: { ...existing.hooks, [arm]: value }
1930
+ }));
1931
+ }
1932
+ async function persistPublishMode(dir, mode) {
1933
+ await persist(dir, (existing) => ({
1934
+ ...existing,
1935
+ publish: { ...existing.publish, mode }
1936
+ }));
1937
+ }
1938
+ async function persistRouterProject(dir, projectDir, present = true) {
1939
+ await persist(dir, (existing) => {
1940
+ const known = new Set(existing.install?.routerProjects ?? []);
1941
+ if (present) known.add(projectDir);
1942
+ else known.delete(projectDir);
1943
+ return { ...existing, install: { ...existing.install, routerProjects: [...known].sort() } };
1944
+ });
1945
+ }
1946
+ async function persistRouterDefaults(dir, refresh = false, limits = ROUTER_DEFAULTS) {
1947
+ const result = { set: [], kept: [], removed: [] };
1948
+ if (refresh && retiredPaymentKeys(await loadRawConfig(dir)).length === 0) return result;
1949
+ await persist(dir, (existing) => {
1950
+ const next = { ...existing };
1951
+ result.removed = retiredPaymentKeys(existing);
1952
+ for (const key of result.removed) delete next[key];
1953
+ if (refresh) return next;
1954
+ for (const key of Object.keys(ROUTER_DEFAULTS)) {
1955
+ const value = limits[key];
1956
+ if (existing[key] !== void 0) result.kept.push(key);
1957
+ else if (value !== void 0) {
1958
+ next[key] = value;
1959
+ result.set.push(key);
1960
+ }
1961
+ }
1962
+ return next;
1963
+ });
1703
1964
  return result;
1704
1965
  }
1705
- async function tightenFile(path) {
1706
- const found = await stat3(path).catch(() => null);
1707
- if (found === null || (found.mode & 63) === 0) return;
1708
- await chmod2(path, 384).catch(() => void 0);
1709
- }
1710
- async function writePlainEntries(opts, plan, declaredPath, activation) {
1711
- const harness = opts.adapter.id;
1712
- const found = await inspectHooksFile(declaredPath);
1713
- if ("refusal" in found) {
1714
- return skip2(found.refusal.reason, {
1715
- harness,
1716
- path: found.refusal.path,
1717
- warning: found.refusal.message,
1718
- fix: fixFor2(found.refusal.reason)
1719
- });
1966
+ async function persistInstallHarness(dir, harness) {
1967
+ await persist(dir, (existing) => ({
1968
+ ...existing,
1969
+ install: { ...existing.install, harness: [...harness] }
1970
+ }));
1971
+ }
1972
+ async function persistGrantDeclined(dir, declined) {
1973
+ await persist(dir, (existing) => ({
1974
+ ...existing,
1975
+ install: { ...existing.install, grantDeclined: declined }
1976
+ }));
1977
+ }
1978
+ async function resolveFromContext(ctx) {
1979
+ const config = await loadRawConfig(ctx.dataDir);
1980
+ const project = await loadProjectConfig(process.cwd());
1981
+ return resolveSettings({
1982
+ config,
1983
+ flags: { baseUrl: ctx.flags.baseUrl },
1984
+ env: process.env,
1985
+ project: project?.layer
1986
+ });
1987
+ }
1988
+ function assertKey(key) {
1989
+ if (key === "bazaarPay" || key === "confirm") {
1990
+ throw new CliError("USAGE", `Retired config key: ${key}`, { fix: RETIRED_PAYMENT_GUIDANCE });
1720
1991
  }
1721
- const { path, raw, settings, hooks } = found;
1722
- const nextHooks = pruneHooks(hooks, opts.dataDir).next;
1723
- for (const [event, mine] of groupPlan(plan)) {
1724
- const kept = nextHooks[event];
1725
- nextHooks[event] = Array.isArray(kept) ? [...kept, ...mine] : mine;
1992
+ if (CONFIG_KEYS.includes(key)) return key;
1993
+ throw new CliError("USAGE", `Unknown config key: ${JSON.stringify(key)}`, {
1994
+ fix: `Valid keys: ${[...CONFIG_KEYS, ...PUBLISH_CONFIG_KEYS, ...HOOKS_CONFIG_KEYS, ...ROUTER_CONFIG_KEYS, ...EXPERIMENTAL_CONFIG_KEYS].join(", ")}.`
1995
+ });
1996
+ }
1997
+ function renderSetting(key, stored, source) {
1998
+ return { ...renderValue(key, stored), source };
1999
+ }
2000
+ function renderPublishSetting(key, settings) {
2001
+ if (key === "publish.mode") {
2002
+ return { value: settings.publishMode.value, source: settings.publishMode.source };
1726
2003
  }
1727
- const next = `${JSON.stringify({ ...settings, hooks: nextHooks }, null, 2)}
1728
- `;
1729
- const result = {
1730
- harness,
1731
- path,
1732
- entries: plan.length,
1733
- wrote: next !== raw,
1734
- ...activation
2004
+ if (key === "publish.ackServerWarnings") {
2005
+ return {
2006
+ value: settings.publishAckServerWarnings.value,
2007
+ source: settings.publishAckServerWarnings.source
2008
+ };
2009
+ }
2010
+ return {
2011
+ value: toMoney(settings.publishDefaultPrice.value),
2012
+ source: settings.publishDefaultPrice.source
1735
2013
  };
1736
- if (next === raw) {
1737
- await tightenFile(path);
1738
- return result;
2014
+ }
2015
+ function renderHooksSetting(key, settings) {
2016
+ const { value, source } = settings.hooks[key.slice("hooks.".length)];
2017
+ return { value, source };
2018
+ }
2019
+ function renderValue(key, stored) {
2020
+ if (key === "shelfBypassSecret") {
2021
+ return { value: typeof stored === "string" && stored.length > 0 ? "set" : "unset" };
2022
+ }
2023
+ if (Array.isArray(stored) || typeof stored === "boolean") return { value: stored };
2024
+ if (key === "sessionBudget" && stored === "none") return { value: null };
2025
+ if (key === "maxAutoSpend" || key === "sessionBudget") return { value: toMoney(stored) };
2026
+ if (key === "sendMaxAmount") {
2027
+ return { value: stored === "none" || stored === SEND_MAX_UNSET ? stored : toMoney(stored) };
2028
+ }
2029
+ return { value: stored };
2030
+ }
2031
+ function parseValue(key, value) {
2032
+ switch (key) {
2033
+ case "sessionBudget":
2034
+ return value === "none" ? "none" : parseUsdToAtomic(value);
2035
+ case "maxAutoSpend":
2036
+ return parseUsdToAtomic(value);
2037
+ // throws USAGE on a bad amount
2038
+ case "sendMaxAmount":
2039
+ return value === "none" ? "none" : parseUsdToAtomic(value);
2040
+ case "allowlistCreators":
2041
+ return parseAllowlist(value);
2042
+ case "baseUrl":
2043
+ case "publicShelfUrl":
2044
+ case "rpcUrl":
2045
+ return parseHttpUrl(value);
2046
+ case "shelfBypassSecret":
2047
+ return value.trim();
2048
+ case "evalCohort":
2049
+ return parseBoolean(value);
2050
+ case "bazaarRegistries":
2051
+ return parseRegistryList(value);
2052
+ }
2053
+ }
2054
+ function parseRegistryList(value) {
2055
+ return value.split(",").map((entry) => entry.trim()).filter((entry) => entry.length > 0).map((entry) => parseHttpUrl(entry));
2056
+ }
2057
+ function parseBoolean(value) {
2058
+ if (value === "true" || value === "on") return true;
2059
+ if (value === "false" || value === "off") return false;
2060
+ throw new CliError("USAGE", `Invalid boolean value: ${JSON.stringify(value)}`, {
2061
+ fix: 'Use "on" or "off" (or "true"/"false").'
2062
+ });
2063
+ }
2064
+ function parseAllowlist(value) {
2065
+ const entries = value.split(",").map((entry) => entry.trim()).filter((entry) => entry.length > 0);
2066
+ for (const entry of entries) {
2067
+ if (/\s/.test(entry)) {
2068
+ throw new CliError("USAGE", `Invalid creator entry: ${JSON.stringify(entry)}`, {
2069
+ fix: "Creator entries cannot contain spaces; separate multiple with commas."
2070
+ });
2071
+ }
1739
2072
  }
1740
- if (await readFile2(path, "utf8").catch(() => null) !== raw) {
1741
- return skip2("changed-since-read", {
1742
- harness,
1743
- path,
1744
- warning: `${path} changed while it was being updated, so no hooks were registered. Re-run \`tenjin install\`.`,
1745
- fix: fixFor2("changed-since-read")
2073
+ return entries;
2074
+ }
2075
+ function parseHttpUrl(value) {
2076
+ let url;
2077
+ try {
2078
+ url = new URL(value);
2079
+ } catch {
2080
+ throw new CliError("USAGE", `Invalid URL: ${JSON.stringify(value)}`, {
2081
+ fix: `Pass an absolute http(s) URL like ${PRODUCTION_ORIGIN}.`
1746
2082
  });
1747
2083
  }
2084
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
2085
+ throw new CliError("USAGE", `URL must be http or https: ${JSON.stringify(value)}`, {
2086
+ fix: `Pass an absolute http(s) URL like ${PRODUCTION_ORIGIN}.`
2087
+ });
2088
+ }
2089
+ return value;
2090
+ }
2091
+ async function persist(dir, merge) {
2092
+ await mkdir2(dir, { recursive: true, mode: 448 });
2093
+ const lockPath = `${configPath(dir)}.lock`;
1748
2094
  try {
1749
- await writeFileAtomic(path, next, { mode: 384 });
1750
- } catch (err) {
1751
- return skip2("unwritable", {
1752
- harness,
1753
- path,
1754
- warning: `${path} could not be written (${err instanceof Error ? err.message : String(err)}); no hook entry was registered.`,
1755
- fix: fixFor2("unwritable")
2095
+ await withFileLock(lockPath, async () => {
2096
+ const existing = await loadRawConfig(dir);
2097
+ const merged = merge(existing);
2098
+ const validated = RawConfigSchema.parse(merged);
2099
+ await writeFileAtomic(configPath(dir), `${JSON.stringify(validated, null, 2)}
2100
+ `, {
2101
+ mode: 384,
2102
+ dirMode: 448
2103
+ });
1756
2104
  });
2105
+ } catch (err) {
2106
+ if (err instanceof LockTimeoutError) {
2107
+ throw new CliError("INTERNAL", err.message, {
2108
+ fix: `If no other tenjin process is running, remove ${lockPath} and retry.`,
2109
+ cause: err
2110
+ });
2111
+ }
2112
+ throw err;
1757
2113
  }
1758
- return result;
1759
2114
  }
1760
- function groupPlan(plan) {
1761
- const planned = /* @__PURE__ */ new Map();
1762
- for (const item of plan) {
1763
- if (!isPlainObject2(item) || typeof item.event !== "string") continue;
1764
- const { event, ...entry } = item;
1765
- const list = planned.get(event) ?? [];
1766
- list.push(entry);
1767
- planned.set(event, list);
2115
+ function formatLine(key, entry) {
2116
+ const label = key.padEnd(KEY_WIDTH);
2117
+ const where = entry.path !== void 0 && (entry.source === "project" || entry.source === "local") ? ` ${entry.path}` : "";
2118
+ return ` ${label} ${displayValue(entry)} ${style("dim", `(${entry.source}${where})`)}`;
2119
+ }
2120
+ function describedLine(key, entry, note) {
2121
+ const description = KEY_DESCRIPTIONS[key];
2122
+ let line = formatLine(key, entry);
2123
+ if (description !== void 0) line += ` ${style("dim", `- ${description}`)}`;
2124
+ return withNote(line, note);
2125
+ }
2126
+ function withNote(line, note) {
2127
+ return note !== void 0 ? `${line} ${style("dim", `(${note})`)}` : line;
2128
+ }
2129
+ function downgradeNote(key, settings) {
2130
+ if (key !== "publish.mode" || settings.publishMode.downgradedWarning === void 0) {
2131
+ return void 0;
1768
2132
  }
1769
- return planned;
2133
+ return "downgraded from full-auto: committed .tenjin.json (gitignore it to opt in)";
2134
+ }
2135
+ function displayValue(entry) {
2136
+ const { value } = entry;
2137
+ if (Array.isArray(value)) return value.length > 0 ? value.join(", ") : "(empty)";
2138
+ if (typeof value === "boolean") return value ? "true" : "false";
2139
+ if (value === null) return "none (no daily limit)";
2140
+ if (typeof value === "object") return `${value.usd} USD`;
2141
+ return value;
1770
2142
  }
1771
2143
 
1772
2144
  export {
1773
- claudeSettingsPath,
1774
- MODE_GATED_RULES,
1775
- retractModeGatedRules,
1776
- wireFreeVerbAllowlist,
1777
- inspectFreeVerbRules,
1778
- appendAllowlistRules,
1779
- claudeAdapter,
1780
- ADAPTERS,
1781
- ownsHookEntry,
1782
- pruneOurHandlers,
1783
- pruneHooks,
2145
+ RETIRED_SKILL_NAMES,
2146
+ SHIPPED_SKILL_FILES,
2147
+ CLI_SKILL_NAMES,
2148
+ skillsDirsFor,
2149
+ readSkillFile,
2150
+ skillFrontmatterName,
1784
2151
  inspectHooksFile,
1785
- registeredHooks,
1786
- writeHooks
2152
+ EXPERIMENTAL_BAZAAR_WARNING,
2153
+ runConfigList,
2154
+ runConfigGet,
2155
+ runConfigSet,
2156
+ persistHookArm,
2157
+ persistPublishMode,
2158
+ persistRouterProject,
2159
+ persistRouterDefaults,
2160
+ persistInstallHarness,
2161
+ persistGrantDeclined
1787
2162
  };
1788
- //# sourceMappingURL=chunk-XVYATBKD.js.map
2163
+ //# sourceMappingURL=chunk-25GGN553.js.map