@kodycodes/cli 1.26.1 → 1.26.3

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 (271) hide show
  1. package/dist/auth-4FW6GCLG.js +26 -0
  2. package/dist/auth-4FW6GCLG.js.map +6 -0
  3. package/dist/bin.js +27 -3
  4. package/dist/bin.js.map +6 -1
  5. package/dist/chunk-46IJPEID.js +30 -0
  6. package/dist/chunk-46IJPEID.js.map +6 -0
  7. package/dist/chunk-4D6ORNXY.js +24404 -0
  8. package/dist/chunk-4D6ORNXY.js.map +6 -0
  9. package/dist/chunk-64IM6G4Z.js +341 -0
  10. package/dist/chunk-64IM6G4Z.js.map +6 -0
  11. package/dist/{package-local-runtime-source.js → chunk-64XN367G.js} +373 -52
  12. package/dist/chunk-64XN367G.js.map +6 -0
  13. package/dist/chunk-6XQP5SWX.js +26 -0
  14. package/dist/chunk-6XQP5SWX.js.map +6 -0
  15. package/dist/chunk-75RZUXQL.js +62 -0
  16. package/dist/chunk-75RZUXQL.js.map +6 -0
  17. package/dist/chunk-BISUL7CE.js +106 -0
  18. package/dist/chunk-BISUL7CE.js.map +6 -0
  19. package/dist/chunk-BPGY4IE7.js +57 -0
  20. package/dist/chunk-BPGY4IE7.js.map +6 -0
  21. package/dist/chunk-CASGRYOF.js +21 -0
  22. package/dist/chunk-CASGRYOF.js.map +6 -0
  23. package/dist/chunk-CWWHR4FH.js +19 -0
  24. package/dist/chunk-CWWHR4FH.js.map +6 -0
  25. package/dist/chunk-D55XPY3T.js +1382 -0
  26. package/dist/chunk-D55XPY3T.js.map +6 -0
  27. package/dist/chunk-EOCV74B2.js +948 -0
  28. package/dist/chunk-EOCV74B2.js.map +6 -0
  29. package/dist/chunk-FBVNFWR6.js +437 -0
  30. package/dist/chunk-FBVNFWR6.js.map +6 -0
  31. package/dist/chunk-G4YN6XP5.js +14 -0
  32. package/dist/chunk-G4YN6XP5.js.map +6 -0
  33. package/dist/chunk-G6LJWROP.js +18 -0
  34. package/dist/chunk-G6LJWROP.js.map +6 -0
  35. package/dist/chunk-IHP6PV6X.js +49 -0
  36. package/dist/chunk-IHP6PV6X.js.map +6 -0
  37. package/dist/chunk-JWEFKKAD.js +24 -0
  38. package/dist/chunk-JWEFKKAD.js.map +6 -0
  39. package/dist/chunk-LWNB26KO.js +147 -0
  40. package/dist/chunk-LWNB26KO.js.map +6 -0
  41. package/dist/chunk-OVGXPRSY.js +20 -0
  42. package/dist/chunk-OVGXPRSY.js.map +6 -0
  43. package/dist/chunk-PDWCKWQF.js +453 -0
  44. package/dist/chunk-PDWCKWQF.js.map +6 -0
  45. package/dist/chunk-QHBCP4OB.js +44 -0
  46. package/dist/chunk-QHBCP4OB.js.map +6 -0
  47. package/dist/chunk-R4IUV5P5.js +664 -0
  48. package/dist/chunk-R4IUV5P5.js.map +6 -0
  49. package/dist/chunk-RM34N3KI.js +525 -0
  50. package/dist/chunk-RM34N3KI.js.map +6 -0
  51. package/dist/chunk-RTWUNV76.js +309 -0
  52. package/dist/chunk-RTWUNV76.js.map +6 -0
  53. package/dist/chunk-SMURF26I.js +23 -0
  54. package/dist/chunk-SMURF26I.js.map +6 -0
  55. package/dist/chunk-SXHULGL4.js +426 -0
  56. package/dist/chunk-SXHULGL4.js.map +6 -0
  57. package/dist/chunk-TIL35OWA.js +1959 -0
  58. package/dist/chunk-TIL35OWA.js.map +6 -0
  59. package/dist/chunk-VQS5YSCI.js +54 -0
  60. package/dist/chunk-VQS5YSCI.js.map +6 -0
  61. package/dist/chunk-XDCOWU5R.js +696 -0
  62. package/dist/chunk-XDCOWU5R.js.map +6 -0
  63. package/dist/chunk-XOPPGRUP.js +605 -0
  64. package/dist/chunk-XOPPGRUP.js.map +6 -0
  65. package/dist/cli.js +74 -1500
  66. package/dist/cli.js.map +6 -1
  67. package/dist/dev/dev-watcher.d.ts +5 -1
  68. package/dist/dev-command-3LX234N6.js +4900 -0
  69. package/dist/dev-command-3LX234N6.js.map +6 -0
  70. package/dist/git-credential-FUE3JE3T.js +163 -0
  71. package/dist/git-credential-FUE3JE3T.js.map +6 -0
  72. package/dist/install-ZML2TCDG.js +10694 -0
  73. package/dist/install-ZML2TCDG.js.map +6 -0
  74. package/dist/local-execute-SZV6XN4T.js +368 -0
  75. package/dist/local-execute-SZV6XN4T.js.map +6 -0
  76. package/dist/local-package-run-2TMCAZZ2.js +23 -0
  77. package/dist/local-package-run-2TMCAZZ2.js.map +6 -0
  78. package/dist/mcp-G2AWTIXR.js +21 -0
  79. package/dist/mcp-G2AWTIXR.js.map +6 -0
  80. package/dist/mock-dep-resolve-TVABDNR7.js +52 -0
  81. package/dist/mock-dep-resolve-TVABDNR7.js.map +6 -0
  82. package/dist/mock-fetch-gateway-B5TFGGQS.js +34 -0
  83. package/dist/mock-fetch-gateway-B5TFGGQS.js.map +6 -0
  84. package/dist/mock-local-deps-5SZT3PWT.js +197 -0
  85. package/dist/mock-local-deps-5SZT3PWT.js.map +6 -0
  86. package/dist/mock-server-SV2IKC4I.js +21 -0
  87. package/dist/mock-server-SV2IKC4I.js.map +6 -0
  88. package/dist/open-api-client-DVVMLY7P.js +42 -0
  89. package/dist/open-api-client-DVVMLY7P.js.map +6 -0
  90. package/dist/org-X7B5BI4R.js +132 -0
  91. package/dist/org-X7B5BI4R.js.map +6 -0
  92. package/dist/package-manifest-QH2RU64C.js +14 -0
  93. package/dist/package-manifest-QH2RU64C.js.map +6 -0
  94. package/dist/remote-execute-QMQDVHOY.js +110 -0
  95. package/dist/remote-execute-QMQDVHOY.js.map +6 -0
  96. package/dist/setup-git-5KCUBYPB.js +88 -0
  97. package/dist/setup-git-5KCUBYPB.js.map +6 -0
  98. package/dist/skill-ENPATRIW.js +43 -0
  99. package/dist/skill-ENPATRIW.js.map +6 -0
  100. package/dist/store-WTMRH527.js +48 -0
  101. package/dist/store-WTMRH527.js.map +6 -0
  102. package/dist/structured-error-C65GQ53Z.js +13 -0
  103. package/dist/structured-error-C65GQ53Z.js.map +6 -0
  104. package/dist/target-3QHY7JT4.js +45 -0
  105. package/dist/target-3QHY7JT4.js.map +6 -0
  106. package/dist/webapi-NTVP4BO3.js +2482 -0
  107. package/dist/webapi-NTVP4BO3.js.map +6 -0
  108. package/package.json +8 -8
  109. package/dist/add-mcp-install.js +0 -59
  110. package/dist/add-mcp-install.js.map +0 -1
  111. package/dist/api-token-store.js +0 -120
  112. package/dist/api-token-store.js.map +0 -1
  113. package/dist/api-token.js +0 -238
  114. package/dist/api-token.js.map +0 -1
  115. package/dist/auth-bootstrap.js +0 -373
  116. package/dist/auth-bootstrap.js.map +0 -1
  117. package/dist/auth.js +0 -386
  118. package/dist/auth.js.map +0 -1
  119. package/dist/capability-proxy.js +0 -527
  120. package/dist/capability-proxy.js.map +0 -1
  121. package/dist/credential-call-map.js +0 -155
  122. package/dist/credential-call-map.js.map +0 -1
  123. package/dist/credential-client-runtime-source.js +0 -9
  124. package/dist/credential-client-runtime-source.js.map +0 -1
  125. package/dist/credentialed-fetch-scan.js +0 -98
  126. package/dist/credentialed-fetch-scan.js.map +0 -1
  127. package/dist/defaults.js +0 -34
  128. package/dist/defaults.js.map +0 -1
  129. package/dist/detect-running-hosts.js +0 -13
  130. package/dist/detect-running-hosts.js.map +0 -1
  131. package/dist/dev/dev-assets.js +0 -202
  132. package/dist/dev/dev-assets.js.map +0 -1
  133. package/dist/dev/dev-bundler.js +0 -65
  134. package/dist/dev/dev-bundler.js.map +0 -1
  135. package/dist/dev/dev-events.js +0 -94
  136. package/dist/dev/dev-events.js.map +0 -1
  137. package/dist/dev/dev-port.js +0 -80
  138. package/dist/dev/dev-port.js.map +0 -1
  139. package/dist/dev/dev-protocol.js +0 -14
  140. package/dist/dev/dev-protocol.js.map +0 -1
  141. package/dist/dev/dev-registry.js +0 -95
  142. package/dist/dev/dev-registry.js.map +0 -1
  143. package/dist/dev/dev-watcher.js +0 -156
  144. package/dist/dev/dev-watcher.js.map +0 -1
  145. package/dist/dev/error-page.js +0 -64
  146. package/dist/dev/error-page.js.map +0 -1
  147. package/dist/dev/live-reload.js +0 -148
  148. package/dist/dev/live-reload.js.map +0 -1
  149. package/dist/dev/prebuild.js +0 -102
  150. package/dist/dev/prebuild.js.map +0 -1
  151. package/dist/dev/process-reaper.js +0 -151
  152. package/dist/dev/process-reaper.js.map +0 -1
  153. package/dist/dev/stack-trace.js +0 -56
  154. package/dist/dev/stack-trace.js.map +0 -1
  155. package/dist/dev/workerd-process.js +0 -118
  156. package/dist/dev/workerd-process.js.map +0 -1
  157. package/dist/dev-command.js +0 -672
  158. package/dist/dev-command.js.map +0 -1
  159. package/dist/discover-login-identity.js +0 -77
  160. package/dist/discover-login-identity.js.map +0 -1
  161. package/dist/discover-org.js +0 -62
  162. package/dist/discover-org.js.map +0 -1
  163. package/dist/git-credential.js +0 -147
  164. package/dist/git-credential.js.map +0 -1
  165. package/dist/help.js +0 -333
  166. package/dist/help.js.map +0 -1
  167. package/dist/host-catalog.js +0 -427
  168. package/dist/host-catalog.js.map +0 -1
  169. package/dist/host-config.js +0 -80
  170. package/dist/host-config.js.map +0 -1
  171. package/dist/http-error-body.js +0 -35
  172. package/dist/http-error-body.js.map +0 -1
  173. package/dist/install-hosts.js +0 -328
  174. package/dist/install-hosts.js.map +0 -1
  175. package/dist/install.js +0 -120
  176. package/dist/install.js.map +0 -1
  177. package/dist/invoke-passthrough.js +0 -60
  178. package/dist/invoke-passthrough.js.map +0 -1
  179. package/dist/local-bundle.js +0 -200
  180. package/dist/local-bundle.js.map +0 -1
  181. package/dist/local-execute-auth.js +0 -53
  182. package/dist/local-execute-auth.js.map +0 -1
  183. package/dist/local-execute.js +0 -338
  184. package/dist/local-execute.js.map +0 -1
  185. package/dist/local-gateway-fetch-forward.js +0 -135
  186. package/dist/local-gateway-fetch-forward.js.map +0 -1
  187. package/dist/local-host-runtime-surface.js +0 -75
  188. package/dist/local-host-runtime-surface.js.map +0 -1
  189. package/dist/local-package-graph.js +0 -405
  190. package/dist/local-package-graph.js.map +0 -1
  191. package/dist/local-package-run.js +0 -307
  192. package/dist/local-package-run.js.map +0 -1
  193. package/dist/local-runtime-bridge.js +0 -132
  194. package/dist/local-runtime-bridge.js.map +0 -1
  195. package/dist/local-runtime-source.js +0 -541
  196. package/dist/local-runtime-source.js.map +0 -1
  197. package/dist/login-callback-assets.js +0 -10
  198. package/dist/login-callback-assets.js.map +0 -1
  199. package/dist/login-callback-page.js +0 -362
  200. package/dist/login-callback-page.js.map +0 -1
  201. package/dist/mcp.js +0 -134
  202. package/dist/mcp.js.map +0 -1
  203. package/dist/mock/ensure-msw.js +0 -215
  204. package/dist/mock/ensure-msw.js.map +0 -1
  205. package/dist/mock/install-mock-fetch-shim.js +0 -36
  206. package/dist/mock/install-mock-fetch-shim.js.map +0 -1
  207. package/dist/mock/load-package-mocks.js +0 -136
  208. package/dist/mock/load-package-mocks.js.map +0 -1
  209. package/dist/mock/mock-fetch-gateway.js +0 -343
  210. package/dist/mock/mock-fetch-gateway.js.map +0 -1
  211. package/dist/mock/mock-gateway-fetch-shim.js +0 -104
  212. package/dist/mock/mock-gateway-fetch-shim.js.map +0 -1
  213. package/dist/mock/mock-server.js +0 -499
  214. package/dist/mock/mock-server.js.map +0 -1
  215. package/dist/mock/mock-storage.js +0 -186
  216. package/dist/mock/mock-storage.js.map +0 -1
  217. package/dist/mock/mock-supported.js +0 -63
  218. package/dist/mock/mock-supported.js.map +0 -1
  219. package/dist/mock-dep-resolve.js +0 -47
  220. package/dist/mock-dep-resolve.js.map +0 -1
  221. package/dist/mock-local-deps.js +0 -207
  222. package/dist/mock-local-deps.js.map +0 -1
  223. package/dist/network-error.js +0 -11
  224. package/dist/network-error.js.map +0 -1
  225. package/dist/node-engine.js +0 -21
  226. package/dist/node-engine.js.map +0 -1
  227. package/dist/oauth-provider.js +0 -107
  228. package/dist/oauth-provider.js.map +0 -1
  229. package/dist/onboarding-prompt.js +0 -15
  230. package/dist/onboarding-prompt.js.map +0 -1
  231. package/dist/open-api-client.js +0 -432
  232. package/dist/open-api-client.js.map +0 -1
  233. package/dist/open-url.js +0 -21
  234. package/dist/open-url.js.map +0 -1
  235. package/dist/org-resolve.js +0 -16
  236. package/dist/org-resolve.js.map +0 -1
  237. package/dist/org-slug.js +0 -11
  238. package/dist/org-slug.js.map +0 -1
  239. package/dist/org.js +0 -100
  240. package/dist/org.js.map +0 -1
  241. package/dist/package-app-dev.js +0 -905
  242. package/dist/package-app-dev.js.map +0 -1
  243. package/dist/package-collaborators.js +0 -179
  244. package/dist/package-collaborators.js.map +0 -1
  245. package/dist/package-info.js +0 -19
  246. package/dist/package-info.js.map +0 -1
  247. package/dist/package-local-runtime-source.js.map +0 -1
  248. package/dist/package-manifest.js +0 -364
  249. package/dist/package-manifest.js.map +0 -1
  250. package/dist/process-info.js +0 -14
  251. package/dist/process-info.js.map +0 -1
  252. package/dist/redact.js +0 -16
  253. package/dist/redact.js.map +0 -1
  254. package/dist/remote-execute.js +0 -108
  255. package/dist/remote-execute.js.map +0 -1
  256. package/dist/setup-git.js +0 -676
  257. package/dist/setup-git.js.map +0 -1
  258. package/dist/skill.js +0 -35
  259. package/dist/skill.js.map +0 -1
  260. package/dist/store.js +0 -597
  261. package/dist/store.js.map +0 -1
  262. package/dist/structured-error.js +0 -57
  263. package/dist/structured-error.js.map +0 -1
  264. package/dist/target.js +0 -52
  265. package/dist/target.js.map +0 -1
  266. package/dist/tool-result.js +0 -19
  267. package/dist/tool-result.js.map +0 -1
  268. package/dist/which.js +0 -22
  269. package/dist/which.js.map +0 -1
  270. package/dist/workerd-binary.js +0 -98
  271. package/dist/workerd-binary.js.map +0 -1
@@ -0,0 +1,696 @@
1
+ import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
+ import {
3
+ unmockedRequestError
4
+ } from "./chunk-XOPPGRUP.js";
5
+ import {
6
+ StructuredCliError,
7
+ notImplementedInMock
8
+ } from "./chunk-BPGY4IE7.js";
9
+ import {
10
+ userCacheDir
11
+ } from "./chunk-BISUL7CE.js";
12
+
13
+ // src/mock/mock-server.ts
14
+ import {
15
+ createServer
16
+ } from "node:http";
17
+
18
+ // src/mock/mock-supported.ts
19
+ var mockOpenApiOperationIds = [
20
+ "search",
21
+ "metaGetCurrentUser",
22
+ "usageGet"
23
+ ];
24
+ var mockCapabilityPaths = [
25
+ "kody.metaGetCurrentUser",
26
+ "kody.search",
27
+ "kody.execute",
28
+ "kody.usageGet",
29
+ // Local package scratch storage via capability hops used by packageStorage()
30
+ // bridging in the mock runtime (see mock-server call dispatch).
31
+ "kody.__mockPackageStorageGet",
32
+ "kody.__mockPackageStorageSet",
33
+ "kody.__mockPackageStorageDelete",
34
+ "kody.__mockPackageStorageList",
35
+ "kody.__mockPackageStorageSql",
36
+ // Published package-app-kit / packageStorage helpers may hop these names
37
+ // directly (same scratch store as the __mock* bridges above).
38
+ "kody.packageStorageGet",
39
+ "kody.packageStorageSet",
40
+ "kody.packageStorageDelete",
41
+ "kody.packageStorageList",
42
+ "kody.packageStorageSql",
43
+ // Credential client: fake metadata + handles only (never prod secrets).
44
+ "kody.credentialClientOpen",
45
+ "kody.credentialClientOpenAll",
46
+ "kody.credentialClientCheck",
47
+ "kody.credentialClientRefresh",
48
+ // OAuth / ambient outbound hops — intercepted by the Node MSW gateway on
49
+ // --target mock (see mock-fetch-gateway.ts). Listed here so CapabilityProxy
50
+ // session probes treat them as known; the mock HTTP server refuses with
51
+ // unmocked_request if a call somehow bypasses the bridge.
52
+ "kody.authenticatedFetch",
53
+ "kody.gatewayFetch",
54
+ "kody.gatewayFetchStream",
55
+ // Read-only admin fixture so gift-cliff-ops-style packages can smoke locally.
56
+ "kody.adminUserList"
57
+ ];
58
+ function isMockCapabilityPath(pathKey) {
59
+ return mockCapabilityPaths.includes(pathKey);
60
+ }
61
+
62
+ // src/mock/mock-storage.ts
63
+ import { mkdirSync } from "node:fs";
64
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
65
+ import { join } from "node:path";
66
+ import { DatabaseSync } from "node:sqlite";
67
+ var mockStateFile = "state.json";
68
+ function mockSessionRoot(sessionId, env = process.env) {
69
+ return join(userCacheDir(env), "mock-sessions", sessionId);
70
+ }
71
+ function defaultMockSessionId(env = process.env) {
72
+ return env.KODY_MOCK_SESSION_ID?.trim() || "default";
73
+ }
74
+ async function loadMockSession(input) {
75
+ const env = input.env ?? process.env;
76
+ const sessionId = input.sessionId ?? defaultMockSessionId(env);
77
+ const root = mockSessionRoot(sessionId, env);
78
+ if (input.reset) {
79
+ await rm(root, { recursive: true, force: true });
80
+ }
81
+ await mkdir(root, { recursive: true });
82
+ const path = join(root, mockStateFile);
83
+ try {
84
+ const raw = JSON.parse(await readFile(path, "utf8"));
85
+ if (raw?.version === 1 && raw.sessionId === sessionId) {
86
+ return normalizeMockSessionCredentials(raw);
87
+ }
88
+ } catch {
89
+ }
90
+ const now = (/* @__PURE__ */ new Date()).toISOString();
91
+ const fresh = {
92
+ version: 1,
93
+ sessionId,
94
+ createdAt: now,
95
+ updatedAt: now,
96
+ packageStorage: {},
97
+ credentials: {
98
+ MOCK_SECRET: {
99
+ id: "cred_mock_secret",
100
+ name: "MOCK_SECRET",
101
+ kind: "secret",
102
+ hosts: ["example.com"],
103
+ scope: "personal",
104
+ mockValue: "mock-secret-value"
105
+ }
106
+ },
107
+ searchCatalog: [
108
+ {
109
+ type: "guide",
110
+ id: "local_execute",
111
+ title: "Local CLI execute",
112
+ description: "Prefer @kodycodes/cli execute --local when Node \u226522."
113
+ },
114
+ {
115
+ type: "capability",
116
+ id: "metaGetCurrentUser",
117
+ title: "metaGetCurrentUser",
118
+ description: "Return the current authenticated user and org binding."
119
+ },
120
+ {
121
+ type: "guide",
122
+ id: "package_apps",
123
+ title: "Package apps",
124
+ description: "Hosted Worker apps on *.kody.run; use kody dev for local."
125
+ }
126
+ ]
127
+ };
128
+ await persistMockSession(fresh, env);
129
+ return fresh;
130
+ }
131
+ async function persistMockSession(state, env = process.env) {
132
+ state.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
133
+ const root = mockSessionRoot(state.sessionId, env);
134
+ await mkdir(root, { recursive: true });
135
+ await writeFile(join(root, mockStateFile), `${JSON.stringify(state, null, 2)}
136
+ `);
137
+ }
138
+ function normalizeMockSessionCredentials(state) {
139
+ const credentials = {};
140
+ for (const [key, cred] of Object.entries(state.credentials ?? {})) {
141
+ credentials[key] = {
142
+ ...cred,
143
+ hosts: Array.isArray(cred.hosts) && cred.hosts.length > 0 ? cred.hosts : ["example.com"],
144
+ scope: cred.scope === "org" ? "org" : "personal"
145
+ };
146
+ }
147
+ if (!credentials.MOCK_SECRET) {
148
+ credentials.MOCK_SECRET = {
149
+ id: "cred_mock_secret",
150
+ name: "MOCK_SECRET",
151
+ kind: "secret",
152
+ hosts: ["example.com"],
153
+ scope: "personal",
154
+ mockValue: "mock-secret-value"
155
+ };
156
+ }
157
+ state.credentials = credentials;
158
+ return state;
159
+ }
160
+ function packageStorageGet(state, packageId, key) {
161
+ return state.packageStorage[packageId]?.rows[key];
162
+ }
163
+ function packageStorageSet(state, packageId, key, value) {
164
+ const bucket = state.packageStorage[packageId] ??= { rows: {} };
165
+ bucket.rows[key] = value;
166
+ }
167
+ function packageStorageDelete(state, packageId, key) {
168
+ const bucket = state.packageStorage[packageId];
169
+ if (!bucket || !(key in bucket.rows)) return false;
170
+ delete bucket.rows[key];
171
+ return true;
172
+ }
173
+ function packageStorageList(state, packageId) {
174
+ const rows = state.packageStorage[packageId]?.rows ?? {};
175
+ return Object.entries(rows).map(([key, value]) => ({ key, value }));
176
+ }
177
+ var openSqlDbs = /* @__PURE__ */ new Map();
178
+ function packageSqlDbPath(state, packageId, env = process.env) {
179
+ const safe = packageId.replace(/[^a-zA-Z0-9._-]+/g, "_");
180
+ const dir = join(mockSessionRoot(state.sessionId, env), "sqlite");
181
+ mkdirSync(dir, { recursive: true });
182
+ return join(dir, `${safe || "package"}.sqlite`);
183
+ }
184
+ function openPackageSqlDb(state, packageId, env = process.env) {
185
+ const path = packageSqlDbPath(state, packageId, env);
186
+ const cacheKey = `${state.sessionId}:${path}`;
187
+ const existing = openSqlDbs.get(cacheKey);
188
+ if (existing) return existing;
189
+ const db = new DatabaseSync(path);
190
+ openSqlDbs.set(cacheKey, db);
191
+ return db;
192
+ }
193
+ function closePackageSqlDbsForSession(sessionId) {
194
+ for (const [key, db] of openSqlDbs) {
195
+ if (!key.startsWith(`${sessionId}:`)) continue;
196
+ try {
197
+ db.close();
198
+ } catch {
199
+ }
200
+ openSqlDbs.delete(key);
201
+ }
202
+ }
203
+ function packageStorageSql(state, packageId, query, bindings = [], env = process.env) {
204
+ const db = openPackageSqlDb(state, packageId, env);
205
+ const stmt = db.prepare(query);
206
+ const params = bindings.map((value) => {
207
+ if (value === null) return null;
208
+ if (typeof value === "string" || typeof value === "number" || typeof value === "bigint") {
209
+ return value;
210
+ }
211
+ if (typeof value === "boolean") return value ? 1 : 0;
212
+ if (value instanceof Uint8Array) return value;
213
+ return String(value);
214
+ });
215
+ const trimmed = query.trimStart().toLowerCase();
216
+ const isQuery = trimmed.startsWith("select") || trimmed.startsWith("with") || trimmed.startsWith("pragma") || trimmed.startsWith("explain");
217
+ if (isQuery) {
218
+ const rows = stmt.all(...params);
219
+ return { rows };
220
+ }
221
+ const info = stmt.run(...params);
222
+ return { rows: [], changes: typeof info.changes === "number" ? info.changes : 0 };
223
+ }
224
+
225
+ // src/mock/mock-server.ts
226
+ var mockTokenPrefix = "kody_mock_";
227
+ function isMockApiToken(token) {
228
+ return token.startsWith(mockTokenPrefix) || token === "mock";
229
+ }
230
+ function mintMockApiToken(sessionId) {
231
+ return `${mockTokenPrefix}${sessionId}`;
232
+ }
233
+ async function startMockServer(options = {}) {
234
+ const sessionIdForClose = options.sessionId?.trim() || defaultMockSessionId(options.env ?? process.env);
235
+ if (options.resetStorage) {
236
+ closePackageSqlDbsForSession(sessionIdForClose);
237
+ }
238
+ let state = await loadMockSession({
239
+ sessionId: options.sessionId,
240
+ env: options.env,
241
+ reset: options.resetStorage
242
+ });
243
+ const packageId = options.packageId ?? `local-${state.sessionId}`;
244
+ const orgSlug = options.orgSlug?.trim() || "mock-org";
245
+ const env = options.env;
246
+ const server = createServer((req, res) => {
247
+ void handleRequest(req, res, {
248
+ getState: () => state,
249
+ setState: async (next) => {
250
+ state = next;
251
+ await persistMockSession(state, env);
252
+ },
253
+ packageId,
254
+ orgSlug,
255
+ env
256
+ });
257
+ });
258
+ const host = options.host ?? "127.0.0.1";
259
+ const port = options.port ?? 0;
260
+ await new Promise((resolve, reject) => {
261
+ server.once("error", reject);
262
+ server.listen(port, host, () => resolve());
263
+ });
264
+ const address = server.address();
265
+ const url = `http://${host}:${address.port}`;
266
+ return {
267
+ url,
268
+ port: address.port,
269
+ sessionId: state.sessionId,
270
+ state: () => state,
271
+ close: () => new Promise((resolve, reject) => {
272
+ server.close((error) => error ? reject(error) : resolve());
273
+ })
274
+ };
275
+ }
276
+ async function ensureMockTarget(input) {
277
+ if (input.existing) {
278
+ return {
279
+ apiUrl: input.existing.url,
280
+ token: mintMockApiToken(input.existing.sessionId),
281
+ server: input.existing,
282
+ started: false
283
+ };
284
+ }
285
+ const server = await startMockServer({
286
+ sessionId: input.sessionId,
287
+ resetStorage: input.resetStorage,
288
+ packageId: input.packageId,
289
+ orgSlug: input.orgSlug,
290
+ env: input.env
291
+ });
292
+ return {
293
+ apiUrl: server.url,
294
+ token: mintMockApiToken(server.sessionId),
295
+ server,
296
+ started: true
297
+ };
298
+ }
299
+ async function handleRequest(req, res, ctx) {
300
+ try {
301
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
302
+ const method = (req.method ?? "GET").toUpperCase();
303
+ const body = await readJsonBody(req);
304
+ const requestOrg = url.searchParams.get("org")?.trim() || void 0;
305
+ const effectiveOrg = requestOrg || ctx.orgSlug;
306
+ const callCtx = { ...ctx, orgSlug: effectiveOrg };
307
+ if (method === "GET" && url.pathname === "/openapi.json") {
308
+ return sendJson(res, 200, mockOpenApiDocument());
309
+ }
310
+ if (method === "GET" && url.pathname === "/v1/capability-proxy/session") {
311
+ assertMockAuth(req);
312
+ return sendJson(res, 200, {
313
+ scopes: ["org:execute", "org:read", "package:execute", "package:read", "search:read"],
314
+ features: ["local-execute", "credential-call-map"],
315
+ expiresAt: new Date(Date.now() + 864e5).toISOString()
316
+ });
317
+ }
318
+ if (method === "POST" && url.pathname === "/v1/capability-proxy/call") {
319
+ assertMockAuth(req);
320
+ const path = Array.isArray(body?.path) ? body.path : null;
321
+ const args = Array.isArray(body?.args) ? body.args : [];
322
+ if (!path || path.length === 0) {
323
+ return sendJson(res, 400, {
324
+ error: { code: "invalid_request", message: "path is required" }
325
+ });
326
+ }
327
+ const pathKey = path.join(".");
328
+ if (!isMockCapabilityPath(pathKey)) {
329
+ const err2 = notImplementedInMock({ operation: `CapabilityProxy ${pathKey}` });
330
+ return sendJson(res, 501, { error: err2.toJSON() });
331
+ }
332
+ try {
333
+ const result = await dispatchCapabilityCall(pathKey, args, callCtx);
334
+ return sendJson(res, 200, { result });
335
+ } catch (error) {
336
+ if (error instanceof StructuredCliError) {
337
+ const status = error.code === "unmocked_request" ? 400 : 501;
338
+ return sendJson(res, status, { error: error.toJSON() });
339
+ }
340
+ throw error;
341
+ }
342
+ }
343
+ if (method === "POST" && url.pathname === "/v1/local-execute/package-graph") {
344
+ assertMockAuth(req);
345
+ return sendJson(res, 200, {
346
+ modules: [],
347
+ compatibilityDate: "2026-04-16",
348
+ compatibilityFlags: ["nodejs_compat"]
349
+ });
350
+ }
351
+ if (method === "GET" && url.pathname === "/v1/search") {
352
+ assertMockAuth(req);
353
+ const query = url.searchParams.get("query") ?? "";
354
+ const entity = url.searchParams.get("entity") ?? void 0;
355
+ return sendJson(res, 200, mockSearch(callCtx.getState(), { query, entity }));
356
+ }
357
+ if (method === "GET" && url.pathname === "/v1/me") {
358
+ assertMockAuth(req);
359
+ return sendJson(res, 200, mockCurrentUser(callCtx.getState(), callCtx.orgSlug));
360
+ }
361
+ if (url.pathname.startsWith("/v1/")) {
362
+ const err2 = notImplementedInMock({
363
+ operation: `${method} ${url.pathname}`
364
+ });
365
+ return sendJson(res, 501, { error: err2.toJSON() });
366
+ }
367
+ const err = notImplementedInMock({ operation: `${method} ${url.pathname}` });
368
+ return sendJson(res, 501, { error: err.toJSON() });
369
+ } catch (error) {
370
+ if (error instanceof AuthError) {
371
+ return sendJson(res, 401, {
372
+ error: { code: "unauthorized", message: error.message }
373
+ });
374
+ }
375
+ const message = error instanceof Error ? error.message : String(error);
376
+ return sendJson(res, 500, {
377
+ error: { code: "mock_internal_error", message }
378
+ });
379
+ }
380
+ }
381
+ var AuthError = class extends Error {
382
+ constructor(message) {
383
+ super(message);
384
+ this.name = "AuthError";
385
+ }
386
+ };
387
+ function assertMockAuth(req) {
388
+ const header = req.headers.authorization;
389
+ if (typeof header !== "string" || !header.toLowerCase().startsWith("bearer ")) {
390
+ throw new AuthError("Mock API requires Authorization: Bearer <token>.");
391
+ }
392
+ const token = header.slice("bearer ".length).trim();
393
+ if (!isMockApiToken(token) && !token.startsWith("kody_at_") && token.length > 0) {
394
+ return;
395
+ }
396
+ if (!token) throw new AuthError("Mock API bearer token is empty.");
397
+ }
398
+ async function dispatchCapabilityCall(pathKey, args, ctx) {
399
+ const state = ctx.getState();
400
+ switch (pathKey) {
401
+ case "kody.metaGetCurrentUser":
402
+ return mockCurrentUser(state, ctx.orgSlug);
403
+ case "kody.search": {
404
+ const params = args[0] ?? {};
405
+ return mockSearch(state, params);
406
+ }
407
+ case "kody.usageGet":
408
+ return {
409
+ period: "mock",
410
+ credits: { used: 0, limit: null },
411
+ note: "Mock usage \u2014 not real entitlement data."
412
+ };
413
+ case "kody.execute": {
414
+ const params = args[0] ?? {};
415
+ throw notImplementedInMock({
416
+ operation: "kody.execute (cloud sandbox)",
417
+ fix: "Use `kody execute --local --target mock` so the module runs in local workerd against this mock."
418
+ });
419
+ }
420
+ case "kody.__mockPackageStorageGet":
421
+ case "kody.packageStorageGet": {
422
+ const key = String(args[0]?.key ?? "");
423
+ return { value: packageStorageGet(state, ctx.packageId, key) ?? null };
424
+ }
425
+ case "kody.__mockPackageStorageSet":
426
+ case "kody.packageStorageSet": {
427
+ const input = args[0];
428
+ packageStorageSet(state, ctx.packageId, String(input?.key ?? ""), input?.value);
429
+ await ctx.setState(state);
430
+ return { ok: true };
431
+ }
432
+ case "kody.__mockPackageStorageDelete":
433
+ case "kody.packageStorageDelete": {
434
+ const key = String(args[0]?.key ?? "");
435
+ const deleted = packageStorageDelete(state, ctx.packageId, key);
436
+ await ctx.setState(state);
437
+ return { deleted };
438
+ }
439
+ case "kody.__mockPackageStorageList":
440
+ case "kody.packageStorageList": {
441
+ return { entries: packageStorageList(state, ctx.packageId) };
442
+ }
443
+ case "kody.__mockPackageStorageSql":
444
+ case "kody.packageStorageSql": {
445
+ const input = args[0] ?? {};
446
+ const query = String(input.query ?? "");
447
+ if (!query.trim()) {
448
+ throw new Error("packageStorage().sql requires a non-empty query string.");
449
+ }
450
+ return packageStorageSql(
451
+ state,
452
+ ctx.packageId,
453
+ query,
454
+ Array.isArray(input.bindings) ? input.bindings : [],
455
+ ctx.env
456
+ );
457
+ }
458
+ case "kody.credentialClientOpen": {
459
+ const input = args[0] ?? {};
460
+ const key = String(input.key ?? input.name ?? args[0] ?? "").trim();
461
+ const opened = openMockCredential(state, key);
462
+ return { ok: true, value: opened };
463
+ }
464
+ case "kody.credentialClientOpenAll": {
465
+ const key = String(args[0]?.key ?? "").trim();
466
+ const matches = Object.values(state.credentials).filter(
467
+ (cred) => !key || cred.name === key || cred.name.toUpperCase() === key.toUpperCase() || cred.id === key
468
+ );
469
+ if (key && matches.length === 0) {
470
+ return { ok: true, value: [] };
471
+ }
472
+ const opened = (key ? matches : Object.values(state.credentials)).map(
473
+ (cred) => mockOpenedCredential(cred)
474
+ );
475
+ return { ok: true, value: opened };
476
+ }
477
+ case "kody.credentialClientCheck":
478
+ return { ok: true, value: { warnings: [], checked: args[0] ?? null, strict: false } };
479
+ case "kody.credentialClientRefresh":
480
+ return { ok: true, value: { refreshed: false, mock: true } };
481
+ case "kody.authenticatedFetch":
482
+ case "kody.gatewayFetch":
483
+ case "kody.gatewayFetchStream": {
484
+ const request = args[0] ?? {};
485
+ const nested = request.request ?? request;
486
+ const method = String(nested.method ?? "GET").toUpperCase();
487
+ const url = String(nested.url ?? "");
488
+ if (url) throw unmockedRequestError(method, url);
489
+ throw new StructuredCliError({
490
+ code: "unmocked_request",
491
+ message: `Unmocked ${pathKey} under --target mock (missing request.url).`,
492
+ target: "mock",
493
+ where: pathKey,
494
+ fix: "Pass request.url, or add handlers in .kody/mocks.ts. createAuthenticatedFetch, credential().fetch, gatewayFetch, and gatewayFetchStream go through the same MSW gateway.",
495
+ details: { mocksPath: ".kody/mocks.ts" }
496
+ });
497
+ }
498
+ case "kody.adminUserList": {
499
+ const params = args[0] ?? {};
500
+ const page = typeof params.page === "number" ? params.page : 1;
501
+ const pageSize = typeof params.pageSize === "number" ? params.pageSize : typeof params.limit === "number" ? params.limit : 20;
502
+ return {
503
+ total: 1,
504
+ page,
505
+ pageSize,
506
+ users: [
507
+ {
508
+ stableUserId: "user_mock",
509
+ username: "mock-user",
510
+ email: "mock@example.com",
511
+ email_verified: true,
512
+ email_verified_at: "2026-01-01T00:00:00.000Z",
513
+ plan: "free",
514
+ manualPlan: "free",
515
+ stripePlan: null,
516
+ effectivePlan: "free",
517
+ secondAgentGiftExpiresAt: null,
518
+ referralCreditExpiresAt: null,
519
+ overlayExpiresAt: null,
520
+ isProOverlay: false,
521
+ overlayType: null,
522
+ entitlementLadder: "public",
523
+ stripeCustomerLinked: false,
524
+ suspended_at: null,
525
+ email_outbound_paused_at: null,
526
+ email_verification_delivery: null,
527
+ email_verification_delivery_detail: null,
528
+ utm_source: null,
529
+ utm_medium: null,
530
+ utm_campaign: null,
531
+ utm_content: null,
532
+ utm_term: null,
533
+ first_touch_landing_path: null,
534
+ first_touch_referrer: null,
535
+ first_mcp_connected_at: null,
536
+ first_execute_at: null,
537
+ first_search_at: null,
538
+ first_saved_package_at: null,
539
+ mcp_client_name: null,
540
+ last_active_at: null,
541
+ created_at: "2026-01-01T00:00:00.000Z",
542
+ updated_at: "2026-01-01T00:00:00.000Z",
543
+ roles: ["user"]
544
+ }
545
+ ]
546
+ };
547
+ }
548
+ default: {
549
+ const exhaustive = pathKey;
550
+ throw notImplementedInMock({ operation: String(exhaustive) });
551
+ }
552
+ }
553
+ }
554
+ function openMockCredential(state, key) {
555
+ const cred = state.credentials[key] ?? state.credentials[key.toUpperCase()] ?? Object.values(state.credentials).find(
556
+ (entry) => entry.name === key || entry.name.toUpperCase() === key.toUpperCase()
557
+ );
558
+ if (!cred) {
559
+ throw new StructuredCliError({
560
+ code: "missing_secret",
561
+ message: `Mock credential ${JSON.stringify(key)} is not defined for this session.`,
562
+ target: "mock",
563
+ fix: "Add a fake credential to the mock session state or use --target prod with a real allow-listed secret.",
564
+ details: { key }
565
+ });
566
+ }
567
+ return mockOpenedCredential(cred);
568
+ }
569
+ function mockOpenedCredential(cred) {
570
+ return {
571
+ handle: `mock-handle:${cred.id}`,
572
+ key: cred.name,
573
+ name: cred.name,
574
+ scope: cred.scope ?? "personal",
575
+ kind: cred.kind,
576
+ hosts: [...cred.hosts?.length ? cred.hosts : ["example.com"]],
577
+ hint: "mock",
578
+ // Never expose a real secret; mockValue stays session-local scratch only.
579
+ metadata: { mock: true }
580
+ };
581
+ }
582
+ function mockCurrentUser(state, orgSlug) {
583
+ return {
584
+ user_id: "user_mock",
585
+ username: "mock-user",
586
+ email: "mock@example.com",
587
+ display_name: "Mock User",
588
+ org: {
589
+ slug: orgSlug || "mock-org"
590
+ },
591
+ mockSessionId: state.sessionId
592
+ };
593
+ }
594
+ function mockSearch(state, params) {
595
+ if (params.entity) {
596
+ const hit = state.searchCatalog.find(
597
+ (item) => `${item.type}:${item.id}` === params.entity || item.id === params.entity
598
+ );
599
+ return {
600
+ conversationId: `mock-${state.sessionId}`,
601
+ matches: hit ? [
602
+ {
603
+ type: hit.type,
604
+ id: hit.id,
605
+ entityRef: `${hit.type}:${hit.id}`,
606
+ title: hit.title,
607
+ description: hit.description
608
+ }
609
+ ] : [],
610
+ offline: false,
611
+ warnings: [],
612
+ guidance: "Mock catalog \u2014 not the live Kody search index."
613
+ };
614
+ }
615
+ const q = (params.query ?? "").toLowerCase().trim();
616
+ const matches = state.searchCatalog.filter(
617
+ (item) => !q || item.title.toLowerCase().includes(q) || item.description.toLowerCase().includes(q) || item.id.toLowerCase().includes(q)
618
+ ).slice(0, params.limit ?? 20).map((item) => ({
619
+ type: item.type,
620
+ id: item.id,
621
+ entityRef: `${item.type}:${item.id}`,
622
+ title: item.title,
623
+ description: item.description
624
+ }));
625
+ return {
626
+ conversationId: `mock-${state.sessionId}`,
627
+ matches,
628
+ offline: false,
629
+ warnings: [],
630
+ guidance: "Mock catalog \u2014 not the live Kody search index."
631
+ };
632
+ }
633
+ function mockOpenApiDocument() {
634
+ return {
635
+ openapi: "3.1.0",
636
+ info: {
637
+ title: "Kody API (CLI mock)",
638
+ version: "mock",
639
+ description: "Subset document for the CLI mock. Unsupported operations refuse with not_implemented_in_mock."
640
+ },
641
+ paths: {
642
+ "/v1/search": {
643
+ get: {
644
+ operationId: "search",
645
+ summary: "Search the mock catalog"
646
+ }
647
+ },
648
+ "/v1/me": {
649
+ get: {
650
+ operationId: "metaGetCurrentUser",
651
+ summary: "Mock current user"
652
+ }
653
+ }
654
+ },
655
+ "x-kody-mock-operations": [...mockOpenApiOperationIds]
656
+ };
657
+ }
658
+ async function readJsonBody(req) {
659
+ const chunks = [];
660
+ for await (const chunk of req) {
661
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
662
+ }
663
+ if (chunks.length === 0) return null;
664
+ const text = Buffer.concat(chunks).toString("utf8").trim();
665
+ if (!text) return null;
666
+ try {
667
+ return JSON.parse(text);
668
+ } catch {
669
+ return null;
670
+ }
671
+ }
672
+ function sendJson(res, status, body) {
673
+ const payload = JSON.stringify(body);
674
+ res.writeHead(status, {
675
+ "content-type": "application/json; charset=utf-8",
676
+ "content-length": Buffer.byteLength(payload)
677
+ });
678
+ res.end(payload);
679
+ }
680
+ async function withMockServer(options, fn) {
681
+ const server = await startMockServer(options);
682
+ try {
683
+ return await fn(server);
684
+ } finally {
685
+ await server.close();
686
+ }
687
+ }
688
+
689
+ export {
690
+ isMockApiToken,
691
+ mintMockApiToken,
692
+ startMockServer,
693
+ ensureMockTarget,
694
+ withMockServer
695
+ };
696
+ //# sourceMappingURL=chunk-XDCOWU5R.js.map