tenjin-cli 0.1.0-alpha.3 → 0.1.0-alpha.5

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 (157) hide show
  1. package/README.md +322 -197
  2. package/dist/{_esm-FEASBWRP.js → _esm-N4KAVXQR.js} +9 -9
  3. package/dist/buy-YMXXVNFH.js +42 -0
  4. package/dist/candidate-H7FR4AU5.js +22 -0
  5. package/dist/{ccip-XR5NE5QK.js → ccip-RPPPKTJR.js} +5 -5
  6. package/dist/{ccip-NQXCEK2U.js → ccip-ZGGWQN4X.js} +4 -4
  7. package/dist/{chunk-MUBUQVC3.js → chunk-2JQ5JSG6.js} +3 -2
  8. package/dist/{chunk-MUBUQVC3.js.map → chunk-2JQ5JSG6.js.map} +1 -1
  9. package/dist/{chunk-662MSGZB.js → chunk-3IRDP7TN.js} +100 -66
  10. package/dist/chunk-3IRDP7TN.js.map +1 -0
  11. package/dist/{chunk-YALGASEU.js → chunk-47PP7TAG.js} +1610 -1610
  12. package/dist/chunk-47PP7TAG.js.map +1 -0
  13. package/dist/{buy-EE6SEXP6.js → chunk-4WVKXKDK.js} +27 -59
  14. package/dist/chunk-4WVKXKDK.js.map +1 -0
  15. package/dist/chunk-5SCU253N.js +412 -0
  16. package/dist/chunk-5SCU253N.js.map +1 -0
  17. package/dist/{chunk-UGX7YPX2.js → chunk-7FK2UN2T.js} +65 -65
  18. package/dist/{chunk-UGX7YPX2.js.map → chunk-7FK2UN2T.js.map} +1 -1
  19. package/dist/chunk-ADJYSM45.js +135 -0
  20. package/dist/chunk-ADJYSM45.js.map +1 -0
  21. package/dist/{chunk-DXTQ3CSI.js → chunk-BIKAUVC2.js} +43 -11
  22. package/dist/chunk-BIKAUVC2.js.map +1 -0
  23. package/dist/{chunk-Z6MFJV5Z.js → chunk-C444K6MI.js} +266 -55
  24. package/dist/chunk-C444K6MI.js.map +1 -0
  25. package/dist/{chunk-JPHG2JW3.js → chunk-CVX6JNGD.js} +26 -26
  26. package/dist/chunk-CVX6JNGD.js.map +1 -0
  27. package/dist/{chunk-S3IGX57D.js → chunk-FU6MCSLG.js} +9 -9
  28. package/dist/{lookup-ZPN2Q67N.js → chunk-HTDALK7M.js} +46 -32
  29. package/dist/chunk-HTDALK7M.js.map +1 -0
  30. package/dist/chunk-IOPWPMT2.js +239 -0
  31. package/dist/chunk-IOPWPMT2.js.map +1 -0
  32. package/dist/{chunk-5CLSD5YN.js → chunk-KYQVEKP5.js} +7 -7
  33. package/dist/{chunk-RRN3YTK7.js → chunk-KZAAWQNP.js} +3 -3
  34. package/dist/{chunk-7KUW4MJD.js → chunk-L4IHCN6B.js} +11 -7
  35. package/dist/chunk-L4IHCN6B.js.map +1 -0
  36. package/dist/{chunk-XHC6FCGZ.js → chunk-LAM66WFJ.js} +25 -11
  37. package/dist/chunk-LAM66WFJ.js.map +1 -0
  38. package/dist/{chunk-NCE5NSN6.js → chunk-M2O56UK7.js} +158 -158
  39. package/dist/chunk-M2O56UK7.js.map +1 -0
  40. package/dist/{chunk-GO75V3NZ.js → chunk-MDDGEGSW.js} +8 -6
  41. package/dist/chunk-MDDGEGSW.js.map +1 -0
  42. package/dist/{chunk-XJIW7USF.js → chunk-MJZZTKCC.js} +112 -6
  43. package/dist/chunk-MJZZTKCC.js.map +1 -0
  44. package/dist/{chunk-Z52RA3NC.js → chunk-NFSOVL3C.js} +51 -21
  45. package/dist/chunk-NFSOVL3C.js.map +1 -0
  46. package/dist/{chunk-FJPLRISB.js → chunk-NJF2WENW.js} +5 -4
  47. package/dist/chunk-NJF2WENW.js.map +1 -0
  48. package/dist/{chunk-OYMYCW7J.js → chunk-PAUXMRSF.js} +45 -4
  49. package/dist/{chunk-OYMYCW7J.js.map → chunk-PAUXMRSF.js.map} +1 -1
  50. package/dist/{chunk-ZABPQJ3M.js → chunk-POJRB2AE.js} +2 -2
  51. package/dist/{publish-BKBQQAW4.js → chunk-PYNSGYBE.js} +254 -57
  52. package/dist/chunk-PYNSGYBE.js.map +1 -0
  53. package/dist/{chunk-YN5SHIXQ.js → chunk-QONTBYQW.js} +12 -9
  54. package/dist/chunk-QONTBYQW.js.map +1 -0
  55. package/dist/chunk-QW2Q2KAH.js +27 -0
  56. package/dist/chunk-QW2Q2KAH.js.map +1 -0
  57. package/dist/chunk-RTJLLPFA.js +599 -0
  58. package/dist/chunk-RTJLLPFA.js.map +1 -0
  59. package/dist/{chunk-CYOF7ROH.js → chunk-S5RYMCV6.js} +3 -3
  60. package/dist/chunk-TXPPMK4L.js +59 -0
  61. package/dist/chunk-TXPPMK4L.js.map +1 -0
  62. package/dist/{chunk-ZMHYXMO6.js → chunk-U5S527PP.js} +3 -3
  63. package/dist/{chunk-RY4XKNV3.js → chunk-UHTVXQ2O.js} +3 -3
  64. package/dist/{chunk-QVX5MWJZ.js → chunk-W6R3HAAG.js} +2 -2
  65. package/dist/{chunk-3OV7E5G5.js → chunk-WWX32ML4.js} +1 -1
  66. package/dist/{chunk-3OV7E5G5.js.map → chunk-WWX32ML4.js.map} +1 -1
  67. package/dist/{chunk-HIVZG55D.js → chunk-XJN5WUKL.js} +2 -2
  68. package/dist/{chunk-HSDCI7OV.js → chunk-YLYINX2H.js} +3 -3
  69. package/dist/{chunk-4ONXEEQL.js → chunk-ZDY2KY5X.js} +2 -2
  70. package/dist/{chunk-4ONXEEQL.js.map → chunk-ZDY2KY5X.js.map} +1 -1
  71. package/dist/{chunk-TLCMMYLY.js → chunk-ZIYVN4CD.js} +6 -6
  72. package/dist/chunk-ZIYVN4CD.js.map +1 -0
  73. package/dist/{candidate-ERMSYYQZ.js → chunk-ZW3B5LWX.js} +15 -19
  74. package/dist/{candidate-ERMSYYQZ.js.map → chunk-ZW3B5LWX.js.map} +1 -1
  75. package/dist/{cli-SBXI5AMS.js → cli-IW76QTN3.js} +64 -40
  76. package/dist/{cli-SBXI5AMS.js.map → cli-IW76QTN3.js.map} +1 -1
  77. package/dist/{config-VELDKLHY.js → config-VCOS7P5K.js} +8 -6
  78. package/dist/{doctor-T3KWNNP2.js → doctor-WS65JG3V.js} +9 -8
  79. package/dist/{ethersCompat-Df4a6QIZ-3YZIAXDK.js → ethersCompat-Df4a6QIZ-WHYKB6HA.js} +5 -5
  80. package/dist/index.js +1 -1
  81. package/dist/inspect-SFJWUQHO.js +33 -0
  82. package/dist/install-RVPQPCKH.js +589 -0
  83. package/dist/install-RVPQPCKH.js.map +1 -0
  84. package/dist/outcome-GNYCSZ7J.js +20 -0
  85. package/dist/publish-DSFWQRUN.js +36 -0
  86. package/dist/publish-DSFWQRUN.js.map +1 -0
  87. package/dist/run-OMPKA43G.js +16807 -0
  88. package/dist/run-OMPKA43G.js.map +1 -0
  89. package/dist/search-KOI6Y7P6.js +24 -0
  90. package/dist/search-KOI6Y7P6.js.map +1 -0
  91. package/dist/{secp256k1-N3ZHU7LB.js → secp256k1-XRPVBC6V.js} +3 -3
  92. package/dist/secp256k1-XRPVBC6V.js.map +1 -0
  93. package/dist/send-3G4C64HJ.js +222 -0
  94. package/dist/send-3G4C64HJ.js.map +1 -0
  95. package/dist/usdc-4VCDHFWX.js +38 -0
  96. package/dist/usdc-4VCDHFWX.js.map +1 -0
  97. package/dist/{viemAdapter-By13KInL-ZZE6UV4Y.js → viemAdapter-By13KInL-TUQJBMHM.js} +5 -5
  98. package/dist/viemAdapter-By13KInL-TUQJBMHM.js.map +1 -0
  99. package/dist/wallet-B7KJS2R5.js +40 -0
  100. package/dist/wallet-B7KJS2R5.js.map +1 -0
  101. package/dist/wallet-PP22LAX7.js +31 -0
  102. package/dist/wallet-PP22LAX7.js.map +1 -0
  103. package/package.json +4 -3
  104. package/skills/tenjin/SKILL.md +83 -15
  105. package/skills/tenjin-publish/SKILL.md +118 -18
  106. package/skills/tenjin-search/SKILL.md +149 -31
  107. package/dist/buy-EE6SEXP6.js.map +0 -1
  108. package/dist/chunk-662MSGZB.js.map +0 -1
  109. package/dist/chunk-7KUW4MJD.js.map +0 -1
  110. package/dist/chunk-AWPAWHNX.js +0 -333
  111. package/dist/chunk-AWPAWHNX.js.map +0 -1
  112. package/dist/chunk-DXTQ3CSI.js.map +0 -1
  113. package/dist/chunk-ESPNTPQ2.js +0 -207
  114. package/dist/chunk-ESPNTPQ2.js.map +0 -1
  115. package/dist/chunk-FJPLRISB.js.map +0 -1
  116. package/dist/chunk-GO75V3NZ.js.map +0 -1
  117. package/dist/chunk-JPHG2JW3.js.map +0 -1
  118. package/dist/chunk-NCE5NSN6.js.map +0 -1
  119. package/dist/chunk-TLCMMYLY.js.map +0 -1
  120. package/dist/chunk-XHC6FCGZ.js.map +0 -1
  121. package/dist/chunk-XJIW7USF.js.map +0 -1
  122. package/dist/chunk-YALGASEU.js.map +0 -1
  123. package/dist/chunk-YN5SHIXQ.js.map +0 -1
  124. package/dist/chunk-Z52RA3NC.js.map +0 -1
  125. package/dist/chunk-Z6MFJV5Z.js.map +0 -1
  126. package/dist/inspect-LMKOXE4Y.js +0 -96
  127. package/dist/inspect-LMKOXE4Y.js.map +0 -1
  128. package/dist/install-LEX3ENQ6.js +0 -387
  129. package/dist/install-LEX3ENQ6.js.map +0 -1
  130. package/dist/lookup-ZPN2Q67N.js.map +0 -1
  131. package/dist/outcome-N7TAK6WR.js +0 -66
  132. package/dist/outcome-N7TAK6WR.js.map +0 -1
  133. package/dist/publish-BKBQQAW4.js.map +0 -1
  134. package/dist/usdc-JIAJW4SV.js +0 -22
  135. package/dist/wallet-CWEMYVIH.js +0 -179
  136. package/dist/wallet-CWEMYVIH.js.map +0 -1
  137. package/dist/wallet-PA54CRBL.js +0 -30
  138. /package/dist/{_esm-FEASBWRP.js.map → _esm-N4KAVXQR.js.map} +0 -0
  139. /package/dist/{ccip-NQXCEK2U.js.map → buy-YMXXVNFH.js.map} +0 -0
  140. /package/dist/{ccip-XR5NE5QK.js.map → candidate-H7FR4AU5.js.map} +0 -0
  141. /package/dist/{config-VELDKLHY.js.map → ccip-RPPPKTJR.js.map} +0 -0
  142. /package/dist/{doctor-T3KWNNP2.js.map → ccip-ZGGWQN4X.js.map} +0 -0
  143. /package/dist/{chunk-S3IGX57D.js.map → chunk-FU6MCSLG.js.map} +0 -0
  144. /package/dist/{chunk-5CLSD5YN.js.map → chunk-KYQVEKP5.js.map} +0 -0
  145. /package/dist/{chunk-RRN3YTK7.js.map → chunk-KZAAWQNP.js.map} +0 -0
  146. /package/dist/{chunk-ZABPQJ3M.js.map → chunk-POJRB2AE.js.map} +0 -0
  147. /package/dist/{chunk-CYOF7ROH.js.map → chunk-S5RYMCV6.js.map} +0 -0
  148. /package/dist/{chunk-ZMHYXMO6.js.map → chunk-U5S527PP.js.map} +0 -0
  149. /package/dist/{chunk-RY4XKNV3.js.map → chunk-UHTVXQ2O.js.map} +0 -0
  150. /package/dist/{chunk-QVX5MWJZ.js.map → chunk-W6R3HAAG.js.map} +0 -0
  151. /package/dist/{chunk-HIVZG55D.js.map → chunk-XJN5WUKL.js.map} +0 -0
  152. /package/dist/{chunk-HSDCI7OV.js.map → chunk-YLYINX2H.js.map} +0 -0
  153. /package/dist/{ethersCompat-Df4a6QIZ-3YZIAXDK.js.map → config-VCOS7P5K.js.map} +0 -0
  154. /package/dist/{secp256k1-N3ZHU7LB.js.map → doctor-WS65JG3V.js.map} +0 -0
  155. /package/dist/{usdc-JIAJW4SV.js.map → ethersCompat-Df4a6QIZ-WHYKB6HA.js.map} +0 -0
  156. /package/dist/{viemAdapter-By13KInL-ZZE6UV4Y.js.map → inspect-SFJWUQHO.js.map} +0 -0
  157. /package/dist/{wallet-PA54CRBL.js.map → outcome-GNYCSZ7J.js.map} +0 -0
@@ -0,0 +1,42 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ runBuy
4
+ } from "./chunk-4WVKXKDK.js";
5
+ import "./chunk-BIKAUVC2.js";
6
+ import "./chunk-FU6MCSLG.js";
7
+ import "./chunk-POJRB2AE.js";
8
+ import "./chunk-QW2Q2KAH.js";
9
+ import "./chunk-C444K6MI.js";
10
+ import "./chunk-QONTBYQW.js";
11
+ import "./chunk-L4IHCN6B.js";
12
+ import "./chunk-CVX6JNGD.js";
13
+ import "./chunk-3IRDP7TN.js";
14
+ import "./chunk-WWX32ML4.js";
15
+ import "./chunk-ZDY2KY5X.js";
16
+ import "./chunk-NJF2WENW.js";
17
+ import "./chunk-NFSOVL3C.js";
18
+ import "./chunk-2I4QTOLB.js";
19
+ import "./chunk-KZAAWQNP.js";
20
+ import "./chunk-S5RYMCV6.js";
21
+ import "./chunk-YLYINX2H.js";
22
+ import "./chunk-MDDGEGSW.js";
23
+ import "./chunk-YBMMV4Y4.js";
24
+ import "./chunk-UO22YNY4.js";
25
+ import "./chunk-5SCU253N.js";
26
+ import "./chunk-2JQ5JSG6.js";
27
+ import "./chunk-PAUXMRSF.js";
28
+ import "./chunk-MJZZTKCC.js";
29
+ import "./chunk-7FK2UN2T.js";
30
+ import "./chunk-M2O56UK7.js";
31
+ import "./chunk-UHTVXQ2O.js";
32
+ import "./chunk-W6R3HAAG.js";
33
+ import "./chunk-U5S527PP.js";
34
+ import "./chunk-47PP7TAG.js";
35
+ import "./chunk-XJN5WUKL.js";
36
+ import "./chunk-RBJPAZFI.js";
37
+ import "./chunk-KYQVEKP5.js";
38
+ import "./chunk-ZXTAQYNA.js";
39
+ export {
40
+ runBuy
41
+ };
42
+ //# sourceMappingURL=buy-YMXXVNFH.js.map
@@ -0,0 +1,22 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ runCandidateAdd,
4
+ runCandidateDrop,
5
+ runCandidateList
6
+ } from "./chunk-ZW3B5LWX.js";
7
+ import "./chunk-ZIYVN4CD.js";
8
+ import "./chunk-WWX32ML4.js";
9
+ import "./chunk-NFSOVL3C.js";
10
+ import "./chunk-2I4QTOLB.js";
11
+ import "./chunk-MDDGEGSW.js";
12
+ import "./chunk-UO22YNY4.js";
13
+ import "./chunk-5SCU253N.js";
14
+ import "./chunk-2JQ5JSG6.js";
15
+ import "./chunk-PAUXMRSF.js";
16
+ import "./chunk-ZXTAQYNA.js";
17
+ export {
18
+ runCandidateAdd,
19
+ runCandidateDrop,
20
+ runCandidateList
21
+ };
22
+ //# sourceMappingURL=candidate-H7FR4AU5.js.map
@@ -4,11 +4,11 @@ import {
4
4
  offchainLookup,
5
5
  offchainLookupAbiItem,
6
6
  offchainLookupSignature
7
- } from "./chunk-ZMHYXMO6.js";
8
- import "./chunk-YALGASEU.js";
9
- import "./chunk-HIVZG55D.js";
7
+ } from "./chunk-U5S527PP.js";
8
+ import "./chunk-47PP7TAG.js";
9
+ import "./chunk-XJN5WUKL.js";
10
10
  import "./chunk-RBJPAZFI.js";
11
- import "./chunk-5CLSD5YN.js";
11
+ import "./chunk-KYQVEKP5.js";
12
12
  import "./chunk-ZXTAQYNA.js";
13
13
  export {
14
14
  ccipRequest,
@@ -16,4 +16,4 @@ export {
16
16
  offchainLookupAbiItem,
17
17
  offchainLookupSignature
18
18
  };
19
- //# sourceMappingURL=ccip-XR5NE5QK.js.map
19
+ //# sourceMappingURL=ccip-RPPPKTJR.js.map
@@ -4,10 +4,10 @@ import {
4
4
  offchainLookup,
5
5
  offchainLookupAbiItem,
6
6
  offchainLookupSignature
7
- } from "./chunk-RRN3YTK7.js";
8
- import "./chunk-HIVZG55D.js";
7
+ } from "./chunk-KZAAWQNP.js";
8
+ import "./chunk-XJN5WUKL.js";
9
9
  import "./chunk-RBJPAZFI.js";
10
- import "./chunk-5CLSD5YN.js";
10
+ import "./chunk-KYQVEKP5.js";
11
11
  import "./chunk-ZXTAQYNA.js";
12
12
  export {
13
13
  ccipRequest,
@@ -15,4 +15,4 @@ export {
15
15
  offchainLookupAbiItem,
16
16
  offchainLookupSignature
17
17
  };
18
- //# sourceMappingURL=ccip-NQXCEK2U.js.map
18
+ //# sourceMappingURL=ccip-ZGGWQN4X.js.map
@@ -62,6 +62,7 @@ async function fsyncDir(dir) {
62
62
 
63
63
  export {
64
64
  writeFileAtomic,
65
- writeFileAtomicExclusive
65
+ writeFileAtomicExclusive,
66
+ fsyncDir
66
67
  };
67
- //# sourceMappingURL=chunk-MUBUQVC3.js.map
68
+ //# sourceMappingURL=chunk-2JQ5JSG6.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/lib/atomic-json.ts"],"sourcesContent":["import { chmod, link, mkdir, open, rename, rm, writeFile } from 'node:fs/promises';\nimport { randomBytes } from 'node:crypto';\nimport { basename, dirname, join } from 'node:path';\n\n/** fs modes are no-ops on Windows; the 0600/0700 custody story does not apply. */\nconst isWindows = process.platform === 'win32';\n\nexport interface AtomicWriteOptions {\n /** Mode for the written file (ignored on win32). Default 0o644. */\n mode?: number;\n /** Mode for the parent dir when this call creates it (ignored on win32). Default 0o755. */\n dirMode?: number;\n}\n\n/**\n * Write `data` to `targetPath` atomically: a uniquely-named temp file is created\n * in the SAME directory (so the rename is atomic — a cross-filesystem rename is\n * not), given the final mode at open time, then renamed over the target. A\n * reader therefore sees either the old file or the fully-written new one, never\n * a partial write.\n *\n * The temp file is born with the caller's `mode` (0o600 for a wallet key) so the\n * bytes are never written through a world-readable descriptor; the follow-up\n * chmod only makes the mode exact under an unusual umask and only ever touches\n * the temp path, so the live target still appears atomically at its final mode.\n */\nexport async function writeFileAtomic(\n targetPath: string,\n data: string | Buffer,\n opts: AtomicWriteOptions = {},\n): Promise<void> {\n const dir = dirname(targetPath);\n const fileMode = opts.mode ?? 0o644;\n const dirMode = opts.dirMode ?? 0o755;\n\n await mkdir(dir, { recursive: true, ...(isWindows ? {} : { mode: dirMode }) });\n\n const tmpPath = join(dir, `.${basename(targetPath)}.${randomBytes(6).toString('hex')}.tmp`);\n try {\n await writeFile(tmpPath, data, isWindows ? undefined : { mode: fileMode });\n if (!isWindows) await chmod(tmpPath, fileMode);\n await rename(tmpPath, targetPath);\n } catch (err) {\n await rm(tmpPath, { force: true }).catch(() => undefined);\n throw err;\n }\n}\n\n/**\n * Like {@link writeFileAtomic} but NO-CLOBBER and crash-durable: the commit fails\n * with `EEXIST` when `targetPath` already exists instead of replacing it, and the\n * new entry is fsynced before returning. This is what a wallet key needs — two\n * concurrent `create`/`import` runs must not both \"succeed\" and silently lose one\n * key; the loser gets a distinguishable EEXIST the wallet layer maps to\n * WALLET_EXISTS.\n *\n * The temp file is fsynced, then `link()` commits it — link is atomic and throws\n * EEXIST if the target already exists, so the check-then-write race is closed at\n * the filesystem, not by an earlier stat. The parent dir is then fsynced so the\n * new entry survives a crash. On win32, link semantics differ and a directory\n * cannot be fsynced, so we fall back to an exclusive `wx` open (still atomic\n * create-or-EEXIST, just not crash-durable — win32 has no 0600 custody story to\n * protect anyway).\n */\nexport async function writeFileAtomicExclusive(\n targetPath: string,\n data: string,\n opts: AtomicWriteOptions = {},\n): Promise<void> {\n const dir = dirname(targetPath);\n const fileMode = opts.mode ?? 0o644;\n const dirMode = opts.dirMode ?? 0o755;\n\n await mkdir(dir, { recursive: true, ...(isWindows ? {} : { mode: dirMode }) });\n\n if (isWindows) {\n const handle = await open(targetPath, 'wx');\n try {\n await handle.writeFile(data);\n await handle.sync();\n } finally {\n await handle.close();\n }\n return;\n }\n\n const tmpPath = join(dir, `.${basename(targetPath)}.${randomBytes(6).toString('hex')}.tmp`);\n try {\n const handle = await open(tmpPath, 'wx', fileMode);\n try {\n await handle.writeFile(data);\n await handle.chmod(fileMode); // exact mode even under an unusual umask\n await handle.sync();\n } finally {\n await handle.close();\n }\n await link(tmpPath, targetPath); // atomic; throws EEXIST when the target exists\n await fsyncDir(dir);\n } finally {\n // On success the temp is now a redundant link to the target; on EEXIST it is\n // the orphaned write. Either way remove it before returning/throwing.\n await rm(tmpPath, { force: true }).catch(() => undefined);\n }\n}\n\n/** fsync a directory so a freshly linked entry is durable. Never called on win32. */\nasync function fsyncDir(dir: string): Promise<void> {\n const handle = await open(dir, 'r');\n try {\n await handle.sync();\n } finally {\n await handle.close();\n }\n}\n"],"mappings":";;;AAAA,SAAS,OAAO,MAAM,OA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AAC,IAAI,YAAY,CAAC,EAAE,SAAS,KAAK,CAAC,MAAM;AAC1F,MAAI;AACF,UAAM,SAAS,MAAM,KAAK,SAAS,MAAM,QAAQ;AACjD,QAAI;AACF,YAAM,OAAO,UAAU,IAAI;AAC3B,YAAM,OAAO,MAAM,QAAQ;AAC3B,YAAM,OAAO,KAAK;AAAA,IACpB,UAAE;AACA,YAAM,OAAO,MAAM;AAAA,IACrB;AACA,UAAM,KAAK,SAAS,UAAU;AAC9B,UAAM,SAAS,GAAG;AAAA,EACpB,UAAE;AAGA,UAAM,GAAG,SAAS,EAAE,OAAO,KAAK,CAAC,EAAE,MAAM,MAAM,MAAS;AAAA,EAC1D;AACF;AAGA,eAAe,SAAS,KAA4B;AAClD,QAAM,SAAS,MAAM,KAAK,KAAK,GAAG;AAClC,MAAI;AACF,UAAM,OAAO,KAAK;AAAA,EACpB,UAAE;AACA,UAAM,OAAO,MAAM;AAAA,EACrB;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/lib/atomic-json.ts"],"sourcesContent":["import { chmod, link, mkdir, open, rename, rm, writeFile } from 'node:fs/promises';\nimport { randomBytes } from 'node:crypto';\nimport { basename, dirname, join } from 'node:path';\n\n/** fs modes are no-ops on Windows; the 0600/0700 custody story does not apply. */\nconst isWindows = process.platform === 'win32';\n\nexport interface AtomicWriteOptions {\n /** Mode for the written file (ignored on win32). Default 0o644. */\n mode?: number;\n /** Mode for the parent dir when this call creates it (ignored on win32). Default 0o755. */\n dirMode?: number;\n}\n\n/**\n * Write `data` to `targetPath` atomically: a uniquely-named temp file is created\n * in the SAME directory (so the rename is atomic — a cross-filesystem rename is\n * not), given the final mode at open time, then renamed over the target. A\n * reader therefore sees either the old file or the fully-written new one, never\n * a partial write.\n *\n * The temp file is born with the caller's `mode` (0o600 for a wallet key) so the\n * bytes are never written through a world-readable descriptor; the follow-up\n * chmod only makes the mode exact under an unusual umask and only ever touches\n * the temp path, so the live target still appears atomically at its final mode.\n */\nexport async function writeFileAtomic(\n targetPath: string,\n data: string | Buffer,\n opts: AtomicWriteOptions = {},\n): Promise<void> {\n const dir = dirname(targetPath);\n const fileMode = opts.mode ?? 0o644;\n const dirMode = opts.dirMode ?? 0o755;\n\n await mkdir(dir, { recursive: true, ...(isWindows ? {} : { mode: dirMode }) });\n\n const tmpPath = join(dir, `.${basename(targetPath)}.${randomBytes(6).toString('hex')}.tmp`);\n try {\n await writeFile(tmpPath, data, isWindows ? undefined : { mode: fileMode });\n if (!isWindows) await chmod(tmpPath, fileMode);\n await rename(tmpPath, targetPath);\n } catch (err) {\n await rm(tmpPath, { force: true }).catch(() => undefined);\n throw err;\n }\n}\n\n/**\n * Like {@link writeFileAtomic} but NO-CLOBBER and crash-durable: the commit fails\n * with `EEXIST` when `targetPath` already exists instead of replacing it, and the\n * new entry is fsynced before returning. This is what a wallet key needs — two\n * concurrent `create`/`import` runs must not both \"succeed\" and silently lose one\n * key; the loser gets a distinguishable EEXIST the wallet layer maps to\n * WALLET_EXISTS.\n *\n * The temp file is fsynced, then `link()` commits it — link is atomic and throws\n * EEXIST if the target already exists, so the check-then-write race is closed at\n * the filesystem, not by an earlier stat. The parent dir is then fsynced so the\n * new entry survives a crash. On win32, link semantics differ and a directory\n * cannot be fsynced, so we fall back to an exclusive `wx` open (still atomic\n * create-or-EEXIST, just not crash-durable — win32 has no 0600 custody story to\n * protect anyway).\n */\nexport async function writeFileAtomicExclusive(\n targetPath: string,\n data: string,\n opts: AtomicWriteOptions = {},\n): Promise<void> {\n const dir = dirname(targetPath);\n const fileMode = opts.mode ?? 0o644;\n const dirMode = opts.dirMode ?? 0o755;\n\n await mkdir(dir, { recursive: true, ...(isWindows ? {} : { mode: dirMode }) });\n\n if (isWindows) {\n const handle = await open(targetPath, 'wx');\n try {\n await handle.writeFile(data);\n await handle.sync();\n } finally {\n await handle.close();\n }\n return;\n }\n\n const tmpPath = join(dir, `.${basename(targetPath)}.${randomBytes(6).toString('hex')}.tmp`);\n try {\n const handle = await open(tmpPath, 'wx', fileMode);\n try {\n await handle.writeFile(data);\n await handle.chmod(fileMode); // exact mode even under an unusual umask\n await handle.sync();\n } finally {\n await handle.close();\n }\n await link(tmpPath, targetPath); // atomic; throws EEXIST when the target exists\n await fsyncDir(dir);\n } finally {\n // On success the temp is now a redundant link to the target; on EEXIST it is\n // the orphaned write. Either way remove it before returning/throwing.\n await rm(tmpPath, { force: true }).catch(() => undefined);\n }\n}\n\n/** fsync a directory so a freshly linked entry is durable. Never call on win32. */\nexport async function fsyncDir(dir: string): Promise<void> {\n const handle = await open(dir, 'r');\n try {\n await handle.sync();\n } finally {\n await handle.close();\n }\n}\n"],"mappings":";;;AAAA,SAAS,OAAO,MAAM,OAAO,MAAM,QAAQ,IAAI,iBAAiB;AAChE,SAAS,mBAAmB;AAC5B,SAAS,UAAU,SAAS,YAAY;AAGxC,IAAM,YAAY,QAAQ,aAAa;AAqBvC,eAAsB,gBACpB,YACA,MACA,OAA2B,CAAC,GACb;AACf,QAAM,MAAM,QAAQ,UAAU;AAC9B,QAAM,WAAW,KAAK,QAAQ;AAC9B,QAAM,UAAU,KAAK,WAAW;AAEhC,QAAM,MAAM,KAAK,EAAE,WAAW,MAAM,GAAI,YAAY,CAAC,IAAI,EAAE,MAAM,QAAQ,EAAG,CAAC;AAE7E,QAAM,UAAU,KAAK,KAAK,IAAI,SAAS,UAAU,CAAC,IAAI,YAAY,CAAC,EAAE,SAAS,KAAK,CAAC,MAAM;AAC1F,MAAI;AACF,UAAM,UAAU,SAAS,MAAM,YAAY,SAAY,EAAE,MAAM,SAAS,CAAC;AACzE,QAAI,CAAC,UAAW,OAAM,MAAM,SAAS,QAAQ;AAC7C,UAAM,OAAO,SAAS,UAAU;AAAA,EAClC,SAAS,KAAK;AACZ,UAAM,GAAG,SAAS,EAAE,OAAO,KAAK,CAAC,EAAE,MAAM,MAAM,MAAS;AACxD,UAAM;AAAA,EACR;AACF;AAkBA,eAAsB,yBACpB,YACA,MACA,OAA2B,CAAC,GACb;AACf,QAAM,MAAM,QAAQ,UAAU;AAC9B,QAAM,WAAW,KAAK,QAAQ;AAC9B,QAAM,UAAU,KAAK,WAAW;AAEhC,QAAM,MAAM,KAAK,EAAE,WAAW,MAAM,GAAI,YAAY,CAAC,IAAI,EAAE,MAAM,QAAQ,EAAG,CAAC;AAE7E,MAAI,WAAW;AACb,UAAM,SAAS,MAAM,KAAK,YAAY,IAAI;AAC1C,QAAI;AACF,YAAM,OAAO,UAAU,IAAI;AAC3B,YAAM,OAAO,KAAK;AAAA,IACpB,UAAE;AACA,YAAM,OAAO,MAAM;AAAA,IACrB;AACA;AAAA,EACF;AAEA,QAAM,UAAU,KAAK,KAAK,IAAI,SAAS,UAAU,CAAC,IAAI,YAAY,CAAC,EAAE,SAAS,KAAK,CAAC,MAAM;AAC1F,MAAI;AACF,UAAM,SAAS,MAAM,KAAK,SAAS,MAAM,QAAQ;AACjD,QAAI;AACF,YAAM,OAAO,UAAU,IAAI;AAC3B,YAAM,OAAO,MAAM,QAAQ;AAC3B,YAAM,OAAO,KAAK;AAAA,IACpB,UAAE;AACA,YAAM,OAAO,MAAM;AAAA,IACrB;AACA,UAAM,KAAK,SAAS,UAAU;AAC9B,UAAM,SAAS,GAAG;AAAA,EACpB,UAAE;AAGA,UAAM,GAAG,SAAS,EAAE,OAAO,KAAK,CAAC,EAAE,MAAM,MAAM,MAAS;AAAA,EAC1D;AACF;AAGA,eAAsB,SAAS,KAA4B;AACzD,QAAM,SAAS,MAAM,KAAK,KAAK,GAAG;AAClC,MAAI;AACF,UAAM,OAAO,KAAK;AAAA,EACpB,UAAE;AACA,UAAM,OAAO,MAAM;AAAA,EACrB;AACF;","names":[]}
@@ -2,21 +2,22 @@ import { createRequire as __tenjinCreateRequire } from 'node:module'; const requ
2
2
  import {
3
3
  ATOMIC_RE,
4
4
  UUID_RE
5
- } from "./chunk-3OV7E5G5.js";
5
+ } from "./chunk-WWX32ML4.js";
6
6
  import {
7
7
  CLIENT_HEADER,
8
8
  httpRequest,
9
9
  trimSlash
10
- } from "./chunk-4ONXEEQL.js";
10
+ } from "./chunk-ZDY2KY5X.js";
11
11
  import {
12
12
  CliError,
13
13
  external_exports
14
- } from "./chunk-OYMYCW7J.js";
14
+ } from "./chunk-PAUXMRSF.js";
15
15
 
16
16
  // src/lib/agent-api.ts
17
17
  var FRESH_WITHIN_RE = /^P(\d+)[DWMY]$/;
18
18
  var CANONICAL_KEY_RE = /^[a-z][a-z0-9_]{0,31}$/;
19
- function buildLookupRequest(input) {
19
+ var MAX_LIMIT = 10;
20
+ function buildSearchRequest(input) {
20
21
  const question = input.question.trim();
21
22
  if (question.length === 0 || question.length > 512) {
22
23
  throw new CliError("USAGE", "question must be 1 to 512 characters", {
@@ -37,9 +38,9 @@ function buildLookupRequest(input) {
37
38
  });
38
39
  }
39
40
  const limit = input.limit ?? 5;
40
- if (!Number.isInteger(limit) || limit < 1 || limit > 10) {
41
+ if (!Number.isInteger(limit) || limit < 1 || limit > MAX_LIMIT) {
41
42
  throw new CliError("USAGE", `Invalid --limit: ${JSON.stringify(input.limit)}`, {
42
- fix: "Pass an integer between 1 and 10."
43
+ fix: `Pass an integer between 1 and ${MAX_LIMIT}.`
43
44
  });
44
45
  }
45
46
  if (input.appliesTo !== void 0) {
@@ -72,7 +73,7 @@ function buildLookupRequest(input) {
72
73
  }
73
74
  }
74
75
  return {
75
- schemaVersion: 1,
76
+ schemaVersion: 2,
76
77
  question,
77
78
  ...input.freshWithin !== void 0 ? { freshWithin: input.freshWithin } : {},
78
79
  ...input.maxPrice !== void 0 ? { maxPrice: input.maxPrice } : {},
@@ -80,35 +81,49 @@ function buildLookupRequest(input) {
80
81
  limit
81
82
  };
82
83
  }
83
- var lookupCandidateSchema = external_exports.object({
84
+ var searchCandidateSchema = external_exports.object({
84
85
  resourceId: external_exports.string().regex(UUID_RE, "resourceId must be a uuid"),
85
86
  url: external_exports.string(),
87
+ slug: external_exports.string(),
86
88
  title: external_exports.string(),
87
89
  artifactType: external_exports.string(),
88
90
  price: external_exports.string().regex(ATOMIC_RE, "price must be an atomic integer string"),
89
91
  asOf: external_exports.string().nullable(),
90
92
  validUntil: external_exports.string().nullable(),
91
- temporalMode: external_exports.string(),
92
- appliesTo: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())),
93
- questionsAnswered: external_exports.array(external_exports.string()),
94
- tasksSupported: external_exports.array(external_exports.string()),
95
- scope: external_exports.string().nullable(),
96
- exclusions: external_exports.string().nullable(),
97
93
  matchReasons: external_exports.array(external_exports.string()),
98
94
  estimatedTokens: external_exports.number(),
99
95
  creator: external_exports.object({ handle: external_exports.string() }).passthrough()
100
96
  }).passthrough();
101
- var lookupResponseSchema = external_exports.object({
102
- schemaVersion: external_exports.literal(1),
103
- lookupId: external_exports.string().regex(UUID_RE, "lookupId must be a uuid"),
97
+ var BROWSE_BOUNDS = { title: 200, url: 512, handle: 64 };
98
+ var searchBrowseSchema = external_exports.object({
99
+ resourceId: external_exports.string().regex(UUID_RE, "resourceId must be a uuid"),
100
+ url: external_exports.string().max(BROWSE_BOUNDS.url, `url must be at most ${BROWSE_BOUNDS.url} characters`),
101
+ title: external_exports.string(),
102
+ price: external_exports.string().regex(ATOMIC_RE, "price must be an atomic integer string"),
103
+ creator: external_exports.object({ handle: external_exports.string() }).passthrough()
104
+ }).passthrough();
105
+ var searchResponseSchema = external_exports.object({
106
+ schemaVersion: external_exports.literal(2),
107
+ searchId: external_exports.string().regex(UUID_RE, "searchId must be a uuid"),
104
108
  decision: external_exports.enum(["CANDIDATES", "MISS"]),
105
109
  calibration: external_exports.string(),
106
- candidates: external_exports.array(lookupCandidateSchema).optional()
110
+ candidates: external_exports.array(searchCandidateSchema).optional(),
111
+ // Set only when the server's size backstop dropped trailing candidates the
112
+ // requested limit had room for; omitted entirely otherwise. There is no cursor,
113
+ // so a retry at a SMALLER limit returns strictly fewer rows; the ceiling scales
114
+ // with the candidates returned, so a LARGER limit (up to MAX_LIMIT) is what
115
+ // recovers the tail, and at MAX_LIMIT the tail is unrecoverable and narrowing the
116
+ // question is the remedy. `runSearch` picks the half that applies.
117
+ truncated: external_exports.literal(true).optional(),
118
+ // Omitted entirely by the server when empty, and only ever present on a MISS.
119
+ // Not enforced here (a stricter schema would reject an otherwise-usable
120
+ // response); truncateResponse drops it on a CANDIDATES decision instead.
121
+ browse: external_exports.array(searchBrowseSchema).optional()
107
122
  });
108
123
  function apiFailure(url, result) {
109
124
  const code = result.kind === "network" || result.kind === "timeout" ? "NETWORK_ERROR" : "API_UNREACHABLE";
110
125
  return new CliError(code, `${url}: ${result.message}`, {
111
- fix: "Check --base-url and your network, then retry."
126
+ fix: "Check your network and the configured base URL (`tenjin config get baseUrl`), then retry."
112
127
  });
113
128
  }
114
129
  function rateLimitError(url, header) {
@@ -134,8 +149,8 @@ function serverErrorMessage(json) {
134
149
  }
135
150
  return void 0;
136
151
  }
137
- async function postLookup(body, opts) {
138
- const url = `${trimSlash(opts.baseUrl)}/api/agent/lookup`;
152
+ async function postSearch(body, opts) {
153
+ const url = `${trimSlash(opts.baseUrl)}/api/agent/search`;
139
154
  const res = await httpRequest(url, {
140
155
  method: "POST",
141
156
  timeoutMs: opts.timeoutMs,
@@ -149,64 +164,82 @@ async function postLookup(body, opts) {
149
164
  if (!res.ok) throw apiFailure(url, res);
150
165
  if (res.status === 429) throw rateLimitError(url, (n) => res.header(n));
151
166
  if (res.status !== 200) {
167
+ if (res.status === 400 && rejectedSchemaVersion(res.json)) {
168
+ throw outdatedServerError("The server rejected schemaVersion 2: it predates search v2.", {
169
+ details: res.json
170
+ });
171
+ }
152
172
  throw new CliError(
153
173
  "API_UNREACHABLE",
154
- serverErrorMessage(res.json) ?? `Lookup failed (${res.status})`,
174
+ serverErrorMessage(res.json) ?? `Search failed (${res.status})`,
155
175
  {
156
- fix: "Retry; if it persists the lookup endpoint may be unavailable.",
176
+ fix: "Retry; if it persists the search endpoint may be unavailable.",
157
177
  details: res.json
158
178
  }
159
179
  );
160
180
  }
161
- const parsed = lookupResponseSchema.safeParse(res.json);
181
+ const parsed = searchResponseSchema.safeParse(res.json);
162
182
  if (!parsed.success) {
163
- throw new CliError("CONTRACT_MISMATCH", "Lookup response did not match the expected contract", {
183
+ const served = serverSchemaVersion(res.json);
184
+ if (served !== void 0 && served !== 2) {
185
+ throw outdatedServerError(
186
+ `Search response is schemaVersion ${served}; this CLI requires 2 (search v2).`,
187
+ { details: parsed.error.issues }
188
+ );
189
+ }
190
+ throw new CliError("CONTRACT_MISMATCH", "Search response did not match the expected contract", {
164
191
  fix: "Update tenjin-cli; the server contract may have changed.",
165
192
  details: parsed.error.issues
166
193
  });
167
194
  }
168
195
  return truncateResponse(parsed.data);
169
196
  }
197
+ function outdatedServerError(message, opts) {
198
+ return new CliError("CONTRACT_MISMATCH", message, {
199
+ fix: "The server predates search v2. Point the configured base URL (`tenjin config set baseUrl`) at an updated deployment, or install an older tenjin-cli.",
200
+ details: opts.details
201
+ });
202
+ }
203
+ function rejectedSchemaVersion(json) {
204
+ const record = (v) => typeof v === "object" && v !== null ? v : void 0;
205
+ const fieldErrors = record(record(record(json)?.error)?.details)?.fieldErrors;
206
+ return Array.isArray(record(fieldErrors)?.schemaVersion);
207
+ }
208
+ function serverSchemaVersion(json) {
209
+ if (typeof json !== "object" || json === null) return void 0;
210
+ const v = json.schemaVersion;
211
+ return typeof v === "number" ? v : void 0;
212
+ }
170
213
  var CAND_BOUNDS = {
171
214
  title: 200,
172
- scope: 240,
173
- exclusions: 240,
174
- listItems: 4,
175
- listItemChars: 160,
176
215
  matchReasons: 3,
177
- matchReasonChars: 80,
178
- appliesToKeys: 6,
179
- appliesToValues: 5,
180
- appliesToValueChars: 80
216
+ matchReasonChars: 80
181
217
  };
218
+ var cap = (s, n) => s.length > n ? s.slice(0, n) : s;
182
219
  function truncateResponse(res) {
183
- if (res.candidates === void 0) return res;
184
- return { ...res, candidates: res.candidates.map(truncateCandidate) };
220
+ const out = { ...res };
221
+ if (res.candidates !== void 0) out.candidates = res.candidates.map(truncateCandidate);
222
+ if (res.browse !== void 0 && res.decision === "MISS") {
223
+ out.browse = res.browse.slice(0, BROWSE_MAX).map((b) => ({
224
+ resourceId: b.resourceId,
225
+ // Not capped: the schema already refused anything over BROWSE_BOUNDS.url,
226
+ // so this is the url the server sent, verbatim and payable.
227
+ url: b.url,
228
+ title: cap(b.title, BROWSE_BOUNDS.title),
229
+ price: b.price,
230
+ creator: { handle: cap(b.creator.handle, BROWSE_BOUNDS.handle) }
231
+ }));
232
+ } else {
233
+ delete out.browse;
234
+ }
235
+ return out;
185
236
  }
237
+ var BROWSE_MAX = 3;
186
238
  function truncateCandidate(c) {
187
- const cap = (s, n) => s.length > n ? s.slice(0, n) : s;
188
- const capList = (list, items, chars) => list.slice(0, items).map((s) => cap(s, chars));
189
- const appliesTo = {};
190
- for (const key of Object.keys(c.appliesTo).slice(0, CAND_BOUNDS.appliesToKeys)) {
191
- appliesTo[cap(key, CAND_BOUNDS.appliesToValueChars)] = capList(
192
- c.appliesTo[key] ?? [],
193
- CAND_BOUNDS.appliesToValues,
194
- CAND_BOUNDS.appliesToValueChars
195
- );
196
- }
197
239
  return {
198
240
  ...c,
199
241
  title: cap(c.title, CAND_BOUNDS.title),
200
- scope: c.scope === null ? null : cap(c.scope, CAND_BOUNDS.scope),
201
- exclusions: c.exclusions === null ? null : cap(c.exclusions, CAND_BOUNDS.exclusions),
202
- questionsAnswered: capList(
203
- c.questionsAnswered,
204
- CAND_BOUNDS.listItems,
205
- CAND_BOUNDS.listItemChars
206
- ),
207
- tasksSupported: capList(c.tasksSupported, CAND_BOUNDS.listItems, CAND_BOUNDS.listItemChars),
208
- matchReasons: capList(c.matchReasons, CAND_BOUNDS.matchReasons, CAND_BOUNDS.matchReasonChars),
209
- appliesTo
242
+ matchReasons: c.matchReasons.slice(0, CAND_BOUNDS.matchReasons).map((r) => cap(r, CAND_BOUNDS.matchReasonChars))
210
243
  };
211
244
  }
212
245
  var OUTCOME_STATUSES = [
@@ -226,7 +259,7 @@ function buildOutcomeItem(input) {
226
259
  }
227
260
  if (input.resourceId !== void 0 && !UUID_RE.test(input.resourceId)) {
228
261
  throw new CliError("USAGE", `Invalid --resource id: ${JSON.stringify(input.resourceId)}`, {
229
- fix: "Pass the resourceId (a uuid) from a lookup candidate."
262
+ fix: "Pass the resourceId (a uuid) from a search candidate."
230
263
  });
231
264
  }
232
265
  if (input.contentHash !== void 0 && !CONTENT_HASH_RE.test(input.contentHash)) {
@@ -240,11 +273,11 @@ function buildOutcomeItem(input) {
240
273
  ...input.contentHash !== void 0 ? { contentHash: input.contentHash } : {}
241
274
  };
242
275
  }
243
- var LOOKUP_ID_RE = UUID_RE;
244
- async function postOutcomes(lookupId, items, opts) {
245
- if (!LOOKUP_ID_RE.test(lookupId)) {
246
- throw new CliError("USAGE", `Invalid lookup id: ${JSON.stringify(lookupId)}`, {
247
- fix: "Pass the lookupId from a prior lookup (or use --last)."
276
+ var SEARCH_ID_RE = UUID_RE;
277
+ async function postOutcomes(searchId, items, opts) {
278
+ if (!SEARCH_ID_RE.test(searchId)) {
279
+ throw new CliError("USAGE", `Invalid search id: ${JSON.stringify(searchId)}`, {
280
+ fix: "Pass the searchId from a prior search (or use --last)."
248
281
  });
249
282
  }
250
283
  if (items.length === 0 || items.length > 10) {
@@ -252,7 +285,7 @@ async function postOutcomes(lookupId, items, opts) {
252
285
  fix: "Report between 1 and 10 outcomes per call."
253
286
  });
254
287
  }
255
- const url = `${trimSlash(opts.baseUrl)}/api/agent/lookups/${lookupId}/outcomes`;
288
+ const url = `${trimSlash(opts.baseUrl)}/api/agent/searches/${searchId}/outcomes`;
256
289
  const res = await httpRequest(url, {
257
290
  method: "POST",
258
291
  timeoutMs: opts.timeoutMs,
@@ -267,7 +300,7 @@ async function postOutcomes(lookupId, items, opts) {
267
300
  "API_UNREACHABLE",
268
301
  serverErrorMessage(res.json) ?? `Outcome report failed (${res.status})`,
269
302
  {
270
- fix: "Check the status vocabulary and lookup id, then retry.",
303
+ fix: "Check the status vocabulary and search id, then retry.",
271
304
  details: res.json
272
305
  }
273
306
  );
@@ -277,10 +310,11 @@ async function postOutcomes(lookupId, items, opts) {
277
310
  }
278
311
 
279
312
  export {
280
- buildLookupRequest,
313
+ MAX_LIMIT,
314
+ buildSearchRequest,
281
315
  rateLimitError,
282
- postLookup,
316
+ postSearch,
283
317
  buildOutcomeItem,
284
318
  postOutcomes
285
319
  };
286
- //# sourceMappingURL=chunk-662MSGZB.js.map
320
+ //# sourceMappingURL=chunk-3IRDP7TN.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/agent-api.ts"],"sourcesContent":["import { z } from 'zod';\nimport { CliError } from './errors';\nimport { httpRequest, type HttpResult } from './http';\nimport { CLIENT_HEADER } from './client-meta';\nimport { ATOMIC_RE, UUID_RE } from './ids';\nimport { trimSlash } from './url';\n\n/**\n * The search + outcome HTTP contract (A2, tenjin#370). Request building and\n * response validation live here; the wire shape is validated defensively, an\n * unknown `schemaVersion` degrades to a parse refusal rather than a guess, and\n * unrecognized candidate fields are ignored (forward-compatible), per spec 10.\n *\n * These endpoints are anonymous: no wallet, no SIWX. The only header of note is\n * `X-Tenjin-Client`, which attributes a later purchase back to the search flow.\n */\n\nconst FRESH_WITHIN_RE = /^P(\\d+)[DWMY]$/;\nconst CANONICAL_KEY_RE = /^[a-z][a-z0-9_]{0,31}$/;\n\n/** The server's `limit` ceiling. Exported because the truncation advice in\n * `search` has to name it: past search v2 the response budget scales with the\n * candidates returned, so a truncated page is recovered by asking for MORE, and\n * this is the value to ask for. One definition, so the cap the CLI enforces and\n * the number it tells the operator to retry with cannot drift apart. */\nexport const MAX_LIMIT = 10;\n\n/** Client-side search request (mirrors the server lookupRequestSchema bounds\n * so a malformed flag fails locally as USAGE, before a round trip). */\nexport interface SearchInput {\n question: string;\n freshWithin?: string;\n maxPrice?: string;\n appliesTo?: Record<string, string[]>;\n limit?: number;\n}\n\nexport interface SearchRequestBody {\n schemaVersion: 2;\n question: string;\n freshWithin?: string;\n maxPrice?: string;\n appliesTo?: Record<string, string[]>;\n limit: number;\n}\n\nexport function buildSearchRequest(input: SearchInput): SearchRequestBody {\n const question = input.question.trim();\n if (question.length === 0 || question.length > 512) {\n throw new CliError('USAGE', 'question must be 1 to 512 characters', {\n fix: 'Pass a non-empty question under 512 characters.',\n });\n }\n if (input.freshWithin !== undefined) {\n // The server rejects ANY zero-valued duration (P0D, P0W, P00M, ...), so a\n // zero window fails here as USAGE instead of a remote 400.\n const digits = FRESH_WITHIN_RE.exec(input.freshWithin)?.[1];\n if (digits === undefined || Number(digits) === 0) {\n throw new CliError('USAGE', `Invalid --fresh-within: ${JSON.stringify(input.freshWithin)}`, {\n fix: 'Use a nonzero ISO-like window P<n>[DWMY], e.g. P30D, P2W, P1Y.',\n });\n }\n }\n if (input.maxPrice !== undefined && !ATOMIC_RE.test(input.maxPrice)) {\n throw new CliError('USAGE', `Invalid --max-price: ${JSON.stringify(input.maxPrice)}`, {\n fix: 'Pass an atomic USDC integer, e.g. 100000 for $0.10.',\n });\n }\n const limit = input.limit ?? 5;\n if (!Number.isInteger(limit) || limit < 1 || limit > MAX_LIMIT) {\n throw new CliError('USAGE', `Invalid --limit: ${JSON.stringify(input.limit)}`, {\n fix: `Pass an integer between 1 and ${MAX_LIMIT}.`,\n });\n }\n if (input.appliesTo !== undefined) {\n // Mirror the server's strictObject bounds (<=8 keys, <=20 values/key,\n // 1..120 chars/value) so a bad filter fails locally, never as a remote 400.\n const keys = Object.keys(input.appliesTo);\n if (keys.length > 8) {\n throw new CliError('USAGE', 'Too many --applies-to keys (max 8).');\n }\n for (const [key, values] of Object.entries(input.appliesTo)) {\n if (!CANONICAL_KEY_RE.test(key)) {\n throw new CliError('USAGE', `Invalid appliesTo key: ${JSON.stringify(key)}`, {\n fix: 'Keys must be canonical lowercase identifiers, e.g. products=Vercel.',\n });\n }\n if (values.length === 0) {\n throw new CliError('USAGE', `appliesTo key ${JSON.stringify(key)} has no values`, {\n fix: 'Give each --applies-to key at least one value.',\n });\n }\n if (values.length > 20) {\n throw new CliError('USAGE', `Too many --applies-to values for ${key} (max 20).`);\n }\n for (const value of values) {\n if (value.length === 0 || value.length > 120) {\n throw new CliError(\n 'USAGE',\n `Invalid --applies-to value for ${key}: must be 1 to 120 characters.`,\n );\n }\n }\n }\n }\n return {\n schemaVersion: 2,\n question,\n ...(input.freshWithin !== undefined ? { freshWithin: input.freshWithin } : {}),\n ...(input.maxPrice !== undefined ? { maxPrice: input.maxPrice } : {}),\n ...(input.appliesTo !== undefined ? { appliesTo: input.appliesTo } : {}),\n limit,\n };\n}\n\n// Response schemas. `.passthrough()` on the candidate keeps unknown future fields\n// instead of stripping them (forward-compatible), while still requiring the\n// contract fields this CLI reads. `decision` is uppercase on the wire.\n//\n// A candidate is a LEAN hit (search v2): identity, price, freshness and why it\n// matched, and nothing more. The full answer card is one free unpaid GET of `url`\n// away, which is what `tenjin inspect` does, so breadth here costs no depth there.\nexport const searchCandidateSchema = z\n .object({\n resourceId: z.string().regex(UUID_RE, 'resourceId must be a uuid'),\n url: z.string(),\n slug: z.string(),\n title: z.string(),\n artifactType: z.string(),\n price: z.string().regex(ATOMIC_RE, 'price must be an atomic integer string'),\n asOf: z.string().nullable(),\n validUntil: z.string().nullable(),\n matchReasons: z.array(z.string()),\n estimatedTokens: z.number(),\n creator: z.object({ handle: z.string() }).passthrough(),\n })\n .passthrough();\n\nexport type SearchCandidate = z.infer<typeof searchCandidateSchema>;\n\n/** Per-field caps for a browse pointer's free-form strings. `url` gets its own,\n * looser bound so a legitimate read URL is never mangled while an invented one\n * still cannot run away. Declared above the schema because the schema enforces\n * the `url` bound at parse time (see below). */\nconst BROWSE_BOUNDS = { title: 200, url: 512, handle: 64 } as const;\n\n// A browse pointer, carried ONLY on a MISS (tenjin#460): a piece from the broad\n// discoverable corpus with deliberately NO matchReasons, NO estimatedTokens and\n// no confidence field. It is a \"you might browse this\" hint, never a scored\n// answer candidate, so it is kept strictly out of `candidates` and never\n// recorded in the local search store.\n//\n// That store exclusion makes `inspect`/`buy`/`outcome` unreachable BY\n// `resourceId` (resolveResourceRef's uuid arm needs a store hit and fails with\n// RESOURCE_NOT_FOUND), but NOT by url: resolveResourceRef's URL arm is gated on\n// origin alone and never consults the store, so `tenjin buy <browse url>` does\n// pay. That is by design here, since the url is the payable read endpoint and\n// the contract re-emits it verbatim, but it is a real spend path, so the human\n// hint line carries the price and every spend gate still applies. Do not\n// restate the old \"never reachable by inspect/buy/outcome\" claim: it was false.\n//\n// A malformed pointer fails the WHOLE response into CONTRACT_MISMATCH rather\n// than being dropped. Deliberate: this client is fail-closed on every other\n// contract deviation, and silently swallowing a bad tail would hide server\n// drift that contract.test.ts exists to catch. Pinned in agent-api.test.ts.\n//\n// The `url` bound is enforced HERE rather than by truncation in the projection\n// below, and that asymmetry with `title`/`handle` is deliberate. Those two are\n// display strings: clipping one degrades gracefully and the human still reads\n// something true. `url` is an actionable payable pointer, and a clipped url is\n// not a shorter url, it is a DIFFERENT and broken one that still looks payable\n// in `--json`. Refusing is also the only ordering-independent answer: capping\n// first would hand the origin assertion in `runSearch` a string the server never\n// sent. 512 is far above any real read endpoint, so exceeding it is server drift.\nexport const searchBrowseSchema = z\n .object({\n resourceId: z.string().regex(UUID_RE, 'resourceId must be a uuid'),\n url: z.string().max(BROWSE_BOUNDS.url, `url must be at most ${BROWSE_BOUNDS.url} characters`),\n title: z.string(),\n price: z.string().regex(ATOMIC_RE, 'price must be an atomic integer string'),\n creator: z.object({ handle: z.string() }).passthrough(),\n })\n .passthrough();\n\nexport type SearchBrowse = z.infer<typeof searchBrowseSchema>;\n\nexport const searchResponseSchema = z.object({\n schemaVersion: z.literal(2),\n searchId: z.string().regex(UUID_RE, 'searchId must be a uuid'),\n decision: z.enum(['CANDIDATES', 'MISS']),\n calibration: z.string(),\n candidates: z.array(searchCandidateSchema).optional(),\n // Set only when the server's size backstop dropped trailing candidates the\n // requested limit had room for; omitted entirely otherwise. There is no cursor,\n // so a retry at a SMALLER limit returns strictly fewer rows; the ceiling scales\n // with the candidates returned, so a LARGER limit (up to MAX_LIMIT) is what\n // recovers the tail, and at MAX_LIMIT the tail is unrecoverable and narrowing the\n // question is the remedy. `runSearch` picks the half that applies.\n truncated: z.literal(true).optional(),\n // Omitted entirely by the server when empty, and only ever present on a MISS.\n // Not enforced here (a stricter schema would reject an otherwise-usable\n // response); truncateResponse drops it on a CANDIDATES decision instead.\n browse: z.array(searchBrowseSchema).optional(),\n});\n\nexport type SearchResponse = z.infer<typeof searchResponseSchema>;\n\nexport interface AgentApiOptions {\n baseUrl: string;\n timeoutMs: number;\n fetchImpl?: typeof fetch;\n /** Spec 09 §3 evaluation-cohort opt-in: sends X-Tenjin-Eval-Cohort: 1. */\n evalCohort?: boolean;\n}\n\n/** Turn a non-2xx / transport HttpResult into the CLI error contract. */\nfunction apiFailure(url: string, result: Exclude<HttpResult, { ok: true }>): CliError {\n const code =\n result.kind === 'network' || result.kind === 'timeout' ? 'NETWORK_ERROR' : 'API_UNREACHABLE';\n return new CliError(code, `${url}: ${result.message}`, {\n fix: 'Check your network and the configured base URL (`tenjin config get baseUrl`), then retry.',\n });\n}\n\n/** 429 with Retry-After: a recoverable pause, not an outage; agents branch on it. */\nexport function rateLimitError(\n url: string,\n header: (name: string) => string | undefined,\n): CliError {\n const retryAfter = header('retry-after');\n const seconds = retryAfter !== undefined ? Number(retryAfter) : undefined;\n return new CliError('RATE_LIMITED', `${url}: rate limited by the server.`, {\n fix:\n seconds !== undefined && Number.isFinite(seconds)\n ? `Retry after ${seconds}s.`\n : 'Back off and retry shortly.',\n details: {\n ...(seconds !== undefined && Number.isFinite(seconds) ? { retryAfterSeconds: seconds } : {}),\n },\n });\n}\n\nfunction serverErrorMessage(json: unknown): string | undefined {\n if (typeof json === 'object' && json !== null) {\n const rec = json as Record<string, unknown>;\n const err = rec.error;\n if (typeof err === 'string') return err;\n if (typeof err === 'object' && err !== null) {\n const m = (err as Record<string, unknown>).message;\n if (typeof m === 'string') return m;\n }\n if (typeof rec.message === 'string') return rec.message;\n }\n return undefined;\n}\n\nexport async function postSearch(\n body: SearchRequestBody,\n opts: AgentApiOptions,\n): Promise<SearchResponse> {\n const url = `${trimSlash(opts.baseUrl)}/api/agent/search`;\n const res = await httpRequest(url, {\n method: 'POST',\n timeoutMs: opts.timeoutMs,\n headers: {\n 'x-tenjin-client': CLIENT_HEADER,\n ...(opts.evalCohort === true ? { 'x-tenjin-eval-cohort': '1' } : {}),\n },\n jsonBody: body,\n fetchImpl: opts.fetchImpl,\n });\n if (!res.ok) throw apiFailure(url, res);\n if (res.status === 429) throw rateLimitError(url, (n) => res.header(n));\n if (res.status !== 200) {\n // The REQUEST gate is where a pre-v2 server actually refuses us, and it is\n // the arm that fires in practice. Old tenjin declares `schemaVersion:\n // z.literal(1)` inside a strictObject, so a v2 request never reaches the\n // handler: it comes back 400 \"Invalid request body\" with the zod flatten in\n // `error.details`, and the response check further down can never see it.\n // Without this the operator is told to retry a request that cannot succeed.\n if (res.status === 400 && rejectedSchemaVersion(res.json)) {\n throw outdatedServerError('The server rejected schemaVersion 2: it predates search v2.', {\n details: res.json,\n });\n }\n throw new CliError(\n 'API_UNREACHABLE',\n serverErrorMessage(res.json) ?? `Search failed (${res.status})`,\n {\n fix: 'Retry; if it persists the search endpoint may be unavailable.',\n details: res.json,\n },\n );\n }\n const parsed = searchResponseSchema.safeParse(res.json);\n if (!parsed.success) {\n // The other way a stale server surfaces: it answered 200 with a v1 body.\n // Unreachable against today's old tenjin (the request gate above refuses\n // first), but correct for anything that accepts the request and replies v1.\n const served = serverSchemaVersion(res.json);\n if (served !== undefined && served !== 2) {\n throw outdatedServerError(\n `Search response is schemaVersion ${served}; this CLI requires 2 (search v2).`,\n { details: parsed.error.issues },\n );\n }\n throw new CliError('CONTRACT_MISMATCH', 'Search response did not match the expected contract', {\n fix: 'Update tenjin-cli; the server contract may have changed.',\n details: parsed.error.issues,\n });\n }\n return truncateResponse(parsed.data);\n}\n\n/** One wording for both ways a pre-v2 server refuses this CLI, so the request-gate\n * arm and the response arm can never drift apart. */\nfunction outdatedServerError(message: string, opts: { details: unknown }): CliError {\n return new CliError('CONTRACT_MISMATCH', message, {\n fix: 'The server predates search v2. Point the configured base URL (`tenjin config set baseUrl`) at an updated deployment, or install an older tenjin-cli.',\n details: opts.details,\n });\n}\n\n/** True when a 400 body is the old server's request-gate refusal of our\n * `schemaVersion`: an ApiError envelope whose zod `flatten()` details carry a\n * `schemaVersion` fieldError. Keyed on the field, never the message text. */\nfunction rejectedSchemaVersion(json: unknown): boolean {\n const record = (v: unknown): Record<string, unknown> | undefined =>\n typeof v === 'object' && v !== null ? (v as Record<string, unknown>) : undefined;\n const fieldErrors = record(record(record(json)?.error)?.details)?.fieldErrors;\n return Array.isArray(record(fieldErrors)?.schemaVersion);\n}\n\n/** The `schemaVersion` an unparsed body claims, when it claims a number at all. */\nfunction serverSchemaVersion(json: unknown): number | undefined {\n if (typeof json !== 'object' || json === null) return undefined;\n const v = (json as { schemaVersion?: unknown }).schemaVersion;\n return typeof v === 'number' ? v : undefined;\n}\n\n/**\n * The server bounds every free-form candidate string (spec 09); re-apply the same\n * caps defensively so a misbehaving server cannot blow up an agent transcript\n * through the CLI (spec 10 response-size discipline).\n *\n * `slug` is deliberately absent: it is an identifier, not display text, so\n * clipping it would not shorten it but change it into a slug that resolves to\n * nothing while still looking usable in `--json`. The server tolerates an\n * uncapped slug for the same reason (that is the one case its `truncated` flag\n * exists for), so capping here would fail on a response the server calls valid.\n */\nconst CAND_BOUNDS = {\n title: 200,\n matchReasons: 3,\n matchReasonChars: 80,\n} as const;\n\nconst cap = (s: string, n: number): string => (s.length > n ? s.slice(0, n) : s);\n\nfunction truncateResponse(res: SearchResponse): SearchResponse {\n const out: SearchResponse = { ...res };\n if (res.candidates !== undefined) out.candidates = res.candidates.map(truncateCandidate);\n // Browse pointers ride the same defensive discipline, and then some. The\n // schema is `.passthrough()` so a server-invented key would otherwise survive\n // at unbounded length into `--json` and MCP structuredContent; we rebuild each\n // pointer explicitly from the five contract fields instead of spreading, which\n // drops unknown keys and is what makes the contract.test.ts \"no score-like\n // field\" pin hold at runtime and not just against the fixture. Count is capped\n // at the server's BROWSE_MAX, and every free-form string (title, url, handle)\n // at its own bound.\n //\n // `browse` is MISS-only by contract; drop it outright on a CANDIDATES decision\n // rather than trust the server, since humanLines renders no hint line there and\n // it would otherwise be an unrendered channel of server text and payable urls.\n if (res.browse !== undefined && res.decision === 'MISS') {\n out.browse = res.browse.slice(0, BROWSE_MAX).map((b) => ({\n resourceId: b.resourceId,\n // Not capped: the schema already refused anything over BROWSE_BOUNDS.url,\n // so this is the url the server sent, verbatim and payable.\n url: b.url,\n title: cap(b.title, BROWSE_BOUNDS.title),\n price: b.price,\n creator: { handle: cap(b.creator.handle, BROWSE_BOUNDS.handle) },\n }));\n } else {\n delete out.browse;\n }\n return out;\n}\n\n/** Mirrors the server's BROWSE_MAX (lib/search-browse.ts): a MISS carries at\n * most three browse pointers. */\nconst BROWSE_MAX = 3;\n\nfunction truncateCandidate(c: SearchCandidate): SearchCandidate {\n return {\n ...c,\n title: cap(c.title, CAND_BOUNDS.title),\n matchReasons: c.matchReasons\n .slice(0, CAND_BOUNDS.matchReasons)\n .map((r) => cap(r, CAND_BOUNDS.matchReasonChars)),\n };\n}\n\nconst OUTCOME_STATUSES = [\n 'used',\n 'partially_used',\n 'rejected',\n 'regenerated',\n 'purchase_declined',\n] as const;\nexport type OutcomeStatus = (typeof OUTCOME_STATUSES)[number];\nexport const OUTCOME_STATUS_VALUES: readonly string[] = OUTCOME_STATUSES;\n\nconst CONTENT_HASH_RE = /^sha256:[0-9a-f]{64}$/;\n\nexport interface OutcomeInput {\n status: string;\n resourceId?: string;\n contentHash?: string;\n}\n\nexport interface OutcomeBodyItem {\n status: OutcomeStatus;\n resourceId?: string;\n contentHash?: string;\n}\n\nexport function buildOutcomeItem(input: OutcomeInput): OutcomeBodyItem {\n if (!OUTCOME_STATUS_VALUES.includes(input.status)) {\n throw new CliError('USAGE', `Invalid outcome status: ${JSON.stringify(input.status)}`, {\n fix: `Use one of: ${OUTCOME_STATUSES.join(', ')}.`,\n });\n }\n if (input.resourceId !== undefined && !UUID_RE.test(input.resourceId)) {\n throw new CliError('USAGE', `Invalid --resource id: ${JSON.stringify(input.resourceId)}`, {\n fix: 'Pass the resourceId (a uuid) from a search candidate.',\n });\n }\n if (input.contentHash !== undefined && !CONTENT_HASH_RE.test(input.contentHash)) {\n throw new CliError('USAGE', `Invalid content hash: ${JSON.stringify(input.contentHash)}`, {\n fix: 'A content hash is \"sha256:<64 hex>\".',\n });\n }\n return {\n status: input.status as OutcomeStatus,\n ...(input.resourceId !== undefined ? { resourceId: input.resourceId } : {}),\n ...(input.contentHash !== undefined ? { contentHash: input.contentHash } : {}),\n };\n}\n\nconst SEARCH_ID_RE = UUID_RE;\n\nexport async function postOutcomes(\n searchId: string,\n items: OutcomeBodyItem[],\n opts: AgentApiOptions,\n): Promise<{ accepted: number }> {\n if (!SEARCH_ID_RE.test(searchId)) {\n throw new CliError('USAGE', `Invalid search id: ${JSON.stringify(searchId)}`, {\n fix: 'Pass the searchId from a prior search (or use --last).',\n });\n }\n if (items.length === 0 || items.length > 10) {\n throw new CliError('USAGE', 'An outcome report carries 1 to 10 items', {\n fix: 'Report between 1 and 10 outcomes per call.',\n });\n }\n const url = `${trimSlash(opts.baseUrl)}/api/agent/searches/${searchId}/outcomes`;\n const res = await httpRequest(url, {\n method: 'POST',\n timeoutMs: opts.timeoutMs,\n headers: { 'x-tenjin-client': CLIENT_HEADER },\n jsonBody: items.length === 1 ? items[0] : items,\n fetchImpl: opts.fetchImpl,\n });\n if (!res.ok) throw apiFailure(url, res);\n if (res.status === 429) throw rateLimitError(url, (n) => res.header(n));\n // 202 is the only success; the body is a uniform { accepted } regardless of\n // whether the searchId existed (no existence oracle, by design).\n if (res.status !== 202) {\n throw new CliError(\n 'API_UNREACHABLE',\n serverErrorMessage(res.json) ?? `Outcome report failed (${res.status})`,\n {\n fix: 'Check the status vocabulary and search id, then retry.',\n details: res.json,\n },\n );\n }\n const accepted =\n typeof res.json === 'object' && res.json !== null && 'accepted' in res.json\n ? Number((res.json as { accepted: unknown }).accepted)\n : items.length;\n return { accepted: Number.isFinite(accepted) ? accepted : items.length };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAiBA,IAAM,kBAAkB;AACxB,IAAM,mBAAmB;AAOlB,IAAM,YAAY;AAqBlB,SAAS,mBAAmB,OAAuC;AACxE,QAAM,WAAW,MAAM,SAAS,KAAK;AACrC,MAAI,SAAS,WAAW,KAAK,SAAS,SAAS,KAAK;AAClD,UAAM,IAAI,SAAS,SAAS,wCAAwC;AAAA,MAClE,KAAK;AAAA,IACP,CAAC;AAAA,EACH;AACA,MAAI,MAAM,gBAAgB,QAAW;AAGnC,UAAM,SAAS,gBAAgB,KAAK,MAAM,WAAW,IAAI,CAAC;AAC1D,QAAI,WAAW,UAAa,OAAO,MAAM,MAAM,GAAG;AAChD,YAAM,IAAI,SAAS,SAAS,2BAA2B,KAAK,UAAU,MAAM,WAAW,CAAC,IAAI;AAAA,QAC1F,KAAK;AAAA,MACP,CAAC;AAAA,IACH;AAAA,EACF;AACA,MAAI,MAAM,aAAa,UAAa,CAAC,UAAU,KAAK,MAAM,QAAQ,GAAG;AACnE,UAAM,IAAI,SAAS,SAAS,wBAAwB,KAAK,UAAU,MAAM,QAAQ,CAAC,IAAI;AAAA,MACpF,KAAK;AAAA,IACP,CAAC;AAAA,EACH;AACA,QAAM,QAAQ,MAAM,SAAS;AAC7B,MAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,KAAK,QAAQ,WAAW;AAC9D,UAAM,IAAI,SAAS,SAAS,oBAAoB,KAAK,UAAU,MAAM,KAAK,CAAC,IAAI;AAAA,MAC7E,KAAK,iCAAiC,SAAS;AAAA,IACjD,CAAC;AAAA,EACH;AACA,MAAI,MAAM,cAAc,QAAW;AAGjC,UAAM,OAAO,OAAO,KAAK,MAAM,SAAS;AACxC,QAAI,KAAK,SAAS,GAAG;AACnB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