tenjin-cli 0.1.0-alpha.13 → 0.1.0-alpha.14

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 (131) hide show
  1. package/README.md +35 -2
  2. package/dist/{buy-X4VPHFUA.js → buy-2JBYPHAI.js} +16 -14
  3. package/dist/{chunk-6JKD46OJ.js → chunk-3ZW7HPY5.js} +4 -4
  4. package/dist/chunk-4UHNXY6B.js +786 -0
  5. package/dist/chunk-4UHNXY6B.js.map +1 -0
  6. package/dist/{chunk-IFPKA32J.js → chunk-4Y53PDH6.js} +2 -2
  7. package/dist/{chunk-SPUORKD7.js → chunk-54AJIO3E.js} +11 -12
  8. package/dist/chunk-54AJIO3E.js.map +1 -0
  9. package/dist/{chunk-JVBMPU5G.js → chunk-7GJQ5RGA.js} +5 -3
  10. package/dist/{chunk-JVBMPU5G.js.map → chunk-7GJQ5RGA.js.map} +1 -1
  11. package/dist/{chunk-BRAVLUGI.js → chunk-7NADDA2V.js} +9 -6
  12. package/dist/{chunk-BRAVLUGI.js.map → chunk-7NADDA2V.js.map} +1 -1
  13. package/dist/{chunk-T4UWMVKV.js → chunk-ACBEHJAH.js} +4 -4
  14. package/dist/{chunk-XXY77EZJ.js → chunk-DAZAXFSF.js} +7 -7
  15. package/dist/{chunk-OE36HRWG.js → chunk-DTCXO7HS.js} +257 -405
  16. package/dist/chunk-DTCXO7HS.js.map +1 -0
  17. package/dist/{chunk-CA3JV7FX.js → chunk-ETKZWJ4B.js} +2 -2
  18. package/dist/{chunk-CA3JV7FX.js.map → chunk-ETKZWJ4B.js.map} +1 -1
  19. package/dist/{chunk-NKN4YC5C.js → chunk-FDUD3W5V.js} +2 -2
  20. package/dist/{chunk-L4XNT3UW.js → chunk-GEHL43VE.js} +49 -17
  21. package/dist/chunk-GEHL43VE.js.map +1 -0
  22. package/dist/chunk-IU2HVT3Y.js +313 -0
  23. package/dist/chunk-IU2HVT3Y.js.map +1 -0
  24. package/dist/{chunk-OXUJ3FXU.js → chunk-IUQZ4Z7M.js} +36 -8
  25. package/dist/chunk-IUQZ4Z7M.js.map +1 -0
  26. package/dist/{chunk-YMUJZWHB.js → chunk-IXZJ3JOO.js} +5 -5
  27. package/dist/{chunk-47YKYDOF.js → chunk-L6G35FU5.js} +2 -2
  28. package/dist/{chunk-ELVDOTU7.js → chunk-LSWP7MU2.js} +4 -4
  29. package/dist/chunk-LSWP7MU2.js.map +1 -0
  30. package/dist/{chunk-OUJDDY5L.js → chunk-MJSXP4LW.js} +30 -28
  31. package/dist/chunk-MJSXP4LW.js.map +1 -0
  32. package/dist/{chunk-WVHPGQH5.js → chunk-NAAMHWSI.js} +5 -2
  33. package/dist/chunk-NAAMHWSI.js.map +1 -0
  34. package/dist/{chunk-IKAJSA7E.js → chunk-O75FOHXS.js} +29 -11
  35. package/dist/chunk-O75FOHXS.js.map +1 -0
  36. package/dist/{chunk-WMFRCSNC.js → chunk-PCX2JQ2J.js} +3 -3
  37. package/dist/{chunk-IGHSLJUF.js → chunk-PKW3H26Z.js} +5 -5
  38. package/dist/{chunk-3NZCU6SD.js → chunk-PQZVDCCA.js} +4 -4
  39. package/dist/{chunk-OC3EIDCP.js → chunk-QWBUKIP2.js} +7 -1
  40. package/dist/chunk-QWBUKIP2.js.map +1 -0
  41. package/dist/{chunk-FKSAUOJU.js → chunk-UO22YNY4.js} +1 -69
  42. package/dist/chunk-UO22YNY4.js.map +1 -0
  43. package/dist/chunk-VEAERJVJ.js +43 -0
  44. package/dist/chunk-VEAERJVJ.js.map +1 -0
  45. package/dist/{chunk-GCGMXA2O.js → chunk-VRPLZERE.js} +16 -5
  46. package/dist/chunk-VRPLZERE.js.map +1 -0
  47. package/dist/{chunk-IAR25V2E.js → chunk-W4VW5XYB.js} +4 -4
  48. package/dist/chunk-WYLMJQVH.js +240 -0
  49. package/dist/chunk-WYLMJQVH.js.map +1 -0
  50. package/dist/{chunk-TXVC46SA.js → chunk-XVPQGCH4.js} +11 -10
  51. package/dist/chunk-XVPQGCH4.js.map +1 -0
  52. package/dist/chunk-ZOBNS7CX.js +73 -0
  53. package/dist/chunk-ZOBNS7CX.js.map +1 -0
  54. package/dist/{cli-XK5JZWU6.js → cli-U2BEUA55.js} +34 -36
  55. package/dist/{cli-XK5JZWU6.js.map → cli-U2BEUA55.js.map} +1 -1
  56. package/dist/{config-CNK7MYUR.js → config-CNUIX23Q.js} +12 -6
  57. package/dist/{doctor-R7N7FUX5.js → doctor-QJJXRWTO.js} +11 -7
  58. package/dist/{edit-QSUEG7CL.js → edit-HJ44P44P.js} +13 -11
  59. package/dist/{fund-JF6A76YS.js → fund-Y5IAHZ5D.js} +10 -8
  60. package/dist/index.js +1 -1
  61. package/dist/{inspect-NFNAA4LA.js → inspect-NFQ6SQQQ.js} +14 -12
  62. package/dist/{install-YQVM3SUW.js → install-DXX7PVUP.js} +122 -401
  63. package/dist/install-DXX7PVUP.js.map +1 -0
  64. package/dist/outcome-ANV4QIED.js +24 -0
  65. package/dist/{publish-O2I6IAEL.js → publish-PCBTCXCZ.js} +14 -12
  66. package/dist/{read-UF7QVQOU.js → read-W7QVRBVD.js} +14 -12
  67. package/dist/{read-UF7QVQOU.js.map → read-W7QVRBVD.js.map} +1 -1
  68. package/dist/{run-GDZWHNWZ.js → run-CJWPGMIQ.js} +26 -24
  69. package/dist/{run-GDZWHNWZ.js.map → run-CJWPGMIQ.js.map} +1 -1
  70. package/dist/search-JGAVKTYJ.js +25 -0
  71. package/dist/{send-SI254H3R.js → send-C5EOKXOU.js} +7 -6
  72. package/dist/{send-SI254H3R.js.map → send-C5EOKXOU.js.map} +1 -1
  73. package/dist/{session-GJZJEXLJ.js → session-OBCUUIFX.js} +7 -6
  74. package/dist/{session-GJZJEXLJ.js.map → session-OBCUUIFX.js.map} +1 -1
  75. package/dist/{skill-heal-BPFT22XS.js → skill-heal-D6EPLPS6.js} +3 -3
  76. package/dist/skill-heal-D6EPLPS6.js.map +1 -0
  77. package/dist/{uninstall-7ZZG6WQ5.js → uninstall-OWJNJ5LI.js} +11 -5
  78. package/dist/uninstall-OWJNJ5LI.js.map +1 -0
  79. package/dist/{update-FPSBITLB.js → update-24Y2CQTT.js} +16 -13
  80. package/dist/update-24Y2CQTT.js.map +1 -0
  81. package/dist/{wallet-TZVD2M4I.js → wallet-OFXDIIGP.js} +7 -6
  82. package/dist/{wallet-NS7TYWNN.js → wallet-SLRIYJ2U.js} +4 -3
  83. package/docs/agent-permissions.md +100 -16
  84. package/docs/command-reference.md +21 -11
  85. package/package.json +1 -1
  86. package/skills/tenjin-publish/SKILL.md +181 -205
  87. package/skills/tenjin-publish/references/maintain.md +39 -0
  88. package/skills/tenjin-search/SKILL.md +86 -279
  89. package/skills/tenjin-search/references/permissions.md +106 -0
  90. package/dist/chunk-ELVDOTU7.js.map +0 -1
  91. package/dist/chunk-FKSAUOJU.js.map +0 -1
  92. package/dist/chunk-GCGMXA2O.js.map +0 -1
  93. package/dist/chunk-IKAJSA7E.js.map +0 -1
  94. package/dist/chunk-L4XNT3UW.js.map +0 -1
  95. package/dist/chunk-OC3EIDCP.js.map +0 -1
  96. package/dist/chunk-OE36HRWG.js.map +0 -1
  97. package/dist/chunk-OUJDDY5L.js.map +0 -1
  98. package/dist/chunk-OXUJ3FXU.js.map +0 -1
  99. package/dist/chunk-SPUORKD7.js.map +0 -1
  100. package/dist/chunk-TXVC46SA.js.map +0 -1
  101. package/dist/chunk-UUARTUY2.js +0 -349
  102. package/dist/chunk-UUARTUY2.js.map +0 -1
  103. package/dist/chunk-WVHPGQH5.js.map +0 -1
  104. package/dist/install-YQVM3SUW.js.map +0 -1
  105. package/dist/outcome-IUSYFJTN.js +0 -22
  106. package/dist/search-JVOHEF3E.js +0 -23
  107. package/dist/skill-heal-BPFT22XS.js.map +0 -1
  108. package/dist/uninstall-7ZZG6WQ5.js.map +0 -1
  109. package/dist/update-FPSBITLB.js.map +0 -1
  110. /package/dist/{buy-X4VPHFUA.js.map → buy-2JBYPHAI.js.map} +0 -0
  111. /package/dist/{chunk-6JKD46OJ.js.map → chunk-3ZW7HPY5.js.map} +0 -0
  112. /package/dist/{chunk-IFPKA32J.js.map → chunk-4Y53PDH6.js.map} +0 -0
  113. /package/dist/{chunk-T4UWMVKV.js.map → chunk-ACBEHJAH.js.map} +0 -0
  114. /package/dist/{chunk-XXY77EZJ.js.map → chunk-DAZAXFSF.js.map} +0 -0
  115. /package/dist/{chunk-NKN4YC5C.js.map → chunk-FDUD3W5V.js.map} +0 -0
  116. /package/dist/{chunk-YMUJZWHB.js.map → chunk-IXZJ3JOO.js.map} +0 -0
  117. /package/dist/{chunk-47YKYDOF.js.map → chunk-L6G35FU5.js.map} +0 -0
  118. /package/dist/{chunk-WMFRCSNC.js.map → chunk-PCX2JQ2J.js.map} +0 -0
  119. /package/dist/{chunk-IGHSLJUF.js.map → chunk-PKW3H26Z.js.map} +0 -0
  120. /package/dist/{chunk-3NZCU6SD.js.map → chunk-PQZVDCCA.js.map} +0 -0
  121. /package/dist/{chunk-IAR25V2E.js.map → chunk-W4VW5XYB.js.map} +0 -0
  122. /package/dist/{config-CNK7MYUR.js.map → config-CNUIX23Q.js.map} +0 -0
  123. /package/dist/{doctor-R7N7FUX5.js.map → doctor-QJJXRWTO.js.map} +0 -0
  124. /package/dist/{edit-QSUEG7CL.js.map → edit-HJ44P44P.js.map} +0 -0
  125. /package/dist/{fund-JF6A76YS.js.map → fund-Y5IAHZ5D.js.map} +0 -0
  126. /package/dist/{inspect-NFNAA4LA.js.map → inspect-NFQ6SQQQ.js.map} +0 -0
  127. /package/dist/{outcome-IUSYFJTN.js.map → outcome-ANV4QIED.js.map} +0 -0
  128. /package/dist/{publish-O2I6IAEL.js.map → publish-PCBTCXCZ.js.map} +0 -0
  129. /package/dist/{search-JVOHEF3E.js.map → search-JGAVKTYJ.js.map} +0 -0
  130. /package/dist/{wallet-NS7TYWNN.js.map → wallet-OFXDIIGP.js.map} +0 -0
  131. /package/dist/{wallet-TZVD2M4I.js.map → wallet-SLRIYJ2U.js.map} +0 -0
@@ -1,349 +0,0 @@
1
- import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
- import {
3
- loadProjectConfig
4
- } from "./chunk-IGHSLJUF.js";
5
- import {
6
- LockTimeoutError,
7
- withFileLock
8
- } from "./chunk-FKSAUOJU.js";
9
- import {
10
- parseUsdToAtomic,
11
- toMoney
12
- } from "./chunk-736DW4V3.js";
13
- import {
14
- CONFIG_KEYS,
15
- HOOKS_CONFIG_KEYS,
16
- PUBLISH_CONFIG_KEYS,
17
- PublishModeSchema,
18
- RawConfigSchema,
19
- SEND_MAX_UNSET,
20
- UPDATE_CONFIG_KEYS,
21
- loadRawConfig,
22
- parseSearchHookModeFlag,
23
- parseStopNagFlag,
24
- parseUpdateModeFlag,
25
- resolveSettings
26
- } from "./chunk-ELVDOTU7.js";
27
- import {
28
- configPath
29
- } from "./chunk-ZQIQ55KK.js";
30
- import {
31
- CliError,
32
- writeFileAtomic
33
- } from "./chunk-PAOVPSP6.js";
34
-
35
- // src/commands/config.ts
36
- import { mkdir } from "fs/promises";
37
- import { styleText } from "util";
38
- var CONFIRM_ABOVE = "above:";
39
- var KEY_WIDTH = Math.max(
40
- ...[...CONFIG_KEYS, ...PUBLISH_CONFIG_KEYS, ...HOOKS_CONFIG_KEYS, ...UPDATE_CONFIG_KEYS].map(
41
- (key) => key.length
42
- )
43
- );
44
- var KEY_DESCRIPTIONS = {
45
- maxAutoSpend: "auto-approve a read up to this amount",
46
- sessionBudget: "cap on total auto-spend per session",
47
- confirm: "when to ask before paying",
48
- sendMaxAmount: "hard cap per tenjin send; unset = send refuses until set, 0 disables send, none = uncapped; never bypassed by --yes",
49
- allowlistCreators: "only auto-pay these creators (empty = any)",
50
- baseUrl: "Tenjin API base URL",
51
- rpcUrl: "Base RPC endpoint for balance reads",
52
- evalCohort: "opt in to the search evaluation cohort",
53
- "publish.mode": "review=always ask, auto=ask on findings, full-auto=only hard blocks stop it",
54
- "publish.defaultPrice": "price used when none is given",
55
- "hooks.searchMode": "harness WebSearch hook: auto=ask Tenjin first, remind=static reminder, off=inert",
56
- "hooks.stopNag": "end-of-turn reminder about searches nothing answered yet",
57
- "update.mode": "nudge=report a newer version (stderr line, JSON envelope, hook output), off=neither report nor ask npm"
58
- };
59
- function isPublishKey(key) {
60
- return PUBLISH_CONFIG_KEYS.includes(key);
61
- }
62
- function isHooksKey(key) {
63
- return HOOKS_CONFIG_KEYS.includes(key);
64
- }
65
- function isUpdateKey(key) {
66
- return UPDATE_CONFIG_KEYS.includes(key);
67
- }
68
- async function runConfigList(ctx) {
69
- const settings = await resolveFromContext(ctx);
70
- const data = {};
71
- const humanLines = [];
72
- for (const key of CONFIG_KEYS) {
73
- const entry = renderSetting(key, settings[key].value, settings[key].source);
74
- data[key] = entry;
75
- humanLines.push(describedLine(key, entry));
76
- }
77
- for (const key of PUBLISH_CONFIG_KEYS) {
78
- const entry = renderPublishSetting(key, settings);
79
- data[key] = entry;
80
- humanLines.push(describedLine(key, entry, downgradeNote(key, settings)));
81
- }
82
- for (const key of HOOKS_CONFIG_KEYS) {
83
- const entry = renderHooksSetting(key, settings);
84
- data[key] = entry;
85
- humanLines.push(describedLine(key, entry));
86
- }
87
- for (const key of UPDATE_CONFIG_KEYS) {
88
- const entry = {
89
- value: settings.updateMode.value,
90
- source: settings.updateMode.source
91
- };
92
- data[key] = entry;
93
- humanLines.push(describedLine(key, entry));
94
- }
95
- return { data, humanLines };
96
- }
97
- async function runConfigGet({ key }, ctx) {
98
- if (isPublishKey(key)) {
99
- const settings2 = await resolveFromContext(ctx);
100
- const entry2 = renderPublishSetting(key, settings2);
101
- return {
102
- data: { key, ...entry2 },
103
- humanLines: [withNote(formatLine(key, entry2), downgradeNote(key, settings2))]
104
- };
105
- }
106
- if (isHooksKey(key)) {
107
- const entry2 = renderHooksSetting(key, await resolveFromContext(ctx));
108
- return { data: { key, ...entry2 }, humanLines: [formatLine(key, entry2)] };
109
- }
110
- if (isUpdateKey(key)) {
111
- const { updateMode } = await resolveFromContext(ctx);
112
- const entry2 = { value: updateMode.value, source: updateMode.source };
113
- return { data: { key, ...entry2 }, humanLines: [formatLine(key, entry2)] };
114
- }
115
- const configKey = assertKey(key);
116
- const settings = await resolveFromContext(ctx);
117
- const entry = renderSetting(configKey, settings[configKey].value, settings[configKey].source);
118
- return { data: { key: configKey, ...entry }, humanLines: [formatLine(configKey, entry)] };
119
- }
120
- async function runConfigSet({ key, value }, ctx) {
121
- if (isPublishKey(key)) return setPublishKey(key, value, ctx);
122
- if (isHooksKey(key)) return setHooksKey(key, value, ctx);
123
- if (isUpdateKey(key)) return setUpdateKey(key, value, ctx);
124
- const configKey = assertKey(key);
125
- const stored = parseValue(configKey, value);
126
- await persist(ctx.dataDir, (existing) => ({ ...existing, [configKey]: stored }));
127
- const entry = renderSetting(configKey, stored, "file");
128
- return { data: { key: configKey, ...entry }, humanLines: [formatLine(configKey, entry)] };
129
- }
130
- async function setPublishKey(key, value, ctx) {
131
- const entry = key === "publish.mode" ? { value: parsePublishMode(value), source: "file" } : { value: toMoney(parseUsdToAtomic(value)), source: "file" };
132
- const subkey = key === "publish.mode" ? "mode" : "defaultPrice";
133
- const stored = key === "publish.mode" ? entry.value : entry.value.atomic;
134
- await persist(ctx.dataDir, (existing) => ({
135
- ...existing,
136
- publish: { ...existing.publish, [subkey]: stored }
137
- }));
138
- return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };
139
- }
140
- async function setHooksKey(key, value, ctx) {
141
- const subkey = key === "hooks.searchMode" ? "searchMode" : "stopNag";
142
- const parsed = key === "hooks.searchMode" ? parseSearchHookModeFlag(value, key) : parseStopNagFlag(value, key);
143
- await persist(ctx.dataDir, (existing) => ({
144
- ...existing,
145
- hooks: { ...existing.hooks, [subkey]: parsed }
146
- }));
147
- const entry = { value: parsed, source: "file" };
148
- return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };
149
- }
150
- async function setUpdateKey(key, value, ctx) {
151
- const parsed = parseUpdateModeFlag(value, key);
152
- await persist(ctx.dataDir, (existing) => ({
153
- ...existing,
154
- update: { ...existing.update, mode: parsed }
155
- }));
156
- const entry = { value: parsed, source: "file" };
157
- return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };
158
- }
159
- function parsePublishMode(value) {
160
- const parsed = PublishModeSchema.safeParse(value);
161
- if (parsed.success) return parsed.data;
162
- throw new CliError("USAGE", `Invalid publish mode: ${JSON.stringify(value)}`, {
163
- fix: 'Use "review", "auto", or "full-auto".'
164
- });
165
- }
166
- async function persistPublishMode(dir, mode) {
167
- await persist(dir, (existing) => ({
168
- ...existing,
169
- publish: { ...existing.publish, mode }
170
- }));
171
- }
172
- async function persistSearchHookMode(dir, mode) {
173
- await persist(dir, (existing) => ({
174
- ...existing,
175
- hooks: { ...existing.hooks, searchMode: mode }
176
- }));
177
- }
178
- async function persistInstallHarness(dir, harness) {
179
- await persist(dir, (existing) => ({
180
- ...existing,
181
- install: { ...existing.install, harness: [...harness] }
182
- }));
183
- }
184
- async function resolveFromContext(ctx) {
185
- const config = await loadRawConfig(ctx.dataDir);
186
- const project = await loadProjectConfig(process.cwd());
187
- return resolveSettings({
188
- config,
189
- flags: { baseUrl: ctx.flags.baseUrl },
190
- env: process.env,
191
- project: project?.layer
192
- });
193
- }
194
- function assertKey(key) {
195
- if (CONFIG_KEYS.includes(key)) return key;
196
- throw new CliError("USAGE", `Unknown config key: ${JSON.stringify(key)}`, {
197
- fix: `Valid keys: ${[...CONFIG_KEYS, ...PUBLISH_CONFIG_KEYS, ...HOOKS_CONFIG_KEYS].join(", ")}.`
198
- });
199
- }
200
- function renderSetting(key, stored, source) {
201
- return { ...renderValue(key, stored), source };
202
- }
203
- function renderPublishSetting(key, settings) {
204
- if (key === "publish.mode") {
205
- return { value: settings.publishMode.value, source: settings.publishMode.source };
206
- }
207
- return {
208
- value: toMoney(settings.publishDefaultPrice.value),
209
- source: settings.publishDefaultPrice.source
210
- };
211
- }
212
- function renderHooksSetting(key, settings) {
213
- const resolved = key === "hooks.searchMode" ? settings.hooksSearchMode : settings.hooksStopNag;
214
- return { value: resolved.value, source: resolved.source };
215
- }
216
- function renderValue(key, stored) {
217
- if (Array.isArray(stored) || typeof stored === "boolean") return { value: stored };
218
- if (key === "maxAutoSpend" || key === "sessionBudget") return { value: toMoney(stored) };
219
- if (key === "sendMaxAmount") {
220
- return { value: stored === "none" || stored === SEND_MAX_UNSET ? stored : toMoney(stored) };
221
- }
222
- if (key === "confirm" && stored.startsWith(CONFIRM_ABOVE)) {
223
- return { value: stored, threshold: toMoney(stored.slice(CONFIRM_ABOVE.length)) };
224
- }
225
- return { value: stored };
226
- }
227
- function parseValue(key, value) {
228
- switch (key) {
229
- case "maxAutoSpend":
230
- case "sessionBudget":
231
- return parseUsdToAtomic(value);
232
- // throws USAGE on a bad amount
233
- case "sendMaxAmount":
234
- return value === "none" ? "none" : parseUsdToAtomic(value);
235
- case "confirm":
236
- return parseConfirm(value);
237
- case "allowlistCreators":
238
- return parseAllowlist(value);
239
- case "baseUrl":
240
- case "rpcUrl":
241
- return parseHttpUrl(value);
242
- case "evalCohort":
243
- return parseBoolean(value);
244
- }
245
- }
246
- function parseBoolean(value) {
247
- if (value === "true") return true;
248
- if (value === "false") return false;
249
- throw new CliError("USAGE", `Invalid boolean value: ${JSON.stringify(value)}`, {
250
- fix: 'Use "true" or "false".'
251
- });
252
- }
253
- function parseConfirm(value) {
254
- if (value === "always") return "always";
255
- if (value.startsWith(CONFIRM_ABOVE)) {
256
- return `${CONFIRM_ABOVE}${parseUsdToAtomic(value.slice(CONFIRM_ABOVE.length))}`;
257
- }
258
- throw new CliError("USAGE", `Invalid confirm value: ${JSON.stringify(value)}`, {
259
- fix: 'Use "always" or "above:<usd>", e.g. above:0.25.'
260
- });
261
- }
262
- function parseAllowlist(value) {
263
- const entries = value.split(",").map((entry) => entry.trim()).filter((entry) => entry.length > 0);
264
- for (const entry of entries) {
265
- if (/\s/.test(entry)) {
266
- throw new CliError("USAGE", `Invalid creator entry: ${JSON.stringify(entry)}`, {
267
- fix: "Creator entries cannot contain spaces; separate multiple with commas."
268
- });
269
- }
270
- }
271
- return entries;
272
- }
273
- function parseHttpUrl(value) {
274
- let url;
275
- try {
276
- url = new URL(value);
277
- } catch {
278
- throw new CliError("USAGE", `Invalid URL: ${JSON.stringify(value)}`, {
279
- fix: "Pass an absolute http(s) URL like https://tenjin.blog."
280
- });
281
- }
282
- if (url.protocol !== "http:" && url.protocol !== "https:") {
283
- throw new CliError("USAGE", `URL must be http or https: ${JSON.stringify(value)}`, {
284
- fix: "Pass an absolute http(s) URL like https://tenjin.blog."
285
- });
286
- }
287
- return value;
288
- }
289
- async function persist(dir, merge) {
290
- await mkdir(dir, { recursive: true, mode: 448 });
291
- const lockPath = `${configPath(dir)}.lock`;
292
- try {
293
- await withFileLock(lockPath, async () => {
294
- const existing = await loadRawConfig(dir);
295
- const merged = merge(existing);
296
- const validated = RawConfigSchema.parse(merged);
297
- await writeFileAtomic(configPath(dir), `${JSON.stringify(validated, null, 2)}
298
- `, {
299
- mode: 420,
300
- dirMode: 448
301
- });
302
- });
303
- } catch (err) {
304
- if (err instanceof LockTimeoutError) {
305
- throw new CliError("INTERNAL", err.message, {
306
- fix: `If no other tenjin process is running, remove ${lockPath} and retry.`,
307
- cause: err
308
- });
309
- }
310
- throw err;
311
- }
312
- }
313
- function formatLine(key, entry) {
314
- const label = key.padEnd(KEY_WIDTH);
315
- return ` ${label} ${displayValue(entry)} ${styleText("dim", `(${entry.source})`)}`;
316
- }
317
- function describedLine(key, entry, note) {
318
- const description = KEY_DESCRIPTIONS[key];
319
- let line = formatLine(key, entry);
320
- if (description !== void 0) line += ` ${styleText("dim", `- ${description}`)}`;
321
- return withNote(line, note);
322
- }
323
- function withNote(line, note) {
324
- return note !== void 0 ? `${line} ${styleText("dim", `(${note})`)}` : line;
325
- }
326
- function downgradeNote(key, settings) {
327
- if (key !== "publish.mode" || settings.publishMode.downgradedWarning === void 0) {
328
- return void 0;
329
- }
330
- return "downgraded from full-auto: committed .tenjin.json (gitignore it to opt in)";
331
- }
332
- function displayValue(entry) {
333
- const { value } = entry;
334
- if (Array.isArray(value)) return value.length > 0 ? value.join(", ") : "(empty)";
335
- if (typeof value === "boolean") return value ? "true" : "false";
336
- if (typeof value === "object") return `${value.usd} USD`;
337
- if (entry.threshold !== void 0) return `above ${entry.threshold.usd} USD`;
338
- return value;
339
- }
340
-
341
- export {
342
- runConfigList,
343
- runConfigGet,
344
- runConfigSet,
345
- persistPublishMode,
346
- persistSearchHookMode,
347
- persistInstallHarness
348
- };
349
- //# sourceMappingURL=chunk-UUARTUY2.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/config.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { styleText } from 'node:util';\nimport { CliError } from '../lib/errors';\nimport {\n CONFIG_KEYS,\n HOOKS_CONFIG_KEYS,\n PUBLISH_CONFIG_KEYS,\n PublishModeSchema,\n RawConfigSchema,\n SEND_MAX_UNSET,\n UPDATE_CONFIG_KEYS,\n loadRawConfig,\n parseSearchHookModeFlag,\n parseStopNagFlag,\n parseUpdateModeFlag,\n resolveSettings,\n} from '../lib/config';\nimport type {\n EffectiveSettings,\n HooksConfigKey,\n PartialConfig,\n Provenance,\n PublishConfigKey,\n PublishMode,\n ScalarConfigKey,\n SearchHookMode,\n UpdateConfigKey,\n} from '../lib/config';\nimport type { HarnessTarget } from '../lib/skill-wiring';\nimport { loadProjectConfig } from '../lib/settings';\nimport { configPath } from '../lib/paths';\nimport { writeFileAtomic } from '../lib/atomic-json';\nimport { withFileLock, LockTimeoutError } from '../lib/lock';\nimport { parseUsdToAtomic, toMoney } from '../lib/money';\nimport type { Money } from '../schemas';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * How one config key is presented in `data`. `value` is the machine form: dual\n * Money for the spend keys, the stored string for `confirm`/URLs, the string[]\n * for the allowlist. `threshold` rides along only for `confirm: above:<atomic>`\n * so an agent reads the dollar amount without re-parsing the string.\n */\ninterface RenderedValue {\n value: Money | string | string[] | boolean;\n threshold?: Money;\n}\ninterface RenderedSetting extends RenderedValue {\n source: Provenance;\n}\n\nconst CONFIRM_ABOVE = 'above:';\nconst KEY_WIDTH = Math.max(\n ...[...CONFIG_KEYS, ...PUBLISH_CONFIG_KEYS, ...HOOKS_CONFIG_KEYS, ...UPDATE_CONFIG_KEYS].map(\n (key) => key.length,\n ),\n);\n\n/**\n * A one-line human description per key, appended (dim) to the bare `config`\n * listing only. Machine `data` is unchanged; these are humanLines decoration.\n */\nconst KEY_DESCRIPTIONS: Record<string, string> = {\n maxAutoSpend: 'auto-approve a read up to this amount',\n sessionBudget: 'cap on total auto-spend per session',\n confirm: 'when to ask before paying',\n sendMaxAmount:\n 'hard cap per tenjin send; unset = send refuses until set, 0 disables send, none = uncapped; never bypassed by --yes',\n allowlistCreators: 'only auto-pay these creators (empty = any)',\n baseUrl: 'Tenjin API base URL',\n rpcUrl: 'Base RPC endpoint for balance reads',\n evalCohort: 'opt in to the search evaluation cohort',\n 'publish.mode': 'review=always ask, auto=ask on findings, full-auto=only hard blocks stop it',\n 'publish.defaultPrice': 'price used when none is given',\n 'hooks.searchMode':\n 'harness WebSearch hook: auto=ask Tenjin first, remind=static reminder, off=inert',\n 'hooks.stopNag': 'end-of-turn reminder about searches nothing answered yet',\n 'update.mode':\n 'nudge=report a newer version (stderr line, JSON envelope, hook output), off=neither report nor ask npm',\n};\n\nfunction isPublishKey(key: string): key is PublishConfigKey {\n return (PUBLISH_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\nfunction isHooksKey(key: string): key is HooksConfigKey {\n return (HOOKS_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\nfunction isUpdateKey(key: string): key is UpdateConfigKey {\n return (UPDATE_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\n/**\n * Show every effective key with its value and provenance. `data` is keyed by\n * config key; provenance comes from resolveSettings over the *raw* file (not the\n * defaults-merged config), so a key the user never set reads `default`, not\n * `file`.\n */\nexport async function runConfigList(ctx: CommandContext): Promise<CommandResult> {\n const settings = await resolveFromContext(ctx);\n const data: Record<string, RenderedSetting> = {};\n const humanLines: string[] = [];\n for (const key of CONFIG_KEYS) {\n const entry = renderSetting(key, settings[key].value, settings[key].source);\n data[key] = entry;\n humanLines.push(describedLine(key, entry));\n }\n for (const key of PUBLISH_CONFIG_KEYS) {\n const entry = renderPublishSetting(key, settings);\n data[key] = entry;\n humanLines.push(describedLine(key, entry, downgradeNote(key, settings)));\n }\n for (const key of HOOKS_CONFIG_KEYS) {\n const entry = renderHooksSetting(key, settings);\n data[key] = entry;\n humanLines.push(describedLine(key, entry));\n }\n for (const key of UPDATE_CONFIG_KEYS) {\n const entry: RenderedSetting = {\n value: settings.updateMode.value,\n source: settings.updateMode.source,\n };\n data[key] = entry;\n humanLines.push(describedLine(key, entry));\n }\n return { data, humanLines };\n}\n\n/** Same per-key shape as list, for one key. Unknown key is a USAGE failure. */\nexport async function runConfigGet(\n { key }: { key: string },\n ctx: CommandContext,\n): Promise<CommandResult> {\n if (isPublishKey(key)) {\n const settings = await resolveFromContext(ctx);\n const entry = renderPublishSetting(key, settings);\n return {\n data: { key, ...entry },\n humanLines: [withNote(formatLine(key, entry), downgradeNote(key, settings))],\n };\n }\n if (isHooksKey(key)) {\n const entry = renderHooksSetting(key, await resolveFromContext(ctx));\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n }\n if (isUpdateKey(key)) {\n const { updateMode } = await resolveFromContext(ctx);\n const entry: RenderedSetting = { value: updateMode.value, source: updateMode.source };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n }\n const configKey = assertKey(key);\n const settings = await resolveFromContext(ctx);\n const entry = renderSetting(configKey, settings[configKey].value, settings[configKey].source);\n return { data: { key: configKey, ...entry }, humanLines: [formatLine(configKey, entry)] };\n}\n\n/**\n * Parse the value for this key, then persist it merged into the existing raw\n * file — never materializing defaults for keys the user did not set, so\n * provenance stays truthful. The written key now reads `file`.\n */\nexport async function runConfigSet(\n { key, value }: { key: string; value: string },\n ctx: CommandContext,\n): Promise<CommandResult> {\n if (isPublishKey(key)) return setPublishKey(key, value, ctx);\n if (isHooksKey(key)) return setHooksKey(key, value, ctx);\n if (isUpdateKey(key)) return setUpdateKey(key, value, ctx);\n const configKey = assertKey(key);\n const stored = parseValue(configKey, value);\n await persist(ctx.dataDir, (existing) => ({ ...existing, [configKey]: stored }));\n const entry = renderSetting(configKey, stored, 'file');\n return { data: { key: configKey, ...entry }, humanLines: [formatLine(configKey, entry)] };\n}\n\n/**\n * `config set publish.mode|publish.defaultPrice`. mode validates to the enum;\n * defaultPrice parses decimal USD at the edge into atomic (matching the spend\n * keys). The subkey is merged into the nested publish block, so a sibling subkey\n * (or an unknown one a newer CLI wrote) is preserved.\n */\nasync function setPublishKey(\n key: PublishConfigKey,\n value: string,\n ctx: CommandContext,\n): Promise<CommandResult> {\n const entry: RenderedSetting =\n key === 'publish.mode'\n ? { value: parsePublishMode(value), source: 'file' }\n : { value: toMoney(parseUsdToAtomic(value)), source: 'file' };\n const subkey = key === 'publish.mode' ? 'mode' : 'defaultPrice';\n const stored = key === 'publish.mode' ? (entry.value as string) : (entry.value as Money).atomic;\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n publish: { ...existing.publish, [subkey]: stored },\n }));\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n}\n\n/**\n * `config set hooks.searchMode`. Merged into the nested hooks block through the\n * same locked read-modify-write every other set uses, so a subkey a newer CLI\n * wrote survives. The installed hook script reads this file on every run, so the\n * new mode takes effect immediately with no re-install.\n */\nasync function setHooksKey(\n key: HooksConfigKey,\n value: string,\n ctx: CommandContext,\n): Promise<CommandResult> {\n const subkey = key === 'hooks.searchMode' ? 'searchMode' : 'stopNag';\n const parsed =\n key === 'hooks.searchMode' ? parseSearchHookModeFlag(value, key) : parseStopNagFlag(value, key);\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n hooks: { ...existing.hooks, [subkey]: parsed },\n }));\n const entry: RenderedSetting = { value: parsed, source: 'file' };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n}\n\n/**\n * `config set update.mode`. Same locked merge-write as every other set, so the\n * next command reports (or stops reporting) under the new mode immediately,\n * with nothing to re-install and no process to restart.\n */\nasync function setUpdateKey(\n key: UpdateConfigKey,\n value: string,\n ctx: CommandContext,\n): Promise<CommandResult> {\n const parsed = parseUpdateModeFlag(value, key);\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n update: { ...existing.update, mode: parsed },\n }));\n const entry: RenderedSetting = { value: parsed, source: 'file' };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n}\n\nfunction parsePublishMode(value: string): string {\n const parsed = PublishModeSchema.safeParse(value);\n if (parsed.success) return parsed.data;\n throw new CliError('USAGE', `Invalid publish mode: ${JSON.stringify(value)}`, {\n fix: 'Use \"review\", \"auto\", or \"full-auto\".',\n });\n}\n\n/**\n * Persist just `publish.mode` into the global config through the same locked\n * merge-write every `config set` uses (never a raw overwrite), so a sibling\n * subkey or an unknown block a newer CLI wrote is preserved. Used by `install`'s\n * setup prompt; the mode is a validated PublishMode.\n */\nexport async function persistPublishMode(dir: string, mode: PublishMode): Promise<void> {\n await persist(dir, (existing) => ({\n ...existing,\n publish: { ...existing.publish, mode },\n }));\n}\n\n/**\n * Persist `hooks.searchMode` through the same locked merge-write, for `install`'s\n * hook decision. The mode is already a validated SearchHookMode.\n */\nexport async function persistSearchHookMode(dir: string, mode: SearchHookMode): Promise<void> {\n await persist(dir, (existing) => ({\n ...existing,\n hooks: { ...existing.hooks, searchMode: mode },\n }));\n}\n\n/**\n * Record the explicit `--harness` set `install` was given, through the same locked\n * merge-write. It REPLACES the previous record rather than unioning with it: the last\n * explicit request is the current intent, and re-running install with the right flag\n * is then the way out of a mistaken one. Detected harnesses are never recorded — they\n * are re-probed on every `doctor` — so this file holds only what detection cannot see.\n */\nexport async function persistInstallHarness(\n dir: string,\n harness: readonly HarnessTarget[],\n): Promise<void> {\n await persist(dir, (existing) => ({\n ...existing,\n install: { ...existing.install, harness: [...harness] },\n }));\n}\n\nasync function resolveFromContext(ctx: CommandContext): Promise<EffectiveSettings> {\n const config = await loadRawConfig(ctx.dataDir);\n // Feed the per-project `.tenjin.json` layer so the publish keys read out what a\n // real `publish` would resolve (project/env included), not a global-only guess.\n const project = await loadProjectConfig(process.cwd());\n return resolveSettings({\n config,\n flags: { baseUrl: ctx.flags.baseUrl },\n env: process.env,\n project: project?.layer,\n });\n}\n\nfunction assertKey(key: string): ScalarConfigKey {\n if ((CONFIG_KEYS as string[]).includes(key)) return key as ScalarConfigKey;\n throw new CliError('USAGE', `Unknown config key: ${JSON.stringify(key)}`, {\n fix: `Valid keys: ${[...CONFIG_KEYS, ...PUBLISH_CONFIG_KEYS, ...HOOKS_CONFIG_KEYS].join(', ')}.`,\n });\n}\n\nfunction renderSetting(\n key: ScalarConfigKey,\n stored: string | string[] | boolean,\n source: Provenance,\n): RenderedSetting {\n return { ...renderValue(key, stored), source };\n}\n\n/**\n * The list/get shape for a publish key, read from the resolved effective\n * settings, which now include the per-project `.tenjin.json` layer (see\n * resolveFromContext) so the source reflects what a publish would actually use.\n */\nfunction renderPublishSetting(key: PublishConfigKey, settings: EffectiveSettings): RenderedSetting {\n if (key === 'publish.mode') {\n return { value: settings.publishMode.value, source: settings.publishMode.source };\n }\n return {\n value: toMoney(settings.publishDefaultPrice.value),\n source: settings.publishDefaultPrice.source,\n };\n}\n\n/** The list/get shape for a hooks key: a plain enum string either way. */\nfunction renderHooksSetting(key: HooksConfigKey, settings: EffectiveSettings): RenderedSetting {\n const resolved = key === 'hooks.searchMode' ? settings.hooksSearchMode : settings.hooksStopNag;\n return { value: resolved.value, source: resolved.source };\n}\n\nfunction renderValue(key: ScalarConfigKey, stored: string | string[] | boolean): RenderedValue {\n if (Array.isArray(stored) || typeof stored === 'boolean') return { value: stored };\n if (key === 'maxAutoSpend' || key === 'sessionBudget') return { value: toMoney(stored) };\n if (key === 'sendMaxAmount') {\n // 'unset' is the resolved sentinel for an absent key (send refuses), never\n // a stored value; 'none' is the explicit uncapped opt-in.\n return { value: stored === 'none' || stored === SEND_MAX_UNSET ? stored : toMoney(stored) };\n }\n if (key === 'confirm' && stored.startsWith(CONFIRM_ABOVE)) {\n return { value: stored, threshold: toMoney(stored.slice(CONFIRM_ABOVE.length)) };\n }\n return { value: stored };\n}\n\n/** Per-key edge parsing. Returns the persisted form; throws USAGE on bad input. */\nfunction parseValue(key: ScalarConfigKey, value: string): string | string[] | boolean {\n switch (key) {\n case 'maxAutoSpend':\n case 'sessionBudget':\n return parseUsdToAtomic(value); // throws USAGE on a bad amount\n case 'sendMaxAmount':\n return value === 'none' ? 'none' : parseUsdToAtomic(value);\n case 'confirm':\n return parseConfirm(value);\n case 'allowlistCreators':\n return parseAllowlist(value);\n case 'baseUrl':\n case 'rpcUrl':\n return parseHttpUrl(value);\n case 'evalCohort':\n return parseBoolean(value);\n }\n}\n\nfunction parseBoolean(value: string): boolean {\n if (value === 'true') return true;\n if (value === 'false') return false;\n throw new CliError('USAGE', `Invalid boolean value: ${JSON.stringify(value)}`, {\n fix: 'Use \"true\" or \"false\".',\n });\n}\n\nfunction parseConfirm(value: string): string {\n if (value === 'always') return 'always';\n if (value.startsWith(CONFIRM_ABOVE)) {\n return `${CONFIRM_ABOVE}${parseUsdToAtomic(value.slice(CONFIRM_ABOVE.length))}`;\n }\n throw new CliError('USAGE', `Invalid confirm value: ${JSON.stringify(value)}`, {\n fix: 'Use \"always\" or \"above:<usd>\", e.g. above:0.25.',\n });\n}\n\nfunction parseAllowlist(value: string): string[] {\n // \"\" clears to []; comma-split, trim, drop empties. Reject an entry with\n // internal whitespace — a creator handle/address is a single token.\n const entries = value\n .split(',')\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0);\n for (const entry of entries) {\n if (/\\s/.test(entry)) {\n throw new CliError('USAGE', `Invalid creator entry: ${JSON.stringify(entry)}`, {\n fix: 'Creator entries cannot contain spaces; separate multiple with commas.',\n });\n }\n }\n return entries;\n}\n\nfunction parseHttpUrl(value: string): string {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new CliError('USAGE', `Invalid URL: ${JSON.stringify(value)}`, {\n fix: 'Pass an absolute http(s) URL like https://tenjin.blog.',\n });\n }\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n throw new CliError('USAGE', `URL must be http or https: ${JSON.stringify(value)}`, {\n fix: 'Pass an absolute http(s) URL like https://tenjin.blog.',\n });\n }\n return value;\n}\n\n/**\n * Apply `merge` to the raw file and write it back atomically. Uses the partial\n * schema and writeFileAtomic (not writeConfig, which would materialize every\n * default into the file and corrupt provenance). loadRawConfig surfaces a\n * corrupt existing file as CONFIG_INVALID, which propagates.\n *\n * The whole read-merge-write runs under a cross-process file lock: without it two\n * concurrent `config set` on different keys race on the read, and the last writer\n * drops the other's update (worst case, a zeroed maxAutoSpend resurrected). The\n * data dir is ensured first so the lock's mkdir has a parent on a fresh install.\n */\nasync function persist(\n dir: string,\n merge: (existing: PartialConfig) => PartialConfig,\n): Promise<void> {\n await mkdir(dir, { recursive: true, mode: 0o700 });\n const lockPath = `${configPath(dir)}.lock`;\n try {\n await withFileLock(lockPath, async () => {\n const existing = await loadRawConfig(dir);\n const merged = merge(existing);\n const validated = RawConfigSchema.parse(merged);\n await writeFileAtomic(configPath(dir), `${JSON.stringify(validated, null, 2)}\\n`, {\n mode: 0o644,\n dirMode: 0o700,\n });\n });\n } catch (err) {\n // A lock timeout is not the user's malformed input; surface it as INTERNAL with\n // the one manual step (there is no auto-steal), keeping the JSON error contract.\n if (err instanceof LockTimeoutError) {\n throw new CliError('INTERNAL', err.message, {\n fix: `If no other tenjin process is running, remove ${lockPath} and retry.`,\n cause: err,\n });\n }\n throw err;\n }\n}\n\nfunction formatLine(key: string, entry: RenderedSetting): string {\n const label = key.padEnd(KEY_WIDTH);\n return ` ${label} ${displayValue(entry)} ${styleText('dim', `(${entry.source})`)}`;\n}\n\n/** The list variant: the value line, a dim description, and an optional dim note. */\nfunction describedLine(key: string, entry: RenderedSetting, note?: string): string {\n const description = KEY_DESCRIPTIONS[key];\n let line = formatLine(key, entry);\n if (description !== undefined) line += ` ${styleText('dim', `- ${description}`)}`;\n return withNote(line, note);\n}\n\n/** Append a dim parenthetical note (e.g. the full-auto downgrade) when present. */\nfunction withNote(line: string, note?: string): string {\n return note !== undefined ? `${line} ${styleText('dim', `(${note})`)}` : line;\n}\n\n/**\n * The `publish.mode` line gains a downgrade note when the effective mode came from\n * a committed `.tenjin.json` asking for `full-auto` (the loosening gate demoted it\n * to `auto`). Human-only; the machine `data` shape is unchanged.\n */\nfunction downgradeNote(key: PublishConfigKey, settings: EffectiveSettings): string | undefined {\n if (key !== 'publish.mode' || settings.publishMode.downgradedWarning === undefined) {\n return undefined;\n }\n return 'downgraded from full-auto: committed .tenjin.json (gitignore it to opt in)';\n}\n\nfunction displayValue(entry: RenderedSetting): string {\n const { value } = entry;\n if (Array.isArray(value)) return value.length > 0 ? value.join(', ') : '(empty)';\n if (typeof value === 'boolean') return value ? 'true' : 'false'; // evalCohort\n if (typeof value === 'object') return `${value.usd} USD`; // Money (spend keys)\n if (entry.threshold !== undefined) return `above ${entry.threshold.usd} USD`; // confirm\n return value; // 'always', baseUrl, rpcUrl\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAa;AACtB,SAAS,iBAAiB;AAkD1B,IAAM,gBAAgB;AACtB,IAAM,YAAY,KAAK;AAAA,EACrB,GAAG,CAAC,GAAG,aAAa,GAAG,qBAAqB,GAAG,mBAAmB,GAAG,kBAAkB,EAAE;AAAA,IACvF,CAAC,QAAQ,IAAI;AAAA,EACf;AACF;AAMA,IAAM,mBAA2C;AAAA,EAC/C,cAAc;AAAA,EACd,eAAe;AAAA,EACf,SAAS;AAAA,EACT,eACE;AAAA,EACF,mBAAmB;AAAA,EACnB,SAAS;AAAA,EACT,Q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AAM,QAAQ,IAAI,OAAO,SAAS;AAClC,SAAO,KAAK,KAAK,KAAK,aAAa,KAAK,CAAC,KAAK,UAAU,OAAO,IAAI,MAAM,MAAM,GAAG,CAAC;AACrF;AAGA,SAAS,cAAc,KAAa,OAAwB,MAAuB;AACjF,QAAM,cAAc,iBAAiB,GAAG;AACxC,MAAI,OAAO,WAAW,KAAK,KAAK;AAChC,MAAI,gBAAgB,OAAW,SAAQ,KAAK,UAAU,OAAO,KAAK,WAAW,EAAE,CAAC;AAChF,SAAO,SAAS,MAAM,IAAI;AAC5B;AAGA,SAAS,SAAS,MAAc,MAAuB;AACrD,SAAO,SAAS,SAAY,GAAG,IAAI,KAAK,UAAU,OAAO,IAAI,IAAI,GAAG,CAAC,KAAK;AAC5E;AAOA,SAAS,cAAc,KAAuB,UAAiD;AAC7F,MAAI,QAAQ,kBAAkB,SAAS,YAAY,sBAAsB,QAAW;AAClF,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAEA,SAAS,aAAa,OAAgC;AACpD,QAAM,EAAE,MAAM,IAAI;AAClB,MAAI,MAAM,QAAQ,KAAK,EAAG,QAAO,MAAM,SAAS,IAAI,MAAM,KAAK,IAAI,IAAI;AACvE,MAAI,OAAO,UAAU,UAAW,QAAO,QAAQ,SAAS;AACxD,MAAI,OAAO,UAAU,SAAU,QAAO,GAAG,MAAM,GAAG;AAClD,MAAI,MAAM,cAAc,OAAW,QAAO,SAAS,MAAM,UAAU,GAAG;AACtE,SAAO;AACT;","names":["settings","entry"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/skill-writer.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { lstat, readFile, readdir, realpath, stat } from 'node:fs/promises';\nimport { dirname, join, relative } from 'node:path';\nimport { writeFileAtomic } from './atomic-json';\nimport { hasCode } from './errno';\nimport { CliError } from './errors';\nimport { HOSTED_SKILL_NAME, readSkillFile } from './skill-wiring';\n\n/**\n * Writing one packaged skill into one harness directory, and the path guards that\n * write needs. Its own module, free of the command layer's dependencies, because\n * `install` and the post-command self-heal both write skills and the heal runs on\n * every command: reaching into commands/install would parse the wallet's viem\n * chunk on a `tenjin config`.\n */\n\nexport type SkillInstallStatus =\n 'installed' | 'updated' | 'up-to-date' | 'would-install' | 'would-update';\n\nexport interface SkillInstallResult {\n status: SkillInstallStatus;\n warning?: string;\n /** Was a real copy (a SKILL.md, not just the directory) already on disk before this run? */\n preexisting: boolean;\n}\n\nexport interface SkillWriteOptions {\n /**\n * Write THROUGH a symlinked destination (default), or replace it. `install`\n * follows the link, because the operator pointed it somewhere on purpose. The\n * unattended self-heal does not, and passes false: it has already refused every\n * link it could see, and this closes the gap between that look and this write,\n * where a link appearing in between would otherwise be followed. `rename` never\n * follows its final component, so the worst a race can now do is leave our\n * regular file where the new link was.\n */\n followSymlinks?: boolean;\n}\n\nexport async function installSkill(\n srcDir: string,\n destDir: string,\n dryRun: boolean,\n name: string,\n opts: SkillWriteOptions = {},\n): Promise<SkillInstallResult> {\n const src = await readTree(srcDir);\n if (src === null) {\n // assertSkillsSource already guards SKILL.md; this is defensive for an empty dir.\n throw new CliError('INTERNAL', `Packaged skill source ${srcDir} is empty`);\n }\n\n // Only the files this package SHIPS are read and written. Everything else in the\n // directory belongs to the operator: never inspected, listed, or removed. That is\n // what package managers do (npm, dpkg, Homebrew all own their files, not the\n // directory), and wholesale replacement was the single cause behind a run of\n // data-loss, symlink and enumeration bugs.\n //\n // Resolved on BOTH paths, dry run included, so a dry run cannot promise a write\n // the real run refuses.\n const writeTo = new Map<string, string>();\n await assertReachable(destDir, name);\n await assertNoCaseCollision(destDir, name);\n for (const rel of src.keys()) {\n const declared = join(destDir, rel);\n writeTo.set(\n rel,\n opts.followSymlinks === false ? declared : await resolveThroughLink(declared, name),\n );\n }\n\n let differs = false;\n let preexisting = false;\n for (const [rel, content] of src) {\n const current = await readShippedFile(writeTo.get(rel)!, name, destDir);\n if (rel === 'SKILL.md') preexisting = current !== null;\n if (current === null || !current.equals(content)) differs = true;\n }\n const change = !preexisting ? 'create' : differs ? 'update' : 'none';\n\n if (!dryRun && change !== 'none') {\n for (const [rel, content] of src) {\n const target = writeTo.get(rel)!;\n try {\n // An existing file keeps the mode it has. A skill an operator (or their\n // dotfiles) made group-readable or read-only is theirs to have set that\n // way, and an update is no reason to hand it back at the default 0644.\n const current = await stat(target).catch(() => null);\n await writeFileAtomic(\n target,\n content,\n current === null ? {} : { mode: current.mode & 0o777 },\n );\n } catch (err) {\n // Culprit is derived from the file that FAILED, not assumed to be the\n // skills root: an existing skill directory that refuses the temp file is\n // itself the thing to chmod, and a symlinked SKILL.md fails in the link's\n // TARGET directory, which no path under destDir names.\n throw wrapWriteError(\n err,\n destDir,\n `the ${name} skill`,\n await deepestExisting(dirname(target)),\n { expected: ': a skill is a directory holding SKILL.md' },\n );\n }\n }\n }\n\n if (change === 'create') return { status: dryRun ? 'would-install' : 'installed', preexisting };\n if (change === 'none') return { status: 'up-to-date', preexisting };\n return {\n status: dryRun ? 'would-update' : 'updated',\n preexisting,\n // The hosted skill is a MIRROR of tenjin.blog/skills.md (roadmap G4), so a\n // differing local copy is a replacement, not the drift warning the CLI skills\n // get. Neither side carries a version or date, so the wording claims no\n // direction: the local file may well be a newer fetch than this package's copy.\n warning:\n name === HOSTED_SKILL_NAME\n ? `${destDir}: the hosted Tenjin skill differed and ${dryRun ? 'would be' : 'was'} replaced by this package's mirror of tenjin.blog/skills.md, which may be older; it stays as the zero-install fallback. Re-fetch it from tenjin.blog/skills.md if you need the current one.`\n : `${destDir}: local edits to ${name}'s SKILL.md ${dryRun ? 'would be' : 'were'} overwritten (the packaged copy is canonical).`,\n };\n}\n\n/**\n * Read a shipped file, or null when it is not there.\n *\n * The node-type guard lives in `readSkillFile`, shared with the wiring check and\n * the staleness check, because all three read the same operator-controlled paths\n * and a pipe at one of them used to hang whichever command got there first.\n */\nasync function readShippedFile(\n path: string,\n name: string,\n destDir: string,\n): Promise<Buffer | null> {\n const read = await readSkillFile(path);\n if (read.kind === 'absent') return null;\n if (read.kind === 'ok') return read.bytes;\n if (read.kind === 'not-regular') {\n throw new CliError('INTERNAL', `${path} is not a regular file, so ${name} was not written.`, {\n fix: `A skill file must be a regular file. Check what is there (\\`ls -l ${path}\\`) and remove or replace it, then re-run \\`tenjin install\\`.`,\n });\n }\n // Names the FILE, not its directory: this is a read failure, and pointing at a\n // perfectly writable parent is what sent operators to chmod the wrong thing.\n throw wrapWriteError(read.err, destDir, `the ${name} skill`, path, { verb: 'read' });\n}\n\n/**\n * A destination the operator manages through a symlink is written THROUGH it, so\n * their link survives and their target is what actually changes. Same call the\n * settings.json writer makes, and the same reason: committing with `rename` over a\n * link would replace it with a regular file and strand the target.\n */\nexport async function resolveThroughLink(path: string, name: string): Promise<string> {\n const entry = await lstat(path).catch(() => null);\n if (entry === null || !entry.isSymbolicLink()) return path;\n const target = await realpath(path).catch(() => null);\n if (target !== null) return target;\n throw new CliError('INTERNAL', `${path} is a broken symlink, so ${name} was not written.`, {\n fix: `Point it at a path that exists, or remove it (\\`ls -ld ${path}\\`), then re-run \\`tenjin install\\`.`,\n });\n}\n\n/**\n * On a case-insensitive filesystem (the macOS default), a user directory named a\n * case variant of a shipped skill ALIASES the skill's path, so the write would\n * replace the user's own SKILL.md under a warning naming a path that is not on\n * disk. Detected by the alias itself: the destination resolves but the parent\n * lists only a differently-cased entry, which also means a case-SENSITIVE\n * filesystem (where both names can coexist) never trips this. Dry runs too.\n */\nasync function assertNoCaseCollision(destDir: string, name: string): Promise<void> {\n if (!existsSync(destDir)) return;\n const entries = await readdir(dirname(destDir)).catch(() => null);\n if (entries === null || entries.includes(name)) return;\n const variant = entries.find((e) => e.toLowerCase() === name.toLowerCase());\n if (variant === undefined) return;\n const actual = join(dirname(destDir), variant);\n throw new CliError(\n 'INTERNAL',\n `${actual} is a case variant of the ${name} skill and this filesystem treats them as the same directory, so ${name} was not written.`,\n {\n fix: `Rename or remove ${actual}, then re-run \\`tenjin install\\`.`,\n },\n );\n}\n\n/**\n * Fail a destination directory that is a BROKEN SYMLINK, on dry runs too, so a dry\n * run cannot report `would-install` where the real run cannot write. It checks only\n * that: an unwritable but real directory passes here and fails at the write, with\n * the permission-denied error.\n */\nasync function assertReachable(destDir: string, name: string): Promise<void> {\n const entry = await lstat(destDir).catch(() => null);\n if (entry?.isSymbolicLink() !== true) return;\n if ((await realpath(destDir).catch(() => null)) !== null) return;\n throw new CliError('INTERNAL', `${destDir} is a broken symlink, so ${name} was not written.`, {\n fix: `Point it at a directory that exists, or remove it (\\`ls -ld ${destDir}\\`), then re-run \\`tenjin install\\`.`,\n });\n}\n\n/**\n * The directory a denied WRITE should point the operator at: the deepest existing\n * ancestor of the failed target's directory, RESOLVED. An existing skill directory\n * that refuses the temp file names itself; a directory that could not be created\n * names the ancestor that refused to create it, because `ls -ld` on a path that is\n * not there says nothing. Resolved because a destination managed through a symlink\n * denies the write in the link's TARGET, and telling the operator to chmod the\n * link's path leaves them staring at a healthy link.\n */\nexport async function deepestExisting(dir: string): Promise<string> {\n for (let cur = dir; ; cur = dirname(cur)) {\n if (existsSync(cur)) return realpath(cur).catch(() => cur);\n if (dirname(cur) === cur) return cur;\n }\n}\n\n/** A raw errno under INTERNAL reads as a CLI bug and carries no fix. */\nexport function wrapWriteError(\n err: unknown,\n /** The destination as the operator knows it (the declared path, pre-resolution). */\n dest: string,\n /** What could not be written, e.g. `the tenjin-search skill` or `the Tenjin pointer`. */\n subject: string,\n /**\n * The path to point the operator at. A READ failure names the file itself, which\n * is the thing whose mode is wrong. A WRITE failure names the deepest existing\n * directory on the failed target's resolved path.\n */\n culprit: string,\n opts: {\n /** Which side failed; a read error reported as \"could not write\" misleads. */\n verb?: 'read' | 'write';\n /** Sentence tail for the wrong-kind fix, telling the operator the expected shape. */\n expected?: string;\n } = {},\n): unknown {\n const verb = opts.verb ?? 'write';\n const denied = hasCode(err, 'EACCES') || hasCode(err, 'EPERM');\n const missing = hasCode(err, 'ENOENT');\n // A skills directory that resolves to a regular file, or a SKILL.md that resolves\n // to a directory. Pathological, but a raw ENOTDIR/EISDIR says nothing about which\n // path is the wrong kind of thing.\n const wrongKind = hasCode(err, 'ENOTDIR') || hasCode(err, 'EISDIR');\n if (!denied && !missing && !wrongKind) return err;\n const fix = denied\n ? `Permission denied on ${culprit}. Check it (\\`ls -ld ${culprit}\\`), then re-run \\`tenjin install\\`.`\n : wrongKind\n ? `${dest} (or a path inside it) is not the kind of thing it needs to be${opts.expected ?? ''}. Check it (\\`ls -ld ${dest}\\`), then re-run \\`tenjin install\\`.`\n : `${dest} could not be created; if it is a symlink, check that its target exists (\\`ls -ld ${dest}\\`), then re-run \\`tenjin install\\`.`;\n return new CliError(\n 'INTERNAL',\n `Could not ${verb} ${subject} ${verb === 'read' ? 'at' : 'to'} ${dest}.`,\n { fix, cause: err },\n );\n}\n\n/**\n * Read a directory tree into a rel-path -> content map, or null when it does not\n * exist. Reads as raw `Buffer`, not `utf8`: today's skills are markdown-only, but\n * this is a general recursive dir-copy, and decoding to a string here would\n * silently corrupt a future non-text asset (an image, a font) on write, or worse,\n * make two different corrupted binaries both decode to U+FFFD and compare equal.\n */\nasync function readTree(dir: string): Promise<Map<string, Buffer> | null> {\n if (!existsSync(dir)) return null;\n const entries = await readdir(dir, { recursive: true, withFileTypes: true });\n const files = new Map<string, Buffer>();\n for (const entry of entries) {\n if (!entry.isFile()) continue;\n const full = join(entry.parentPath, entry.name);\n files.set(relative(dir, full), await readFile(full));\n }\n return files;\n}\n"],"mappings":";;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,OAAO,UAAU,SAAS,UAAU,YAAY;AACzD,SAAS,SAAS,MAAM,gBAAgB;AAqCxC,eAAsB,aACpB,QACA,SACA,QACA,MACA,OAA0B,CAAC,GACE;AAC7B,QAAM,MAAM,MAAM,SAAS,MAAM;AACjC,MAAI,QAAQ,MAAM;AAEhB,UAAM,IAAI,SAAS,YAAY,yBAAyB,MAAM,WAAW;AAAA,EAC3E;AAUA,QAAM,UA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