@tangle-network/agent-app 0.60.249 → 0.60.251

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 (225) hide show
  1. package/dist/DesignCanvas-L6J72JQ2.js +15 -0
  2. package/dist/DesignCanvasEditor-QFQD63MR.js +18 -0
  3. package/dist/agent-enrollment/drizzle.js +3 -3
  4. package/dist/agent-enrollment/index.js +3 -3
  5. package/dist/app-auth/drizzle.d.ts +561 -0
  6. package/dist/app-auth/drizzle.js +72 -0
  7. package/dist/app-auth/drizzle.js.map +1 -0
  8. package/dist/app-auth/index.js +5 -3
  9. package/dist/app-auth/index.js.map +1 -1
  10. package/dist/app-oauth/drizzle.d.ts +2080 -0
  11. package/dist/app-oauth/drizzle.js +161 -0
  12. package/dist/app-oauth/drizzle.js.map +1 -0
  13. package/dist/app-oauth/index.d.ts +4 -0
  14. package/dist/app-oauth/index.js +8 -222
  15. package/dist/app-oauth/index.js.map +1 -1
  16. package/dist/app-oauth/issuer.d.ts +133 -0
  17. package/dist/app-oauth/issuer.js +247 -0
  18. package/dist/app-oauth/issuer.js.map +1 -0
  19. package/dist/assistant/index.js +13 -13
  20. package/dist/chat-react/index.js +4 -4
  21. package/dist/chat-routes/dispatch-first.d.ts +43 -0
  22. package/dist/chat-routes/index.js +37 -67
  23. package/dist/chat-routes/index.js.map +1 -1
  24. package/dist/chat-routes/promote-file-part.d.ts +2 -3
  25. package/dist/chat-routes/turn-execution.d.ts +3 -1
  26. package/dist/chat-routes/turn-route-contracts.d.ts +31 -0
  27. package/dist/chat-store/index.js +4 -4
  28. package/dist/{chunk-MY3EJJ6Y.js → chunk-4FEH6266.js} +2 -2
  29. package/dist/{chunk-5Y7Z5G3Y.js → chunk-4GCPADYG.js} +20 -336
  30. package/dist/chunk-4GCPADYG.js.map +1 -0
  31. package/dist/{chunk-X556WVBG.js → chunk-4ZSLX3LY.js} +2 -2
  32. package/dist/chunk-57XPEL7X.js +26 -0
  33. package/dist/chunk-57XPEL7X.js.map +1 -0
  34. package/dist/chunk-6Z7TZVKZ.js +26 -0
  35. package/dist/chunk-6Z7TZVKZ.js.map +1 -0
  36. package/dist/{chunk-7KKOFMLD.js → chunk-AWIQQEFP.js} +1 -1
  37. package/dist/chunk-AWIQQEFP.js.map +1 -0
  38. package/dist/{chunk-VBKP2NLI.js → chunk-BTKI4XMM.js} +2 -2
  39. package/dist/{chunk-63QAQP7I.js → chunk-CNBVWPQC.js} +7 -7
  40. package/dist/{chunk-FENBDSIW.js → chunk-CQGEGPY7.js} +75 -3
  41. package/dist/chunk-CQGEGPY7.js.map +1 -0
  42. package/dist/chunk-CTREXL3O.js +335 -0
  43. package/dist/chunk-CTREXL3O.js.map +1 -0
  44. package/dist/chunk-DLWO3J7D.js +238 -0
  45. package/dist/chunk-DLWO3J7D.js.map +1 -0
  46. package/dist/{chunk-LWSJK546.js → chunk-DSMGS4IV.js} +5 -5
  47. package/dist/{chunk-LWSJK546.js.map → chunk-DSMGS4IV.js.map} +1 -1
  48. package/dist/{chunk-BDCC6UVW.js → chunk-EFPIHR6F.js} +161 -40
  49. package/dist/chunk-EFPIHR6F.js.map +1 -0
  50. package/dist/chunk-FRAICFTZ.js +191 -0
  51. package/dist/chunk-FRAICFTZ.js.map +1 -0
  52. package/dist/chunk-GS7VWV26.js +61 -0
  53. package/dist/chunk-GS7VWV26.js.map +1 -0
  54. package/dist/{chunk-NMSAZFRL.js → chunk-H5GQMLHA.js} +2 -2
  55. package/dist/{chunk-OQE6WMDP.js → chunk-HN6MZ2XL.js} +5 -5
  56. package/dist/chunk-HY57QRRW.js +11 -0
  57. package/dist/chunk-HY57QRRW.js.map +1 -0
  58. package/dist/{chunk-TCGZFSN5.js → chunk-KH4QSBNI.js} +2 -2
  59. package/dist/{chunk-JH3CKHF4.js → chunk-KJODHPWM.js} +8 -8
  60. package/dist/chunk-LSBI5MWS.js +66 -0
  61. package/dist/chunk-LSBI5MWS.js.map +1 -0
  62. package/dist/chunk-MDRH3SDA.js +106 -0
  63. package/dist/chunk-MDRH3SDA.js.map +1 -0
  64. package/dist/{chunk-VBWYH7UZ.js → chunk-NHYRIM4I.js} +3 -3
  65. package/dist/{chunk-BYP54FMI.js → chunk-O2RCDK5D.js} +30 -15
  66. package/dist/{chunk-BYP54FMI.js.map → chunk-O2RCDK5D.js.map} +1 -1
  67. package/dist/{chunk-EWOJATDS.js → chunk-PDD5A43Y.js} +3 -3
  68. package/dist/{chunk-23JUSUUB.js → chunk-RZLCBWGG.js} +2 -2
  69. package/dist/chunk-SFZELD6V.js +52 -0
  70. package/dist/chunk-SFZELD6V.js.map +1 -0
  71. package/dist/{chunk-Y4W6GK5X.js → chunk-UGFCLD32.js} +2 -2
  72. package/dist/{chunk-ZGUXI5SI.js → chunk-VUBJZEZB.js} +2 -2
  73. package/dist/{chunk-LQYIBL3G.js → chunk-WL7PZK7Q.js} +71 -1
  74. package/dist/chunk-WL7PZK7Q.js.map +1 -0
  75. package/dist/{chunk-7HZCFG2A.js → chunk-WP2GYFZ4.js} +38 -1
  76. package/dist/chunk-WP2GYFZ4.js.map +1 -0
  77. package/dist/{chunk-JK7R7BZQ.js → chunk-ZWJ3SZ2G.js} +2 -2
  78. package/dist/crypto/digest.d.ts +2 -0
  79. package/dist/crypto/index.d.ts +1 -0
  80. package/dist/crypto/index.js +6 -2
  81. package/dist/design-canvas/index.js +5 -3
  82. package/dist/design-canvas/index.js.map +1 -1
  83. package/dist/design-canvas-react/engine.js +7 -5
  84. package/dist/design-canvas-react/index.js +14 -12
  85. package/dist/design-canvas-react/index.js.map +1 -1
  86. package/dist/design-canvas-react/lazy.js +1 -1
  87. package/dist/eval/index.d.ts +4 -0
  88. package/dist/eval/index.js +125 -0
  89. package/dist/eval/index.js.map +1 -1
  90. package/dist/eval/persona-driver.d.ts +37 -0
  91. package/dist/eval/research-plan.d.ts +25 -0
  92. package/dist/eval/research-plan.js +55 -0
  93. package/dist/eval/research-plan.js.map +1 -0
  94. package/dist/eval/scorecard.d.ts +38 -0
  95. package/dist/forms/blank.d.ts +2 -2
  96. package/dist/forms/index.js +4 -5
  97. package/dist/forms/index.js.map +1 -1
  98. package/dist/hosted-agent/application.js +2 -2
  99. package/dist/interactions/index.js +3 -3
  100. package/dist/knowledge/prelaunch-audit.d.ts +17 -0
  101. package/dist/knowledge/prelaunch-audit.js +67 -0
  102. package/dist/knowledge/prelaunch-audit.js.map +1 -0
  103. package/dist/media/drizzle.d.ts +207 -0
  104. package/dist/media/drizzle.js +26 -0
  105. package/dist/media/drizzle.js.map +1 -0
  106. package/dist/media/generate-request.d.ts +53 -0
  107. package/dist/media/generation-record.d.ts +68 -0
  108. package/dist/media/index.d.ts +13 -0
  109. package/dist/media/index.js +653 -0
  110. package/dist/media/index.js.map +1 -0
  111. package/dist/media/model-catalog.d.ts +109 -0
  112. package/dist/media/router-client.d.ts +40 -0
  113. package/dist/media/router-generation.d.ts +44 -0
  114. package/dist/media/speech-script.d.ts +20 -0
  115. package/dist/openui/index.js +1 -1
  116. package/dist/operator/index.js +4 -5
  117. package/dist/operator/index.js.map +1 -1
  118. package/dist/plans/decision.d.ts +48 -0
  119. package/dist/plans/drizzle.d.ts +25 -0
  120. package/dist/plans/drizzle.js +97 -0
  121. package/dist/plans/drizzle.js.map +1 -0
  122. package/dist/plans/index.d.ts +1 -1
  123. package/dist/plans/index.js +11 -3
  124. package/dist/platform/billing-config.d.ts +22 -0
  125. package/dist/platform/billing-config.js +36 -0
  126. package/dist/platform/billing-config.js.map +1 -0
  127. package/dist/platform/index.js +13 -11
  128. package/dist/platform/index.js.map +1 -1
  129. package/dist/preset-cloudflare/index.js +2 -1
  130. package/dist/preset-cloudflare/index.js.map +1 -1
  131. package/dist/profile/index.js +4 -5
  132. package/dist/profile/index.js.map +1 -1
  133. package/dist/public-consultation/index.js +13 -11
  134. package/dist/public-consultation/index.js.map +1 -1
  135. package/dist/runtime/telemetry-cap.d.ts +24 -0
  136. package/dist/runtime/telemetry-cap.js +36 -0
  137. package/dist/runtime/telemetry-cap.js.map +1 -0
  138. package/dist/sandbox/index.js +12 -9
  139. package/dist/sequences/index.js +4 -2
  140. package/dist/sequences/index.js.map +1 -1
  141. package/dist/skills-placement/box.d.ts +50 -0
  142. package/dist/skills-placement/box.js +204 -0
  143. package/dist/skills-placement/box.js.map +1 -0
  144. package/dist/skills-placement/index.js +8 -96
  145. package/dist/skills-placement/index.js.map +1 -1
  146. package/dist/spend/budget.d.ts +13 -0
  147. package/dist/spend/drizzle.d.ts +55 -0
  148. package/dist/spend/drizzle.js +131 -0
  149. package/dist/spend/drizzle.js.map +1 -0
  150. package/dist/spend/index.d.ts +2 -1
  151. package/dist/spend/index.js +77 -58
  152. package/dist/spend/index.js.map +1 -1
  153. package/dist/spend/platform-settlements.d.ts +46 -0
  154. package/dist/stream/index.js +19 -19
  155. package/dist/studio/generated-media/index.d.ts +6 -0
  156. package/dist/studio/generated-media/index.js +590 -0
  157. package/dist/studio/generated-media/index.js.map +1 -0
  158. package/dist/studio/generated-media/output.d.ts +27 -0
  159. package/dist/studio/generated-media/store.d.ts +175 -0
  160. package/dist/studio-react/download-generations.d.ts +7 -0
  161. package/dist/studio-react/index.d.ts +1 -0
  162. package/dist/studio-react/index.js +85 -0
  163. package/dist/studio-react/index.js.map +1 -1
  164. package/dist/studio-react/use-studio-route.d.ts +44 -0
  165. package/dist/teams/invitations-api.d.ts +4 -0
  166. package/dist/teams/invitations-api.js +44 -32
  167. package/dist/teams/invitations-api.js.map +1 -1
  168. package/dist/theme/dom.d.ts +22 -0
  169. package/dist/theme/dom.js +18 -0
  170. package/dist/theme/dom.js.map +1 -0
  171. package/dist/vault/collaboration.d.ts +83 -0
  172. package/dist/vault/collaboration.js +215 -0
  173. package/dist/vault/collaboration.js.map +1 -0
  174. package/dist/vault/server.js +6 -53
  175. package/dist/vault/server.js.map +1 -1
  176. package/dist/vault/store/coordinator.d.ts +64 -0
  177. package/dist/vault/store/index.d.ts +12 -0
  178. package/dist/vault/store/index.js +1202 -0
  179. package/dist/vault/store/index.js.map +1 -0
  180. package/dist/vault/store/paths.d.ts +65 -0
  181. package/dist/vault/store/revisions.d.ts +211 -0
  182. package/dist/vault/store/sandbox-sync.d.ts +74 -0
  183. package/dist/vault/store/store.d.ts +161 -0
  184. package/dist/vault/store/tree.d.ts +11 -0
  185. package/dist/web/entry-server.d.ts +7 -0
  186. package/dist/web/entry-server.js +29 -0
  187. package/dist/web/entry-server.js.map +1 -0
  188. package/dist/web/fetch-guard.d.ts +6 -0
  189. package/dist/web/index.d.ts +3 -0
  190. package/dist/web/index.js +20 -4
  191. package/dist/web/mime.d.ts +16 -0
  192. package/dist/web/rate-limit.d.ts +25 -0
  193. package/dist/web/timeout.d.ts +9 -0
  194. package/dist/web-react/agent-profile-editor.js +3 -3
  195. package/dist/web-react/api-access-panel.d.ts +4 -2
  196. package/dist/web-react/document.d.ts +41 -0
  197. package/dist/web-react/document.js +103 -0
  198. package/dist/web-react/document.js.map +1 -0
  199. package/dist/web-react/index.js +31 -31
  200. package/dist/workspace-react/index.js +5 -5
  201. package/package.json +95 -4
  202. package/dist/DesignCanvas-OW3W2QXW.js +0 -13
  203. package/dist/DesignCanvasEditor-TCHZF25W.js +0 -16
  204. package/dist/chunk-5Y7Z5G3Y.js.map +0 -1
  205. package/dist/chunk-7HZCFG2A.js.map +0 -1
  206. package/dist/chunk-7KKOFMLD.js.map +0 -1
  207. package/dist/chunk-BDCC6UVW.js.map +0 -1
  208. package/dist/chunk-FENBDSIW.js.map +0 -1
  209. package/dist/chunk-LQYIBL3G.js.map +0 -1
  210. /package/dist/{DesignCanvas-OW3W2QXW.js.map → DesignCanvas-L6J72JQ2.js.map} +0 -0
  211. /package/dist/{DesignCanvasEditor-TCHZF25W.js.map → DesignCanvasEditor-QFQD63MR.js.map} +0 -0
  212. /package/dist/{chunk-MY3EJJ6Y.js.map → chunk-4FEH6266.js.map} +0 -0
  213. /package/dist/{chunk-X556WVBG.js.map → chunk-4ZSLX3LY.js.map} +0 -0
  214. /package/dist/{chunk-VBKP2NLI.js.map → chunk-BTKI4XMM.js.map} +0 -0
  215. /package/dist/{chunk-63QAQP7I.js.map → chunk-CNBVWPQC.js.map} +0 -0
  216. /package/dist/{chunk-NMSAZFRL.js.map → chunk-H5GQMLHA.js.map} +0 -0
  217. /package/dist/{chunk-OQE6WMDP.js.map → chunk-HN6MZ2XL.js.map} +0 -0
  218. /package/dist/{chunk-TCGZFSN5.js.map → chunk-KH4QSBNI.js.map} +0 -0
  219. /package/dist/{chunk-JH3CKHF4.js.map → chunk-KJODHPWM.js.map} +0 -0
  220. /package/dist/{chunk-VBWYH7UZ.js.map → chunk-NHYRIM4I.js.map} +0 -0
  221. /package/dist/{chunk-EWOJATDS.js.map → chunk-PDD5A43Y.js.map} +0 -0
  222. /package/dist/{chunk-23JUSUUB.js.map → chunk-RZLCBWGG.js.map} +0 -0
  223. /package/dist/{chunk-Y4W6GK5X.js.map → chunk-UGFCLD32.js.map} +0 -0
  224. /package/dist/{chunk-ZGUXI5SI.js.map → chunk-VUBJZEZB.js.map} +0 -0
  225. /package/dist/{chunk-JK7R7BZQ.js.map → chunk-ZWJ3SZ2G.js.map} +0 -0
@@ -4,7 +4,7 @@ import {
4
4
  boundsIntersect,
5
5
  elementAabb,
6
6
  scaleForPreset
7
- } from "./chunk-JK7R7BZQ.js";
7
+ } from "./chunk-ZWJ3SZ2G.js";
8
8
 
9
9
  // src/design-canvas-react/engine/snap.ts
10
10
  var KIND_PRIORITY = {
@@ -447,4 +447,4 @@ export {
447
447
  buildInsertImageOp,
448
448
  DEFAULT_INSERT_TEMPLATES
449
449
  };
450
- //# sourceMappingURL=chunk-X556WVBG.js.map
450
+ //# sourceMappingURL=chunk-4ZSLX3LY.js.map
@@ -0,0 +1,26 @@
1
+ // src/web/fetch-guard.ts
2
+ function isBlockedFetchHostname(hostname) {
3
+ const input = hostname.toLowerCase().replace(/\.$/, "");
4
+ let host;
5
+ try {
6
+ host = new URL(`http://${input.includes(":") && !input.startsWith("[") ? `[${input}]` : input}`).hostname.replace(/^\[|\]$/g, "");
7
+ } catch {
8
+ return true;
9
+ }
10
+ if (host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local")) return true;
11
+ if (host.includes(":")) return true;
12
+ return isBlockedIpv4Hostname(host);
13
+ }
14
+ function isBlockedIpv4Hostname(host) {
15
+ const ipv4Parts = host.split(".");
16
+ if (ipv4Parts.length !== 4) return false;
17
+ const octets = ipv4Parts.map((part) => Number(part));
18
+ if (octets.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) return false;
19
+ const [first, second] = octets;
20
+ return first === 10 || first === 127 || first === 169 && second === 254 || first === 172 && second >= 16 && second <= 31 || first === 192 && second === 168 || first === 0;
21
+ }
22
+
23
+ export {
24
+ isBlockedFetchHostname
25
+ };
26
+ //# sourceMappingURL=chunk-57XPEL7X.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/web/fetch-guard.ts"],"sourcesContent":["/**\n * Server-side fetch target guard: refuse hosts that resolve to this machine or a\n * private network, so a user- or model-supplied URL cannot reach internal\n * services. URL canonicalization covers alternate IPv4 spellings. No imports.\n */\nexport function isBlockedFetchHostname(hostname: string): boolean {\n const input = hostname.toLowerCase().replace(/\\.$/, '')\n let host: string\n try {\n host = new URL(`http://${input.includes(':') && !input.startsWith('[') ? `[${input}]` : input}`).hostname.replace(/^\\[|\\]$/g, '')\n } catch {\n return true\n }\n if (host === 'localhost' || host.endsWith('.localhost') || host.endsWith('.local')) return true\n // Conservatively refuse IPv6 literals, including mapped IPv4. A partial\n // string-based range parser cannot establish that such a target is public.\n if (host.includes(':')) return true\n return isBlockedIpv4Hostname(host)\n}\n\nfunction isBlockedIpv4Hostname(host: string): boolean {\n const ipv4Parts = host.split('.')\n if (ipv4Parts.length !== 4) return false\n const octets = ipv4Parts.map((part) => Number(part))\n if (octets.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) return false\n // Four octets were checked above, so both are defined.\n const [first, second] = octets as [number, number, number, number]\n return first === 10\n || first === 127\n || (first === 169 && second === 254)\n || (first === 172 && second >= 16 && second <= 31)\n || (first === 192 && second === 168)\n || first === 0\n}\n"],"mappings":";AAKO,SAAS,uBAAuB,UAA2B;AAChE,QAAM,QAAQ,SAAS,YAAY,EAAE,QAAQ,OAAO,EAAE;AACtD,MAAI;AACJ,MAAI;AACF,WAAO,IAAI,IAAI,UAAU,MAAM,SAAS,GAAG,KAAK,CAAC,MAAM,WAAW,GAAG,IAAI,IAAI,KAAK,MAAM,KAAK,EAAE,EAAE,SAAS,QAAQ,YAAY,EAAE;AAAA,EAClI,QAAQ;AACN,WAAO;AAAA,EACT;AACA,MAAI,SAAS,eAAe,KAAK,SAAS,YAAY,KAAK,KAAK,SAAS,QAAQ,EAAG,QAAO;AAG3F,MAAI,KAAK,SAAS,GAAG,EAAG,QAAO;AAC/B,SAAO,sBAAsB,IAAI;AACnC;AAEA,SAAS,sBAAsB,MAAuB;AACpD,QAAM,YAAY,KAAK,MAAM,GAAG;AAChC,MAAI,UAAU,WAAW,EAAG,QAAO;AACnC,QAAM,SAAS,UAAU,IAAI,CAAC,SAAS,OAAO,IAAI,CAAC;AACnD,MAAI,OAAO,KAAK,CAAC,SAAS,CAAC,OAAO,UAAU,IAAI,KAAK,OAAO,KAAK,OAAO,GAAG,EAAG,QAAO;AAErF,QAAM,CAAC,OAAO,MAAM,IAAI;AACxB,SAAO,UAAU,MACZ,UAAU,OACT,UAAU,OAAO,WAAW,OAC5B,UAAU,OAAO,UAAU,MAAM,UAAU,MAC3C,UAAU,OAAO,WAAW,OAC7B,UAAU;AACjB;","names":[]}
@@ -0,0 +1,26 @@
1
+ // src/web/timeout.ts
2
+ async function withTimeout(operation, timeoutMs, message) {
3
+ const controller = new AbortController();
4
+ let timeout;
5
+ let timedOut = false;
6
+ const timeoutPromise = new Promise((_, reject) => {
7
+ timeout = setTimeout(() => {
8
+ timedOut = true;
9
+ controller.abort(message);
10
+ reject(new Error(message));
11
+ }, timeoutMs);
12
+ });
13
+ try {
14
+ return await Promise.race([operation(controller.signal), timeoutPromise]);
15
+ } catch (err) {
16
+ if (timedOut || controller.signal.aborted) throw new Error(message);
17
+ throw err;
18
+ } finally {
19
+ if (timeout) clearTimeout(timeout);
20
+ }
21
+ }
22
+
23
+ export {
24
+ withTimeout
25
+ };
26
+ //# sourceMappingURL=chunk-6Z7TZVKZ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/web/timeout.ts"],"sourcesContent":["/**\n * Race an async operation against a timeout. The operation receives an\n * AbortSignal that fires when the timeout elapses, so a hung request is\n * aborted and rejected with `message` instead of hanging forever. The timer is\n * cleared the moment the operation settles, so wrapping a streaming `fetch`\n * (which resolves at response headers) guards only the connect/first-byte\n * phase and never truncates a long-lived response body. Browser-safe.\n */\nexport async function withTimeout<T>(\n operation: (signal: AbortSignal) => Promise<T>,\n timeoutMs: number,\n message: string,\n): Promise<T> {\n const controller = new AbortController()\n let timeout: ReturnType<typeof setTimeout> | undefined\n let timedOut = false\n const timeoutPromise = new Promise<never>((_, reject) => {\n timeout = setTimeout(() => {\n timedOut = true\n controller.abort(message)\n reject(new Error(message))\n }, timeoutMs)\n })\n\n try {\n return await Promise.race([operation(controller.signal), timeoutPromise])\n } catch (err) {\n // A timeout must always surface as `message`; the merged fetch signal can\n // reject with a bare AbortError before the timeout promise rejects.\n if (timedOut || controller.signal.aborted) throw new Error(message)\n throw err\n } finally {\n if (timeout) clearTimeout(timeout)\n }\n}\n"],"mappings":";AAQA,eAAsB,YACpB,WACA,WACA,SACY;AACZ,QAAM,aAAa,IAAI,gBAAgB;AACvC,MAAI;AACJ,MAAI,WAAW;AACf,QAAM,iBAAiB,IAAI,QAAe,CAAC,GAAG,WAAW;AACvD,cAAU,WAAW,MAAM;AACzB,iBAAW;AACX,iBAAW,MAAM,OAAO;AACxB,aAAO,IAAI,MAAM,OAAO,CAAC;AAAA,IAC3B,GAAG,SAAS;AAAA,EACd,CAAC;AAED,MAAI;AACF,WAAO,MAAM,QAAQ,KAAK,CAAC,UAAU,WAAW,MAAM,GAAG,cAAc,CAAC;AAAA,EAC1E,SAAS,KAAK;AAGZ,QAAI,YAAY,WAAW,OAAO,QAAS,OAAM,IAAI,MAAM,OAAO;AAClE,UAAM;AAAA,EACR,UAAE;AACA,QAAI,QAAS,cAAa,OAAO;AAAA,EACnC;AACF;","names":[]}
@@ -101,4 +101,4 @@ export {
101
101
  encryptBytes,
102
102
  decryptBytes
103
103
  };
104
- //# sourceMappingURL=chunk-7KKOFMLD.js.map
104
+ //# sourceMappingURL=chunk-AWIQQEFP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/crypto/index.ts"],"sourcesContent":["/**\n * AES-256-GCM field encryption (for PII at rest — SSN/EIN/ID numbers, secrets).\n * WebCrypto only — runs on Cloudflare Workers, Node, and the browser with no\n * Node `crypto` dependency. The 32-byte key is a PARAMETER (64-char hex); the\n * framework never reads env — the product binds its own `ENCRYPTION_KEY` (this\n * is the concrete impl behind the `KeyCrypto` seam in `../billing`).\n *\n * Wire format: base64(iv ‖ ciphertext ‖ tag) — the 12-byte IV is prepended; the\n * GCM auth tag is appended by WebCrypto inside the ciphertext.\n */\n\nexport { sha256Hex } from './digest'\n\nconst IV_LENGTH = 12\nconst TAG_LENGTH = 16\nconst ALGORITHM = 'AES-GCM'\n\n/** Validate + decode a 64-char hex key to 32 bytes. Throws on the wrong shape so\n * a misconfigured key fails loud, never silently weakens encryption. */\nexport function decodeHexKey(keyHex: string): Uint8Array {\n // Charset-validated BEFORE decoding: `parseInt('zz', 16)` is NaN, and a NaN\n // assignment to a Uint8Array silently stores 0 — a 64-char non-hex string\n // would otherwise produce an all-zero key instead of throwing, contradicting\n // the fail-loud contract above (found in redteam review, issue #747).\n if (!/^[0-9a-fA-F]{64}$/.test(keyHex)) {\n throw new Error('encryption key must be a 64-char hex string (32 bytes)')\n }\n const bytes = new Uint8Array(32)\n for (let i = 0; i < 64; i += 2) bytes[i / 2] = parseInt(keyHex.substring(i, i + 2), 16)\n return bytes\n}\n\nasync function importKey(keyHex: string): Promise<CryptoKey> {\n const raw = decodeHexKey(keyHex)\n return crypto.subtle.importKey('raw', raw.buffer as ArrayBuffer, { name: ALGORITHM } as Algorithm, false, ['encrypt', 'decrypt'])\n}\n\nfunction toBase64(data: Uint8Array): string {\n let binary = ''\n for (let i = 0; i < data.length; i++) binary += String.fromCharCode(data[i]!)\n return btoa(binary)\n}\n\nfunction fromBase64(b64: string): Uint8Array {\n const binary = atob(b64)\n const bytes = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)\n return bytes\n}\n\n/** Encrypt `plaintext` with AES-256-GCM under `keyHex`. Returns\n * base64(iv ‖ ciphertext ‖ tag). A fresh random IV per call. */\nexport async function encryptAesGcm(plaintext: string, keyHex: string): Promise<string> {\n const key = await importKey(keyHex)\n const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH))\n const ciphertext = await crypto.subtle.encrypt({ name: ALGORITHM, iv, tagLength: TAG_LENGTH * 8 }, key, new TextEncoder().encode(plaintext))\n const result = new Uint8Array(IV_LENGTH + ciphertext.byteLength)\n result.set(iv, 0)\n result.set(new Uint8Array(ciphertext), IV_LENGTH)\n return toBase64(result)\n}\n\n/** Decrypt a base64(iv ‖ ciphertext ‖ tag) string under `keyHex`. Throws if the\n * tag fails (tamper/wrong key). */\nexport async function decryptAesGcm(encrypted: string, keyHex: string): Promise<string> {\n const key = await importKey(keyHex)\n const data = fromBase64(encrypted)\n const iv = data.slice(0, IV_LENGTH)\n const ciphertext = data.slice(IV_LENGTH)\n const plain = await crypto.subtle.decrypt({ name: ALGORITHM, iv, tagLength: TAG_LENGTH * 8 }, key, ciphertext)\n return new TextDecoder().decode(plain)\n}\n\n/** Build a {@link import('../billing').KeyCrypto}-compatible pair bound to a key\n * (or a key-resolver, for env-backed keys resolved per call). */\nexport function createFieldCrypto(key: string | (() => string)): { encrypt(s: string): Promise<string>; decrypt(s: string): Promise<string> } {\n const resolve = typeof key === 'function' ? key : () => key\n return {\n encrypt: (s) => encryptAesGcm(s, resolve()),\n decrypt: (s) => decryptAesGcm(s, resolve()),\n }\n}\n\n/**\n * --- Passphrase-derived key path (PBKDF2 → AES-256-GCM CryptoKey) ---\n *\n * The `encryptAesGcm`/`decryptAesGcm` path takes a raw 64-char-hex key. Some\n * products instead bind a SECRET STRING (not a hex key) and derive the AES key\n * with PBKDF2 — and need a BINARY path (encrypting document bytes, not just\n * strings). Both are exposed here so a product never hand-rolls WebCrypto.\n *\n * The derivation parameters (salt, iterations) are PARAMETERS — a product pins\n * its own so the derived key bytes stay stable for data already at rest. The\n * defaults are a sensible baseline; any product supplies its own via\n * {@link DeriveKeyOptions}.\n */\n\nexport interface DeriveKeyOptions {\n /** PBKDF2 salt. A product MUST pin this — changing it changes the derived key\n * bytes and orphans every value already encrypted at rest. */\n salt: Uint8Array | string\n /** PBKDF2 iteration count. Pin it for the same reason as `salt`. */\n iterations: number\n /** PBKDF2 hash. Default `'SHA-256'`. */\n hash?: 'SHA-256' | 'SHA-384' | 'SHA-512'\n}\n\n/** Derive an AES-256-GCM `CryptoKey` from a secret string via PBKDF2. The key is\n * non-extractable and usable only for encrypt/decrypt. */\nexport async function deriveKey(secret: string, opts: DeriveKeyOptions): Promise<CryptoKey> {\n const salt = typeof opts.salt === 'string' ? new TextEncoder().encode(opts.salt) : opts.salt\n const keyMaterial = await crypto.subtle.importKey('raw', new TextEncoder().encode(secret), 'PBKDF2', false, ['deriveKey'])\n return crypto.subtle.deriveKey(\n { name: 'PBKDF2', salt: salt as BufferSource, iterations: opts.iterations, hash: opts.hash ?? 'SHA-256' },\n keyMaterial,\n { name: ALGORITHM, length: 256 },\n false,\n ['encrypt', 'decrypt'],\n )\n}\n\n/** Encrypt `plaintext` under a derived `CryptoKey`. Returns base64(iv ‖ ct ‖ tag). */\nexport async function encryptWithKey(plaintext: string, key: CryptoKey): Promise<string> {\n const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH))\n const ciphertext = await crypto.subtle.encrypt({ name: ALGORITHM, iv }, key, new TextEncoder().encode(plaintext))\n const out = new Uint8Array(IV_LENGTH + ciphertext.byteLength)\n out.set(iv, 0)\n out.set(new Uint8Array(ciphertext), IV_LENGTH)\n return toBase64(out)\n}\n\n/** Decrypt a base64(iv ‖ ct ‖ tag) string under a derived `CryptoKey`. */\nexport async function decryptWithKey(encoded: string, key: CryptoKey): Promise<string> {\n const raw = fromBase64(encoded)\n const iv = raw.slice(0, IV_LENGTH)\n const ciphertext = raw.slice(IV_LENGTH)\n const plain = await crypto.subtle.decrypt({ name: ALGORITHM, iv }, key, ciphertext)\n return new TextDecoder().decode(plain)\n}\n\n/** Encrypt binary data under a derived `CryptoKey`. Returns an ArrayBuffer:\n * 12-byte IV ‖ ciphertext ‖ 16-byte GCM tag (same wire layout as the string\n * path, raw bytes instead of base64). */\nexport async function encryptBytes(data: ArrayBuffer, key: CryptoKey): Promise<ArrayBuffer> {\n const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH))\n const ciphertext = await crypto.subtle.encrypt({ name: ALGORITHM, iv }, key, data)\n const out = new Uint8Array(IV_LENGTH + ciphertext.byteLength)\n out.set(iv, 0)\n out.set(new Uint8Array(ciphertext), IV_LENGTH)\n return out.buffer\n}\n\n/** Decrypt binary data (IV ‖ ciphertext ‖ tag) under a derived `CryptoKey`. */\nexport async function decryptBytes(data: ArrayBuffer, key: CryptoKey): Promise<ArrayBuffer> {\n const raw = new Uint8Array(data)\n const iv = raw.slice(0, IV_LENGTH)\n const ciphertext = raw.slice(IV_LENGTH)\n return crypto.subtle.decrypt({ name: ALGORITHM, iv }, key, ciphertext)\n}\n"],"mappings":";AAaA,IAAM,YAAY;AAClB,IAAM,aAAa;AACnB,IAAM,YAAY;AAIX,SAAS,aAAa,QAA4B;AAKvD,MAAI,CAAC,oBAAoB,KAAK,MAAM,GAAG;AACrC,UAAM,IAAI,MAAM,wDAAwD;AAAA,EAC1E;AACA,QAAM,QAAQ,IAAI,WA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AG;AACrB;AAGA,eAAsB,eAAe,SAAiB,KAAiC;AACrF,QAAM,MAAM,WAAW,OAAO;AAC9B,QAAM,KAAK,IAAI,MAAM,GAAG,SAAS;AACjC,QAAM,aAAa,IAAI,MAAM,SAAS;AACtC,QAAM,QAAQ,MAAM,OAAO,OAAO,QAAQ,EAAE,MAAM,WAAW,GAAG,GAAG,KAAK,UAAU;AAClF,SAAO,IAAI,YAAY,EAAE,OAAO,KAAK;AACvC;AAKA,eAAsB,aAAa,MAAmB,KAAsC;AAC1F,QAAM,KAAK,OAAO,gBAAgB,IAAI,WAAW,SAAS,CAAC;AAC3D,QAAM,aAAa,MAAM,OAAO,OAAO,QAAQ,EAAE,MAAM,WAAW,GAAG,GAAG,KAAK,IAAI;AACjF,QAAM,MAAM,IAAI,WAAW,YAAY,WAAW,UAAU;AAC5D,MAAI,IAAI,IAAI,CAAC;AACb,MAAI,IAAI,IAAI,WAAW,UAAU,GAAG,SAAS;AAC7C,SAAO,IAAI;AACb;AAGA,eAAsB,aAAa,MAAmB,KAAsC;AAC1F,QAAM,MAAM,IAAI,WAAW,IAAI;AAC/B,QAAM,KAAK,IAAI,MAAM,GAAG,SAAS;AACjC,QAAM,aAAa,IAAI,MAAM,SAAS;AACtC,SAAO,OAAO,OAAO,QAAQ,EAAE,MAAM,WAAW,GAAG,GAAG,KAAK,UAAU;AACvE;","names":[]}
@@ -3,7 +3,7 @@ import {
3
3
  applySceneOperations,
4
4
  requireElement,
5
5
  requirePage
6
- } from "./chunk-JK7R7BZQ.js";
6
+ } from "./chunk-ZWJ3SZ2G.js";
7
7
 
8
8
  // src/design-canvas-react/engine/command-stack.ts
9
9
  var SCENE_COMMAND_HISTORY_LIMIT = 200;
@@ -601,4 +601,4 @@ export {
601
601
  bindSlotCommand,
602
602
  setDocumentTitleCommand
603
603
  };
604
- //# sourceMappingURL=chunk-VBKP2NLI.js.map
604
+ //# sourceMappingURL=chunk-BTKI4XMM.js.map
@@ -1,12 +1,6 @@
1
1
  import {
2
2
  joinClasses
3
3
  } from "./chunk-L7MB2LLM.js";
4
- import {
5
- useWorkspacePrewarmHandle
6
- } from "./chunk-2HQP2CTA.js";
7
- import {
8
- filterCommandPaletteItems
9
- } from "./chunk-SJWIZT7B.js";
10
4
  import {
11
5
  AgentSessionControls,
12
6
  acceptRejectionReason,
@@ -14,11 +8,17 @@ import {
14
8
  isAcceptedFileType,
15
9
  renamePastedImages
16
10
  } from "./chunk-G4F2NWZH.js";
11
+ import {
12
+ useWorkspacePrewarmHandle
13
+ } from "./chunk-2HQP2CTA.js";
17
14
  import {
18
15
  OVERLAY_SHADOW,
19
16
  POPOVER_OPTION_FOCUS,
20
17
  PopoverSurface
21
18
  } from "./chunk-R4X5474U.js";
19
+ import {
20
+ filterCommandPaletteItems
21
+ } from "./chunk-SJWIZT7B.js";
22
22
  import {
23
23
  ALLOWED_ATTACHMENT_SNIFFED_MIMES,
24
24
  ATTACHMENT_ACCEPT,
@@ -1603,4 +1603,4 @@ export {
1603
1603
  ComposerModeControls,
1604
1604
  EntryComposer
1605
1605
  };
1606
- //# sourceMappingURL=chunk-63QAQP7I.js.map
1606
+ //# sourceMappingURL=chunk-CNBVWPQC.js.map
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  readCookieValue,
3
3
  serializeCookie
4
- } from "./chunk-7HZCFG2A.js";
4
+ } from "./chunk-WP2GYFZ4.js";
5
5
 
6
6
  // src/web/message-groups.ts
7
7
  function groupConversationMessages(items = []) {
@@ -105,10 +105,82 @@ function firstTouchAcquisitionCookie(request, cookieName, now = Date.now(), igno
105
105
  });
106
106
  }
107
107
 
108
+ // src/web/mime.ts
109
+ var BASE_EXT_TO_MIME = {
110
+ md: "text/markdown",
111
+ markdown: "text/markdown",
112
+ txt: "text/plain",
113
+ log: "text/plain",
114
+ csv: "text/csv",
115
+ tsv: "text/tab-separated-values",
116
+ json: "application/json",
117
+ yaml: "text/yaml",
118
+ yml: "text/yaml",
119
+ xml: "application/xml",
120
+ html: "text/html",
121
+ htm: "text/html",
122
+ pdf: "application/pdf",
123
+ png: "image/png",
124
+ jpg: "image/jpeg",
125
+ jpeg: "image/jpeg",
126
+ gif: "image/gif",
127
+ webp: "image/webp",
128
+ avif: "image/avif",
129
+ heic: "image/heic",
130
+ heif: "image/heif",
131
+ svg: "image/svg+xml",
132
+ mp4: "video/mp4",
133
+ webm: "video/webm",
134
+ mov: "video/quicktime",
135
+ mp3: "audio/mpeg",
136
+ wav: "audio/wav",
137
+ ogg: "audio/ogg",
138
+ m4a: "audio/mp4",
139
+ aac: "audio/aac"
140
+ };
141
+ var PREVIEW_EXT_TO_MIME = {
142
+ ...BASE_EXT_TO_MIME,
143
+ mdx: "text/markdown",
144
+ ts: "text/typescript",
145
+ tsx: "text/typescript-jsx",
146
+ js: "text/javascript",
147
+ jsx: "text/jsx",
148
+ py: "text/x-python",
149
+ rs: "text/x-rust",
150
+ go: "text/x-go",
151
+ java: "text/x-java",
152
+ rb: "text/x-ruby",
153
+ sh: "text/x-shellscript",
154
+ bash: "text/x-shellscript",
155
+ zsh: "text/x-shellscript",
156
+ toml: "text/x-toml",
157
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
158
+ xls: "application/vnd.ms-excel"
159
+ };
160
+ function lookup(table, filename) {
161
+ const ext = filename.split(".").pop()?.toLowerCase();
162
+ if (!ext) return "text/plain";
163
+ return table[ext] ?? "text/plain";
164
+ }
165
+ function sniffMimeFromName(filename) {
166
+ return lookup(BASE_EXT_TO_MIME, filename);
167
+ }
168
+ function sniffMime(filename, extraExtensions) {
169
+ const ext = filename.split(".").pop()?.toLowerCase();
170
+ if (ext && extraExtensions && Object.hasOwn(extraExtensions, ext)) return extraExtensions[ext];
171
+ return lookup(PREVIEW_EXT_TO_MIME, filename);
172
+ }
173
+ function isEditableMime(mime) {
174
+ return mime === "text/markdown";
175
+ }
176
+
108
177
  export {
109
178
  groupConversationMessages,
110
179
  acquisitionFromRequest,
111
180
  readFirstTouchAcquisition,
112
- firstTouchAcquisitionCookie
181
+ firstTouchAcquisitionCookie,
182
+ sniffMimeFromName,
183
+ sniffMime,
184
+ isEditableMime
113
185
  };
114
- //# sourceMappingURL=chunk-FENBDSIW.js.map
186
+ //# sourceMappingURL=chunk-CQGEGPY7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/web/message-groups.ts","../src/web/acquisition.ts","../src/web/mime.ts"],"sourcesContent":["/** Renderer-neutral attribution. Not a transcript merger or an execution state machine. */\nexport interface ConversationGroupItem {\n id?: string | number\n kind?: string\n role?: string\n /** A different assistant/persona must never inherit the previous speaker's label. */\n speakerId?: string\n /** Distinct threads must not be grouped if their rows share a viewport. */\n conversationId?: string\n}\nexport type GroupedConversationItem<T> = T & { isContinuation?: boolean; groupId?: string }\n\n/**\n * Annotate assistant rows until an actual user message, speaker or conversation change.\n * Tool/progress notices do not interrupt the group. The first visible assistant is\n * always labeled, including when a renderer has paged earlier history away.\n * Pass display order; stored content, IDs, timestamps and input objects are untouched.\n */\nexport function groupConversationMessages<T extends ConversationGroupItem>(items: readonly T[] = []): GroupedConversationItem<T>[] {\n let speaker: string | null = null\n let conversation: string | undefined\n let groupId: string | undefined\n return items.map((item, index) => {\n if (item.conversationId !== undefined && item.conversationId !== conversation) {\n conversation = item.conversationId\n speaker = null\n groupId = undefined\n }\n const role = item.kind === 'thinking' ? 'assistant' : (!item.kind || item.kind === 'message' ? item.role : undefined)\n if (role === 'user') { speaker = null; groupId = undefined; return { ...item, isContinuation: false } }\n if (role !== 'assistant') return item\n const current = item.speakerId ?? 'assistant'\n const isContinuation = speaker === current\n if (!isContinuation) groupId = String(item.id ?? `assistant-${index}`)\n speaker = current\n return { ...item, isContinuation, groupId }\n })\n}\n","import { readCookieValue, serializeCookie } from './core'\n\nconst RETENTION_SECONDS = 30 * 24 * 60 * 60\nconst MAX_COOKIE_BYTES = 3600\nconst CAMPAIGN_FIELDS = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term'] as const\nconst CLICK_FIELDS = ['gclid', 'gbraid', 'wbraid', 'fbclid', 'msclkid', 'ttclid', 'li_fat_id', 'twclid'] as const\nconst FIELDS = [...CAMPAIGN_FIELDS, ...CLICK_FIELDS] as const\n\n/** Untrusted acquisition hints. Never use these fields for identity or authorization. */\nexport interface FirstTouchAcquisition {\n parameters: Partial<Record<typeof FIELDS[number], string>>\n referrerOrigin: string | null\n landingPath: string\n firstSeenAt: number\n test: boolean\n}\n\nfunction bounded(value: unknown, limit = 160): string | undefined {\n if (typeof value !== 'string') return undefined\n const text = value.trim().replace(/[\\u0000-\\u001f\\u007f]/g, '').slice(0, limit)\n return text || undefined\n}\n\nfunction origin(value: string | null): string | null {\n if (!value) return null\n try {\n const url = new URL(value)\n return ['https:', 'http:'].includes(url.protocol) ? url.origin : null\n } catch { return null }\n}\n\n/** Capture only campaign fields and an external origin, never URL queries or referrer paths. */\nexport function acquisitionFromRequest(request: Request, now = Date.now(), ignoredReferrerOrigins: readonly string[] = []): FirstTouchAcquisition | null {\n const url = new URL(request.url)\n const parameters: FirstTouchAcquisition['parameters'] = {}\n for (const field of FIELDS) {\n const value = bounded(url.searchParams.get(field))\n if (value) parameters[field] = value\n }\n const referrer = origin(request.headers.get('referer'))\n const referrerOrigin = referrer === url.origin || (referrer !== null && ignoredReferrerOrigins.includes(referrer)) ? null : referrer\n if (!Object.keys(parameters).length && !referrerOrigin) return null\n return {\n parameters,\n referrerOrigin,\n landingPath: url.pathname.slice(0, 300),\n firstSeenAt: now,\n test: url.searchParams.get('attribution_test') === '1',\n }\n}\n\n/** Reject expired, future, malformed, and oversized hints without affecting authentication. */\nexport function readFirstTouchAcquisition(request: Request, cookieName: string, now = Date.now()): FirstTouchAcquisition | null {\n const raw = readCookieValue(request.headers.get('cookie'), cookieName)\n if (!raw || encodeURIComponent(raw).length > MAX_COOKIE_BYTES) return null\n try {\n const value: unknown = JSON.parse(raw)\n if (!value || typeof value !== 'object' || Array.isArray(value)) return null\n const input = value as Record<string, unknown>\n if (typeof input.firstSeenAt !== 'number' || !Number.isFinite(input.firstSeenAt)\n || input.firstSeenAt > now || input.firstSeenAt < now - RETENTION_SECONDS * 1000) return null\n if (typeof input.landingPath !== 'string' || !input.landingPath.startsWith('/')\n || input.landingPath.includes('?') || input.landingPath.includes('#')) return null\n if (!input.parameters || typeof input.parameters !== 'object' || Array.isArray(input.parameters)) return null\n const parameters: FirstTouchAcquisition['parameters'] = {}\n const source = input.parameters as Record<string, unknown>\n for (const field of FIELDS) {\n const value = bounded(source[field])\n if (value) parameters[field] = value\n }\n const referrerOrigin = typeof input.referrerOrigin === 'string' ? origin(input.referrerOrigin) : null\n if (!Object.keys(parameters).length && !referrerOrigin) return null\n return { parameters, referrerOrigin, landingPath: input.landingPath.slice(0, 300), firstSeenAt: input.firstSeenAt, test: input.test === true }\n } catch { return null }\n}\n\n/** Host-only HttpOnly cookie survives a top-level sign-in round trip. First valid touch wins. */\nexport function firstTouchAcquisitionCookie(request: Request, cookieName: string, now = Date.now(), ignoredReferrerOrigins: readonly string[] = []): string | null {\n if (readFirstTouchAcquisition(request, cookieName, now)) return null\n const acquisition = acquisitionFromRequest(request, now, ignoredReferrerOrigins)\n if (!acquisition) return null\n const raw = JSON.stringify(acquisition)\n if (encodeURIComponent(raw).length > MAX_COOKIE_BYTES) return null\n return serializeCookie(raw, {\n name: cookieName,\n httpOnly: true,\n sameSite: 'Lax',\n secure: new URL(request.url).protocol === 'https:',\n maxAgeSeconds: RETENTION_SECONDS,\n })\n}\n","/**\n * Filename extension → media type. Browser-safe; no imports.\n *\n * `sniffMimeFromName` is the generic last-resort typing for uploads and\n * promoted agent files. `sniffMime` adds the code, MDX and spreadsheet types a\n * file preview picks its renderer from (rendered markdown, line-numbered code,\n * image, video, tabular CSV, embedded PDF, monospace text fallback). An unknown\n * extension falls to `text/plain`; it is never a rejection.\n */\n\nconst BASE_EXT_TO_MIME: Readonly<Record<string, string>> = {\n md: 'text/markdown',\n markdown: 'text/markdown',\n txt: 'text/plain',\n log: 'text/plain',\n csv: 'text/csv',\n tsv: 'text/tab-separated-values',\n json: 'application/json',\n yaml: 'text/yaml',\n yml: 'text/yaml',\n xml: 'application/xml',\n html: 'text/html',\n htm: 'text/html',\n pdf: 'application/pdf',\n png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n gif: 'image/gif',\n webp: 'image/webp',\n avif: 'image/avif',\n heic: 'image/heic',\n heif: 'image/heif',\n svg: 'image/svg+xml',\n mp4: 'video/mp4',\n webm: 'video/webm',\n mov: 'video/quicktime',\n mp3: 'audio/mpeg',\n wav: 'audio/wav',\n ogg: 'audio/ogg',\n m4a: 'audio/mp4',\n aac: 'audio/aac',\n}\n\nconst PREVIEW_EXT_TO_MIME: Readonly<Record<string, string>> = {\n ...BASE_EXT_TO_MIME,\n mdx: 'text/markdown',\n ts: 'text/typescript',\n tsx: 'text/typescript-jsx',\n js: 'text/javascript',\n jsx: 'text/jsx',\n py: 'text/x-python',\n rs: 'text/x-rust',\n go: 'text/x-go',\n java: 'text/x-java',\n rb: 'text/x-ruby',\n sh: 'text/x-shellscript',\n bash: 'text/x-shellscript',\n zsh: 'text/x-shellscript',\n toml: 'text/x-toml',\n xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n xls: 'application/vnd.ms-excel',\n}\n\nfunction lookup(table: Readonly<Record<string, string>>, filename: string): string {\n const ext = filename.split('.').pop()?.toLowerCase()\n if (!ext) return 'text/plain'\n return table[ext] ?? 'text/plain'\n}\n\n/** Generic extension → mime for uploads and promoted files. */\nexport function sniffMimeFromName(filename: string): string {\n return lookup(BASE_EXT_TO_MIME, filename)\n}\n\n/** Extension → mime for choosing a file preview renderer. A product's own\n * file types (e.g. `{ fountain: 'text/plain' }`) go in `extraExtensions`. */\nexport function sniffMime(filename: string, extraExtensions?: Readonly<Record<string, string>>): string {\n const ext = filename.split('.').pop()?.toLowerCase()\n if (ext && extraExtensions && Object.hasOwn(extraExtensions, ext)) return extraExtensions[ext]!\n return lookup(PREVIEW_EXT_TO_MIME, filename)\n}\n\n/** The vault editor surface is Markdown-only. */\nexport function isEditableMime(mime: string): boolean {\n return mime === 'text/markdown'\n}\n"],"mappings":";;;;;;AAkBO,SAAS,0BAA2D,QAAsB,CAAC,GAAiC;AACjI,MAAI,UAAyB;AAC7B,MAAI;AACJ,MAAI;AACJ,SAAO,MAAM,IAAI,CAAC,MAAM,UAAU;AAChC,QAAI,KAAK,mBAAmB,UAAa,KAAK,mBAAmB,cAAc;AAC7E,qBAAe,KAAK;AACpB,gBAAU;AACV,gBAAU;AAAA,IACZ;AACA,UAAM,OAAO,KAAK,SAAS,aAAa,cAAe,CAAC,KAAK,QAAQ,KAAK,SAAS,YAAY,KAAK,OAAO;AAC3G,QAAI,SAAS,QAAQ;AAAE,gBAAU;AAAM,gBAAU;AAAW,aAAO,EAAE,GAAG,MAAM,gBAAgB,MAAM;AAAA,IAAE;AACtG,QAAI,SAAS,YAAa,QAAO;AACjC,UAAM,UAAU,KAAK,aAAa;AAClC,UAAM,iBAAiB,YAAY;AACnC,QAAI,CAAC,eAAgB,WAAU,OAAO,KAAK,MAAM,aAAa,KAAK,EAAE;AACrE,cAAU;AACV,WAAO,EAAE,GAAG,MAAM,gBAAgB,QAAQ;AAAA,EAC5C,CAAC;AACH;;;ACnCA,IAAM,oBAAoB,KAAK,KAAK,KAAK;AACzC,IAAM,mBAAmB;AACzB,IAAM,kBAAkB,CAAC,cAAc,cAAc,gBAAgB,eAAe,UAAU;AAC9F,IAAM,eAAe,CAAC,SAAS,UAAU,UAAU,UAAU,WAAW,UAAU,aAAa,QAAQ;AACvG,IAAM,SAAS,CAAC,GAAG,iBAAiB,GAAG,YAAY;AAWnD,SAAS,QAAQ,OAAgB,QAAQ,KAAyB;AAChE,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,QAAM,OAAO,MAAM,KAAK,EAAE,QAAQ,0BAA0B,EAAE,EAAE,MAAM,GAAG,KAAK;AAC9E,SAAO,QAAQ;AACjB;AAE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G,YAAY;AACnD,MAAI,OAAO,mBAAmB,OAAO,OAAO,iBAAiB,GAAG,EAAG,QAAO,gBAAgB,GAAG;AAC7F,SAAO,OAAO,qBAAqB,QAAQ;AAC7C;AAGO,SAAS,eAAe,MAAuB;AACpD,SAAO,SAAS;AAClB;","names":["value"]}
@@ -0,0 +1,335 @@
1
+ // src/sandbox/exec-failure.ts
2
+ var ProfileWriteExecTimeoutError = class extends Error {
3
+ constructor(timeoutMs) {
4
+ super(`exec exceeded ${timeoutMs}ms (proxy hang/wedge)`);
5
+ this.name = "ProfileWriteExecTimeoutError";
6
+ }
7
+ };
8
+ var TRANSIENT_EXEC_STATUS_CODES = /* @__PURE__ */ new Set([408, 409, 425, 429, 500, 502, 503, 504]);
9
+ var TRANSIENT_EXEC_CODE_RE = /^(ECONNRESET|ECONNREFUSED|ETIMEDOUT|EPIPE|ECONNABORTED)$/i;
10
+ var TRANSIENT_EXEC_MESSAGE_RE = /\b(408|409|425|429|500|502|503|504)\b|rate.?limit|too many requests|\bfetch failed\b|network error|connection reset|socket hang up|timed? out|service unavailable|bad gateway|gateway timeout|internal server error|\b(?:sidecar|runtime|exec(?:ution)?|terminal|sandbox|service|command(?:s)?|proxy)\b.{0,80}\bnot ready\b|\bnot ready\b.{0,80}\b(?:sidecar|runtime|exec(?:ution)?|terminal|sandbox|service|command(?:s)?|proxy)\b/i;
11
+ function errorStatus(err) {
12
+ const rawStatus = err.status ?? err.statusCode ?? (err.response && typeof err.response === "object" ? err.response.status : void 0);
13
+ if (typeof rawStatus === "number") return rawStatus;
14
+ if (typeof rawStatus === "string" && /^\d+$/.test(rawStatus)) return Number(rawStatus);
15
+ return void 0;
16
+ }
17
+ function retryAfterMs(err, seen = /* @__PURE__ */ new Set()) {
18
+ if (!err || typeof err !== "object") return void 0;
19
+ if (seen.has(err)) return void 0;
20
+ seen.add(err);
21
+ const e = err;
22
+ if (typeof e.retryAfterMs === "number") return e.retryAfterMs;
23
+ return retryAfterMs(e.cause, seen);
24
+ }
25
+ function isTransientExecError(err, seen = /* @__PURE__ */ new Set()) {
26
+ if (!err || typeof err !== "object") return false;
27
+ if (seen.has(err)) return false;
28
+ seen.add(err);
29
+ const e = err;
30
+ const status = errorStatus(e);
31
+ if (status !== void 0 && TRANSIENT_EXEC_STATUS_CODES.has(status)) return true;
32
+ if (typeof e.code === "string") {
33
+ if (TRANSIENT_EXEC_CODE_RE.test(e.code)) return true;
34
+ if (/rate.?limit|too.?many.?requests|429|server.?error|service.?unavailable/i.test(e.code)) return true;
35
+ }
36
+ if (typeof e.message === "string" && TRANSIENT_EXEC_MESSAGE_RE.test(e.message)) return true;
37
+ return isTransientExecError(e.cause, seen);
38
+ }
39
+ function isRuntimeExecAuthError(err, seen = /* @__PURE__ */ new Set()) {
40
+ if (!err || typeof err !== "object") return false;
41
+ if (seen.has(err)) return false;
42
+ seen.add(err);
43
+ const e = err;
44
+ if (errorStatus(e) === 401) return true;
45
+ if (typeof e.code === "string" && /^(AUTH_ERROR|AUTHENTICATION_ERROR|UNAUTHORIZED|UNAUTHENTICATED|ERR_UNAUTHORIZED|ERR_UNAUTHENTICATED|401)$/i.test(e.code)) {
46
+ return true;
47
+ }
48
+ if (typeof e.name === "string" && /^(AuthError|AuthenticationError|UnauthorizedError|UnauthenticatedError|SandboxAuthError)$/i.test(e.name)) {
49
+ return true;
50
+ }
51
+ return isRuntimeExecAuthError(e.cause, seen);
52
+ }
53
+ function isRuntimeAuthRefreshDenied(err) {
54
+ if (!err || typeof err !== "object") return false;
55
+ return isRuntimeExecAuthError(err) || errorStatus(err) === 403;
56
+ }
57
+ function transientExecError(err) {
58
+ if (err instanceof ProfileWriteExecTimeoutError) return { retryable: true };
59
+ if (isTransientExecError(err)) return { retryable: true, retryAfterMs: retryAfterMs(err) };
60
+ return { retryable: false };
61
+ }
62
+
63
+ // src/sandbox/outcome.ts
64
+ var ok = (value) => ({ succeeded: true, value });
65
+ var fail = (error) => ({
66
+ succeeded: false,
67
+ error: error instanceof Error ? error : new Error(String(error))
68
+ });
69
+
70
+ // src/sandbox/profile-files.ts
71
+ import { createHash } from "crypto";
72
+
73
+ // src/sandbox/shell-path.ts
74
+ function shellSingleQuote(value) {
75
+ return `'${value.replace(/'/g, `'\\''`)}'`;
76
+ }
77
+ function shellPath(path) {
78
+ if (path === "~") return '"$HOME"';
79
+ if (path.startsWith("~/")) {
80
+ const rest = path.slice(2);
81
+ return rest ? `"$HOME"/${shellSingleQuote(rest)}` : '"$HOME"';
82
+ }
83
+ return shellSingleQuote(path);
84
+ }
85
+
86
+ // src/sandbox/profile-files.ts
87
+ function splitDeferredProfileFiles(profile) {
88
+ const files = profile.resources?.files ?? [];
89
+ const deferredFiles = [];
90
+ const keptFiles = [];
91
+ for (const mount of files) {
92
+ if (mount.resource.kind === "inline") deferredFiles.push(mount);
93
+ else keptFiles.push(mount);
94
+ }
95
+ if (deferredFiles.length === 0) return { leanProfile: profile, deferredFiles };
96
+ const leanProfile = {
97
+ ...profile,
98
+ resources: { ...profile.resources ?? {}, files: keptFiles }
99
+ };
100
+ return { leanProfile, deferredFiles };
101
+ }
102
+ var PROFILE_WRITE_B64_CHUNK_CHARS = 3e3;
103
+ var PROFILE_WRITE_MAX_RETRIES = 4;
104
+ var PROFILE_WRITE_RETRY_BASE_MS = 250;
105
+ var PROFILE_WRITE_RETRY_MAX_MS = 2e3;
106
+ var PROFILE_WRITE_EXEC_TIMEOUT_MS = 3e4;
107
+ var PROFILE_WRITE_PACE_MS = 150;
108
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
109
+ var PROFILE_BIN_DIR_RE = /(^|\/)(s?bin)\//;
110
+ function execWithTimeout(box, cmd, timeoutMs) {
111
+ return new Promise((resolve, reject) => {
112
+ let settled = false;
113
+ const timer = setTimeout(() => {
114
+ if (settled) return;
115
+ settled = true;
116
+ reject(new ProfileWriteExecTimeoutError(timeoutMs));
117
+ }, timeoutMs);
118
+ box.exec(cmd, { timeoutMs }).then(
119
+ (res) => {
120
+ if (settled) return;
121
+ settled = true;
122
+ clearTimeout(timer);
123
+ resolve(res);
124
+ },
125
+ (err) => {
126
+ if (settled) return;
127
+ settled = true;
128
+ clearTimeout(timer);
129
+ reject(err);
130
+ }
131
+ );
132
+ });
133
+ }
134
+ function fileApiTarget(mount) {
135
+ if (mount.resource.kind !== "inline") return null;
136
+ let rel;
137
+ if (mount.path.startsWith("~/")) rel = mount.path.slice(2);
138
+ else if (mount.path.startsWith("/home/agent/")) rel = mount.path.slice("/home/agent/".length);
139
+ else if (mount.path.startsWith("/") || mount.path.startsWith("~")) return null;
140
+ else rel = mount.path;
141
+ if (rel.length === 0 || rel.startsWith("/") || rel.split("/").some((seg) => seg === ".." || seg === ".sidecar")) {
142
+ return null;
143
+ }
144
+ return rel;
145
+ }
146
+ function isExecutableProfileFile(mount) {
147
+ return mount.executable ?? PROFILE_BIN_DIR_RE.test(mount.path);
148
+ }
149
+ function profileFileMode(mount) {
150
+ return isExecutableProfileFile(mount) ? 493 : void 0;
151
+ }
152
+ var PROFILE_FILE_API_MAX_JSON_BYTES = 1024 * 1024 - 16 * 1024;
153
+ function fitsProfileFileApi(content) {
154
+ const encoder = new TextEncoder();
155
+ if (encoder.encode(content).byteLength * 6 <= PROFILE_FILE_API_MAX_JSON_BYTES) return true;
156
+ return encoder.encode(JSON.stringify(content)).byteLength <= PROFILE_FILE_API_MAX_JSON_BYTES;
157
+ }
158
+ function fileApiSupportsMode(box) {
159
+ const fs = box.fs;
160
+ return fs?.supportsWriteMode === true;
161
+ }
162
+ async function writeProfileFilesToBox(box, files, options = {}) {
163
+ const execTimeoutMs = options.execTimeoutMs ?? PROFILE_WRITE_EXEC_TIMEOUT_MS;
164
+ const paceMs = options.paceMs ?? PROFILE_WRITE_PACE_MS;
165
+ const maxRetries = options.maxRetries ?? PROFILE_WRITE_MAX_RETRIES;
166
+ const fileApiAvailable = typeof box.fs?.writeMany === "function";
167
+ const modeAwareFileApi = fileApiSupportsMode(box);
168
+ const uploadData = box.fs?.uploadData;
169
+ const viaFileApi = [];
170
+ const viaUpload = [];
171
+ const viaExec = [];
172
+ for (const mount of files) {
173
+ if (mount.resource.kind !== "inline") continue;
174
+ const fileApiPath = fileApiAvailable ? fileApiTarget(mount) : null;
175
+ const executable = isExecutableProfileFile(mount);
176
+ if (fileApiPath !== null && (!executable || modeAwareFileApi)) {
177
+ const mode = profileFileMode(mount);
178
+ const content = mount.resource.content ?? "";
179
+ const write = { path: fileApiPath, content, ...mode !== void 0 ? { mode } : {} };
180
+ if (fitsProfileFileApi(content)) viaFileApi.push(write);
181
+ else if (typeof uploadData === "function") viaUpload.push(write);
182
+ else viaExec.push(mount);
183
+ } else viaExec.push(mount);
184
+ }
185
+ if (viaFileApi.length > 0) {
186
+ try {
187
+ await box.fs.writeMany(viaFileApi, { paceMs, maxRetries });
188
+ } catch (err) {
189
+ return fail(new Error("writeProfileFilesToBox: file-API batch write failed", { cause: err }));
190
+ }
191
+ }
192
+ for (const upload of viaUpload) {
193
+ try {
194
+ await uploadData.call(box.fs, upload.path, upload.content, upload.mode !== void 0 ? { mode: upload.mode } : void 0);
195
+ } catch (err) {
196
+ return fail(new Error(`writeProfileFilesToBox: chunked upload failed for ${upload.path}`, { cause: err }));
197
+ }
198
+ }
199
+ let execStarted = false;
200
+ const paceAndRetry = async (run, path) => {
201
+ for (let attempt = 0; ; attempt++) {
202
+ if (execStarted && paceMs > 0) await sleep(paceMs);
203
+ execStarted = true;
204
+ try {
205
+ return ok(await run());
206
+ } catch (err) {
207
+ const { retryable, retryAfterMs: retryAfterMs2 } = transientExecError(err);
208
+ if (retryable && attempt < maxRetries) {
209
+ const backoff = Math.min(PROFILE_WRITE_RETRY_BASE_MS * 2 ** attempt, PROFILE_WRITE_RETRY_MAX_MS);
210
+ await sleep(retryAfterMs2 ?? backoff);
211
+ continue;
212
+ }
213
+ return fail(new Error(`writeProfileFilesToBox: exec failed for ${path}`, { cause: err }));
214
+ }
215
+ }
216
+ };
217
+ for (const mount of viaExec) {
218
+ if (mount.resource.kind !== "inline") continue;
219
+ const content = mount.resource.content ?? "";
220
+ const path = mount.path;
221
+ const b64 = Buffer.from(content, "utf8").toString("base64");
222
+ const b64Chunks = [];
223
+ for (let i = 0; i < b64.length; i += PROFILE_WRITE_B64_CHUNK_CHARS) {
224
+ b64Chunks.push(b64.slice(i, i + PROFILE_WRITE_B64_CHUNK_CHARS));
225
+ }
226
+ const expectedSha256 = createHash("sha256").update(content, "utf8").digest("hex");
227
+ const dir = path.replace(/\/[^/]*$/, "");
228
+ const executable = isExecutableProfileFile(mount);
229
+ const q = shellPath(path);
230
+ const qb64 = shellPath(`${path}.b64`);
231
+ const qtmp = shellPath(`${path}.tmp`);
232
+ const qpartPrefix = shellPath(`${path}.b64.part.`);
233
+ const step = async (cmd) => {
234
+ const res2 = await paceAndRetry(() => execWithTimeout(box, cmd, execTimeoutMs), path);
235
+ if (!res2.succeeded) return res2;
236
+ const exec = res2.value;
237
+ if (exec.exitCode !== 0) {
238
+ return fail(
239
+ new Error(
240
+ `writeProfileFilesToBox: failed to write ${path} (exit ${exec.exitCode}): ${exec.stderr.slice(0, 500)}`
241
+ )
242
+ );
243
+ }
244
+ return ok(void 0);
245
+ };
246
+ const mkdir = dir && dir !== path ? `mkdir -p ${shellPath(dir)}` : ":";
247
+ let res = await step(mkdir);
248
+ if (!res.succeeded) return res;
249
+ for (let i = 0; i < b64Chunks.length; i++) {
250
+ const slice = b64Chunks[i];
251
+ res = await step(`printf '%s' '${slice}' > ${shellPath(`${path}.b64.part.${i}`)}`);
252
+ if (!res.succeeded) return res;
253
+ }
254
+ const chmod = executable ? `chmod +x ${q} || exit 1; ` : "";
255
+ const checksumMismatch = shellSingleQuote(`writeProfileFilesToBox: checksum mismatch for ${path}`);
256
+ const finalCmd = `expected='${expectedSha256}'; if [ -f ${q} ] && [ "$(sha256sum ${q} | awk '{print $1}')" = "$expected" ]; then ${chmod}rm -f ${qb64} ${qtmp}; i=0; while [ "$i" -lt ${b64Chunks.length} ]; do rm -f ${qpartPrefix}$i; i=$((i+1)); done; exit 0; fi; : > ${qb64} && i=0; while [ "$i" -lt ${b64Chunks.length} ]; do cat ${qpartPrefix}$i >> ${qb64} || exit 1; i=$((i+1)); done && base64 -d < ${qb64} > ${qtmp} && [ "$(sha256sum ${qtmp} | awk '{print $1}')" = "$expected" ] || { echo ${checksumMismatch} >&2; exit 1; }; mv ${qtmp} ${q} && ${executable ? `chmod +x ${q} && ` : ""}[ "$(sha256sum ${q} | awk '{print $1}')" = "$expected" ] || { echo ${checksumMismatch} >&2; exit 1; }; rm -f ${qb64} ${qtmp}; i=0; while [ "$i" -lt ${b64Chunks.length} ]; do rm -f ${qpartPrefix}$i; i=$((i+1)); done`;
257
+ res = await step(finalCmd);
258
+ if (!res.succeeded) return res;
259
+ }
260
+ return ok(void 0);
261
+ }
262
+
263
+ // src/sandbox/binary-read.ts
264
+ function shellQuote(value) {
265
+ return `'${value.replaceAll("'", `'"'"'`)}'`;
266
+ }
267
+ function base64ToBytes(base64) {
268
+ const binary = atob(base64);
269
+ const bytes = new Uint8Array(binary.length);
270
+ for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
271
+ return bytes;
272
+ }
273
+ function execInSandbox(box, command, options) {
274
+ return options?.sessionId ? box.exec(command, { sessionId: options.sessionId }) : box.exec(command);
275
+ }
276
+ async function statSandboxFileSize(box, absolutePath, options) {
277
+ const quotedPath = shellQuote(absolutePath);
278
+ let result;
279
+ try {
280
+ result = await execInSandbox(box, `wc -c < ${quotedPath}`, options);
281
+ } catch (err) {
282
+ return { succeeded: false, error: err instanceof Error ? err.message : String(err) };
283
+ }
284
+ if (result.exitCode !== 0) {
285
+ return { succeeded: false, error: result.stderr || "unknown error" };
286
+ }
287
+ const size = Number.parseInt(result.stdout.trim(), 10);
288
+ if (!Number.isFinite(size)) {
289
+ return { succeeded: false, error: `could not parse file size from "${result.stdout.trim()}"` };
290
+ }
291
+ return { succeeded: true, value: size };
292
+ }
293
+ async function readSandboxBinaryBytes(box, absolutePath, expectedSize, options) {
294
+ const quotedPath = shellQuote(absolutePath);
295
+ let result;
296
+ try {
297
+ result = await execInSandbox(box, `base64 ${quotedPath}`, options);
298
+ } catch (err) {
299
+ return { succeeded: false, error: err instanceof Error ? err.message : String(err) };
300
+ }
301
+ if (result.exitCode !== 0) {
302
+ return { succeeded: false, error: result.stderr || "unknown error" };
303
+ }
304
+ const cleaned = result.stdout.replace(/\s+/g, "");
305
+ let bytes;
306
+ try {
307
+ bytes = base64ToBytes(cleaned);
308
+ } catch (err) {
309
+ return {
310
+ succeeded: false,
311
+ error: `could not decode file contents: ${err instanceof Error ? err.message : String(err)}`
312
+ };
313
+ }
314
+ if (bytes.byteLength !== expectedSize) {
315
+ return {
316
+ succeeded: false,
317
+ error: `read returned ${bytes.byteLength} bytes, expected ${expectedSize} \u2014 output truncated in transit`
318
+ };
319
+ }
320
+ return { succeeded: true, value: { bytes, size: expectedSize } };
321
+ }
322
+
323
+ export {
324
+ isRuntimeExecAuthError,
325
+ isRuntimeAuthRefreshDenied,
326
+ ok,
327
+ fail,
328
+ shellSingleQuote,
329
+ splitDeferredProfileFiles,
330
+ writeProfileFilesToBox,
331
+ shellQuote,
332
+ statSandboxFileSize,
333
+ readSandboxBinaryBytes
334
+ };
335
+ //# sourceMappingURL=chunk-CTREXL3O.js.map