tenjin-cli 0.1.0-alpha.1 → 0.1.0-alpha.11

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 (193) hide show
  1. package/NOTICE.md +33 -0
  2. package/README.md +596 -79
  3. package/dist/{_esm-ZH2J4QEH.js → _esm-C5CRWCYU.js} +2 -2
  4. package/dist/_esm-N4KAVXQR.js +881 -0
  5. package/dist/buy-THMVOPUH.js +44 -0
  6. package/dist/ccip-RPPPKTJR.js +19 -0
  7. package/dist/{ccip-UCLT5VOW.js → ccip-ZGGWQN4X.js} +6 -5
  8. package/dist/chunk-2I4QTOLB.js +11 -0
  9. package/dist/chunk-2I4QTOLB.js.map +1 -0
  10. package/dist/chunk-2SDUV6MQ.js +352 -0
  11. package/dist/chunk-2SDUV6MQ.js.map +1 -0
  12. package/dist/chunk-3GSZUADW.js +199 -0
  13. package/dist/chunk-3GSZUADW.js.map +1 -0
  14. package/dist/{chunk-BRJHUQSY.js → chunk-47PP7TAG.js} +908 -812
  15. package/dist/chunk-47PP7TAG.js.map +1 -0
  16. package/dist/chunk-4NTZETIL.js +158 -0
  17. package/dist/chunk-4NTZETIL.js.map +1 -0
  18. package/dist/chunk-4TCU3YRD.js +130 -0
  19. package/dist/chunk-4TCU3YRD.js.map +1 -0
  20. package/dist/chunk-6BGYHARE.js +14620 -0
  21. package/dist/chunk-6BGYHARE.js.map +1 -0
  22. package/dist/chunk-6UY2UQMY.js +213 -0
  23. package/dist/chunk-6UY2UQMY.js.map +1 -0
  24. package/dist/{chunk-IPOWB3G3.js → chunk-7FK2UN2T.js} +3515 -507
  25. package/dist/chunk-7FK2UN2T.js.map +1 -0
  26. package/dist/chunk-ALUNME53.js +306 -0
  27. package/dist/chunk-ALUNME53.js.map +1 -0
  28. package/dist/{chunk-EXBMF5X7.js → chunk-CNUXRXI2.js} +526 -79
  29. package/dist/chunk-CNUXRXI2.js.map +1 -0
  30. package/dist/chunk-E6YOODH7.js +913 -0
  31. package/dist/chunk-E6YOODH7.js.map +1 -0
  32. package/dist/chunk-EDVI7RRD.js +317 -0
  33. package/dist/chunk-EDVI7RRD.js.map +1 -0
  34. package/dist/chunk-FKSAUOJU.js +137 -0
  35. package/dist/chunk-FKSAUOJU.js.map +1 -0
  36. package/dist/chunk-GKV6VZSZ.js +125 -0
  37. package/dist/chunk-GKV6VZSZ.js.map +1 -0
  38. package/dist/chunk-GUUAYR3K.js +175 -0
  39. package/dist/chunk-GUUAYR3K.js.map +1 -0
  40. package/dist/chunk-IAFYUFIC.js +1408 -0
  41. package/dist/chunk-IAFYUFIC.js.map +1 -0
  42. package/dist/chunk-IB63U6BM.js +185 -0
  43. package/dist/chunk-IB63U6BM.js.map +1 -0
  44. package/dist/chunk-IXTENA2H.js +235 -0
  45. package/dist/chunk-IXTENA2H.js.map +1 -0
  46. package/dist/chunk-JTYIX6OD.js +161 -0
  47. package/dist/chunk-JTYIX6OD.js.map +1 -0
  48. package/dist/chunk-KYQVEKP5.js +209 -0
  49. package/dist/chunk-KYQVEKP5.js.map +1 -0
  50. package/dist/chunk-KZAAWQNP.js +6199 -0
  51. package/dist/chunk-KZAAWQNP.js.map +1 -0
  52. package/dist/{chunk-T4LKNY7T.js → chunk-M2O56UK7.js} +225 -70
  53. package/dist/chunk-M2O56UK7.js.map +1 -0
  54. package/dist/chunk-MJZZTKCC.js +323 -0
  55. package/dist/chunk-MJZZTKCC.js.map +1 -0
  56. package/dist/chunk-NUF2PKJO.js +207 -0
  57. package/dist/chunk-NUF2PKJO.js.map +1 -0
  58. package/dist/chunk-O25VWJCG.js +1357 -0
  59. package/dist/chunk-O25VWJCG.js.map +1 -0
  60. package/dist/chunk-OCN27NJV.js +612 -0
  61. package/dist/chunk-OCN27NJV.js.map +1 -0
  62. package/dist/chunk-OZHJ3FLR.js +105 -0
  63. package/dist/chunk-OZHJ3FLR.js.map +1 -0
  64. package/dist/chunk-P74I3WH4.js +204 -0
  65. package/dist/chunk-P74I3WH4.js.map +1 -0
  66. package/dist/chunk-POJRB2AE.js +83 -0
  67. package/dist/chunk-POJRB2AE.js.map +1 -0
  68. package/dist/{chunk-YG2DO46P.js → chunk-PZRAAAY2.js} +107 -22
  69. package/dist/chunk-PZRAAAY2.js.map +1 -0
  70. package/dist/chunk-PZSUWDF2.js +35 -0
  71. package/dist/chunk-PZSUWDF2.js.map +1 -0
  72. package/dist/chunk-QW2Q2KAH.js +27 -0
  73. package/dist/chunk-QW2Q2KAH.js.map +1 -0
  74. package/dist/{chunk-CUWUHTIL.js → chunk-RBJPAZFI.js} +16 -202
  75. package/dist/chunk-RBJPAZFI.js.map +1 -0
  76. package/dist/chunk-RSBN67PA.js +152 -0
  77. package/dist/chunk-RSBN67PA.js.map +1 -0
  78. package/dist/chunk-S5RYMCV6.js +70 -0
  79. package/dist/chunk-S5RYMCV6.js.map +1 -0
  80. package/dist/chunk-SFGXAZ3M.js +316 -0
  81. package/dist/chunk-SFGXAZ3M.js.map +1 -0
  82. package/dist/chunk-SGK2B724.js +67 -0
  83. package/dist/chunk-SGK2B724.js.map +1 -0
  84. package/dist/chunk-TDDN5GXR.js +145 -0
  85. package/dist/chunk-TDDN5GXR.js.map +1 -0
  86. package/dist/{chunk-LPRVHM7P.js → chunk-U5S527PP.js} +1655 -114
  87. package/dist/chunk-U5S527PP.js.map +1 -0
  88. package/dist/chunk-UFPJBS4C.js +242 -0
  89. package/dist/chunk-UFPJBS4C.js.map +1 -0
  90. package/dist/chunk-UHTVXQ2O.js +140 -0
  91. package/dist/chunk-UHTVXQ2O.js.map +1 -0
  92. package/dist/chunk-UY6CGULW.js +83 -0
  93. package/dist/chunk-UY6CGULW.js.map +1 -0
  94. package/dist/chunk-VWY3U732.js +674 -0
  95. package/dist/chunk-VWY3U732.js.map +1 -0
  96. package/dist/{chunk-Q53IYV2G.js → chunk-W6R3HAAG.js} +20 -17
  97. package/dist/{chunk-Q53IYV2G.js.map → chunk-W6R3HAAG.js.map} +1 -1
  98. package/dist/chunk-XJN5WUKL.js +204 -0
  99. package/dist/chunk-XJN5WUKL.js.map +1 -0
  100. package/dist/chunk-XWHXX2BI.js +149 -0
  101. package/dist/chunk-XWHXX2BI.js.map +1 -0
  102. package/dist/{chunk-DXPYFVKG.js → chunk-Y7ERTA7D.js} +35 -15
  103. package/dist/chunk-Y7ERTA7D.js.map +1 -0
  104. package/dist/chunk-YLYINX2H.js +7806 -0
  105. package/dist/chunk-YLYINX2H.js.map +1 -0
  106. package/dist/chunk-ZE7KOO7A.js +233 -0
  107. package/dist/chunk-ZE7KOO7A.js.map +1 -0
  108. package/dist/chunk-ZQIQ55KK.js +51 -0
  109. package/dist/chunk-ZQIQ55KK.js.map +1 -0
  110. package/dist/{chunk-3IMLRUZE.js → chunk-ZXTAQYNA.js} +6 -2
  111. package/dist/{cli-WA65NP4Y.js → cli-Y2HBOSGK.js} +437 -175
  112. package/dist/cli-Y2HBOSGK.js.map +1 -0
  113. package/dist/config-WDGMZKHU.js +26 -0
  114. package/dist/config-WDGMZKHU.js.map +1 -0
  115. package/dist/dist-U4M6QCKE.js +2842 -0
  116. package/dist/dist-U4M6QCKE.js.map +1 -0
  117. package/dist/doctor-CSIWKWM2.js +27 -0
  118. package/dist/doctor-CSIWKWM2.js.map +1 -0
  119. package/dist/edit-E7N6F3OY.js +38 -0
  120. package/dist/edit-E7N6F3OY.js.map +1 -0
  121. package/dist/ethersCompat-Df4a6QIZ-WHYKB6HA.js +18 -0
  122. package/dist/ethersCompat-Df4a6QIZ-WHYKB6HA.js.map +1 -0
  123. package/dist/fund-OKK627GL.js +38 -0
  124. package/dist/fund-OKK627GL.js.map +1 -0
  125. package/dist/index.js +1 -1
  126. package/dist/inspect-573WHEV4.js +35 -0
  127. package/dist/inspect-573WHEV4.js.map +1 -0
  128. package/dist/install-SQAYMNQC.js +1134 -0
  129. package/dist/install-SQAYMNQC.js.map +1 -0
  130. package/dist/{mine.wasm-GQECMSGN.js → mine.wasm-6PIT3DK6.js} +2 -2
  131. package/dist/outcome-W3KYGF23.js +22 -0
  132. package/dist/outcome-W3KYGF23.js.map +1 -0
  133. package/dist/publish-N5U4XYVA.js +40 -0
  134. package/dist/publish-N5U4XYVA.js.map +1 -0
  135. package/dist/read-PJ7Z6UGF.js +158 -0
  136. package/dist/read-PJ7Z6UGF.js.map +1 -0
  137. package/dist/run-FSO3MMXN.js +16883 -0
  138. package/dist/run-FSO3MMXN.js.map +1 -0
  139. package/dist/search-ZWOP4EGK.js +23 -0
  140. package/dist/search-ZWOP4EGK.js.map +1 -0
  141. package/dist/{secp256k1-BEZS642W.js → secp256k1-XRPVBC6V.js} +5 -4
  142. package/dist/secp256k1-XRPVBC6V.js.map +1 -0
  143. package/dist/send-F34ZDXDZ.js +223 -0
  144. package/dist/send-F34ZDXDZ.js.map +1 -0
  145. package/dist/session-4N4ZT3AH.js +88 -0
  146. package/dist/session-4N4ZT3AH.js.map +1 -0
  147. package/dist/skill-heal-XBEK272G.js +85 -0
  148. package/dist/skill-heal-XBEK272G.js.map +1 -0
  149. package/dist/uninstall-BTKPHPDL.js +68 -0
  150. package/dist/uninstall-BTKPHPDL.js.map +1 -0
  151. package/dist/usdc-4VCDHFWX.js +38 -0
  152. package/dist/usdc-4VCDHFWX.js.map +1 -0
  153. package/dist/viemAdapter-By13KInL-TUQJBMHM.js +14 -0
  154. package/dist/viemAdapter-By13KInL-TUQJBMHM.js.map +1 -0
  155. package/dist/wallet-UL4P2JRO.js +42 -0
  156. package/dist/wallet-UL4P2JRO.js.map +1 -0
  157. package/dist/wallet-WJ6UP5OU.js +32 -0
  158. package/dist/wallet-WJ6UP5OU.js.map +1 -0
  159. package/docs/agent-permissions.md +294 -0
  160. package/package.json +25 -18
  161. package/skills/tenjin/SKILL.md +364 -0
  162. package/skills/tenjin-publish/SKILL.md +232 -0
  163. package/skills/tenjin-search/SKILL.md +341 -0
  164. package/dist/chunk-BRJHUQSY.js.map +0 -1
  165. package/dist/chunk-CUWUHTIL.js.map +0 -1
  166. package/dist/chunk-DXPYFVKG.js.map +0 -1
  167. package/dist/chunk-EXBMF5X7.js.map +0 -1
  168. package/dist/chunk-EZROUI5U.js +0 -135
  169. package/dist/chunk-EZROUI5U.js.map +0 -1
  170. package/dist/chunk-IPOWB3G3.js.map +0 -1
  171. package/dist/chunk-LPRVHM7P.js.map +0 -1
  172. package/dist/chunk-T4LKNY7T.js.map +0 -1
  173. package/dist/chunk-YBMMV4Y4.js +0 -51
  174. package/dist/chunk-YBMMV4Y4.js.map +0 -1
  175. package/dist/chunk-YG2DO46P.js.map +0 -1
  176. package/dist/chunk-ZPZFPVDN.js +0 -67
  177. package/dist/chunk-ZPZFPVDN.js.map +0 -1
  178. package/dist/cli-WA65NP4Y.js.map +0 -1
  179. package/dist/config-CEFTL5ZL.js +0 -164
  180. package/dist/config-CEFTL5ZL.js.map +0 -1
  181. package/dist/doctor-3QBYN46N.js +0 -338
  182. package/dist/doctor-3QBYN46N.js.map +0 -1
  183. package/dist/usdc-44R6XZF2.js +0 -18
  184. package/dist/wallet-ELBTBMXO.js +0 -20
  185. package/dist/wallet-XD576HF3.js +0 -173
  186. package/dist/wallet-XD576HF3.js.map +0 -1
  187. /package/dist/{_esm-ZH2J4QEH.js.map → _esm-C5CRWCYU.js.map} +0 -0
  188. /package/dist/{ccip-UCLT5VOW.js.map → _esm-N4KAVXQR.js.map} +0 -0
  189. /package/dist/{chunk-3IMLRUZE.js.map → buy-THMVOPUH.js.map} +0 -0
  190. /package/dist/{secp256k1-BEZS642W.js.map → ccip-RPPPKTJR.js.map} +0 -0
  191. /package/dist/{usdc-44R6XZF2.js.map → ccip-ZGGWQN4X.js.map} +0 -0
  192. /package/dist/{wallet-ELBTBMXO.js.map → chunk-ZXTAQYNA.js.map} +0 -0
  193. /package/dist/{mine.wasm-GQECMSGN.js.map → mine.wasm-6PIT3DK6.js.map} +0 -0
@@ -0,0 +1,137 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+
3
+ // src/lib/lock.ts
4
+ import { mkdirSync, rmSync } from "fs";
5
+ import { writeFile } from "fs/promises";
6
+ import { join } from "path";
7
+ var owned = /* @__PURE__ */ new Set();
8
+ function ownsAnyLock() {
9
+ return owned.size > 0;
10
+ }
11
+ function releaseOwnedLocks() {
12
+ for (const path of owned) {
13
+ try {
14
+ rmSync(path, { recursive: true, force: true });
15
+ } catch {
16
+ }
17
+ }
18
+ owned.clear();
19
+ }
20
+ var DEFAULTS = { timeoutMs: 5e3, retryMs: 25 };
21
+ var LockTimeoutError = class extends Error {
22
+ lockPath;
23
+ constructor(lockPath, timeoutMs) {
24
+ super(
25
+ `Timed out waiting for lock at ${lockPath} after ${timeoutMs}ms; if no other tenjin process is running, remove that directory and retry.`
26
+ );
27
+ this.name = "LockTimeoutError";
28
+ this.lockPath = lockPath;
29
+ }
30
+ };
31
+ async function withFileLock(lockPath, fn, opts = {}) {
32
+ const { timeoutMs, retryMs } = { ...DEFAULTS, ...opts };
33
+ const metaPath = join(lockPath, "meta");
34
+ const deadline = Date.now() + timeoutMs;
35
+ for (; ; ) {
36
+ try {
37
+ mkdirSync(lockPath);
38
+ owned.add(lockPath);
39
+ break;
40
+ } catch (err) {
41
+ if (!isEexist(err)) throw err;
42
+ if (Date.now() >= deadline) throw new LockTimeoutError(lockPath, timeoutMs);
43
+ await delay(retryMs);
44
+ }
45
+ }
46
+ await writeFile(metaPath, JSON.stringify({ pid: process.pid, acquiredAt: Date.now() })).catch(
47
+ () => void 0
48
+ );
49
+ try {
50
+ return await fn();
51
+ } finally {
52
+ try {
53
+ rmSync(lockPath, { recursive: true, force: true });
54
+ owned.delete(lockPath);
55
+ } catch (err) {
56
+ opts.onReleaseError?.(lockPath, err);
57
+ }
58
+ }
59
+ }
60
+ function isEexist(err) {
61
+ return typeof err === "object" && err !== null && err.code === "EEXIST";
62
+ }
63
+ function delay(ms) {
64
+ return new Promise((resolve) => setTimeout(resolve, ms));
65
+ }
66
+
67
+ // src/lib/policy.ts
68
+ function normCreator(value) {
69
+ return value.trim().toLowerCase();
70
+ }
71
+ function evaluateSpendPolicy(policy, req) {
72
+ if (req.maxPriceAtomic !== void 0 && req.amountAtomic > req.maxPriceAtomic) {
73
+ return {
74
+ decision: "deny",
75
+ reason: "price_cap_exceeded",
76
+ message: `Price ${req.amountAtomic} exceeds the --max-price cap ${req.maxPriceAtomic}.`
77
+ };
78
+ }
79
+ if (policy.allowlistCreators.length > 0) {
80
+ const allowed = policy.allowlistCreators.map(normCreator);
81
+ if (!allowed.includes(normCreator(req.creator))) {
82
+ return {
83
+ decision: "deny",
84
+ reason: "not_allowlisted",
85
+ message: `Creator "${req.creator}" is not in allowlistCreators.`
86
+ };
87
+ }
88
+ }
89
+ if (policy.sessionBudgetAtomic > 0n) {
90
+ const projected = req.sessionSpentAtomic + req.amountAtomic;
91
+ if (projected > policy.sessionBudgetAtomic) {
92
+ return {
93
+ decision: "deny",
94
+ reason: "session_budget_exceeded",
95
+ message: `This spend would bring the session total to ${projected}, over sessionBudget ${policy.sessionBudgetAtomic}.`
96
+ };
97
+ }
98
+ }
99
+ if (req.amountAtomic > policy.maxAutoSpendAtomic) {
100
+ return {
101
+ decision: "confirm",
102
+ reason: "above_auto_spend",
103
+ message: `Price ${req.amountAtomic} is above maxAutoSpend ${policy.maxAutoSpendAtomic}; confirmation required.`
104
+ };
105
+ }
106
+ if (policy.confirm.mode === "always") {
107
+ return {
108
+ decision: "confirm",
109
+ reason: "confirm_always",
110
+ message: 'confirm policy is "always"; confirmation required.'
111
+ };
112
+ }
113
+ if (req.amountAtomic > policy.confirm.thresholdAtomic) {
114
+ return {
115
+ decision: "confirm",
116
+ reason: "above_confirm_threshold",
117
+ message: `Price ${req.amountAtomic} is above the confirm threshold ${policy.confirm.thresholdAtomic}; confirmation required.`
118
+ };
119
+ }
120
+ return { decision: "allow", reason: "within_policy", message: "within spend policy" };
121
+ }
122
+ function parseConfirmPolicy(stored) {
123
+ if (stored === "always") return { mode: "always" };
124
+ const m = /^above:(\d+)$/.exec(stored);
125
+ if (m && m[1] !== void 0) return { mode: "above", thresholdAtomic: BigInt(m[1]) };
126
+ return { mode: "always" };
127
+ }
128
+
129
+ export {
130
+ ownsAnyLock,
131
+ releaseOwnedLocks,
132
+ LockTimeoutError,
133
+ withFileLock,
134
+ evaluateSpendPolicy,
135
+ parseConfirmPolicy
136
+ };
137
+ //# sourceMappingURL=chunk-FKSAUOJU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/lock.ts","../src/lib/policy.ts"],"sourcesContent":["import { mkdirSync, rmSync } from 'node:fs';\nimport { writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\n\n/**\n * Locks this process currently holds. Ownership starts the instant `mkdir`\n * succeeds and ends when the release has removed the directory, so there is no\n * window where a lock is on disk and unaccounted for. A removal that FAILS keeps\n * the lock owned: the directory is still on disk, no successor can claim the path\n * while it exists, and a signal-time release gets another attempt. The one place\n * ownership is dropped without a successful removal is `releaseOwnedLocks`, which\n * runs only as the process exits, where a claim held by a dying process helps\n * nobody.\n *\n * It exists because the default signal action terminates WITHOUT running\n * `finally`: without this, one Ctrl-C leaves a lock nothing will ever clean and\n * every later run of the same command times out on it.\n */\nconst owned = new Set<string>();\n\n/** Does this process hold any lock right now? */\nexport function ownsAnyLock(): boolean {\n return owned.size > 0;\n}\n\n/**\n * Synchronously attempt to release every lock this process holds. BEST EFFORT: a\n * path that refuses to be removed is left on disk and the next run's timeout names\n * it. Safe to call from a signal handler, and a no-op when this process holds\n * none, so a run merely QUEUED behind another cannot remove that other run's lock.\n */\nexport function releaseOwnedLocks(): void {\n for (const path of owned) {\n // NEVER throws. This runs inside a signal handler, and a throw there is an\n // uncaught exception: the process dies with code 1 and a stack trace instead\n // of the diagnostic and exit 130 the handler promises. One lock we could not\n // remove must not cost the report, or the exit code, or the other locks.\n try {\n rmSync(path, { recursive: true, force: true });\n } catch {\n // Left behind; the next run's timeout names the path.\n }\n }\n owned.clear();\n}\n\nexport interface FileLockOptions {\n /** Give up acquiring after this long (ms). */\n timeoutMs?: number;\n /** Poll interval between acquisition attempts (ms). */\n retryMs?: number;\n /**\n * Called when the lock could not be removed on release. The protected work\n * succeeded, so this is not a failure of the command; it is a leftover that will\n * block later runs, and the caller is the only one able to say so.\n */\n onReleaseError?: (lockPath: string, err: unknown) => void;\n}\n\nconst DEFAULTS = { timeoutMs: 5000, retryMs: 25 };\n\n/** Thrown when the lock cannot be acquired within `timeoutMs`. Carries the lock\n * path so a caller can surface the manual-recovery step in its own error contract. */\nexport class LockTimeoutError extends Error {\n readonly lockPath: string;\n constructor(lockPath: string, timeoutMs: number) {\n super(\n `Timed out waiting for lock at ${lockPath} after ${timeoutMs}ms; if no other tenjin process is running, remove that directory and retry.`,\n );\n this.name = 'LockTimeoutError';\n this.lockPath = lockPath;\n }\n}\n\n/**\n * Minimal cross-process mutex: the lock IS a directory, and mkdir is atomic, so a\n * second holder gets EEXIST and retries with backoff until `timeoutMs`, then\n * throws LockTimeoutError. There is deliberately NO auto-steal of a \"stale\" lock:\n * concurrent waiters each judging a lock stale could remove a fresh holder's\n * directory and lose its update. A crashed holder's lock is recovered by hand (the\n * timeout error names the path); the pid+acquiredAt meta exists only to make that\n * manual call diagnosable. Always released in the finally.\n *\n * ⚠ MIRRORED, MUST UPDATE TOGETHER. The generated WebSearch hook script in\n * lib/hook-scripts.ts (`withStoreLock`) reimplements this protocol byte for byte,\n * because it runs as a standalone .mjs outside the CLI and cannot import this\n * module, yet writes the same searches.json. If you change what the lock IS\n * (directory vs file), where it lives, or the no-stale-steal rule, change it\n * there too. Two writers of one file that disagree about the mutex have no mutex.\n * lib/hook-scripts.test.ts pins the two together and fails loudly on drift.\n */\nexport async function withFileLock<T>(\n lockPath: string,\n fn: () => Promise<T>,\n opts: FileLockOptions = {},\n): Promise<T> {\n const { timeoutMs, retryMs } = { ...DEFAULTS, ...opts };\n const metaPath = join(lockPath, 'meta');\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n try {\n // SYNCHRONOUS, for the same reason the release is: `await mkdir` finishes the\n // syscall before the continuation records ownership, so between the two the\n // directory is on disk and unclaimed. A signal there exits without removing\n // it and, with no stale recovery, nothing ever will. mkdirSync and the add\n // are one uninterruptible step.\n mkdirSync(lockPath);\n owned.add(lockPath); // owned from here, released only in the finally below\n break; // acquired\n } catch (err) {\n if (!isEexist(err)) throw err;\n if (Date.now() >= deadline) throw new LockTimeoutError(lockPath, timeoutMs);\n await delay(retryMs);\n }\n }\n await writeFile(metaPath, JSON.stringify({ pid: process.pid, acquiredAt: Date.now() })).catch(\n () => undefined,\n );\n try {\n return await fn();\n } finally {\n // SYNCHRONOUS, and in this order, because both are load-bearing. A signal\n // handler cannot run between two synchronous statements, so there is no instant\n // where the lock is on disk but unclaimed (a signal would exit without removing\n // it, and with no stale recovery nothing ever would) nor one where it is\n // claimed after release (a signal would remove whatever SUCCESSOR had since\n // acquired the path). An `await` here reopens the first window: `rm` yields, the\n // handler runs, sees no ownership, and leaves the directory behind.\n //\n // With no stealing, nothing else ever removes or replaces this directory, so\n // the lock here is provably the one we created — the unconditional rm is sound.\n try {\n rmSync(lockPath, { recursive: true, force: true });\n owned.delete(lockPath);\n } catch (err) {\n // KEEP ownership when the removal fails: the successor-steal risk only\n // exists once the directory is gone and someone else can take the path, so a\n // removal that failed leaves it on disk and still ours, and a signal-time\n // release gets another attempt. That only helps while THIS process lives,\n // though; once it exits normally the leftover blocks every later run, so the\n // caller is told rather than left to discover it as a timeout.\n opts.onReleaseError?.(lockPath, err);\n }\n }\n}\n\nfunction isEexist(err: unknown): boolean {\n return typeof err === 'object' && err !== null && (err as { code?: unknown }).code === 'EEXIST';\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","/**\n * Spend-policy evaluation, pure and provider-agnostic. The wallet provider layer\n * (lib/wallet/spend.ts) owns the ledger and calls this; a future hosted provider\n * (Privy, B5) reuses the same decision rules, so the knobs live in exactly one\n * place. Nothing here does IO, the caller supplies the already-spent total and\n * decides how to satisfy a `confirm` decision (a `--yes`, a TTY prompt, or a\n * non-interactive refusal).\n */\n\n/** How a `confirm` gate is configured (parsed from the stored config string). */\nexport type ConfirmPolicy = { mode: 'always' } | { mode: 'above'; thresholdAtomic: bigint };\n\nexport interface SpendPolicy {\n /** Amounts at or below this auto-approve WITHOUT a prompt (still subject to the\n * confirm gate below). Default 0 → nothing auto-approves. */\n maxAutoSpendAtomic: bigint;\n /** Rolling local ceiling on cumulative session spend. 0 = disabled (no ceiling). */\n sessionBudgetAtomic: bigint;\n /** When a human confirmation is requested. */\n confirm: ConfirmPolicy;\n /** Creators (handle or 0x-address, lowercased) auto-payment is restricted to.\n * Empty = no restriction. A non-empty list is a hard gate: a non-member is\n * denied even with `--yes`. */\n allowlistCreators: string[];\n}\n\nexport interface SpendRequest {\n amountAtomic: bigint;\n /** Creator identity from the 402 preview / candidate, handle or 0x address. */\n creator: string;\n /** The caller's `--max-price` cap, if given. A hard ceiling, never bypassable. */\n maxPriceAtomic?: bigint;\n /** Cumulative spend already recorded in this rolling session window. */\n sessionSpentAtomic: bigint;\n}\n\n/**\n * `allow`: within policy, proceed silently. `confirm`: an approval is required ,\n * the caller satisfies it with `--yes`, an interactive prompt, or refuses. `deny`:\n * a hard gate blocked it (price cap, allowlist, session budget); NOT satisfiable\n * by `--yes` or a prompt.\n */\nexport type SpendDecision = 'allow' | 'confirm' | 'deny';\n\nexport type PolicyReason =\n | 'within_policy'\n | 'price_cap_exceeded'\n | 'not_allowlisted'\n | 'session_budget_exceeded'\n | 'above_auto_spend'\n | 'confirm_always'\n | 'above_confirm_threshold';\n\nexport interface PolicyEvaluation {\n decision: SpendDecision;\n reason: PolicyReason;\n message: string;\n}\n\n/** Normalize a creator identity for allowlist comparison (case-insensitive; a\n * word-handle and a 0x address are both single tokens). */\nfunction normCreator(value: string): string {\n return value.trim().toLowerCase();\n}\n\n/**\n * Evaluate one spend against the policy. Hard gates run first (price cap →\n * allowlist → session budget); only if all pass is the confirm gate consulted. A\n * spend at or below `maxAutoSpend` that the confirm policy would not prompt for is\n * the only `allow`; everything else within the hard gates is `confirm`.\n */\nexport function evaluateSpendPolicy(policy: SpendPolicy, req: SpendRequest): PolicyEvaluation {\n if (req.maxPriceAtomic !== undefined && req.amountAtomic > req.maxPriceAtomic) {\n return {\n decision: 'deny',\n reason: 'price_cap_exceeded',\n message: `Price ${req.amountAtomic} exceeds the --max-price cap ${req.maxPriceAtomic}.`,\n };\n }\n\n if (policy.allowlistCreators.length > 0) {\n const allowed = policy.allowlistCreators.map(normCreator);\n if (!allowed.includes(normCreator(req.creator))) {\n return {\n decision: 'deny',\n reason: 'not_allowlisted',\n message: `Creator \"${req.creator}\" is not in allowlistCreators.`,\n };\n }\n }\n\n if (policy.sessionBudgetAtomic > 0n) {\n const projected = req.sessionSpentAtomic + req.amountAtomic;\n if (projected > policy.sessionBudgetAtomic) {\n return {\n decision: 'deny',\n reason: 'session_budget_exceeded',\n message: `This spend would bring the session total to ${projected}, over sessionBudget ${policy.sessionBudgetAtomic}.`,\n };\n }\n }\n\n if (req.amountAtomic > policy.maxAutoSpendAtomic) {\n return {\n decision: 'confirm',\n reason: 'above_auto_spend',\n message: `Price ${req.amountAtomic} is above maxAutoSpend ${policy.maxAutoSpendAtomic}; confirmation required.`,\n };\n }\n\n if (policy.confirm.mode === 'always') {\n return {\n decision: 'confirm',\n reason: 'confirm_always',\n message: 'confirm policy is \"always\"; confirmation required.',\n };\n }\n\n if (req.amountAtomic > policy.confirm.thresholdAtomic) {\n return {\n decision: 'confirm',\n reason: 'above_confirm_threshold',\n message: `Price ${req.amountAtomic} is above the confirm threshold ${policy.confirm.thresholdAtomic}; confirmation required.`,\n };\n }\n\n return { decision: 'allow', reason: 'within_policy', message: 'within spend policy' };\n}\n\n/** Parse the stored `confirm` config value (\"always\" | \"above:<atomic>\"). */\nexport function parseConfirmPolicy(stored: string): ConfirmPolicy {\n if (stored === 'always') return { mode: 'always' };\n const m = /^above:(\\d+)$/.exec(stored);\n if (m && m[1] !== undefined) return { mode: 'above', thresholdAtomic: BigInt(m[1]) };\n // The config schema already constrains this; a malformed value here is a bug,\n // so fail closed to the safest interpretation rather than throwing mid-buy.\n return { mode: 'always' };\n}\n"],"mappings":";;;AAAA,SAAS,WAAW,cAAc;AAClC,SAAS,iBAAiB;AAC1B,SAAS,YAAY;AAgBrB,IAAM,QAAQ,oBAAI,IAAY;AAGvB,SAAS,cAAuB;AACrC,SAAO,MAAM,OAAO;AACtB;AAQO,SAAS,oBAA0B;AACxC,aAAW,QAAQ,OAAO;AAKxB,QAAI;AACF,aAAO,MAAM,EAAE,WAAW,MAAM,OAAO,KAAK,CAAC;AAAA,IAC/C,QAAQ;AAAA,IAER;AAAA,EACF;AACA,QAAM,MAAM;AACd;AAeA,IAAM,WAAW,EAAE,WAAW,KAAM,SAAS,GAAG;AAIzC,IAAM,mBAAN,cAA+B,MAAM;AAAA,EACjC;AAAA,EACT,YAAY,UAAkB,WAAmB;AAC/C;AAAA,MACE,iCAAiC,QAAQ,UAAU,SAAS;AAAA,IAC9D;AACA,SAAK,OAAO;AACZ,SAAK,WAAW;AAAA,EAClB;AACF;AAmBA,eAAsB,aACpB,UACA,IACA,OAAwB,CAAC,GACb;AACZ,QAAM,EAAE,WAAW,QAAQ,IAAI,EAAE,GAAG,UAAU,GAAG,KAAK;AACtD,QAAM,WAAW,KAAK,UAAU,MAAM;AACtC,QAAM,WAAW,KAAK,IAAI,IAAI;AAC9B,aAAS;AACP,QAAI;AAMF,gBAAU,QAAQ;AAClB,YAAM,IAAI,QAAQ;AAClB;AAAA,IACF,SAAS,KAAK;AACZ,UAAI,CAAC,SAAS,GAAG,EAAG,OAAM;AAC1B,UAAI,KAAK,IAAI,KAAK,SAAU,OAAM,IAAI,iBAAiB,UAAU,SAAS;AAC1E,YAAM,MAAM,OAAO;AAAA,IACrB;AAAA,EACF;AACA,QAAM,UAAU,UAAU,KAAK,UAAU,EAAE,KAAK,QAAQ,KAAK,YAAY,KAAK,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AA,MACrH;AAAA,IACF;AAAA,EACF;AAEA,MAAI,IAAI,eAAe,OAAO,oBAAoB;AAChD,WAAO;AAAA,MACL,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,SAAS,SAAS,IAAI,YAAY,0BAA0B,OAAO,kBAAkB;AAAA,IACvF;AAAA,EACF;AAEA,MAAI,OAAO,QAAQ,SAAS,UAAU;AACpC,WAAO;AAAA,MACL,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,SAAS;AAAA,IACX;AAAA,EACF;AAEA,MAAI,IAAI,eAAe,OAAO,QAAQ,iBAAiB;AACrD,WAAO;AAAA,MACL,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,SAAS,SAAS,IAAI,YAAY,mCAAmC,OAAO,QAAQ,eAAe;AAAA,IACrG;AAAA,EACF;AAEA,SAAO,EAAE,UAAU,SAAS,QAAQ,iBAAiB,SAAS,sBAAsB;AACtF;AAGO,SAAS,mBAAmB,QAA+B;AAChE,MAAI,WAAW,SAAU,QAAO,EAAE,MAAM,SAAS;AACjD,QAAM,IAAI,gBAAgB,KAAK,MAAM;AACrC,MAAI,KAAK,EAAE,CAAC,MAAM,OAAW,QAAO,EAAE,MAAM,SAAS,iBAAiB,OAAO,EAAE,CAAC,CAAC,EAAE;AAGnF,SAAO,EAAE,MAAM,SAAS;AAC1B;","names":[]}
@@ -0,0 +1,125 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ latestSearch,
4
+ loadSearches,
5
+ markSearchResolved
6
+ } from "./chunk-4NTZETIL.js";
7
+ import {
8
+ buildOutcomeItem,
9
+ postOutcomes
10
+ } from "./chunk-EDVI7RRD.js";
11
+ import {
12
+ sanitizeForTerminal
13
+ } from "./chunk-IB63U6BM.js";
14
+ import {
15
+ resolveContextSettings
16
+ } from "./chunk-JTYIX6OD.js";
17
+ import {
18
+ isPaidPrice
19
+ } from "./chunk-ALUNME53.js";
20
+ import {
21
+ CliError
22
+ } from "./chunk-PZRAAAY2.js";
23
+
24
+ // src/commands/outcome.ts
25
+ async function runOutcome(args, ctx, deps = {}) {
26
+ const target = await resolveTarget(args, ctx);
27
+ const item = buildOutcomeItem({
28
+ status: args.status,
29
+ ...args.resource !== void 0 ? { resourceId: args.resource } : {},
30
+ ...args.contentHash !== void 0 ? { contentHash: args.contentHash } : {}
31
+ });
32
+ if (target.stored !== null) assertOutcomeCoherent(item.status, target.stored, item.resourceId);
33
+ const { searchId } = target;
34
+ const question = target.stored !== null ? echoQuestion(target.stored.question) : void 0;
35
+ const settings = await resolveContextSettings(ctx);
36
+ const result = await postOutcomes(searchId, [item], {
37
+ baseUrl: settings.baseUrl,
38
+ timeoutMs: ctx.flags.timeout,
39
+ ...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {}
40
+ });
41
+ await markSearchResolved(ctx.dataDir, searchId, "outcome");
42
+ return {
43
+ data: {
44
+ searchId,
45
+ status: item.status,
46
+ accepted: result.accepted,
47
+ ...question !== void 0 ? { question } : {}
48
+ },
49
+ humanLines: [
50
+ `Reported ${item.status} for search ${searchId}${question !== void 0 ? ` "${sanitizeForTerminal(question)}"` : ""} (accepted ${result.accepted}).`
51
+ ]
52
+ };
53
+ }
54
+ async function resolveTarget(args, ctx) {
55
+ if (args.searchId !== void 0 && args.last === true) {
56
+ throw new CliError("USAGE", "Pass either --search-id or --last, not both.", {
57
+ fix: "Use --search-id <id> for a specific search, or --last for the most recent."
58
+ });
59
+ }
60
+ if (args.searchId !== void 0) {
61
+ const searches = await loadSearches(ctx.dataDir);
62
+ return {
63
+ searchId: args.searchId,
64
+ stored: searches.find((s) => s.searchId === args.searchId) ?? null
65
+ };
66
+ }
67
+ if (args.last === true) {
68
+ const latest = await latestSearch(ctx.dataDir);
69
+ if (latest === null) {
70
+ throw new CliError("SEARCH_NOT_FOUND", "No local search to target with --last.", {
71
+ fix: "Run `tenjin search` first, or pass --search-id <id>."
72
+ });
73
+ }
74
+ return { searchId: latest.searchId, stored: latest };
75
+ }
76
+ throw new CliError("USAGE", "An outcome needs a search to report against.", {
77
+ fix: "Pass --search-id <id> or --last."
78
+ });
79
+ }
80
+ var QUESTION_ECHO_MAX = 80;
81
+ function echoQuestion(question) {
82
+ return question.length > QUESTION_ECHO_MAX ? `${question.slice(0, QUESTION_ECHO_MAX - 1)}\u2026` : question;
83
+ }
84
+ function assertOutcomeCoherent(status, stored, resourceId) {
85
+ const named = resourceId !== void 0 ? stored.candidates.find((c) => c.resourceId === resourceId) : void 0;
86
+ if (resourceId !== void 0 && named === void 0 && stored.decision === "CANDIDATES") {
87
+ throw new CliError(
88
+ "USAGE",
89
+ `Search ${stored.searchId} "${echoQuestion(stored.question)}" surfaced no candidate ${resourceId}, so an outcome naming it would not be recorded.`,
90
+ {
91
+ fix: "Pass a resourceId from this search, or drop --resource to report on the search as a whole."
92
+ }
93
+ );
94
+ }
95
+ if (status !== "purchase_declined") return;
96
+ if (named !== void 0) {
97
+ if (isPaidPrice(named.price) !== false) return;
98
+ throw new CliError(
99
+ "USAGE",
100
+ `Search ${stored.searchId} "${echoQuestion(stored.question)}" listed ${resourceId} at no cost, so purchase_declined cannot describe it.`,
101
+ {
102
+ fix: "A free piece is reported as used, partially_used, rejected or regenerated; pass the --resource you actually declined to buy."
103
+ }
104
+ );
105
+ }
106
+ if (offeredSomethingToBuy(stored) !== false) return;
107
+ throw new CliError(
108
+ "USAGE",
109
+ `Search ${stored.searchId} "${echoQuestion(stored.question)}" was a ${stored.decision} that offered nothing to buy, so purchase_declined cannot describe it.`,
110
+ {
111
+ fix: "Report used, partially_used, rejected or regenerated for this search, or pass --search-id <id> for the search you meant to report against."
112
+ }
113
+ );
114
+ }
115
+ function offeredSomethingToBuy(stored) {
116
+ if (stored.candidates.some((c) => isPaidPrice(c.price) === true)) return true;
117
+ if (stored.candidates.some((c) => isPaidPrice(c.price) === null)) return null;
118
+ if (stored.paidBrowseCount === void 0) return null;
119
+ return stored.paidBrowseCount > 0;
120
+ }
121
+
122
+ export {
123
+ runOutcome
124
+ };
125
+ //# sourceMappingURL=chunk-GKV6VZSZ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/outcome.ts"],"sourcesContent":["import { CliError } from '../lib/errors';\nimport { resolveContextSettings } from '../lib/settings';\nimport { buildOutcomeItem, postOutcomes } from '../lib/agent-api';\nimport {\n latestSearch,\n loadSearches,\n markSearchResolved,\n type StoredSearch,\n} from '../lib/search-store';\nimport { isPaidPrice } from '../lib/money';\nimport { sanitizeForTerminal } from '../lib/output';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * `tenjin outcome --search-id <id> --status <s>`, POST to\n * /api/agent/searches/:id/outcomes, closing the reuse loop (used / partially_used\n * / rejected / regenerated / purchase_declined). The searchId is the capability,\n * so no wallet is needed; `--last` sugar targets the most recent DELIBERATE\n * search — entries the WebSearch hook rode along with are skipped, or every web\n * search in auto mode would silently re-aim the report (a hook entry is reached\n * by explicit --search-id, which is what the Stop hook's reminder names).\n *\n * `--last` binds to whatever search ran most recently, which in a multi-search\n * session is often not the one the agent means (issue #100). Two guards, both\n * local: the targeted search's question is echoed back in the success line and in\n * the machine data, so a misfire is visible in the same breath as the report; and\n * an outcome that could not describe that search, whether by its status or by\n * naming a resource the search never surfaced, is refused before the request.\n */\n\nexport interface OutcomeArgs {\n searchId?: string;\n last?: boolean;\n status: string;\n resource?: string;\n contentHash?: string;\n}\n\nexport interface OutcomeDeps {\n fetchImpl?: typeof fetch;\n}\n\nexport async function runOutcome(\n args: OutcomeArgs,\n ctx: CommandContext,\n deps: OutcomeDeps = {},\n): Promise<CommandResult> {\n const target = await resolveTarget(args, ctx);\n // Status name first, so an unknown status still fails as an unknown status\n // rather than as an incoherent one.\n const item = buildOutcomeItem({\n status: args.status,\n ...(args.resource !== undefined ? { resourceId: args.resource } : {}),\n ...(args.contentHash !== undefined ? { contentHash: args.contentHash } : {}),\n });\n if (target.stored !== null) assertOutcomeCoherent(item.status, target.stored, item.resourceId);\n const { searchId } = target;\n const question = target.stored !== null ? echoQuestion(target.stored.question) : undefined;\n\n const settings = await resolveContextSettings(ctx);\n const result = await postOutcomes(searchId, [item], {\n baseUrl: settings.baseUrl,\n timeoutMs: ctx.flags.timeout,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n\n // The loop is closed, so the Stop hook has nothing left to raise about it.\n // AFTER the post, so a refused or failed report leaves the loop open. Local\n // bookkeeping only, and it never throws: see markSearchResolved.\n await markSearchResolved(ctx.dataDir, searchId, 'outcome');\n\n // The question rides both renderings, so the misfire this guards against is\n // visible whether a human is reading the line or an agent is reading the JSON.\n // Sanitized on the human line only: the envelope is machine data and keeps the\n // bytes it was given (see output.ts).\n return {\n data: {\n searchId,\n status: item.status,\n accepted: result.accepted,\n ...(question !== undefined ? { question } : {}),\n },\n humanLines: [\n `Reported ${item.status} for search ${searchId}${\n question !== undefined ? ` \"${sanitizeForTerminal(question)}\"` : ''\n } (accepted ${result.accepted}).`,\n ],\n };\n}\n\n/** The search this report will land on, plus the local record of it when there is\n * one. `stored` is null for a `--search-id` from another machine or an evicted\n * entry: unknown, so neither echoed nor checked. */\ninterface OutcomeTarget {\n searchId: string;\n stored: StoredSearch | null;\n}\n\nasync function resolveTarget(args: OutcomeArgs, ctx: CommandContext): Promise<OutcomeTarget> {\n if (args.searchId !== undefined && args.last === true) {\n throw new CliError('USAGE', 'Pass either --search-id or --last, not both.', {\n fix: 'Use --search-id <id> for a specific search, or --last for the most recent.',\n });\n }\n if (args.searchId !== undefined) {\n const searches = await loadSearches(ctx.dataDir);\n return {\n searchId: args.searchId,\n stored: searches.find((s) => s.searchId === args.searchId) ?? null,\n };\n }\n if (args.last === true) {\n const latest = await latestSearch(ctx.dataDir);\n if (latest === null) {\n throw new CliError('SEARCH_NOT_FOUND', 'No local search to target with --last.', {\n fix: 'Run `tenjin search` first, or pass --search-id <id>.',\n });\n }\n return { searchId: latest.searchId, stored: latest };\n }\n throw new CliError('USAGE', 'An outcome needs a search to report against.', {\n fix: 'Pass --search-id <id> or --last.',\n });\n}\n\n/** Long enough to tell two searches apart on one line, short enough not to bury\n * the searchId next to it. The ellipsis is part of the echo: a question cut with\n * no marker reads as a shorter question that was never asked. */\nconst QUESTION_ECHO_MAX = 80;\n\nfunction echoQuestion(question: string): string {\n return question.length > QUESTION_ECHO_MAX\n ? `${question.slice(0, QUESTION_ECHO_MAX - 1)}…`\n : question;\n}\n\n/**\n * Refuse an outcome that could not describe the search it is aimed at. Two\n * independent checks, because they answer to different rules.\n *\n * MEMBERSHIP, for any status that names a `--resource`: the id has to be one this\n * search surfaced. On a CANDIDATES decision that is provable, since browse\n * pointers are MISS-only by contract AND truncateResponse deletes the array\n * outright on CANDIDATES rather than trust the server, so `candidates` is the\n * entire payable set the agent was shown and `search` records all of it. A uuid\n * outside it is a typo or another search's, and the server drops the item behind\n * its 202 (tenjin#641) whatever the status says, leaving the CLI to report\n * success for an outcome nobody stored. A MISS keeps the fail-open: its browse\n * tail is payable and deliberately unrecorded, so an absent id there is\n * unknowable rather than wrong. So does any other decision value.\n *\n * PAYABILITY, for `purchase_declined` alone. The status matrix is deliberately\n * one-sided: four of the five describe ANY search, so only this one has a\n * precondition.\n *\n * used, partially_used always. A MISS's browse tail is readable, and a free\n * piece is used without any purchase, so \"used\" on a\n * MISS, or on a free candidate, is a real report and not\n * a mistake (issue #100).\n * rejected, regenerated always. \"Nothing here helped, I wrote it myself\" is\n * exactly what a MISS deserves to record.\n * purchase_declined needs the search to have offered something to buy, or,\n * when `--resource` names a candidate the store knows,\n * needs THAT candidate to have cost money. Declining a\n * purchase nobody offered cannot have happened, and that\n * is the shape the dogfooding misfire took: a\n * purchase_declined aimed at a bare MISS.\n *\n * Local knowledge only, and fail-open by construction: an unknown is never a\n * refusal. The server owns the checks this cannot make.\n */\nfunction assertOutcomeCoherent(status: string, stored: StoredSearch, resourceId?: string): void {\n const named =\n resourceId !== undefined\n ? stored.candidates.find((c) => c.resourceId === resourceId)\n : undefined;\n\n if (resourceId !== undefined && named === undefined && stored.decision === 'CANDIDATES') {\n throw new CliError(\n 'USAGE',\n `Search ${stored.searchId} \"${echoQuestion(stored.question)}\" surfaced no candidate ${resourceId}, so an outcome naming it would not be recorded.`,\n {\n fix: 'Pass a resourceId from this search, or drop --resource to report on the search as a whole.',\n },\n );\n }\n\n if (status !== 'purchase_declined') return;\n\n // A named candidate the store knows answers for itself. A piece that was free\n // is not made purchasable by a paid sibling in the same result, so the specific\n // claim is checked against the specific price rather than the search's total.\n if (named !== undefined) {\n if (isPaidPrice(named.price) !== false) return;\n throw new CliError(\n 'USAGE',\n `Search ${stored.searchId} \"${echoQuestion(stored.question)}\" listed ${resourceId} at no cost, so purchase_declined cannot describe it.`,\n {\n fix: 'A free piece is reported as used, partially_used, rejected or regenerated; pass the --resource you actually declined to buy.',\n },\n );\n }\n\n if (offeredSomethingToBuy(stored) !== false) return;\n throw new CliError(\n 'USAGE',\n `Search ${stored.searchId} \"${echoQuestion(stored.question)}\" was a ${stored.decision} that offered nothing to buy, so purchase_declined cannot describe it.`,\n {\n fix: 'Report used, partially_used, rejected or regenerated for this search, or pass --search-id <id> for the search you meant to report against.',\n },\n );\n}\n\n/**\n * Whether the search put anything payable in front of the agent. Priced at zero\n * does not count: `read` delivers a free piece with no payment, so a result that\n * was free end to end offered no purchase to decline, however many rows it had.\n * Null when the stored entry cannot say: it predates `paidBrowseCount`, so an\n * all-free candidate list might still have sat above a payable browse tail.\n */\nfunction offeredSomethingToBuy(stored: StoredSearch): boolean | null {\n if (stored.candidates.some((c) => isPaidPrice(c.price) === true)) return true;\n // A price the store cannot parse is not evidence that the result was free.\n if (stored.candidates.some((c) => isPaidPrice(c.price) === null)) return null;\n if (stored.paidBrowseCount === undefined) return null;\n return stored.paidBrowseCount > 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA0CA,eAAsB,WACpB,MACA,KACA,OAAoB,CAAC,GACG;AACxB,QAAM,SAAS,M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AAI,sBAAsB,MAAM,MAAM,MAAO;AAC7C,QAAM,IAAI;AAAA,IACR;AAAA,IACA,UAAU,OAAO,QAAQ,KAAK,aAAa,OAAO,QAAQ,CAAC,WAAW,OAAO,QAAQ;AAAA,IACrF;AAAA,MACE,KAAK;AAAA,IACP;AAAA,EACF;AACF;AASA,SAAS,sBAAsB,QAAsC;AACnE,MAAI,OAAO,WAAW,KAAK,CAAC,MAAM,YAAY,EAAE,KAAK,MAAM,IAAI,EAAG,QAAO;AAEzE,MAAI,OAAO,WAAW,KAAK,CAAC,MAAM,YAAY,EAAE,KAAK,MAAM,IAAI,EAAG,QAAO;AACzE,MAAI,OAAO,oBAAoB,OAAW,QAAO;AACjD,SAAO,OAAO,kBAAkB;AAClC;","names":[]}
@@ -0,0 +1,175 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ assertOnBaseOrigin
4
+ } from "./chunk-6UY2UQMY.js";
5
+ import {
6
+ recordSearch
7
+ } from "./chunk-4NTZETIL.js";
8
+ import {
9
+ MAX_LIMIT,
10
+ buildSearchRequest,
11
+ postSearch
12
+ } from "./chunk-EDVI7RRD.js";
13
+ import {
14
+ sanitizeForTerminal
15
+ } from "./chunk-IB63U6BM.js";
16
+ import {
17
+ resolveContextSettings
18
+ } from "./chunk-JTYIX6OD.js";
19
+ import {
20
+ formatUsdDisplay,
21
+ isPaidPrice,
22
+ parseUsdToAtomic
23
+ } from "./chunk-ALUNME53.js";
24
+ import {
25
+ CliError
26
+ } from "./chunk-PZRAAAY2.js";
27
+
28
+ // src/commands/search.ts
29
+ async function runSearch(args, ctx, deps = {}) {
30
+ const settings = await resolveContextSettings(ctx);
31
+ const input = { question: args.question };
32
+ if (args.maxPrice !== void 0) input.maxPrice = parseUsdToAtomic(args.maxPrice);
33
+ if (args.freshWithin !== void 0) input.freshWithin = args.freshWithin;
34
+ if (args.limit !== void 0) input.limit = parseLimit(args.limit);
35
+ if (args.appliesTo !== void 0 && args.appliesTo.length > 0) {
36
+ input.appliesTo = parseAppliesTo(args.appliesTo);
37
+ }
38
+ const sessionId = readSessionId(deps.env ?? process.env);
39
+ const request = buildSearchRequest(input);
40
+ const response = await postSearch(request, {
41
+ baseUrl: settings.baseUrl,
42
+ timeoutMs: ctx.flags.timeout,
43
+ evalCohort: settings.evalCohort,
44
+ ...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {}
45
+ });
46
+ const candidates = response.candidates ?? [];
47
+ for (const c of candidates) {
48
+ try {
49
+ assertOnBaseOrigin(c.url, settings.baseUrl, "search candidate URL");
50
+ } catch (err) {
51
+ throw new CliError(
52
+ "CONTRACT_MISMATCH",
53
+ `Search candidate ${c.resourceId} points off the configured base URL.`,
54
+ { cause: err }
55
+ );
56
+ }
57
+ }
58
+ for (const b of response.browse ?? []) {
59
+ try {
60
+ assertOnBaseOrigin(b.url, settings.baseUrl, "browse pointer URL");
61
+ } catch (err) {
62
+ throw new CliError(
63
+ "CONTRACT_MISMATCH",
64
+ `Browse pointer ${b.resourceId} points off the configured base URL.`,
65
+ { cause: err }
66
+ );
67
+ }
68
+ }
69
+ await recordSearch(ctx.dataDir, {
70
+ searchId: response.searchId,
71
+ at: (/* @__PURE__ */ new Date()).toISOString(),
72
+ question: request.question,
73
+ decision: response.decision,
74
+ // A deliberate search, as opposed to one the WebSearch hook rode along with.
75
+ // The Stop hook nags on the two differently, so the tag has to be written
76
+ // here rather than inferred later from anything.
77
+ source: "cli",
78
+ // Usually absent; see readSessionId. An unstamped entry is raised in every
79
+ // session, which is the safe direction for a reminder.
80
+ ...sessionId !== void 0 ? { sessionId } : {},
81
+ candidates: candidates.map((c) => ({
82
+ resourceId: c.resourceId,
83
+ url: c.url,
84
+ title: c.title,
85
+ price: c.price
86
+ })),
87
+ // The pointers stay unrecorded on purpose (see below); only how many of them
88
+ // cost money, so `outcome` can tell a MISS that offered a payable browse tail
89
+ // from one that offered nothing to buy. A zero-priced pointer does not count:
90
+ // `read` delivers it for nothing, so there was no purchase to decline. Zero on
91
+ // a CANDIDATES decision, where the contract carries no browse array and the
92
+ // parser drops any that appears.
93
+ paidBrowseCount: (response.browse ?? []).filter((b) => isPaidPrice(b.price) === true).length
94
+ });
95
+ if (response.decision === "MISS") {
96
+ ctx.io.stderr.write(`${publishBackLine(response.searchId)}
97
+ `);
98
+ }
99
+ const browse = response.browse ?? [];
100
+ const browseHint = browse.length > 0 ? [
101
+ `no match, ${browse.length} piece(s) you could browse: ${browse.map((b) => `${sanitizeForTerminal(b.title)} (${formatUsdDisplay(b.price)} USD)`).join("; ")}`
102
+ ] : [];
103
+ const truncatedHint = response.truncated === true ? [
104
+ request.limit < MAX_LIMIT ? `some candidates were dropped for size; retry with --limit ${MAX_LIMIT} (the size ceiling grows with the number of candidates returned)` : `some candidates were dropped for size; at --limit ${MAX_LIMIT} the dropped tail cannot be recovered, so narrow the question`
105
+ ] : [];
106
+ const humanLines = response.decision === "MISS" ? [`MISS, no candidates (searchId ${response.searchId})`, ...browseHint, ...truncatedHint] : [
107
+ `${candidates.length} candidate(s) (searchId ${response.searchId}):`,
108
+ // Dollars for the same reason the browse hint uses them: this is the
109
+ // human's cue to size the spend against gates they entered in decimal
110
+ // USD. The machine `candidates` array in --json keeps atomic.
111
+ ...candidates.map(
112
+ (c, i) => ` ${i + 1}. ${sanitizeForTerminal(c.title)}, ${formatUsdDisplay(c.price)} USD, ${sanitizeForTerminal(c.url)}`
113
+ ),
114
+ ...truncatedHint
115
+ ];
116
+ const data = response.decision === "MISS" ? { ...response, publishBack: publishBackHint(response.searchId) } : response;
117
+ return { data, humanLines };
118
+ }
119
+ function readSessionId(env) {
120
+ return firstNonEmpty(env.TENJIN_SESSION_ID) ?? firstNonEmpty(env.CLAUDE_CODE_SESSION_ID);
121
+ }
122
+ function firstNonEmpty(raw) {
123
+ if (typeof raw !== "string") return void 0;
124
+ const trimmed = raw.trim();
125
+ return trimmed.length > 0 ? trimmed : void 0;
126
+ }
127
+ function publishBackHint(searchId) {
128
+ return {
129
+ searchId,
130
+ reason: "Nothing on the marketplace answered this. If you solve it, publish it back.",
131
+ // Both arms carry the searchId, because both are commands to run verbatim and
132
+ // a publish without it leaves this very loop open (see publish's --search-id).
133
+ // The second arm is DECLINE, not park: nothing is saved to come back to, and
134
+ // reporting the outcome is what closes the loop so it never raises again.
135
+ publish: `tenjin publish <file.md> --json --search-id ${searchId}`,
136
+ decline: `tenjin outcome --search-id ${searchId} --status regenerated --json`
137
+ };
138
+ }
139
+ function publishBackLine(searchId) {
140
+ return `Nobody has published this yet - if you solve it, publish it back (tenjin publish <file.md> --search-id ${searchId}); if you will not, close the loop: tenjin outcome --search-id ${searchId} --status regenerated`;
141
+ }
142
+ function parseLimit(raw) {
143
+ const n = Number(raw);
144
+ if (!Number.isInteger(n)) {
145
+ throw new CliError("USAGE", `Invalid --limit: ${JSON.stringify(raw)}`, {
146
+ fix: "Pass an integer between 1 and 10."
147
+ });
148
+ }
149
+ return n;
150
+ }
151
+ function parseAppliesTo(pairs) {
152
+ const out = {};
153
+ for (const pair of pairs) {
154
+ const eq = pair.indexOf("=");
155
+ if (eq <= 0) {
156
+ throw new CliError("USAGE", `Invalid --applies-to: ${JSON.stringify(pair)}`, {
157
+ fix: "Use key=value, e.g. --applies-to products=Vercel."
158
+ });
159
+ }
160
+ const key = pair.slice(0, eq).trim();
161
+ const values = pair.slice(eq + 1).split(",").map((v) => v.trim()).filter((v) => v.length > 0);
162
+ if (values.length === 0) {
163
+ throw new CliError("USAGE", `--applies-to ${JSON.stringify(key)} has no values`, {
164
+ fix: "Give each key at least one value, e.g. products=Vercel."
165
+ });
166
+ }
167
+ out[key] = [...out[key] ?? [], ...values];
168
+ }
169
+ return out;
170
+ }
171
+
172
+ export {
173
+ runSearch
174
+ };
175
+ //# sourceMappingURL=chunk-GUUAYR3K.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/search.ts"],"sourcesContent":["import { CliError } from '../lib/errors';\nimport { formatUsdDisplay, isPaidPrice, parseUsdToAtomic } from '../lib/money';\nimport { resolveContextSettings } from '../lib/settings';\nimport { buildSearchRequest, postSearch, MAX_LIMIT, type SearchInput } from '../lib/agent-api';\nimport { recordSearch } from '../lib/search-store';\nimport { assertOnBaseOrigin } from '../lib/resource-ref';\nimport { sanitizeForTerminal } from '../lib/output';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * `tenjin search \"<question>\"`, one POST to /api/agent/search. Prints the compact\n * CANDIDATES/MISS response (spec 10) and records the searchId + candidates\n * locally so `outcome --last` and `buy <resourceId>` can use them. No wallet, no\n * signing: search is anonymous.\n *\n * The machine envelope is the server's response verbatim plus exactly one\n * CLI-owned key, `publishBack`, and only on a MISS. It carries no server data: it\n * is the local searchId and the two commands that close the loop, which is\n * information the CLI owns and the contract does not describe.\n *\n * Search is the breadth step: a candidate is a lean hit (identity, price,\n * freshness, why it matched), and the full answer card comes from `tenjin inspect`,\n * which is free. So a candidate line stays short on purpose.\n *\n * The response's `searchId` is the outcome-reporting capability for\n * POST /api/agent/searches/<searchId>/outcomes. tenjin#463 renamed both the field\n * (from `lookupId`) and that path, and this client follows the rename end to end,\n * so nothing on the wire or in the local store still speaks `lookupId`.\n */\n\nexport interface SearchArgs {\n question: string;\n /** Decimal USD at the edge (O1); converted to atomic for the wire. */\n maxPrice?: string;\n freshWithin?: string;\n limit?: string;\n /** Raw `k=v` / `k=v1,v2` pairs from repeated --applies-to. */\n appliesTo?: string[];\n}\n\nexport interface SearchDeps {\n fetchImpl?: typeof fetch;\n /** Environment seam (TENJIN_SESSION_ID); defaults to process.env. */\n env?: NodeJS.ProcessEnv;\n}\n\nexport async function runSearch(\n args: SearchArgs,\n ctx: CommandContext,\n deps: SearchDeps = {},\n): Promise<CommandResult> {\n const settings = await resolveContextSettings(ctx);\n const input: SearchInput = { question: args.question };\n if (args.maxPrice !== undefined) input.maxPrice = parseUsdToAtomic(args.maxPrice);\n if (args.freshWithin !== undefined) input.freshWithin = args.freshWithin;\n if (args.limit !== undefined) input.limit = parseLimit(args.limit);\n if (args.appliesTo !== undefined && args.appliesTo.length > 0) {\n input.appliesTo = parseAppliesTo(args.appliesTo);\n }\n\n const sessionId = readSessionId(deps.env ?? process.env);\n const request = buildSearchRequest(input);\n const response = await postSearch(request, {\n baseUrl: settings.baseUrl,\n timeoutMs: ctx.flags.timeout,\n evalCohort: settings.evalCohort,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n\n const candidates = response.candidates ?? [];\n // Ingest trust boundary: a candidate url that points off the configured origin\n // would later route a wallet-signed SIWX header and payment to that host via\n // `buy <resourceId>`. Refuse the whole response as a contract violation.\n for (const c of candidates) {\n try {\n assertOnBaseOrigin(c.url, settings.baseUrl, 'search candidate URL');\n } catch (err) {\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `Search candidate ${c.resourceId} points off the configured base URL.`,\n { cause: err },\n );\n }\n }\n // Browse pointers are never buyable through `buy <resourceId>` (they are not\n // recorded), but their urls are still emitted into the agent's transcript, so\n // they get the same origin check rather than a weaker one.\n for (const b of response.browse ?? []) {\n try {\n assertOnBaseOrigin(b.url, settings.baseUrl, 'browse pointer URL');\n } catch (err) {\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `Browse pointer ${b.resourceId} points off the configured base URL.`,\n { cause: err },\n );\n }\n }\n await recordSearch(ctx.dataDir, {\n searchId: response.searchId,\n at: new Date().toISOString(),\n question: request.question,\n decision: response.decision,\n // A deliberate search, as opposed to one the WebSearch hook rode along with.\n // The Stop hook nags on the two differently, so the tag has to be written\n // here rather than inferred later from anything.\n source: 'cli',\n // Usually absent; see readSessionId. An unstamped entry is raised in every\n // session, which is the safe direction for a reminder.\n ...(sessionId !== undefined ? { sessionId } : {}),\n candidates: candidates.map((c) => ({\n resourceId: c.resourceId,\n url: c.url,\n title: c.title,\n price: c.price,\n })),\n // The pointers stay unrecorded on purpose (see below); only how many of them\n // cost money, so `outcome` can tell a MISS that offered a payable browse tail\n // from one that offered nothing to buy. A zero-priced pointer does not count:\n // `read` delivers it for nothing, so there was no purchase to decline. Zero on\n // a CANDIDATES decision, where the contract carries no browse array and the\n // parser drops any that appears.\n paidBrowseCount: (response.browse ?? []).filter((b) => isPaidPrice(b.price) === true).length,\n });\n\n // One stderr line on a MISS (never in the machine JSON): a MISS is the moment\n // to publish the answer you are about to derive. There is deliberately no\n // second line about drafts waiting somewhere — a reminder that re-raises work\n // nobody chose to come back to is the class this CLI stopped emitting.\n if (response.decision === 'MISS') {\n ctx.io.stderr.write(`${publishBackLine(response.searchId)}\\n`);\n }\n\n // A MISS may carry up to 3 browse pointers from the broad corpus. They are\n // pointers, NOT candidates: rendered as ONE hint line with no scores and no\n // per-item detail, so a MISS still reads as a MISS and an agent is never\n // nudged to treat a browse pointer as an answer. The machine JSON keeps the\n // full `browse` array; this line is only the human tail.\n //\n // The price rides this line because a browse url IS payable: it is the read\n // endpoint that answers a 402, and `buy <url>` resolves the URL arm by origin\n // without consulting the search store, so a browse pointer can be bought even\n // though `buy <resourceId>` can never reach one. All spend gates (price cap,\n // session budget, allowlist, confirm) still run; showing the price keeps the\n // only human-visible surface from being a blind spend.\n //\n // It renders in DOLLARS, not atomic units, because the whole point of the line\n // is that a human can size the spend against the gates they set, and every gate\n // is entered in decimal USD (`--max-price 0.10`, the `maxAutoSpend` config).\n // `formatUsdDisplay` is the canonical human-copy form (always two decimals, so\n // a dime reads \"0.10\" and not \"0.1\"); the machine `browse` array in --json still\n // carries the exact atomic string, per the money-units contract in the README.\n const browse = response.browse ?? [];\n const browseHint =\n browse.length > 0\n ? [\n `no match, ${browse.length} piece(s) you could browse: ${browse\n .map((b) => `${sanitizeForTerminal(b.title)} (${formatUsdDisplay(b.price)} USD)`)\n .join('; ')}`,\n ]\n : [];\n\n // `truncated` means the server's size backstop dropped candidates, either a\n // trailing few the limit had room for or a single oversized one. The response\n // ceiling GROWS with the number of candidates returned (tenjin#501), so the\n // remedy is counter-intuitive and worth stating outright: a larger --limit\n // recovers the tail, a smaller one returns strictly fewer. Only at the maximum\n // is the tail unrecoverable and narrowing the question the answer.\n //\n // The CLI knows the limit it sent, so it names the next step instead of\n // restating the rule and leaving the reader to work out which half applies.\n // The flag stays in the machine envelope (--json) untouched, where it is\n // omitted rather than false when it did not fire.\n //\n // Rendering it on a MISS too is DEFENSIVE, not wire behavior: the server only\n // ever sets the flag alongside candidates it dropped. Handling both keeps the\n // flag from going unrendered if that ever changes.\n const truncatedHint =\n response.truncated === true\n ? [\n request.limit < MAX_LIMIT\n ? `some candidates were dropped for size; retry with --limit ${MAX_LIMIT} (the size ceiling grows with the number of candidates returned)`\n : `some candidates were dropped for size; at --limit ${MAX_LIMIT} the dropped tail cannot be recovered, so narrow the question`,\n ]\n : [];\n\n const humanLines =\n response.decision === 'MISS'\n ? [`MISS, no candidates (searchId ${response.searchId})`, ...browseHint, ...truncatedHint]\n : [\n `${candidates.length} candidate(s) (searchId ${response.searchId}):`,\n // Dollars for the same reason the browse hint uses them: this is the\n // human's cue to size the spend against gates they entered in decimal\n // USD. The machine `candidates` array in --json keeps atomic.\n ...candidates.map(\n (c, i) =>\n ` ${i + 1}. ${sanitizeForTerminal(c.title)}, ${formatUsdDisplay(c.price)} USD, ${sanitizeForTerminal(c.url)}`,\n ),\n ...truncatedHint,\n ];\n\n // The one CLI-owned field in this envelope. Everything else is the server's\n // response verbatim (spec 10), so the addition is namespaced under a key the\n // contract does not define and is present ONLY on a MISS: a MISS is the moment\n // the demand this searcher just expressed can still be met, and the searchId is\n // what ties the answer they are about to derive back to it. A CANDIDATES\n // response is byte-identical to what it was.\n const data =\n response.decision === 'MISS'\n ? { ...response, publishBack: publishBackHint(response.searchId) }\n : response;\n\n return { data, humanLines };\n}\n\n/**\n * The session to stamp this search with, so the Stop hook can tell one session's\n * open loops from a sibling's, or undefined when nothing can say.\n *\n * Two sources, in precedence order. TENJIN_SESSION_ID is the explicit operator\n * override and wins. CLAUDE_CODE_SESSION_ID is what Claude Code exports to Bash\n * tool subprocesses, which is what a `tenjin search` runs as; its value is the\n * same `session_id` the hook scripts are handed on stdin, so a CLI search and a\n * WebSearch-hook search in one session stamp identically. It is verified against\n * a live session rather than documented, hence the fallback rather than a\n * requirement: on a harness that does not export it this stays undefined, and\n * undefined is the safe answer — the hook raises an unstamped entry in every\n * session rather than in none.\n */\nfunction readSessionId(env: NodeJS.ProcessEnv): string | undefined {\n return firstNonEmpty(env.TENJIN_SESSION_ID) ?? firstNonEmpty(env.CLAUDE_CODE_SESSION_ID);\n}\n\nfunction firstNonEmpty(raw: string | undefined): string | undefined {\n if (typeof raw !== 'string') return undefined;\n const trimmed = raw.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n}\n\n/** The publish-back hint, as machine fields rather than prose to re-parse. */\nfunction publishBackHint(searchId: string): {\n searchId: string;\n reason: string;\n publish: string;\n decline: string;\n} {\n return {\n searchId,\n reason: 'Nothing on the marketplace answered this. If you solve it, publish it back.',\n // Both arms carry the searchId, because both are commands to run verbatim and\n // a publish without it leaves this very loop open (see publish's --search-id).\n // The second arm is DECLINE, not park: nothing is saved to come back to, and\n // reporting the outcome is what closes the loop so it never raises again.\n publish: `tenjin publish <file.md> --json --search-id ${searchId}`,\n decline: `tenjin outcome --search-id ${searchId} --status regenerated --json`,\n };\n}\n\n/** The same hint as one stderr line for a human. */\nfunction publishBackLine(searchId: string): string {\n return `Nobody has published this yet - if you solve it, publish it back (tenjin publish <file.md> --search-id ${searchId}); if you will not, close the loop: tenjin outcome --search-id ${searchId} --status regenerated`;\n}\n\nfunction parseLimit(raw: string): number {\n const n = Number(raw);\n if (!Number.isInteger(n)) {\n throw new CliError('USAGE', `Invalid --limit: ${JSON.stringify(raw)}`, {\n fix: 'Pass an integer between 1 and 10.',\n });\n }\n return n;\n}\n\n/** `products=Vercel` or `products=Vercel,Next` → { products: [\"Vercel\",\"Next\"] }. Repeated\n * keys merge their values. */\nfunction parseAppliesTo(pairs: string[]): Record<string, string[]> {\n const out: Record<string, string[]> = {};\n for (const pair of pairs) {\n const eq = pair.indexOf('=');\n if (eq <= 0) {\n throw new CliError('USAGE', `Invalid --applies-to: ${JSON.stringify(pair)}`, {\n fix: 'Use key=value, e.g. --applies-to products=Vercel.',\n });\n }\n const key = pair.slice(0, eq).trim();\n const values = pair\n .slice(eq + 1)\n .split(',')\n .map((v) => v.trim())\n .filter((v) => v.length > 0);\n if (values.length === 0) {\n throw new CliError('USAGE', `--applies-to ${JSON.stringify(key)} has no values`, {\n fix: 'Give each key at least one value, e.g. products=Vercel.',\n });\n }\n out[key] = [...(out[key] ?? []), ...values];\n }\n return out;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,eAAsB,UACpB,MACA,KACA,OAAmB,CAAC,GACI;AACxB,QAAM,WAAW,MAAM,uBAAuB,GAAG;AACjD,QAAM,QAAqB,EAAE,UAAU,KAAK,SAAS;AACrD,MAAI,KAAK,aAAa,OAAW,OAAM,WAAW,iBAAiB,KAAK,QAAQ;AAChF,MAAI,KAAK,gBAAgB,OAAW,OAAM,cAAc,KAAK;AAC7D,MAAI,KAAK,UAAU,OAAW,OAAM,QAAQ,WAAW,KAAK,KAAK;AACjE,MAAI,KAAK,cAAc,UAAa,KAAK,UAAU,SAAS,GAAG;AAC7D,UAAM,YAAY,eAAe,KAAK,SAAS;AAAA,EACjD;AAEA,QAAM,YAAY,cAAc,KAAK,OAAO,QAAQ,GAAG;AACvD,QAAM,UAAU,mBAAmB,KAAK;AACxC,QAAM,WAAW,MAAM,WAAW,SAAS;AAAA,IACzC,SAAS,SAAS;AAAA,IAClB,WAAW,IAAI,MAAM;AAAA,IACrB,YAAY,SAAS;AAAA,IACrB,GAAI,KAAK,cAAc,SAAY,EAAE,WAAW,KAAK,UAAU,IAAI,CAAC;AAAA,EACtE,CAAC;AAED,QAAM,aAAa,SAAS,cAAc,CAAC;AAI3C,aAAW,KAAK,YAAY;AAC1B,QAAI;AACF,yBAAmB,EAAE,KAAK,SAAS,SA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