@wirecat/amo-cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (294) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/LICENSE +204 -0
  3. package/README.md +257 -2
  4. package/contracts/wirecat.json +1356 -0
  5. package/dist/amo/account.d.ts +18 -0
  6. package/dist/amo/account.d.ts.map +1 -0
  7. package/dist/amo/account.js +48 -0
  8. package/dist/amo/account.js.map +1 -0
  9. package/dist/amo/allow-list.d.ts +31 -0
  10. package/dist/amo/allow-list.d.ts.map +1 -0
  11. package/dist/amo/allow-list.js +106 -0
  12. package/dist/amo/allow-list.js.map +1 -0
  13. package/dist/amo/call.d.ts +24 -0
  14. package/dist/amo/call.d.ts.map +1 -0
  15. package/dist/amo/call.js +54 -0
  16. package/dist/amo/call.js.map +1 -0
  17. package/dist/amo/errors.d.ts +12 -0
  18. package/dist/amo/errors.d.ts.map +1 -0
  19. package/dist/amo/errors.js +72 -0
  20. package/dist/amo/errors.js.map +1 -0
  21. package/dist/amo/json.d.ts +3 -0
  22. package/dist/amo/json.d.ts.map +1 -0
  23. package/dist/amo/json.js +3 -0
  24. package/dist/amo/json.js.map +1 -0
  25. package/dist/amo/oauth.d.ts +55 -0
  26. package/dist/amo/oauth.d.ts.map +1 -0
  27. package/dist/amo/oauth.js +189 -0
  28. package/dist/amo/oauth.js.map +1 -0
  29. package/dist/amo/operation.d.ts +45 -0
  30. package/dist/amo/operation.d.ts.map +1 -0
  31. package/dist/amo/operation.js +119 -0
  32. package/dist/amo/operation.js.map +1 -0
  33. package/dist/amo/operations.d.ts +3 -0
  34. package/dist/amo/operations.d.ts.map +1 -0
  35. package/dist/amo/operations.js +1407 -0
  36. package/dist/amo/operations.js.map +1 -0
  37. package/dist/amo/routes.d.ts +67 -0
  38. package/dist/amo/routes.d.ts.map +1 -0
  39. package/dist/amo/routes.js +65 -0
  40. package/dist/amo/routes.js.map +1 -0
  41. package/dist/amo/transport.d.ts +62 -0
  42. package/dist/amo/transport.d.ts.map +1 -0
  43. package/dist/amo/transport.js +282 -0
  44. package/dist/amo/transport.js.map +1 -0
  45. package/dist/api-keys.d.ts +47 -0
  46. package/dist/api-keys.d.ts.map +1 -0
  47. package/dist/api-keys.js +224 -0
  48. package/dist/api-keys.js.map +1 -0
  49. package/dist/bin/amo.d.ts +3 -0
  50. package/dist/bin/amo.d.ts.map +1 -0
  51. package/dist/bin/amo.js +40 -0
  52. package/dist/bin/amo.js.map +1 -0
  53. package/dist/bundle/all-profiles-3KQVWDV4.js +278 -0
  54. package/dist/bundle/amo.js +198 -0
  55. package/dist/bundle/anthropic-N5NOX7K7.js +90 -0
  56. package/dist/bundle/app-server-2MST5EZ5.js +245 -0
  57. package/dist/bundle/bun-4NHWOFX2.js +169 -0
  58. package/dist/bundle/bun-sqlite-DRSXPWPR.js +75 -0
  59. package/dist/bundle/chunk-2I5UVMLW.js +3232 -0
  60. package/dist/bundle/chunk-3IRJDH2U.js +731 -0
  61. package/dist/bundle/chunk-4ZAK773N.js +100 -0
  62. package/dist/bundle/chunk-5D4AEUVA.js +24783 -0
  63. package/dist/bundle/chunk-5D4Z2B5B.js +334 -0
  64. package/dist/bundle/chunk-5E5R65CA.js +54 -0
  65. package/dist/bundle/chunk-5HGGG3QO.js +73 -0
  66. package/dist/bundle/chunk-5RLUHTK6.js +23 -0
  67. package/dist/bundle/chunk-5SBLU7D7.js +63 -0
  68. package/dist/bundle/chunk-5Z5PEEKP.js +206 -0
  69. package/dist/bundle/chunk-63F65DHU.js +29 -0
  70. package/dist/bundle/chunk-6RS7OYTD.js +64 -0
  71. package/dist/bundle/chunk-73CXFE36.js +88 -0
  72. package/dist/bundle/chunk-7GTUZY7M.js +170 -0
  73. package/dist/bundle/chunk-7PKFYX7V.js +189 -0
  74. package/dist/bundle/chunk-7U5HJEPZ.js +1400 -0
  75. package/dist/bundle/chunk-A33TIM5D.js +4172 -0
  76. package/dist/bundle/chunk-ADEWU4P4.js +38 -0
  77. package/dist/bundle/chunk-ADLS6FVG.js +24600 -0
  78. package/dist/bundle/chunk-AHJ4W2IL.js +106 -0
  79. package/dist/bundle/chunk-AUBB72VF.js +2572 -0
  80. package/dist/bundle/chunk-BVMNXI53.js +1266 -0
  81. package/dist/bundle/chunk-CDY2NJFE.js +136 -0
  82. package/dist/bundle/chunk-CHUKWON6.js +244 -0
  83. package/dist/bundle/chunk-CUZRHF34.js +230 -0
  84. package/dist/bundle/chunk-D72URWJE.js +532 -0
  85. package/dist/bundle/chunk-DAY6TSPF.js +786 -0
  86. package/dist/bundle/chunk-DFDN6AUB.js +21 -0
  87. package/dist/bundle/chunk-DJD7TBYG.js +2791 -0
  88. package/dist/bundle/chunk-DOSJONCX.js +1197 -0
  89. package/dist/bundle/chunk-DQV2IKCF.js +72 -0
  90. package/dist/bundle/chunk-DTA5YV5O.js +25 -0
  91. package/dist/bundle/chunk-DXGGCGRP.js +218 -0
  92. package/dist/bundle/chunk-EH6ZEJGT.js +932 -0
  93. package/dist/bundle/chunk-EPOV5UIO.js +185 -0
  94. package/dist/bundle/chunk-EQ7A6NA6.js +53 -0
  95. package/dist/bundle/chunk-EQUKVVHX.js +353 -0
  96. package/dist/bundle/chunk-EROSAUNP.js +133 -0
  97. package/dist/bundle/chunk-ESZSMZKT.js +82 -0
  98. package/dist/bundle/chunk-FKR3M62D.js +407 -0
  99. package/dist/bundle/chunk-GNTJMB6X.js +142 -0
  100. package/dist/bundle/chunk-GQ7VFIYM.js +316 -0
  101. package/dist/bundle/chunk-JH3UOHRE.js +161 -0
  102. package/dist/bundle/chunk-JMDLPBXK.js +1068 -0
  103. package/dist/bundle/chunk-JR6TSMFX.js +9435 -0
  104. package/dist/bundle/chunk-K5UU3IOR.js +27955 -0
  105. package/dist/bundle/chunk-L6AFE73L.js +18 -0
  106. package/dist/bundle/chunk-LDEBZ3IX.js +238 -0
  107. package/dist/bundle/chunk-LGQXGOPJ.js +58 -0
  108. package/dist/bundle/chunk-LJQUYECN.js +6848 -0
  109. package/dist/bundle/chunk-LRBPT7LQ.js +95 -0
  110. package/dist/bundle/chunk-LSND5QYI.js +460 -0
  111. package/dist/bundle/chunk-NHXJYS4R.js +1334 -0
  112. package/dist/bundle/chunk-NJYAL3UW.js +92 -0
  113. package/dist/bundle/chunk-NTLSWCJ5.js +1718 -0
  114. package/dist/bundle/chunk-O2UCU52O.js +4065 -0
  115. package/dist/bundle/chunk-ODNQU7DH.js +1028 -0
  116. package/dist/bundle/chunk-P3WQRTYZ.js +24 -0
  117. package/dist/bundle/chunk-P5LYZRKW.js +63373 -0
  118. package/dist/bundle/chunk-PFO76YFP.js +2003 -0
  119. package/dist/bundle/chunk-PM77PRB6.js +12269 -0
  120. package/dist/bundle/chunk-Q2VNBY4Y.js +38109 -0
  121. package/dist/bundle/chunk-QDMXZZG4.js +604 -0
  122. package/dist/bundle/chunk-QRQYUHCZ.js +761 -0
  123. package/dist/bundle/chunk-RPWAJYI6.js +2336 -0
  124. package/dist/bundle/chunk-SMSTGO2G.js +58 -0
  125. package/dist/bundle/chunk-SZ2V62HB.js +72 -0
  126. package/dist/bundle/chunk-T2UDLX76.js +259 -0
  127. package/dist/bundle/chunk-TGEQNS6G.js +16 -0
  128. package/dist/bundle/chunk-TNUFLULO.js +2333 -0
  129. package/dist/bundle/chunk-U7RLVJ34.js +274 -0
  130. package/dist/bundle/chunk-UBRREVLJ.js +72 -0
  131. package/dist/bundle/chunk-ULXQ5MJM.js +76 -0
  132. package/dist/bundle/chunk-UMVRT7VQ.js +46 -0
  133. package/dist/bundle/chunk-V77XNPXG.js +360 -0
  134. package/dist/bundle/chunk-VVHRQ46X.js +193 -0
  135. package/dist/bundle/chunk-VX37MPTJ.js +7 -0
  136. package/dist/bundle/chunk-WCYCUTSK.js +362 -0
  137. package/dist/bundle/chunk-XEFAMLSD.js +288 -0
  138. package/dist/bundle/chunk-XQL7FEF4.js +721 -0
  139. package/dist/bundle/chunk-XRTD2GCU.js +627 -0
  140. package/dist/bundle/chunk-Y37A3232.js +804 -0
  141. package/dist/bundle/chunk-Y5E2WNWB.js +35 -0
  142. package/dist/bundle/chunk-ZM7I52EP.js +78 -0
  143. package/dist/bundle/chunk-ZVVMGPBJ.js +50 -0
  144. package/dist/bundle/cli-KEGIR67U.js +1193 -0
  145. package/dist/bundle/command-contract-QBUQBXH7.js +39 -0
  146. package/dist/bundle/command-server-entry-5VL5U5EE.js +168 -0
  147. package/dist/bundle/decode-SQ5WGNDX.js +296 -0
  148. package/dist/bundle/dispatch-LA4DFXJD.js +411 -0
  149. package/dist/bundle/dist-XJGFOXYI.js +7577 -0
  150. package/dist/bundle/echarts-25Z3RINX.js +42501 -0
  151. package/dist/bundle/embed-BNOTNXMA.js +37 -0
  152. package/dist/bundle/embedder-BCUT7KKV.js +110 -0
  153. package/dist/bundle/failure-PKAC6XCT.js +24 -0
  154. package/dist/bundle/first-run-EO5K5GME.js +28 -0
  155. package/dist/bundle/first-screen-GMN3T6RW.js +39 -0
  156. package/dist/bundle/instructions-VLM3QAYB.js +11 -0
  157. package/dist/bundle/mcp-7ILNMJH5.js +167 -0
  158. package/dist/bundle/meeting-combined-LAMF7S2B.js +24 -0
  159. package/dist/bundle/meeting-model-GHMMUQ34.js +24 -0
  160. package/dist/bundle/meeting-semantic-BMP6323L.js +21 -0
  161. package/dist/bundle/node-CT3N3TNL.js +176 -0
  162. package/dist/bundle/node-P4E63KXA.js +2340 -0
  163. package/dist/bundle/node-TLZSIHIJ.js +21 -0
  164. package/dist/bundle/node-sqlite-MELD2SBX.js +73 -0
  165. package/dist/bundle/oauth-YBH5OKC2.js +19 -0
  166. package/dist/bundle/open-WNSBWTAG.js +22 -0
  167. package/dist/bundle/openai-XSNMNLW6.js +237 -0
  168. package/dist/bundle/process-I2QKOMM7.js +91 -0
  169. package/dist/bundle/program-VQQTSSAF.js +4940 -0
  170. package/dist/bundle/prompt-SOG4AKPM.js +16 -0
  171. package/dist/bundle/recognize-WMQLWMXH.js +25 -0
  172. package/dist/bundle/remote-4BTFOLFY.js +30 -0
  173. package/dist/bundle/rerank-LJ3TWRNV.js +51 -0
  174. package/dist/bundle/serve-B6UANKXN.js +198 -0
  175. package/dist/bundle/server-S6XD6V6E.js +77 -0
  176. package/dist/bundle/server-YRH6GJ5Z.js +206 -0
  177. package/dist/bundle/source-DGFTA2TN.js +42 -0
  178. package/dist/bundle/sqlite-runtime-R7QFWFE7.js +19 -0
  179. package/dist/bundle/state-DIJ5YUOE.js +35 -0
  180. package/dist/bundle/store-6WFWW7EC.js +294 -0
  181. package/dist/bundle/store-BPNIM4BF.js +32 -0
  182. package/dist/bundle/store-MYTYDV6A.js +177 -0
  183. package/dist/bundle/store-maintenance-command-B5TMKFMG.js +68 -0
  184. package/dist/bundle/writer-GP7VIMAU.js +44 -0
  185. package/dist/commands/account.d.ts +3 -0
  186. package/dist/commands/account.d.ts.map +1 -0
  187. package/dist/commands/account.js +86 -0
  188. package/dist/commands/account.js.map +1 -0
  189. package/dist/commands/api.d.ts +3 -0
  190. package/dist/commands/api.d.ts.map +1 -0
  191. package/dist/commands/api.js +224 -0
  192. package/dist/commands/api.js.map +1 -0
  193. package/dist/commands/comments.d.ts +3 -0
  194. package/dist/commands/comments.d.ts.map +1 -0
  195. package/dist/commands/comments.js +114 -0
  196. package/dist/commands/comments.js.map +1 -0
  197. package/dist/commands/crm-shared.d.ts +8 -0
  198. package/dist/commands/crm-shared.d.ts.map +1 -0
  199. package/dist/commands/crm-shared.js +111 -0
  200. package/dist/commands/crm-shared.js.map +1 -0
  201. package/dist/commands/schedule.d.ts +3 -0
  202. package/dist/commands/schedule.d.ts.map +1 -0
  203. package/dist/commands/schedule.js +9 -0
  204. package/dist/commands/schedule.js.map +1 -0
  205. package/dist/commands/session.d.ts +18 -0
  206. package/dist/commands/session.d.ts.map +1 -0
  207. package/dist/commands/session.js +265 -0
  208. package/dist/commands/session.js.map +1 -0
  209. package/dist/commands/write.d.ts +14 -0
  210. package/dist/commands/write.d.ts.map +1 -0
  211. package/dist/commands/write.js +36 -0
  212. package/dist/commands/write.js.map +1 -0
  213. package/dist/config.d.ts +4 -0
  214. package/dist/config.d.ts.map +1 -0
  215. package/dist/config.js +29 -0
  216. package/dist/config.js.map +1 -0
  217. package/dist/context.d.ts +62 -0
  218. package/dist/context.d.ts.map +1 -0
  219. package/dist/context.js +97 -0
  220. package/dist/context.js.map +1 -0
  221. package/dist/crm/activities.d.ts +32 -0
  222. package/dist/crm/activities.d.ts.map +1 -0
  223. package/dist/crm/activities.js +196 -0
  224. package/dist/crm/activities.js.map +1 -0
  225. package/dist/crm/records.d.ts +20 -0
  226. package/dist/crm/records.d.ts.map +1 -0
  227. package/dist/crm/records.js +175 -0
  228. package/dist/crm/records.js.map +1 -0
  229. package/dist/crm/source.d.ts +41 -0
  230. package/dist/crm/source.d.ts.map +1 -0
  231. package/dist/crm/source.js +673 -0
  232. package/dist/crm/source.js.map +1 -0
  233. package/dist/crm/writer.d.ts +14 -0
  234. package/dist/crm/writer.d.ts.map +1 -0
  235. package/dist/crm/writer.js +247 -0
  236. package/dist/crm/writer.js.map +1 -0
  237. package/dist/identity.d.ts +7 -0
  238. package/dist/identity.d.ts.map +1 -0
  239. package/dist/identity.js +33 -0
  240. package/dist/identity.js.map +1 -0
  241. package/dist/index.d.ts +3 -0
  242. package/dist/index.d.ts.map +1 -0
  243. package/dist/index.js +3 -0
  244. package/dist/index.js.map +1 -0
  245. package/dist/program.d.ts +6 -0
  246. package/dist/program.d.ts.map +1 -0
  247. package/dist/program.js +91 -0
  248. package/dist/program.js.map +1 -0
  249. package/dist/reasons.d.ts +10 -0
  250. package/dist/reasons.d.ts.map +1 -0
  251. package/dist/reasons.js +35 -0
  252. package/dist/reasons.js.map +1 -0
  253. package/dist/sample/comments.d.ts +61 -0
  254. package/dist/sample/comments.d.ts.map +1 -0
  255. package/dist/sample/comments.js +39 -0
  256. package/dist/sample/comments.js.map +1 -0
  257. package/dist/sample/records.d.ts +16 -0
  258. package/dist/sample/records.d.ts.map +1 -0
  259. package/dist/sample/records.js +22 -0
  260. package/dist/sample/records.js.map +1 -0
  261. package/dist/sample/transport.d.ts +42 -0
  262. package/dist/sample/transport.d.ts.map +1 -0
  263. package/dist/sample/transport.js +153 -0
  264. package/dist/sample/transport.js.map +1 -0
  265. package/dist/setup/flow.d.ts +2 -0
  266. package/dist/setup/flow.d.ts.map +1 -0
  267. package/dist/setup/flow.js +127 -0
  268. package/dist/setup/flow.js.map +1 -0
  269. package/dist/setup/texts.en.json +25 -0
  270. package/dist/setup/texts.es.json +25 -0
  271. package/dist/setup/texts.ru.json +25 -0
  272. package/dist/store.d.ts +15 -0
  273. package/dist/store.d.ts.map +1 -0
  274. package/dist/store.js +16 -0
  275. package/dist/store.js.map +1 -0
  276. package/dist/version.d.ts +2 -0
  277. package/dist/version.d.ts.map +1 -0
  278. package/dist/version.js +2 -0
  279. package/dist/version.js.map +1 -0
  280. package/dist/wcat.d.ts +3 -0
  281. package/dist/wcat.d.ts.map +1 -0
  282. package/dist/wcat.js +4 -0
  283. package/dist/wcat.js.map +1 -0
  284. package/dist/whoami.d.ts +24 -0
  285. package/dist/whoami.d.ts.map +1 -0
  286. package/dist/whoami.js +33 -0
  287. package/dist/whoami.js.map +1 -0
  288. package/package.json +85 -4
  289. package/skills/amo-cli/SKILL.md +116 -0
  290. package/skills/amo-cli/references/mcp.md +38 -0
  291. package/skills/amo-cli/references/output.md +42 -0
  292. package/skills/amo-cli/references/reading.md +77 -0
  293. package/skills/amo-cli/references/setup.md +59 -0
  294. package/skills/amo-cli/references/writing.md +85 -0
@@ -0,0 +1,362 @@
1
+ import { createRequire as __bundleRequire } from "node:module";
2
+ const require = __bundleRequire(import.meta.url);
3
+ import {
4
+ isCliFailure
5
+ } from "./chunk-UBRREVLJ.js";
6
+ import {
7
+ secretNamed,
8
+ withoutSecrets
9
+ } from "./chunk-NJYAL3UW.js";
10
+ import {
11
+ isContentKey
12
+ } from "./chunk-DJD7TBYG.js";
13
+ import {
14
+ __name
15
+ } from "./chunk-ZVVMGPBJ.js";
16
+
17
+ // node_modules/.pnpm/@wirecat+cli-core@0.691.0_@wirecat+cli-base@0.113.0_commander@15.0.0_esbuild@0.28.2_typ_9a2e508bb6f63e7e29f0d776540ec8fd/node_modules/@wirecat/cli-core/dist/runs/events.js
18
+ var providerErrorKey = /* @__PURE__ */ __name((value) => typeof value === "string" && /^[A-Za-z][A-Za-z0-9._-]{0,63}$/.test(value) ? value : void 0, "providerErrorKey");
19
+ var renderEvent = /* @__PURE__ */ __name((event) => {
20
+ if (event.event === "store")
21
+ return `${MARK.store} ${event.operation.padEnd(16)} ${event.table} ${event.op} ${event.n}`;
22
+ if (event.event === "progress")
23
+ return `${MARK.progress} ${event.operation.padEnd(16)} ${Object.entries(event.counts).map(([field, count]) => `${count} ${field}`).join(" ")}`;
24
+ if (event.event === "warning") {
25
+ const counts = Object.entries(event.counts ?? {}).map(([field, count]) => `${count} ${field}`);
26
+ return [`${MARK.warning} ${(event.operation ?? "").padEnd(16)} ${event.code}`, ...counts, event.detail].filter(Boolean).join(" ");
27
+ }
28
+ const parts = [];
29
+ if (event.event === "cache") {
30
+ parts.push(event.reason);
31
+ if (event.ageMs !== void 0)
32
+ parts.push(`cached ${age(event.ageMs)}`);
33
+ } else {
34
+ if (event.opcode !== void 0)
35
+ parts.push(`op ${event.opcode}`, `seq ${event.seq}`);
36
+ if (event.method !== void 0 || event.endpointTemplate !== void 0)
37
+ parts.push([event.method, event.endpointTemplate].filter(Boolean).join(" "));
38
+ if (event.status !== void 0)
39
+ parts.push(`${event.status}`);
40
+ if (event.attempt !== void 0 && event.attempt > 1)
41
+ parts.push(`attempt ${event.attempt}`);
42
+ if (event.waitMs !== void 0)
43
+ parts.push(`waited ${age(event.waitMs)}`);
44
+ }
45
+ if (event.ids)
46
+ for (const [name, value] of Object.entries(event.ids))
47
+ parts.push(`${name} ${value}`);
48
+ if (event.event !== "cache") {
49
+ if (event.durationMs !== void 0)
50
+ parts.push(`${event.durationMs}ms`);
51
+ if (event.bytes !== void 0)
52
+ parts.push(size(event.bytes));
53
+ }
54
+ if (event.counts)
55
+ for (const [field, count] of Object.entries(event.counts))
56
+ parts.push(`${count} ${field}`);
57
+ if (event.event !== "cache") {
58
+ if (event.errorCode)
59
+ parts.push(event.errorCode);
60
+ if (event.providerError)
61
+ parts.push(event.providerError);
62
+ }
63
+ return `${MARK[event.event]} ${event.operation.padEnd(16)} ${parts.join(" ")}`.trimEnd();
64
+ }, "renderEvent");
65
+ var MARK = { request: "\u2192", response: "\u2190", cache: "\u2022", warning: "!", store: "+", progress: "\u2026" };
66
+ var age = /* @__PURE__ */ __name((ms) => ms < 1e3 ? `${ms}ms` : `${Math.round(ms / 1e3)}s`, "age");
67
+ var size = /* @__PURE__ */ __name((bytes) => bytes < 1e3 ? `${bytes} B` : `${(bytes / 1e3).toFixed(1)} kB`, "size");
68
+
69
+ // node_modules/.pnpm/@wirecat+cli-core@0.691.0_@wirecat+cli-base@0.113.0_commander@15.0.0_esbuild@0.28.2_typ_9a2e508bb6f63e7e29f0d776540ec8fd/node_modules/@wirecat/cli-core/dist/runs/run-context.js
70
+ import { AsyncLocalStorage } from "node:async_hooks";
71
+ import { createHash } from "node:crypto";
72
+
73
+ // node_modules/.pnpm/@wirecat+cli-core@0.691.0_@wirecat+cli-base@0.113.0_commander@15.0.0_esbuild@0.28.2_typ_9a2e508bb6f63e7e29f0d776540ec8fd/node_modules/@wirecat/cli-core/dist/runs/error-detail.js
74
+ import { homedir } from "node:os";
75
+ var MESSAGE_AT_MOST = 500;
76
+ var CAUSES_AT_MOST = 5;
77
+ var FRAMES_AT_MOST = 15;
78
+ var errorDetailOf = /* @__PURE__ */ __name((error, response) => {
79
+ const details = isCliFailure(error) ? { ...error.details } : {};
80
+ const thrown = error instanceof Error ? error : void 0;
81
+ const code = isCliFailure(error) ? error.code : codeOf(error);
82
+ const reason = typeof details.reason === "string" ? details.reason : void 0;
83
+ const causeCode = typeof details.cause_code === "string" && /^[A-Za-z0-9_.-]{1,40}$/.test(details.cause_code) ? details.cause_code : void 0;
84
+ const message = thrown ? redactText(thrown.message) : void 0;
85
+ const operation = stringOf(details.operation) ?? response?.operation;
86
+ const status = numberOf(details.status) ?? response?.status;
87
+ const method = stringOf(details.method) ?? response?.method;
88
+ const endpoint = stringOf(details.endpoint) ?? response?.endpointTemplate;
89
+ const key = providerErrorKey(details.provider_error) ?? providerErrorKey(response?.providerError);
90
+ const protocol = key !== void 0 && method === void 0 && endpoint === void 0;
91
+ const http = method !== void 0 || endpoint !== void 0 || status !== void 0 && !protocol ? {
92
+ ...method === void 0 ? {} : { method: method.toUpperCase().slice(0, 16) },
93
+ ...endpoint === void 0 ? {} : { endpoint_template: endpointTemplate(endpoint) },
94
+ ...status === void 0 ? {} : { status }
95
+ } : void 0;
96
+ const causes = causesOf(thrown?.cause ?? details.cause);
97
+ const stack = framesOf(thrown);
98
+ return {
99
+ class: classOf(error),
100
+ ...code === void 0 ? {} : { code },
101
+ ...reason === void 0 ? {} : { reason },
102
+ ...causeCode === void 0 ? {} : { cause_code: causeCode },
103
+ ...message ? { message } : {},
104
+ ...operation === void 0 ? {} : { operation },
105
+ ...http ? { http } : {},
106
+ ...key === void 0 ? {} : { provider: { key, ...protocol && status !== void 0 ? { code: status } : {} } },
107
+ ...causes.length > 0 ? { causes } : {},
108
+ ...stack.length > 0 ? { stack } : {}
109
+ };
110
+ }, "errorDetailOf");
111
+ var stringOf = /* @__PURE__ */ __name((value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0, "stringOf");
112
+ var numberOf = /* @__PURE__ */ __name((value) => typeof value === "number" && Number.isInteger(value) ? value : void 0, "numberOf");
113
+ var classOf = /* @__PURE__ */ __name((error) => {
114
+ if (!(error instanceof Error))
115
+ return error === null ? "null" : typeof error;
116
+ const constructed = error.constructor?.name;
117
+ return constructed && constructed !== "Error" && constructed !== error.name ? constructed : error.name;
118
+ }, "classOf");
119
+ var codeOf = /* @__PURE__ */ __name((error) => {
120
+ const code = error?.code;
121
+ return typeof code === "string" && /^[A-Za-z][A-Za-z0-9._-]{0,63}$/.test(code) ? code : void 0;
122
+ }, "codeOf");
123
+ var causesOf = /* @__PURE__ */ __name((first) => {
124
+ const causes = [];
125
+ const seen = /* @__PURE__ */ new Set();
126
+ for (let cause = first; cause !== void 0 && cause !== null && causes.length < CAUSES_AT_MOST; ) {
127
+ if (seen.has(cause))
128
+ break;
129
+ seen.add(cause);
130
+ const message = cause instanceof Error ? redactText(cause.message) : void 0;
131
+ causes.push({ class: classOf(cause), ...message ? { message } : {} });
132
+ cause = cause instanceof Error ? cause.cause : void 0;
133
+ }
134
+ return causes;
135
+ }, "causesOf");
136
+ var framesOf = /* @__PURE__ */ __name((error, limit = FRAMES_AT_MOST) => {
137
+ const stack = error instanceof Error && typeof error.stack === "string" ? error.stack : "";
138
+ return stack.split("\n").filter((line) => line.trimStart().startsWith("at ")).flatMap((line) => {
139
+ const match = /^\s*at (?:async )?(?:(.+?) \()?(.+?):(\d+):\d+\)?$/.exec(line);
140
+ if (!match)
141
+ return [];
142
+ const [, fn, path = "", lineNumber] = match;
143
+ if (path.startsWith("node:"))
144
+ return [];
145
+ return [`${fn ?? "<anonymous>"} ${fileOf(path)}:${lineNumber}`];
146
+ }).slice(0, limit);
147
+ }, "framesOf");
148
+ var fileOf = /* @__PURE__ */ __name((path) => {
149
+ const plain = path.replace(/^file:\/\//, "");
150
+ const packaged = /\/node_modules\/((?:@[^/]+\/)?[^/]+\/.+)$/.exec(plain)?.[1];
151
+ if (packaged)
152
+ return packaged.replace(/\/(?:dist|src)\//, "/");
153
+ return /(?:^|\/)(?:dist|src)\/(.+)$/.exec(plain)?.[1] ?? plain.split("/").at(-1) ?? "?";
154
+ }, "fileOf");
155
+ var endpointTemplate = /* @__PURE__ */ __name((raw) => {
156
+ const trimmed = raw.trim().split(/[?#]/)[0] ?? "";
157
+ const origin = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]*@)?([^/]*)/i.exec(trimmed);
158
+ const path = origin ? trimmed.slice(origin[0].length) : trimmed;
159
+ const scheme = origin ? `${trimmed.slice(0, trimmed.indexOf("://"))}://${origin[1]}` : "";
160
+ const parts = path.split("/");
161
+ const segments = parts.map((segment, at) => {
162
+ if (segment === "" || /^[:{].+/.test(segment))
163
+ return segment;
164
+ if (at >= 2 && parts[at - 2] === "rest" && /^\d+$/.test(parts[at - 1] ?? ""))
165
+ return ":token";
166
+ if (/^bot\d+:/.test(segment) || /^\d{6,}:[\w-]{20,}$/.test(segment))
167
+ return ":token";
168
+ if (/^-?\d+$/.test(segment) || /^[0-9a-f-]{16,}$/i.test(segment))
169
+ return ":id";
170
+ if (!/^[A-Za-z0-9._~-]{1,40}$/.test(segment))
171
+ return ":value";
172
+ return segment;
173
+ });
174
+ return `${scheme}${segments.join("/")}`.slice(0, 300);
175
+ }, "endpointTemplate");
176
+ var INTERNATIONAL_PHONE = /\+\d[\d\s()-]{6,}\d/.source;
177
+ var BARE_PHONE = /(^|[^\w-])\d{11,15}\b/.source;
178
+ var MESSENGER_ID = /\b\d+(?:-\d+)?(?::\d+)?@(?:s\.whatsapp\.net|g\.us|c\.us|lid|broadcast|newsletter)\b/g;
179
+ var redactText = /* @__PURE__ */ __name((text) => {
180
+ const home = homedir();
181
+ let out = home && home !== "/" ? text.split(home).join("~") : text;
182
+ out = withoutSecrets(out.replace(/"[^"\n]*"|“[^”\n]*”|«[^»\n]*»/g, '"[redacted]"')).replace(/\b(bearer|basic|token|key|password|secret)(\s*[:=]\s*|\s+)[^\s'"]+/gi, "$1$2[redacted]").replace(MESSENGER_ID, "[id]").replace(/[\w.+-]+@[\w-]+\.[\w.-]+/g, "[email]").replace(new RegExp(INTERNATIONAL_PHONE, "g"), "[number]").replace(new RegExp(BARE_PHONE, "g"), "$1[number]").replace(/\bbot\d+:[\w-]+/g, "bot[token]").replace(/\b\d{6,}:[\w-]{20,}\b/g, "[token]").replace(/(\?|&)[^\s#]*/g, "$1[redacted]").replace(/\b[A-Za-z0-9_-]{40,}\b/g, "[redacted]");
183
+ return out.length > MESSAGE_AT_MOST ? `${out.slice(0, MESSAGE_AT_MOST)}\u2026` : out;
184
+ }, "redactText");
185
+
186
+ // node_modules/.pnpm/@wirecat+cli-core@0.691.0_@wirecat+cli-base@0.113.0_commander@15.0.0_esbuild@0.28.2_typ_9a2e508bb6f63e7e29f0d776540ec8fd/node_modules/@wirecat/cli-core/dist/runs/run-context.js
187
+ var REDACTED = "[redacted]";
188
+ var keepsSuccess = /* @__PURE__ */ __name(({ record, fromFlag, env, caller, persistent = false }) => {
189
+ if (!record)
190
+ return false;
191
+ if (fromFlag)
192
+ return true;
193
+ if (persistent)
194
+ return false;
195
+ return caller !== void 0 || viaOf(env) !== "desktop";
196
+ }, "keepsSuccess");
197
+ var calls = new AsyncLocalStorage();
198
+ var withCaller = /* @__PURE__ */ __name((caller, work) => calls.run(caller, work), "withCaller");
199
+ var currentCaller = /* @__PURE__ */ __name(() => calls.getStore(), "currentCaller");
200
+ var clientHash = /* @__PURE__ */ __name((id) => createHash("sha256").update(id).digest("hex").slice(0, 8), "clientHash");
201
+ var viaOf = /* @__PURE__ */ __name((env) => env.WIRECAT_CALLER?.trim() === "desktop" ? "desktop" : "cli", "viaOf");
202
+ var agentOf = /* @__PURE__ */ __name((env) => {
203
+ const named = env.AI_AGENT?.trim().split("_")[0];
204
+ const kind = (named && plainWord(named) ? named.toLowerCase() : void 0) ?? (env.CLAUDECODE ? "claude-code" : void 0) ?? (env.CODEX_THREAD_ID || env.CODEX_SESSION_ID || env.CODEX_SANDBOX ? "codex" : void 0) ?? (env.GEMINI_CLI ? "gemini-cli" : void 0) ?? (env.OPENCODE ? "opencode" : void 0) ?? (env.CURSOR_AGENT ? "cursor" : void 0) ?? // Only `exec` is the agent's own command: OpenClaw also sets `tui-local` for what the owner types in its TUI.
205
+ (env.OPENCLAW_SHELL?.trim() === "exec" ? "openclaw" : void 0);
206
+ if (!kind)
207
+ return void 0;
208
+ const session = sessionOf(kind, env);
209
+ return {
210
+ kind,
211
+ session_id: session && SESSION.test(session) ? session : null,
212
+ // OpenClaw passes the sender and chat ids of a chat-started run in this variable; only its presence is kept.
213
+ ...kind === "openclaw" && env.OPENCLAW_CHANNEL_CONTEXT?.trim() ? { from_chat: true } : {}
214
+ };
215
+ }, "agentOf");
216
+ var SESSION = /^[A-Za-z0-9._:-]{1,128}$/;
217
+ var SESSION_VARIABLE = {
218
+ "claude-code": "CLAUDE_CODE_SESSION_ID",
219
+ codex: "CODEX_THREAD_ID",
220
+ opencode: "OPENCODE_SESSION_ID",
221
+ "hermes-agent": "HERMES_SESSION_ID"
222
+ };
223
+ var sessionOf = /* @__PURE__ */ __name((kind, env) => {
224
+ const variable = SESSION_VARIABLE[kind];
225
+ return (variable === void 0 ? void 0 : env[variable]?.trim()) || void 0;
226
+ }, "sessionOf");
227
+ var plainWord = /* @__PURE__ */ __name((word) => /^[A-Za-z][A-Za-z0-9.-]{0,39}$/.test(word), "plainWord");
228
+ var secretInputs = /* @__PURE__ */ new WeakSet();
229
+ var secretInput = /* @__PURE__ */ __name((input) => {
230
+ secretInputs.add(input);
231
+ return input;
232
+ }, "secretInput");
233
+ var secretShaped = /* @__PURE__ */ __name((word) => /:\/\/[^/@\s:]+:[^/@\s]+@/.test(word) || /(^|[^A-Za-z0-9_-])[A-Za-z0-9_-]{40,}($|[^A-Za-z0-9_-])/.test(word), "secretShaped");
234
+ var withoutPhones = /* @__PURE__ */ __name((word) => word.replace(new RegExp(INTERNATIONAL_PHONE, "g"), REDACTED).replace(new RegExp(BARE_PHONE, "g"), `$1${REDACTED}`), "withoutPhones");
235
+ var maskArgv = /* @__PURE__ */ __name((program, words, { keep = false } = {}) => {
236
+ const argv = [];
237
+ let unknownCommand;
238
+ let current = program;
239
+ let positional = 0;
240
+ let profileSeen = false;
241
+ let lost = false;
242
+ const raw = /* @__PURE__ */ __name((word) => keep && !secretShaped(word) ? withoutPhones(withoutSecrets(word, REDACTED)) : REDACTED, "raw");
243
+ const keptValue = /* @__PURE__ */ __name((name, value, input) => keep ? input && secretInputs.has(input) || secretNamed(name) ? REDACTED : raw(value) : maskedValue(name, value, input?.argChoices), "keptValue");
244
+ const optionFor = /* @__PURE__ */ __name((flag) => {
245
+ for (let at = current; at; at = at.parent) {
246
+ const found = at.options.find((option) => option.long === flag || option.short === flag);
247
+ if (found)
248
+ return found;
249
+ }
250
+ return void 0;
251
+ }, "optionFor");
252
+ for (let at = 0; at < words.length; at++) {
253
+ const word = words[at];
254
+ if (word === "--") {
255
+ argv.push("--");
256
+ for (let after = at + 1; after < words.length; after++)
257
+ argv.push(raw(words[after]));
258
+ break;
259
+ }
260
+ if (word.startsWith("-") && word.length > 1 && !NUMBER.test(word)) {
261
+ const equals = word.indexOf("=");
262
+ const flag = equals > 0 ? word.slice(0, equals) : word;
263
+ if (!/^--?[A-Za-z0-9][A-Za-z0-9-]*$/.test(flag)) {
264
+ argv.push(raw(word));
265
+ continue;
266
+ }
267
+ const option = optionFor(flag);
268
+ const name = option?.attributeName() ?? flag.replace(/^-+/, "");
269
+ if (equals > 0) {
270
+ argv.push(`${flag}=${keptValue(name, word.slice(equals + 1), option)}`);
271
+ continue;
272
+ }
273
+ argv.push(flag);
274
+ if (!option && keep && secretNamed(name) && words[at + 1] !== void 0 && !words[at + 1]?.startsWith("-")) {
275
+ at += 1;
276
+ argv.push(REDACTED);
277
+ continue;
278
+ }
279
+ if (!option || !(option.required || option.optional))
280
+ continue;
281
+ const takes = /* @__PURE__ */ __name((next) => next !== void 0 && (option.required || !next.startsWith("-") || NUMBER.test(next)), "takes");
282
+ if (takes(words[at + 1])) {
283
+ at += 1;
284
+ argv.push(keptValue(name, words[at], option));
285
+ while (option.variadic && words[at + 1] !== void 0 && !words[at + 1].startsWith("-")) {
286
+ at += 1;
287
+ argv.push(keptValue(name, words[at], option));
288
+ }
289
+ }
290
+ continue;
291
+ }
292
+ if (!lost && positional === 0) {
293
+ const sub = current.commands.find((one) => one.name() === word || one.aliases().includes(word));
294
+ if (sub) {
295
+ argv.push(word);
296
+ current = sub;
297
+ continue;
298
+ }
299
+ if (current === program && !profileSeen) {
300
+ profileSeen = true;
301
+ argv.push(keep ? raw(word) : PROFILE.test(word) && withoutPhones(withoutSecrets(word)) === word ? word : REDACTED);
302
+ continue;
303
+ }
304
+ if (current.commands.length > 0 && current.registeredArguments.length === 0) {
305
+ lost = true;
306
+ unknownCommand = commandLike(word);
307
+ argv.push(keep ? raw(word) : unknownCommand);
308
+ continue;
309
+ }
310
+ }
311
+ const declared = lost ? void 0 : current.registeredArguments;
312
+ const argument = declared?.[Math.min(positional, declared.length - 1)];
313
+ positional += 1;
314
+ argv.push(secretInputs.has(current) ? REDACTED : argument ? keptValue(argument.name(), word, argument) : raw(word));
315
+ }
316
+ return { argv, ...unknownCommand === void 0 ? {} : { unknownCommand } };
317
+ }, "maskArgv");
318
+ var NUMBER = /^-?\d+(\.\d+)?$/;
319
+ var PROFILE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
320
+ var commandLike = /* @__PURE__ */ __name((word) => /^[a-z][a-z0-9-]{0,31}$/i.test(word) && withoutSecrets(word) === word ? word : REDACTED, "commandLike");
321
+ var maskedValue = /* @__PURE__ */ __name((name, value, choices) => {
322
+ if (isContentKey(name))
323
+ return REDACTED;
324
+ if (name === "profile")
325
+ return PROFILE.test(value) ? value : REDACTED;
326
+ if (name === "json" || name === "fields")
327
+ return /^[a-z0-9_.,]{1,200}$/.test(value) ? value : REDACTED;
328
+ if (choices?.includes(value))
329
+ return value;
330
+ return safeShape(value) ? value : REDACTED;
331
+ }, "maskedValue");
332
+ var safeShape = /* @__PURE__ */ __name((value) => NUMBER.test(value) && !/^\d{11,}$/.test(value) || /^\d+(ms|s|m|h|d|w)$/.test(value) || /^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/.test(value) || value === "true" || value === "false", "safeShape");
333
+ var runContextOf = /* @__PURE__ */ __name(({ bin, command, program, argv, env, recordInput = false, caller }) => {
334
+ const masked = program && argv ? maskArgv(program, argv, { keep: recordInput === true }) : void 0;
335
+ const ifFailed = program && argv && recordInput === "failed" ? maskArgv(program, argv, { keep: true }) : void 0;
336
+ const agent = caller ? caller.agent : agentOf(env);
337
+ return {
338
+ cliCommand: command ? `${bin} ${command}` : bin,
339
+ ...masked ? { argv: masked.argv } : {},
340
+ ...ifFailed ? { argvIfFailed: ifFailed.argv } : {},
341
+ ...masked?.unknownCommand === void 0 ? {} : { unknownCommand: masked.unknownCommand },
342
+ ...agent ? { agent } : {},
343
+ via: caller?.via ?? viaOf(env),
344
+ ...caller?.mcp ? { mcp: caller.mcp } : {}
345
+ };
346
+ }, "runContextOf");
347
+
348
+ export {
349
+ providerErrorKey,
350
+ renderEvent,
351
+ errorDetailOf,
352
+ framesOf,
353
+ endpointTemplate,
354
+ keepsSuccess,
355
+ withCaller,
356
+ currentCaller,
357
+ clientHash,
358
+ agentOf,
359
+ secretInput,
360
+ maskArgv,
361
+ runContextOf
362
+ };
@@ -0,0 +1,288 @@
1
+ import { createRequire as __bundleRequire } from "node:module";
2
+ const require = __bundleRequire(import.meta.url);
3
+ import {
4
+ OAuthError,
5
+ OAuthErrorCode
6
+ } from "./chunk-5D4AEUVA.js";
7
+ import {
8
+ ACCESS_SECONDS,
9
+ REFRESH_SECONDS,
10
+ readStored
11
+ } from "./chunk-JH3UOHRE.js";
12
+ import {
13
+ __name
14
+ } from "./chunk-ZVVMGPBJ.js";
15
+
16
+ // node_modules/.pnpm/@wirecat+cli-core@0.691.0_@wirecat+cli-base@0.113.0_commander@15.0.0_esbuild@0.28.2_typ_9a2e508bb6f63e7e29f0d776540ec8fd/node_modules/@wirecat/cli-core/dist/mcp/http/oauth.js
17
+ import { createHash, randomBytes, randomInt, timingSafeEqual } from "node:crypto";
18
+ import { chmodSync, mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
19
+ import { dirname } from "node:path";
20
+ var AUTH_CODE_MS = 60 * 1e3;
21
+ var LOGIN_CODE_MS = 10 * 60 * 1e3;
22
+ var WRONG_TRIES = 5;
23
+ var WRONG_CODE_WAIT_MS = 3e4;
24
+ var MAX_CLIENTS = 10;
25
+ var CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
26
+ var hash = /* @__PURE__ */ __name((value) => createHash("sha256").update(value).digest("base64url"), "hash");
27
+ var secret = /* @__PURE__ */ __name(() => randomBytes(32).toString("base64url"), "secret");
28
+ var same = /* @__PURE__ */ __name((given, expected) => {
29
+ const left = Buffer.from(given);
30
+ const right = Buffer.from(expected);
31
+ return left.byteLength === right.byteLength && timingSafeEqual(left, right);
32
+ }, "same");
33
+ var tokenFile = /* @__PURE__ */ __name((path) => ({
34
+ read: /* @__PURE__ */ __name(() => readStored(path), "read"),
35
+ write: /* @__PURE__ */ __name((stored) => {
36
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
37
+ const temporary = `${path}.${randomBytes(16).toString("hex")}.tmp`;
38
+ writeFileSync(temporary, JSON.stringify(stored), { mode: 384, flag: "wx" });
39
+ chmodSync(temporary, 384);
40
+ renameSync(temporary, path);
41
+ }, "write")
42
+ }), "tokenFile");
43
+ var revokeAll = /* @__PURE__ */ __name((path) => rmSync(path, { force: true }), "revokeAll");
44
+ var json = /* @__PURE__ */ __name((body, status = 200) => new Response(JSON.stringify(body), {
45
+ status,
46
+ headers: { "content-type": "application/json", "cache-control": "no-store" }
47
+ }), "json");
48
+ var oauthError = /* @__PURE__ */ __name((error, description, status = 400) => json({ error, error_description: description }, status), "oauthError");
49
+ var escapeHtml = /* @__PURE__ */ __name((value) => value.replace(/[&<>"']/g, (character) => `&#${character.charCodeAt(0)};`), "escapeHtml");
50
+ var redirectAllowed = /* @__PURE__ */ __name((uri) => {
51
+ try {
52
+ const url = new URL(uri);
53
+ if (url.hash)
54
+ return false;
55
+ return url.protocol === "https:" || url.protocol === "http:" && ["localhost", "127.0.0.1"].includes(url.hostname);
56
+ } catch {
57
+ return false;
58
+ }
59
+ }, "redirectAllowed");
60
+ var ownerLogin = /* @__PURE__ */ __name(({ issuer, resource, file, appName, reaches = `your ${appName} data`, onCode, now = /* @__PURE__ */ __name(() => Date.now(), "now") }) => {
61
+ const store = tokenFile(file);
62
+ const codes = /* @__PURE__ */ new Map();
63
+ let login = { value: "", expires: 0 };
64
+ let wrong = 0;
65
+ let retryAt = 0;
66
+ let renewal;
67
+ const freshCode = /* @__PURE__ */ __name(() => {
68
+ const part = /* @__PURE__ */ __name(() => Array.from({ length: 4 }, () => CODE_ALPHABET[randomInt(CODE_ALPHABET.length)]).join(""), "part");
69
+ login = { value: `${part()}-${part()}`, expires: now() + LOGIN_CODE_MS };
70
+ clearTimeout(renewal);
71
+ renewal = setTimeout(freshCode, LOGIN_CODE_MS);
72
+ renewal.unref();
73
+ onCode(login.value, new Date(login.expires));
74
+ }, "freshCode");
75
+ freshCode();
76
+ const base = issuer.pathname.replace(/\/+$/, "");
77
+ const endpoint = /* @__PURE__ */ __name((path) => new URL(`${base}${path}`, issuer.origin).href, "endpoint");
78
+ const metadata = {
79
+ issuer: issuer.href,
80
+ authorization_endpoint: endpoint("/authorize"),
81
+ token_endpoint: endpoint("/token"),
82
+ registration_endpoint: endpoint("/register"),
83
+ response_types_supported: ["code"],
84
+ grant_types_supported: ["authorization_code", "refresh_token"],
85
+ code_challenge_methods_supported: ["S256"],
86
+ token_endpoint_auth_methods_supported: ["none", "client_secret_post", "client_secret_basic"]
87
+ };
88
+ const issue = /* @__PURE__ */ __name((stored, clientId) => {
89
+ const access = secret();
90
+ const refresh = secret();
91
+ const seconds = Math.floor(now() / 1e3);
92
+ stored.tokens = stored.tokens.filter((one) => one.expiresAt > seconds);
93
+ stored.tokens.push({ hash: hash(access), kind: "access", clientId, expiresAt: seconds + ACCESS_SECONDS }, { hash: hash(refresh), kind: "refresh", clientId, expiresAt: seconds + REFRESH_SECONDS });
94
+ store.write(stored);
95
+ return json({ access_token: access, token_type: "Bearer", expires_in: ACCESS_SECONDS, refresh_token: refresh });
96
+ }, "issue");
97
+ const clientOf = /* @__PURE__ */ __name((stored, request, form) => {
98
+ let id = form.get("client_id") ?? "";
99
+ let given = form.get("client_secret") ?? void 0;
100
+ const basic = request.headers.get("authorization");
101
+ if (basic?.startsWith("Basic ")) {
102
+ const [user = "", password = ""] = Buffer.from(basic.slice(6), "base64").toString().split(":");
103
+ id = decodeURIComponent(user);
104
+ given = decodeURIComponent(password);
105
+ }
106
+ const client = stored.clients.find((one) => one.id === id);
107
+ if (!client)
108
+ return void 0;
109
+ if (client.authMethod === "none")
110
+ return client;
111
+ return given !== void 0 && client.secretHash && same(hash(given), client.secretHash) ? client : void 0;
112
+ }, "clientOf");
113
+ const register = /* @__PURE__ */ __name(async (request) => {
114
+ const body = await request.json().catch(() => null);
115
+ const uris = Array.isArray(body?.redirect_uris) ? body.redirect_uris.filter((one) => typeof one === "string") : [];
116
+ if (uris.length === 0 || !uris.every(redirectAllowed))
117
+ return oauthError("invalid_redirect_uri", "redirect_uris must be https URLs");
118
+ const requested = body?.token_endpoint_auth_method;
119
+ const authMethod = requested === "client_secret_post" || requested === "client_secret_basic" ? requested : "none";
120
+ const clientSecret = authMethod === "none" ? void 0 : secret();
121
+ const name = typeof body?.client_name === "string" ? body.client_name.slice(0, 100) : void 0;
122
+ const client = {
123
+ id: secret(),
124
+ redirectUris: uris,
125
+ authMethod,
126
+ issuedAt: Math.floor(now() / 1e3),
127
+ ...name ? { name } : {},
128
+ ...clientSecret ? { secretHash: hash(clientSecret) } : {}
129
+ };
130
+ const stored = store.read();
131
+ const seconds = Math.floor(now() / 1e3);
132
+ const holding = new Set(stored.tokens.filter((one) => one.expiresAt > seconds).map((one) => one.clientId));
133
+ stored.clients.push(client);
134
+ while (stored.clients.length > MAX_CLIENTS) {
135
+ const idle = stored.clients.findIndex((one) => !holding.has(one.id));
136
+ if (idle === -1)
137
+ return oauthError("invalid_client_metadata", "too many logged-in apps \u2014 run mcp revoke first");
138
+ stored.clients.splice(idle, 1);
139
+ }
140
+ store.write(stored);
141
+ return json({
142
+ client_id: client.id,
143
+ client_id_issued_at: client.issuedAt,
144
+ redirect_uris: uris,
145
+ token_endpoint_auth_method: authMethod,
146
+ grant_types: ["authorization_code", "refresh_token"],
147
+ response_types: ["code"],
148
+ ...name ? { client_name: name } : {},
149
+ ...clientSecret ? { client_secret: clientSecret, client_secret_expires_at: 0 } : {}
150
+ }, 201);
151
+ }, "register");
152
+ const page = /* @__PURE__ */ __name((params, client, message) => {
153
+ const hidden = ["response_type", "client_id", "redirect_uri", "code_challenge", "code_challenge_method", "state"].map((name) => `<input type="hidden" name="${name}" value="${escapeHtml(params.get(name) ?? "")}">`).join("");
154
+ const who = escapeHtml(client.name ?? "an application");
155
+ const target = new URL(params.get("redirect_uri") ?? "");
156
+ const html = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${escapeHtml(appName)} login</title><style>body{font:16px system-ui,sans-serif;max-width:28rem;margin:3rem auto;padding:0 1rem;color:#1d2430}input[type=text]{font:20px ui-monospace,monospace;letter-spacing:.1em;width:100%;padding:.5rem;margin:.5rem 0 1rem;box-sizing:border-box}button{font:inherit;padding:.5rem 1rem}.error{color:#b42318}</style></head><body><h1>${escapeHtml(appName)}</h1><p>An app that calls itself <strong>${who}</strong> asks to reach ${escapeHtml(reaches)} through <code>${escapeHtml(appName)} mcp serve --http</code>.</p><p>After you allow it, the login goes to <strong>${escapeHtml(target.host)}</strong>. Allow only if that is the app you are connecting, such as chatgpt.com or claude.ai.</p><p>Type the code shown in WireCat Desktop, or in the terminal where the server runs. If you did not start this login, close this page.</p>${message ? `<p class="error">${escapeHtml(message)}</p>` : ""}<form method="post" action="${escapeHtml(`${base}/authorize`)}">${hidden}<label>Login code<input type="text" name="login_code" autocomplete="off" autofocus required></label><button type="submit">Allow</button></form></body></html>`;
157
+ return new Response(html, {
158
+ status: message ? 400 : 200,
159
+ headers: {
160
+ "content-type": "text/html; charset=utf-8",
161
+ "cache-control": "no-store",
162
+ "x-frame-options": "DENY",
163
+ "content-security-policy": `default-src 'none'; style-src 'unsafe-inline'; form-action 'self' ${target.origin}; frame-ancestors 'none'`,
164
+ // no-referrer makes the browser post this form with `Origin: null`, which the Origin check refuses.
165
+ "referrer-policy": "same-origin"
166
+ }
167
+ });
168
+ }, "page");
169
+ const authorize = /* @__PURE__ */ __name(async (request) => {
170
+ const params = request.method === "POST" ? new URLSearchParams(await request.text()) : new URL(request.url).searchParams;
171
+ const stored = store.read();
172
+ const client = stored.clients.find((one) => one.id === params.get("client_id"));
173
+ const redirectUri = params.get("redirect_uri") ?? "";
174
+ if (!client?.redirectUris.includes(redirectUri))
175
+ return new Response("Unknown client or redirect address.", { status: 400 });
176
+ if (params.get("response_type") !== "code" || params.get("code_challenge_method") !== "S256" || !params.get("code_challenge"))
177
+ return new Response("This server needs response_type=code and PKCE with S256.", { status: 400 });
178
+ if (request.method !== "POST")
179
+ return page(params, client);
180
+ const throttled = /* @__PURE__ */ __name(() => new Response("Too many wrong codes. Wait, then try the new code.", {
181
+ status: 429,
182
+ headers: { "retry-after": String(Math.ceil((retryAt - now()) / 1e3)) }
183
+ }), "throttled");
184
+ if (wrong >= WRONG_TRIES) {
185
+ if (now() < retryAt)
186
+ return throttled();
187
+ wrong = 0;
188
+ freshCode();
189
+ }
190
+ const typed = (params.get("login_code") ?? "").trim().toUpperCase();
191
+ if (login.expires < now()) {
192
+ freshCode();
193
+ return page(params, client, "The code expired. A new one is shown in WireCat Desktop and in the terminal.");
194
+ }
195
+ if (!same(typed, login.value)) {
196
+ wrong += 1;
197
+ if (wrong >= WRONG_TRIES) {
198
+ retryAt = now() + WRONG_CODE_WAIT_MS;
199
+ return throttled();
200
+ }
201
+ return page(params, client, `Wrong code. Each code works for one login: after an app logs in, a new one appears in WireCat Desktop and in "${appName} mcp server status". ${WRONG_TRIES - wrong} tries left.`);
202
+ }
203
+ wrong = 0;
204
+ freshCode();
205
+ const code = secret();
206
+ codes.set(hash(code), {
207
+ clientId: client.id,
208
+ redirectUri,
209
+ challenge: params.get("code_challenge") ?? "",
210
+ expires: now() + AUTH_CODE_MS
211
+ });
212
+ const target = new URL(redirectUri);
213
+ target.searchParams.set("code", code);
214
+ const state = params.get("state");
215
+ if (state)
216
+ target.searchParams.set("state", state);
217
+ target.searchParams.set("iss", issuer.href);
218
+ return new Response(null, { status: 302, headers: { location: target.href, "cache-control": "no-store" } });
219
+ }, "authorize");
220
+ const token = /* @__PURE__ */ __name(async (request) => {
221
+ const form = new URLSearchParams(await request.text());
222
+ const stored = store.read();
223
+ const client = clientOf(stored, request, form);
224
+ if (!client)
225
+ return oauthError("invalid_client", "unknown client or wrong secret", 401);
226
+ const requestedResource = form.get("resource");
227
+ if (requestedResource && requestedResource !== resource.href)
228
+ return oauthError("invalid_target", "this server issues tokens only for its own MCP endpoint");
229
+ if (form.get("grant_type") === "authorization_code") {
230
+ const key = hash(form.get("code") ?? "");
231
+ const entry = codes.get(key);
232
+ codes.delete(key);
233
+ const verifier2 = form.get("code_verifier") ?? "";
234
+ const challenge = createHash("sha256").update(verifier2).digest("base64url");
235
+ if (!entry || entry.expires < now() || entry.clientId !== client.id || entry.redirectUri !== form.get("redirect_uri") || !same(challenge, entry.challenge))
236
+ return oauthError("invalid_grant", "the code is wrong, used or expired");
237
+ return issue(stored, client.id);
238
+ }
239
+ if (form.get("grant_type") === "refresh_token") {
240
+ const key = hash(form.get("refresh_token") ?? "");
241
+ const seconds = Math.floor(now() / 1e3);
242
+ const found = stored.tokens.find((one) => one.kind === "refresh" && one.hash === key);
243
+ if (!found || found.clientId !== client.id || found.expiresAt <= seconds)
244
+ return oauthError("invalid_grant", "the refresh token is wrong, used or expired");
245
+ stored.tokens = stored.tokens.filter((one) => one !== found);
246
+ return issue(stored, client.id);
247
+ }
248
+ return oauthError("unsupported_grant_type", "use authorization_code or refresh_token");
249
+ }, "token");
250
+ const verifier = {
251
+ verifyAccessToken: /* @__PURE__ */ __name(async (presented) => {
252
+ const seconds = Math.floor(now() / 1e3);
253
+ const stored = store.read();
254
+ const found = stored.tokens.find((one) => one.kind === "access" && one.hash === hash(presented));
255
+ if (!found || found.expiresAt <= seconds)
256
+ throw new OAuthError(OAuthErrorCode.InvalidToken, "the token is unknown or expired");
257
+ const clientName = stored.clients.find((one) => one.id === found.clientId)?.name;
258
+ return {
259
+ token: presented,
260
+ clientId: found.clientId,
261
+ scopes: [],
262
+ expiresAt: found.expiresAt,
263
+ resource,
264
+ ...clientName ? { extra: { clientName } } : {}
265
+ };
266
+ }, "verifyAccessToken")
267
+ };
268
+ return {
269
+ code: /* @__PURE__ */ __name(() => login.value, "code"),
270
+ close: /* @__PURE__ */ __name(() => clearTimeout(renewal), "close"),
271
+ metadata,
272
+ verifier,
273
+ handle: /* @__PURE__ */ __name(async (request, path = new URL(request.url).pathname) => {
274
+ if (path === `${base}/register` && request.method === "POST")
275
+ return register(request);
276
+ if (path === `${base}/authorize` && (request.method === "GET" || request.method === "POST"))
277
+ return authorize(request);
278
+ if (path === `${base}/token` && request.method === "POST")
279
+ return token(request);
280
+ return void 0;
281
+ }, "handle")
282
+ };
283
+ }, "ownerLogin");
284
+
285
+ export {
286
+ revokeAll,
287
+ ownerLogin
288
+ };