privateer-agent 0.15.4 → 0.15.6

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 (229) hide show
  1. package/README.md +11 -0
  2. package/bin/boot-bundle.d.mts +2 -0
  3. package/bin/boot-bundle.mjs +44 -0
  4. package/bin/fresh-supervisor.d.mts +5 -1
  5. package/bin/fresh-supervisor.mjs +47 -10
  6. package/bin/privateer-launch.mjs +27 -3
  7. package/bin/privateer-subagent.mjs +5 -2
  8. package/bin/privateer-verify.mjs +12 -0
  9. package/bin/session-recovery.d.mts +53 -0
  10. package/bin/session-recovery.mjs +240 -0
  11. package/bin/session-seal-preload.mjs +17 -0
  12. package/bin/session-seal.d.mts +25 -0
  13. package/bin/session-seal.mjs +242 -0
  14. package/dist-boot/boot.mjs +3 -0
  15. package/dist-boot/c-27JKSMWL.mjs +1460 -0
  16. package/dist-boot/c-2BMRFV24.mjs +269 -0
  17. package/dist-boot/c-2CTF6JA3.mjs +166 -0
  18. package/dist-boot/c-2G3BBHRJ.mjs +84 -0
  19. package/dist-boot/c-2IDLKXX6.mjs +250 -0
  20. package/dist-boot/c-2NJD5VYM.mjs +8 -0
  21. package/dist-boot/c-2S5EEQPW.mjs +1602 -0
  22. package/dist-boot/c-2WRDCUVI.mjs +25 -0
  23. package/dist-boot/c-2YN3M256.mjs +14 -0
  24. package/dist-boot/c-37GM3GMU.mjs +187 -0
  25. package/dist-boot/c-3STKRSVO.mjs +2480 -0
  26. package/dist-boot/c-3TPV6TQQ.mjs +2320 -0
  27. package/dist-boot/c-3UVHLQDJ.mjs +225 -0
  28. package/dist-boot/c-42PUUZYC.mjs +697 -0
  29. package/dist-boot/c-4D5UMWVW.mjs +683 -0
  30. package/dist-boot/c-4ETZRMTA.mjs +46 -0
  31. package/dist-boot/c-4QT25BD5.mjs +1482 -0
  32. package/dist-boot/c-4WVR32AP.mjs +2579 -0
  33. package/dist-boot/c-5EMM567G.mjs +152 -0
  34. package/dist-boot/c-5FA4CV63.mjs +145 -0
  35. package/dist-boot/c-5GV3X3RB.mjs +14 -0
  36. package/dist-boot/c-5JCEPRIY.mjs +52 -0
  37. package/dist-boot/c-5NDKIIWT.mjs +16 -0
  38. package/dist-boot/c-5QL3AR26.mjs +4665 -0
  39. package/dist-boot/c-5XY6MFKN.mjs +5142 -0
  40. package/dist-boot/c-65UZIZC7.mjs +2897 -0
  41. package/dist-boot/c-6FUXKHOK.mjs +1969 -0
  42. package/dist-boot/c-6JHWQE4V.mjs +18242 -0
  43. package/dist-boot/c-6LOBR4I6.mjs +5280 -0
  44. package/dist-boot/c-6QHOZXKQ.mjs +14394 -0
  45. package/dist-boot/c-6ZO2SADQ.mjs +178 -0
  46. package/dist-boot/c-6ZORVVZP.mjs +1449 -0
  47. package/dist-boot/c-76QH4UCP.mjs +2441 -0
  48. package/dist-boot/c-77GO5L5Y.mjs +20982 -0
  49. package/dist-boot/c-7M23XFTN.mjs +5052 -0
  50. package/dist-boot/c-7TC367E2.mjs +32 -0
  51. package/dist-boot/c-7UOG7POX.mjs +1524 -0
  52. package/dist-boot/c-7VHP3FLN.mjs +376 -0
  53. package/dist-boot/c-A73JHZP2.mjs +13207 -0
  54. package/dist-boot/c-ABXULAFL.mjs +71 -0
  55. package/dist-boot/c-ANDD2AQO.mjs +74 -0
  56. package/dist-boot/c-AOY77AZL.mjs +1430 -0
  57. package/dist-boot/c-AXEPZ22I.mjs +108 -0
  58. package/dist-boot/c-B2Y7VNHU.mjs +427 -0
  59. package/dist-boot/c-B7VJUH73.mjs +77 -0
  60. package/dist-boot/c-BFW6CDVL.mjs +24 -0
  61. package/dist-boot/c-BHNIF2AR.mjs +188 -0
  62. package/dist-boot/c-BKF2O6BL.mjs +23 -0
  63. package/dist-boot/c-BOZXFTZN.mjs +8 -0
  64. package/dist-boot/c-BRNYJWZL.mjs +28 -0
  65. package/dist-boot/c-C3N4Z2HO.mjs +93 -0
  66. package/dist-boot/c-C4IV7ZFG.mjs +717 -0
  67. package/dist-boot/c-C5NK6UYV.mjs +793 -0
  68. package/dist-boot/c-C67644MB.mjs +1659 -0
  69. package/dist-boot/c-C6S2YB53.mjs +620 -0
  70. package/dist-boot/c-CDBEJSBF.mjs +37 -0
  71. package/dist-boot/c-CG47HBKU.mjs +435 -0
  72. package/dist-boot/c-CKCTWCT5.mjs +51 -0
  73. package/dist-boot/c-CN77DCGF.mjs +60 -0
  74. package/dist-boot/c-CRBXNKFO.mjs +1795 -0
  75. package/dist-boot/c-CRIHASQ6.mjs +973 -0
  76. package/dist-boot/c-CU4NGAUO.mjs +3786 -0
  77. package/dist-boot/c-CWRFLGQU.mjs +1883 -0
  78. package/dist-boot/c-CYQB2USO.mjs +32 -0
  79. package/dist-boot/c-DEE67DJO.mjs +379 -0
  80. package/dist-boot/c-DIFDBYOP.mjs +1258 -0
  81. package/dist-boot/c-DOSGVXDZ.mjs +34879 -0
  82. package/dist-boot/c-DR7XQI32.mjs +381 -0
  83. package/dist-boot/c-DTGPSB46.mjs +14666 -0
  84. package/dist-boot/c-DTHDNA4P.mjs +320 -0
  85. package/dist-boot/c-E4Z3Y5B5.mjs +3864 -0
  86. package/dist-boot/c-E66Z2TI7.mjs +203 -0
  87. package/dist-boot/c-EBU6RLRV.mjs +1527 -0
  88. package/dist-boot/c-EBZZNGSF.mjs +432 -0
  89. package/dist-boot/c-EC3LJ2KF.mjs +1032 -0
  90. package/dist-boot/c-EQBKXWNX.mjs +15829 -0
  91. package/dist-boot/c-EUEPIW4S.mjs +574 -0
  92. package/dist-boot/c-EX4YVWAT.mjs +378 -0
  93. package/dist-boot/c-EYZGSAJU.mjs +98 -0
  94. package/dist-boot/c-F75VRKY4.mjs +172 -0
  95. package/dist-boot/c-FH4NXKHV.mjs +177 -0
  96. package/dist-boot/c-FHNUCTEM.mjs +140 -0
  97. package/dist-boot/c-FJ5T42DS.mjs +5349 -0
  98. package/dist-boot/c-FPCNRL7G.mjs +1728 -0
  99. package/dist-boot/c-G4DLN7Q4.mjs +8 -0
  100. package/dist-boot/c-G56GYQFZ.mjs +2507 -0
  101. package/dist-boot/c-GLIOERDQ.mjs +1200 -0
  102. package/dist-boot/c-GMJ5HUBM.mjs +14 -0
  103. package/dist-boot/c-H3HSGMAQ.mjs +461 -0
  104. package/dist-boot/c-HIKTO6P7.mjs +275 -0
  105. package/dist-boot/c-I2MCJ34O.mjs +464 -0
  106. package/dist-boot/c-I3C6LBW4.mjs +765 -0
  107. package/dist-boot/c-I54OKQHW.mjs +387 -0
  108. package/dist-boot/c-IFSP3R4D.mjs +80 -0
  109. package/dist-boot/c-IZK77VB7.mjs +171 -0
  110. package/dist-boot/c-J3Y25UGE.mjs +54 -0
  111. package/dist-boot/c-J5IESS7W.mjs +27750 -0
  112. package/dist-boot/c-JJWZBY7L.mjs +254 -0
  113. package/dist-boot/c-JKTFXTGF.mjs +463 -0
  114. package/dist-boot/c-JN57AXQ4.mjs +77 -0
  115. package/dist-boot/c-KFIO6LUW.mjs +1096 -0
  116. package/dist-boot/c-KIEMEFWW.mjs +478 -0
  117. package/dist-boot/c-KIVXWBYD.mjs +28 -0
  118. package/dist-boot/c-KP6CRIP4.mjs +580 -0
  119. package/dist-boot/c-L26VOJX4.mjs +11558 -0
  120. package/dist-boot/c-L5GHWG5G.mjs +5988 -0
  121. package/dist-boot/c-M7NSQAKK.mjs +353 -0
  122. package/dist-boot/c-MCEWOPBW.mjs +56 -0
  123. package/dist-boot/c-MGPIEG7I.mjs +20 -0
  124. package/dist-boot/c-NREXJV3M.mjs +393 -0
  125. package/dist-boot/c-O5PP6CTX.mjs +162 -0
  126. package/dist-boot/c-OBQDHSXM.mjs +1774 -0
  127. package/dist-boot/c-OLQHHDD4.mjs +21 -0
  128. package/dist-boot/c-OXW4JQQH.mjs +319 -0
  129. package/dist-boot/c-P3D7ZUWN.mjs +1288 -0
  130. package/dist-boot/c-P4PQZVV5.mjs +948 -0
  131. package/dist-boot/c-P63T3XL2.mjs +26373 -0
  132. package/dist-boot/c-P6N5DQGZ.mjs +194 -0
  133. package/dist-boot/c-P7MLKQFC.mjs +58 -0
  134. package/dist-boot/c-PB3PZJL5.mjs +1276 -0
  135. package/dist-boot/c-PTN4S6G2.mjs +1259 -0
  136. package/dist-boot/c-PYCE5J7U.mjs +1083 -0
  137. package/dist-boot/c-Q4HYCRLB.mjs +19410 -0
  138. package/dist-boot/c-QUXMETGG.mjs +68 -0
  139. package/dist-boot/c-RDMJZCOX.mjs +356 -0
  140. package/dist-boot/c-ROGJK76M.mjs +17 -0
  141. package/dist-boot/c-RQJJ26T4.mjs +708 -0
  142. package/dist-boot/c-RSKCUPJF.mjs +7559 -0
  143. package/dist-boot/c-RVJU4O6P.mjs +37 -0
  144. package/dist-boot/c-S2RVHR3M.mjs +165 -0
  145. package/dist-boot/c-SKMK3PEE.mjs +91120 -0
  146. package/dist-boot/c-TI7SM4EG.mjs +20 -0
  147. package/dist-boot/c-TILJ6GXD.mjs +1235 -0
  148. package/dist-boot/c-TT6BCUJD.mjs +114 -0
  149. package/dist-boot/c-U4ITOXAN.mjs +2107 -0
  150. package/dist-boot/c-UGERXVO2.mjs +7120 -0
  151. package/dist-boot/c-UPBH5AXY.mjs +1363 -0
  152. package/dist-boot/c-US2PUNZL.mjs +597 -0
  153. package/dist-boot/c-UU4WZPPE.mjs +20 -0
  154. package/dist-boot/c-UWVIYPQS.mjs +39 -0
  155. package/dist-boot/c-V4RHQBPQ.mjs +17683 -0
  156. package/dist-boot/c-V5MRVK47.mjs +351 -0
  157. package/dist-boot/c-V6CL266R.mjs +1755 -0
  158. package/dist-boot/c-VJTMFKYE.mjs +14975 -0
  159. package/dist-boot/c-VJTRUKIB.mjs +773 -0
  160. package/dist-boot/c-W4IFSHPW.mjs +43 -0
  161. package/dist-boot/c-WETGB2CF.mjs +113 -0
  162. package/dist-boot/c-WO3QSZUU.mjs +1337 -0
  163. package/dist-boot/c-WQLH73TY.mjs +242 -0
  164. package/dist-boot/c-XL735JW5.mjs +500 -0
  165. package/dist-boot/c-Y7HADL5B.mjs +1107 -0
  166. package/dist-boot/c-YGQHSVSK.mjs +41 -0
  167. package/dist-boot/c-YMP2AMEB.mjs +10350 -0
  168. package/dist-boot/c-YRDO2WEF.mjs +12012 -0
  169. package/dist-boot/c-YUSTRATJ.mjs +8 -0
  170. package/dist-boot/c-Z2262R22.mjs +2697 -0
  171. package/dist-boot/c-Z4ALQMJC.mjs +709 -0
  172. package/dist-boot/c-Z5ZUQVUY.mjs +62 -0
  173. package/dist-boot/c-ZDZUKXF7.mjs +874 -0
  174. package/dist-boot/c-ZJYLGIC3.mjs +32 -0
  175. package/dist-boot/c-ZNA5CDMI.mjs +77 -0
  176. package/dist-boot/c-ZSO6DI3M.mjs +204 -0
  177. package/dist-boot/c-ZWUVHKMK.mjs +100 -0
  178. package/dist-boot/c-ZY4MESEW.mjs +832 -0
  179. package/dist-boot/c-ZZ5REI4L.mjs +329 -0
  180. package/dist-boot/cli.mjs +51 -0
  181. package/dist-boot/ext-anthropic-attribution.mjs +207 -0
  182. package/dist-boot/ext-pi-background-tasks.mjs +7234 -0
  183. package/dist-boot/ext-pi-subagents.mjs +37 -0
  184. package/dist-boot/ext-privateer-account.mjs +4426 -0
  185. package/dist-boot/ext-privateer-brand.mjs +5274 -0
  186. package/dist-boot/ext-privateer-codemode.mjs +37 -0
  187. package/dist-boot/ext-privateer-computer.mjs +626 -0
  188. package/dist-boot/ext-privateer-connect.mjs +1862 -0
  189. package/dist-boot/ext-privateer-context.mjs +323 -0
  190. package/dist-boot/ext-privateer-desktop.mjs +92 -0
  191. package/dist-boot/ext-privateer-final-audit.mjs +48 -0
  192. package/dist-boot/ext-privateer-fresh.mjs +81 -0
  193. package/dist-boot/ext-privateer-gate.mjs +5959 -0
  194. package/dist-boot/ext-privateer-hints.mjs +236 -0
  195. package/dist-boot/ext-privateer-media.mjs +2626 -0
  196. package/dist-boot/ext-privateer-models.mjs +3397 -0
  197. package/dist-boot/ext-privateer-posture.mjs +3006 -0
  198. package/dist-boot/ext-privateer-privacy.mjs +4578 -0
  199. package/dist-boot/ext-privateer-recovery.mjs +287 -0
  200. package/dist-boot/ext-privateer-speak.mjs +4754 -0
  201. package/dist-boot/ext-privateer-terminals.mjs +725 -0
  202. package/dist-boot/ext-privateer-tools.mjs +528 -0
  203. package/dist-boot/ext-privateer-truncation.mjs +74 -0
  204. package/dist-boot/ext-privateer-update.mjs +210 -0
  205. package/dist-boot/ext-privateer-vision.mjs +148 -0
  206. package/dist-boot/ext-privateer-web.mjs +543 -0
  207. package/dist-boot/ext-rpiv-ask-user-question.mjs +710 -0
  208. package/dist-boot/manifest.json +9 -0
  209. package/extensions/privateer-brand.ts +3 -1
  210. package/extensions/privateer-context.ts +4 -2
  211. package/extensions/privateer-final-audit.ts +17 -0
  212. package/extensions/privateer-gate.ts +55 -9
  213. package/extensions/privateer-recovery.ts +175 -0
  214. package/extensions/privateer-web.ts +4 -4
  215. package/package.json +3 -1
  216. package/patches/@earendil-works+pi-coding-agent+1.3.0.patch +199 -2
  217. package/patches/pi-background-tasks+2.6.10.patch +91 -7
  218. package/src/cli/chat.ts +7 -1
  219. package/src/config/moatManifest.json +2 -0
  220. package/src/config/whatsNew.json +4 -4
  221. package/src/context.ts +33 -5
  222. package/src/engine/finalAudit.ts +38 -0
  223. package/src/engine/stallWatchdog.ts +8 -1
  224. package/src/providers/account.ts +34 -3
  225. package/src/remote/attentionPush.ts +40 -0
  226. package/src/remote/liveTaskSession.ts +7 -1
  227. package/src/remote/relayClient.ts +38 -4
  228. package/src/remote/remoteBridge.ts +17 -0
  229. package/src/remote/transcriptSnapshot.ts +104 -0
@@ -0,0 +1,1728 @@
1
+ import{createRequire as __pvCR}from"node:module";import{fileURLToPath as __pvF}from"node:url";import{dirname as __pvD}from"node:path";const require=__pvCR(import.meta.url);const __pvUrl=(r)=>new URL(r,import.meta.url).href;const __pvFile=(r)=>__pvF(new URL(r,import.meta.url));
2
+ import {
3
+ Bm25Ranker,
4
+ CODEMODE_DOCS_PATH,
5
+ CODEMODE_STORE_ENTRY_TYPE,
6
+ DEFAULT_TOOL_SEARCH_LIMIT,
7
+ combineUsage,
8
+ createToolSearchDocument,
9
+ formatSize,
10
+ getCodemodeCallableTools,
11
+ parseCodemodeSource,
12
+ renderToolSample,
13
+ toCodemodeDeclaration,
14
+ toCodemodeIdentifier,
15
+ writeOutputFile
16
+ } from "./c-7UOG7POX.mjs";
17
+ import "./c-6ZO2SADQ.mjs";
18
+ import "./c-CRBXNKFO.mjs";
19
+ import "./c-KP6CRIP4.mjs";
20
+ import "./c-RSKCUPJF.mjs";
21
+ import {
22
+ getCodemodeWorkerSpecifier,
23
+ getQuickJSWasmPath
24
+ } from "./c-PTN4S6G2.mjs";
25
+ import "./c-BHNIF2AR.mjs";
26
+ import "./c-EQBKXWNX.mjs";
27
+ import "./c-RQJJ26T4.mjs";
28
+ import "./c-L5GHWG5G.mjs";
29
+ import {
30
+ __name
31
+ } from "./c-CN77DCGF.mjs";
32
+
33
+ // node_modules/@earendil-works/pi-codemode/dist/runtime/protocol.js
34
+ function isWorkerToHostMessage(value) {
35
+ if (typeof value !== "object" || value === null)
36
+ return false;
37
+ const type = value.type;
38
+ return type === "call" || type === "output" || type === "done" || type === "crash" || type === "started" || type === "idle";
39
+ }
40
+ __name(isWorkerToHostMessage, "isWorkerToHostMessage");
41
+
42
+ // node_modules/@earendil-works/pi-codemode/dist/runtime/execution.js
43
+ var DEFAULT_TIMEOUT_MS = 3e5;
44
+ var IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
45
+ var RESERVED_GLOBALS = /* @__PURE__ */ new Set([
46
+ "tools",
47
+ "ALL_TOOLS",
48
+ "console",
49
+ "text",
50
+ "image",
51
+ "exit",
52
+ "globalThis",
53
+ "store",
54
+ "load"
55
+ ]);
56
+ function errorMessage(error) {
57
+ return error instanceof Error ? error.message : String(error);
58
+ }
59
+ __name(errorMessage, "errorMessage");
60
+ function serializeStore(store) {
61
+ const serialized = {};
62
+ for (const [key, value] of Object.entries(store ?? {})) {
63
+ const json = JSON.stringify(value);
64
+ if (json !== void 0)
65
+ serialized[key] = json;
66
+ }
67
+ return serialized;
68
+ }
69
+ __name(serializeStore, "serializeStore");
70
+ var BridgeError = class extends Error {
71
+ static {
72
+ __name(this, "BridgeError");
73
+ }
74
+ };
75
+ function parseBridgeJson(json, what) {
76
+ try {
77
+ return JSON.parse(json);
78
+ } catch {
79
+ throw new BridgeError(`${what} is not valid JSON`);
80
+ }
81
+ }
82
+ __name(parseBridgeJson, "parseBridgeJson");
83
+ function parseStoreWrites(json) {
84
+ const entries = parseBridgeJson(json, "store writes");
85
+ if (!Array.isArray(entries))
86
+ throw new BridgeError("store writes are not an array");
87
+ const writes = { set: {}, delete: [] };
88
+ for (const entry of entries) {
89
+ if (!Array.isArray(entry) || typeof entry[0] !== "string" || (entry.length === 2 ? typeof entry[1] !== "string" : entry.length !== 1)) {
90
+ throw new BridgeError("store writes contain a malformed entry");
91
+ }
92
+ const [key, value] = entry;
93
+ if (value === void 0)
94
+ writes.delete.push(key);
95
+ else
96
+ writes.set[key] = parseBridgeJson(value, `store value for ${JSON.stringify(key)}`);
97
+ }
98
+ return writes;
99
+ }
100
+ __name(parseStoreWrites, "parseStoreWrites");
101
+ function parseScriptError(json) {
102
+ const parsed = parseBridgeJson(json, "script error");
103
+ if (typeof parsed !== "object" || parsed === null)
104
+ throw new BridgeError("script error is not an object");
105
+ const { name, message, stack } = parsed;
106
+ if (typeof message !== "string" || name !== void 0 && typeof name !== "string" || stack !== void 0 && typeof stack !== "string") {
107
+ throw new BridgeError("script error is malformed");
108
+ }
109
+ return { kind: "script", name, message, stack };
110
+ }
111
+ __name(parseScriptError, "parseScriptError");
112
+ function checkGlobals(globals) {
113
+ const names = /* @__PURE__ */ new Set();
114
+ const namespaces = /* @__PURE__ */ new Set();
115
+ for (const global of globals) {
116
+ const parts = global.name.split(".");
117
+ if (parts.length > 2 || !parts.every((part) => IDENTIFIER.test(part)) || RESERVED_GLOBALS.has(parts[0])) {
118
+ throw new Error(`Invalid global name "${global.name}"`);
119
+ }
120
+ if (names.has(global.name))
121
+ throw new Error(`Global "${global.name}" is already registered`);
122
+ if (parts.length === 2)
123
+ namespaces.add(parts[0]);
124
+ names.add(global.name);
125
+ }
126
+ for (const name of namespaces) {
127
+ if (names.has(name))
128
+ throw new Error(`Global "${name}" conflicts with the namespace "${name}"`);
129
+ }
130
+ }
131
+ __name(checkGlobals, "checkGlobals");
132
+ var Execution = class {
133
+ static {
134
+ __name(this, "Execution");
135
+ }
136
+ promise;
137
+ resolveResult;
138
+ channel;
139
+ /** Replies produced before the launcher returned the channel. */
140
+ unsent = [];
141
+ executors;
142
+ control;
143
+ /** Result numbers `deliver()` used. */
144
+ delivered = /* @__PURE__ */ new Set();
145
+ signal;
146
+ timer;
147
+ output = [];
148
+ calls = [];
149
+ pending = /* @__PURE__ */ new Map();
150
+ /** Whether the execution has its outcome. */
151
+ finished = false;
152
+ constructor(options) {
153
+ this.promise = new Promise((resolve) => {
154
+ this.resolveResult = resolve;
155
+ });
156
+ this.executors = options.executors;
157
+ this.control = options.control;
158
+ this.signal = options.signal;
159
+ if (Number.isFinite(options.timeoutMs)) {
160
+ this.timer = setTimeout(() => {
161
+ this.finish({ kind: "timeout", message: `Execution timed out after ${options.timeoutMs} ms` });
162
+ }, options.timeoutMs);
163
+ }
164
+ if (options.signal) {
165
+ if (options.signal.aborted) {
166
+ this.onAbort();
167
+ } else {
168
+ options.signal.addEventListener("abort", this.onAbort, { once: true });
169
+ }
170
+ }
171
+ if (this.finished)
172
+ return;
173
+ const data = {
174
+ code: options.code,
175
+ tools: options.tools.map((tool) => ({
176
+ name: tool.name,
177
+ jsName: tool.jsName ?? toCodemodeIdentifier(tool.name),
178
+ description: tool.description ?? ""
179
+ })),
180
+ globals: options.globals.map((global) => ({ name: global.name, spread: global.spread === true })),
181
+ memoryLimitBytes: options.memoryLimitBytes,
182
+ store: options.store,
183
+ ...options.deterministic ? { deterministic: options.deterministic } : {}
184
+ };
185
+ const events = {
186
+ message: /* @__PURE__ */ __name((message) => this.receive(message), "message"),
187
+ failure: /* @__PURE__ */ __name((error) => this.finish(error), "failure")
188
+ };
189
+ new Promise((resolve) => resolve(options.launch(data, events))).then((channel) => {
190
+ if (this.finished) {
191
+ void channel.stop().catch(() => void 0);
192
+ return;
193
+ }
194
+ this.channel = channel;
195
+ for (const message of this.unsent.splice(0))
196
+ channel.post(message);
197
+ }, (error) => {
198
+ this.finish({ kind: "sandbox", message: errorMessage(error) });
199
+ });
200
+ }
201
+ /** `CodemodeRun.deliver()`. */
202
+ deliver(seq, now, id, outcome) {
203
+ if (this.finished)
204
+ return;
205
+ if (!Number.isFinite(now))
206
+ throw new Error(`The clock value of result ${seq} is not a finite number`);
207
+ if (!Number.isInteger(seq) || seq < 1 || this.delivered.has(seq)) {
208
+ throw new Error(`Result number ${seq} is not a positive integer used once`);
209
+ }
210
+ const pending = this.pending.get(id);
211
+ if (pending === void 0)
212
+ throw new Error(`Call ${id} is not waiting for a result`);
213
+ if (!outcome.ok && outcome.properties !== void 0) {
214
+ const { properties: properties2 } = outcome;
215
+ if (typeof properties2 !== "object" || properties2 === null || Array.isArray(properties2)) {
216
+ throw new Error(`The properties of result ${seq} are not an object`);
217
+ }
218
+ }
219
+ const payload = outcome.ok ? outcome.value === void 0 ? void 0 : JSON.stringify(outcome.value) : outcome.message;
220
+ const properties = !outcome.ok && outcome.properties !== void 0 ? JSON.stringify(outcome.properties) : void 0;
221
+ this.delivered.add(seq);
222
+ this.pending.delete(id);
223
+ if (pending.record) {
224
+ pending.record.status = outcome.ok ? "ok" : "error";
225
+ pending.record.durationMs = performance.now() - pending.startedAt;
226
+ }
227
+ this.post({
228
+ type: "result",
229
+ id,
230
+ ok: outcome.ok,
231
+ payload,
232
+ seq,
233
+ now,
234
+ ...properties === void 0 ? {} : { properties }
235
+ });
236
+ }
237
+ abort(message) {
238
+ this.finish({ kind: "aborted", message });
239
+ return this.promise;
240
+ }
241
+ onAbort = /* @__PURE__ */ __name(() => {
242
+ const reason = this.signal?.reason;
243
+ this.finish({ kind: "aborted", message: reason instanceof Error ? reason.message : "Execution aborted" });
244
+ }, "onAbort");
245
+ post(message) {
246
+ if (this.channel)
247
+ this.channel.post(message);
248
+ else
249
+ this.unsent.push(message);
250
+ }
251
+ /** An exception here would escape into the launcher's transport and leave the execution unsettled. */
252
+ receive(message) {
253
+ try {
254
+ this.handleMessage(message);
255
+ } catch (error) {
256
+ this.finish({
257
+ kind: "sandbox",
258
+ message: error instanceof BridgeError ? `Sandbox bridge broken: ${error.message}. The script may have modified built-ins such as a prototype's toJSON.` : `Sandbox host failed: ${errorMessage(error)}`
259
+ });
260
+ }
261
+ }
262
+ handleMessage(message) {
263
+ if (this.finished)
264
+ return;
265
+ if (!isWorkerToHostMessage(message))
266
+ throw new BridgeError("unknown message from the worker");
267
+ switch (message.type) {
268
+ case "output":
269
+ this.output.push(message.item);
270
+ break;
271
+ case "call":
272
+ if (this.pending.has(message.id))
273
+ throw new BridgeError(`duplicate call id ${message.id}`);
274
+ if (this.control)
275
+ this.forwardCall(message, this.control);
276
+ else
277
+ void this.handleCall(message);
278
+ break;
279
+ case "started":
280
+ this.control?.onStarted?.(message.fingerprint);
281
+ break;
282
+ case "idle":
283
+ this.control?.onIdle?.(message.seq, message.issued);
284
+ break;
285
+ case "done":
286
+ this.handleDone(message);
287
+ break;
288
+ case "crash":
289
+ this.finish({ kind: "sandbox", message: message.message });
290
+ break;
291
+ }
292
+ }
293
+ handleDone(message) {
294
+ if (!message.ok) {
295
+ this.finish(parseScriptError(message.error), void 0, void 0, message.during);
296
+ return;
297
+ }
298
+ const value = message.value === void 0 ? void 0 : parseBridgeJson(message.value, "return value");
299
+ this.finish(void 0, value, parseStoreWrites(message.writes), message.during);
300
+ }
301
+ /** A host-controlled run: record the call and hand it to the caller, which answers with `deliver()`. */
302
+ forwardCall(message, control) {
303
+ const { id, name, target } = message;
304
+ const args = message.args === void 0 ? void 0 : parseBridgeJson(message.args, "call arguments");
305
+ const record = target === "tool" ? { name, status: "cancelled", durationMs: 0 } : void 0;
306
+ if (record)
307
+ this.calls.push(record);
308
+ this.pending.set(id, { record, startedAt: performance.now(), controller: new AbortController() });
309
+ control.onCall({ id, target, name, args });
310
+ }
311
+ async handleCall(message) {
312
+ const { id, name } = message;
313
+ const isTool = message.target === "tool";
314
+ const record = isTool ? { name, status: "cancelled", durationMs: 0 } : void 0;
315
+ if (record)
316
+ this.calls.push(record);
317
+ const pending = { record, startedAt: performance.now(), controller: new AbortController() };
318
+ this.pending.set(id, pending);
319
+ let status;
320
+ let reply;
321
+ try {
322
+ const tool = (isTool ? this.executors.tools : this.executors.globals).get(name);
323
+ if (!tool)
324
+ throw new Error(`Unknown ${isTool ? "tool" : "global"} "${name}"`);
325
+ const args = message.args === void 0 ? void 0 : JSON.parse(message.args);
326
+ const value = await tool.execute(args, { signal: pending.controller.signal });
327
+ reply = { type: "result", id, ok: true, payload: value === void 0 ? void 0 : JSON.stringify(value) };
328
+ status = "ok";
329
+ } catch (error) {
330
+ reply = { type: "result", id, ok: false, payload: errorMessage(error) };
331
+ status = "error";
332
+ }
333
+ if (!this.pending.delete(id))
334
+ return;
335
+ if (record) {
336
+ record.status = status;
337
+ record.durationMs = performance.now() - pending.startedAt;
338
+ }
339
+ this.post(reply);
340
+ }
341
+ finish(error, value, writes, during) {
342
+ if (this.finished)
343
+ return;
344
+ this.finished = true;
345
+ clearTimeout(this.timer);
346
+ this.signal?.removeEventListener("abort", this.onAbort);
347
+ const now = performance.now();
348
+ for (const pending of this.pending.values()) {
349
+ if (pending.record)
350
+ pending.record.durationMs = now - pending.startedAt;
351
+ pending.controller.abort();
352
+ }
353
+ this.pending.clear();
354
+ this.unsent = [];
355
+ const ended = during === void 0 ? {} : { during: { seq: during.seq, issued: during.issued } };
356
+ const result = error ? { ok: false, error, output: this.output, calls: this.calls, ...ended } : {
357
+ ok: true,
358
+ value,
359
+ output: this.output,
360
+ calls: this.calls,
361
+ storeWrites: writes ?? { set: {}, delete: [] },
362
+ ...ended
363
+ };
364
+ if (!this.channel) {
365
+ this.resolveResult(result);
366
+ return;
367
+ }
368
+ this.channel.stop().catch(() => void 0).then(() => this.resolveResult(result));
369
+ }
370
+ };
371
+ var CodemodeSandboxBase = class {
372
+ static {
373
+ __name(this, "CodemodeSandboxBase");
374
+ }
375
+ toolsByName = /* @__PURE__ */ new Map();
376
+ globalsByName = /* @__PURE__ */ new Map();
377
+ timeoutMs;
378
+ memoryLimitBytes;
379
+ launch;
380
+ running = /* @__PURE__ */ new Set();
381
+ closed = false;
382
+ constructor(options, launch) {
383
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
384
+ this.memoryLimitBytes = options.memoryLimitBytes;
385
+ this.launch = launch;
386
+ for (const tool of options.tools ?? [])
387
+ this.registerTool(tool);
388
+ checkGlobals(options.globals ?? []);
389
+ for (const global of options.globals ?? [])
390
+ this.globalsByName.set(global.name, global);
391
+ }
392
+ /** Throws if a tool with the same name is already registered. */
393
+ registerTool(tool) {
394
+ if (this.toolsByName.has(tool.name))
395
+ throw new Error(`Tool "${tool.name}" is already registered`);
396
+ this.toolsByName.set(tool.name, tool);
397
+ }
398
+ unregisterTool(name) {
399
+ return this.toolsByName.delete(name);
400
+ }
401
+ get tools() {
402
+ return [...this.toolsByName.values()];
403
+ }
404
+ get globals() {
405
+ return [...this.globalsByName.values()];
406
+ }
407
+ /**
408
+ * `code` is an async function body: `return` and top-level `await` work.
409
+ * Never rejects for script failures; those come back as `{ ok: false }`.
410
+ * The script can use `store(key, value)` and `load(key)` on `options.store`.
411
+ */
412
+ execute(code, options = {}) {
413
+ if (this.closed)
414
+ return Promise.reject(new Error("Sandbox is closed"));
415
+ const tools = new Map(this.toolsByName);
416
+ const execution = new Execution({
417
+ code,
418
+ tools: [...tools.values()],
419
+ globals: [...this.globalsByName.values()],
420
+ executors: { tools, globals: this.globalsByName },
421
+ timeoutMs: options.timeoutMs ?? this.timeoutMs,
422
+ signal: options.signal,
423
+ memoryLimitBytes: this.memoryLimitBytes,
424
+ store: serializeStore(options.store),
425
+ launch: this.launch
426
+ });
427
+ this.running.add(execution);
428
+ return execution.promise.finally(() => this.running.delete(execution));
429
+ }
430
+ /**
431
+ * Run `code` deterministically, with the caller answering its calls: the same script, start time, seed, tools,
432
+ * globals, and store, answered with the same results in the same `seq` order, makes the same calls with the same
433
+ * arguments and produces the same output, on any VM with the same fingerprint. A host can therefore replay it
434
+ * after a restart. The VM runs in UTC, its clock reads `startedAt` and then the `now` of the result being
435
+ * processed, its randomness comes from `seed`, and `WeakRef` and `FinalizationRegistry` do not exist.
436
+ *
437
+ * The sandbox's own tools and globals are not used: the run declares its own, and every call goes to
438
+ * `options.onCall`. Never rejects for script failures; abort through `options.signal` to end the run with an
439
+ * error the script cannot catch.
440
+ */
441
+ start(code, options) {
442
+ if (this.closed)
443
+ throw new Error("Sandbox is closed");
444
+ if (!Number.isFinite(options.startedAt) || options.startedAt < 0) {
445
+ throw new Error("startedAt must be a non-negative number of milliseconds since the epoch");
446
+ }
447
+ if (!Number.isInteger(options.seed) || options.seed < 0 || options.seed > 4294967295) {
448
+ throw new Error("seed must be a 32-bit unsigned integer");
449
+ }
450
+ const tools = options.tools ?? [];
451
+ if (new Set(tools.map((tool) => tool.name)).size !== tools.length)
452
+ throw new Error("Tool names must be unique");
453
+ const scriptNames = tools.map((tool) => tool.jsName ?? toCodemodeIdentifier(tool.name));
454
+ if (new Set(scriptNames).size !== tools.length)
455
+ throw new Error("Tool script names must be unique");
456
+ const globals = options.globals ?? [];
457
+ checkGlobals(globals);
458
+ const execution = new Execution({
459
+ code,
460
+ tools,
461
+ globals,
462
+ executors: { tools: /* @__PURE__ */ new Map(), globals: /* @__PURE__ */ new Map() },
463
+ timeoutMs: options.timeoutMs ?? Number.POSITIVE_INFINITY,
464
+ signal: options.signal,
465
+ memoryLimitBytes: this.memoryLimitBytes,
466
+ store: serializeStore(options.store),
467
+ deterministic: { startedAt: options.startedAt, seed: options.seed },
468
+ control: { onStarted: options.onStarted, onCall: options.onCall, onIdle: options.onIdle },
469
+ launch: this.launch
470
+ });
471
+ this.running.add(execution);
472
+ const result = execution.promise.finally(() => this.running.delete(execution));
473
+ return {
474
+ result,
475
+ deliver: /* @__PURE__ */ __name((seq, now, id, outcome) => execution.deliver(seq, now, id, outcome), "deliver"),
476
+ get finished() {
477
+ return execution.finished;
478
+ }
479
+ };
480
+ }
481
+ /** Aborts in-flight executions (they resolve with `kind: "aborted"`) and rejects new ones. */
482
+ async close() {
483
+ this.closed = true;
484
+ await Promise.all([...this.running].map((execution) => execution.abort("Sandbox closed")));
485
+ }
486
+ };
487
+
488
+ // node_modules/@earendil-works/pi-codemode/dist/runtime/host.js
489
+ import { Worker } from "node:worker_threads";
490
+
491
+ // node_modules/@earendil-works/pi-codemode/dist/wasm.js
492
+ import { readFile } from "node:fs/promises";
493
+ import { createRequire } from "node:module";
494
+ var __pvMetaUrl = __pvUrl("../node_modules/@earendil-works/pi-codemode/dist/wasm.js");
495
+ var modules = /* @__PURE__ */ new Map();
496
+ function loadQuickJSWasm(path) {
497
+ const resolved = path ?? createRequire(__pvMetaUrl).resolve("quickjs-wasi/quickjs.wasm");
498
+ let module = modules.get(resolved);
499
+ if (!module) {
500
+ const { WebAssembly: WebAssembly2 } = globalThis;
501
+ module = readFile(resolved).then((bytes) => WebAssembly2.compile(bytes)).catch((error) => {
502
+ modules.delete(resolved);
503
+ throw error;
504
+ });
505
+ modules.set(resolved, module);
506
+ }
507
+ return module;
508
+ }
509
+ __name(loadQuickJSWasm, "loadQuickJSWasm");
510
+
511
+ // node_modules/@earendil-works/pi-codemode/dist/runtime/host.js
512
+ var __pvMetaUrl2 = __pvUrl("../node_modules/@earendil-works/pi-codemode/dist/runtime/host.js");
513
+ function defaultWorkerUrl() {
514
+ return new URL(__pvMetaUrl2.endsWith(".ts") ? "./worker.ts" : "./worker.js", __pvMetaUrl2);
515
+ }
516
+ __name(defaultWorkerUrl, "defaultWorkerUrl");
517
+ function workerLauncher(options) {
518
+ return async (data, events) => {
519
+ let module;
520
+ try {
521
+ module = await (options.wasm ?? loadQuickJSWasm());
522
+ } catch (error) {
523
+ throw new Error(`Failed to load QuickJS: ${errorMessage(error)}`);
524
+ }
525
+ const interrupt = new SharedArrayBuffer(4);
526
+ const workerData = { ...data, wasm: module, interrupt };
527
+ const releaseWorker = options.acquireWorker?.();
528
+ let worker;
529
+ try {
530
+ worker = new Worker(options.workerUrl ?? defaultWorkerUrl(), { workerData });
531
+ } catch (error) {
532
+ releaseWorker?.();
533
+ throw new Error(`Failed to start worker: ${errorMessage(error)}`);
534
+ }
535
+ if (releaseWorker)
536
+ worker.once("exit", releaseWorker);
537
+ worker.on("message", (message) => {
538
+ if (typeof message === "object" && message !== null && ("watch:import" in message || "watch:require" in message))
539
+ return;
540
+ events.message(message);
541
+ });
542
+ worker.on("error", (error) => {
543
+ events.failure({
544
+ kind: "sandbox",
545
+ name: error instanceof Error ? error.name : void 0,
546
+ message: errorMessage(error)
547
+ });
548
+ });
549
+ worker.on("exit", (code) => {
550
+ events.failure({ kind: "sandbox", message: `Worker exited with code ${code} before the script settled` });
551
+ });
552
+ const stop = /* @__PURE__ */ __name(async () => {
553
+ Atomics.store(new Int32Array(interrupt), 0, 1);
554
+ void worker.terminate().catch(() => void 0);
555
+ worker.unref();
556
+ }, "stop");
557
+ try {
558
+ options.onWorkerStarted?.(new Promise((resolve) => worker.once("exit", () => resolve())));
559
+ } catch (error) {
560
+ void stop();
561
+ throw error;
562
+ }
563
+ return { post: /* @__PURE__ */ __name((message) => worker.postMessage(message), "post"), stop };
564
+ };
565
+ }
566
+ __name(workerLauncher, "workerLauncher");
567
+ var CodemodeSandbox = class extends CodemodeSandboxBase {
568
+ static {
569
+ __name(this, "CodemodeSandbox");
570
+ }
571
+ constructor(options = {}) {
572
+ super(options, workerLauncher(options));
573
+ }
574
+ };
575
+
576
+ // node_modules/quickjs-wasi/dist/extensions.js
577
+ var decoder = new TextDecoder();
578
+
579
+ // node_modules/quickjs-wasi/dist/index.js
580
+ var MAX_STACK_SIZE = 512 * 1024;
581
+ var EvalFlags = {
582
+ /** Global script mode (default). */
583
+ TYPE_GLOBAL: 0,
584
+ /**
585
+ * Module mode. `evalCode()` returns a handle to a Promise that resolves
586
+ * to the module's namespace object (its exports), or rejects if module
587
+ * evaluation throws. Use together with `executePendingJobs()` and
588
+ * `resolvePromise()`.
589
+ */
590
+ TYPE_MODULE: 1 << 0,
591
+ /** Force strict mode. */
592
+ STRICT: 1 << 3,
593
+ /** Compile only; do not execute. */
594
+ COMPILE_ONLY: 1 << 5,
595
+ /** Omit stack frames before this eval from Error backtraces. */
596
+ BACKTRACE_BARRIER: 1 << 6,
597
+ /**
598
+ * Allow top-level `await` in global scripts. When used, `evalCode()`
599
+ * returns a handle to a Promise that resolves to the completion value.
600
+ * Use together with `executePendingJobs()` and `resolvePromise()`.
601
+ */
602
+ ASYNC: 1 << 7
603
+ };
604
+ var CompileFlags = {
605
+ /** Strip source code from the bytecode (smaller output, no source in errors). */
606
+ STRIP_SOURCE: 1 << 4,
607
+ /** Strip debug information (line numbers, etc.) from the bytecode. */
608
+ STRIP_DEBUG: 1 << 5
609
+ };
610
+ var Intrinsics = {
611
+ /** `Date` constructor and prototype methods. */
612
+ DATE: 1 << 0,
613
+ /** `eval()` and `Function()` constructor. */
614
+ EVAL: 1 << 1,
615
+ /** `RegExp` constructor, prototype methods, and regex literals. */
616
+ REGEXP: 1 << 2,
617
+ /** `JSON.parse()` and `JSON.stringify()`. */
618
+ JSON: 1 << 3,
619
+ /** `Proxy` and `Reflect`. */
620
+ PROXY: 1 << 4,
621
+ /** `Map`, `Set`, `WeakMap`, `WeakSet`. */
622
+ MAP_SET: 1 << 5,
623
+ /** `ArrayBuffer`, `TypedArray` variants, `DataView`. */
624
+ TYPED_ARRAYS: 1 << 6,
625
+ /** `Promise`, `async`/`await`. */
626
+ PROMISE: 1 << 7,
627
+ /** `BigInt`. Note: BigInt is part of BaseObjects in quickjs-ng and cannot be fully removed. */
628
+ BIG_INT: 1 << 8,
629
+ /** `WeakRef` and `FinalizationRegistry`. */
630
+ WEAK_REF: 1 << 9,
631
+ /** `performance.now()`. */
632
+ PERFORMANCE: 1 << 10,
633
+ /** `DOMException` class. */
634
+ DOM_EXCEPTION: 1 << 11,
635
+ /**
636
+ * `atob()` and `btoa()` global functions. Also pulls in `DOMException` as
637
+ * a dependency (errors thrown by these functions are `DOMException`s).
638
+ */
639
+ ATOB_BTOA: 1 << 12,
640
+ /** All intrinsics enabled (default). */
641
+ ALL: 4294967295
642
+ };
643
+ var wtf8Decoder = new TextDecoder();
644
+ var wtf8Encoder = new TextEncoder();
645
+
646
+ // node_modules/@earendil-works/pi-codemode/dist/runtime/prelude-source.js
647
+ var MAX_STORE_VALUE_CHARS = 256 * 1024;
648
+ var MAX_STORE_TOTAL_CHARS = 1024 * 1024;
649
+ var MAX_OUTPUT_CHARS = 16 * 1024 * 1024;
650
+ var MAX_OUTPUT_ITEMS = 1e5;
651
+ var IMAGE_HELPER_EXPECTS = 'image expects a non-empty image URL string, an object with image_url, or an image block { type: "image", data, mimeType }';
652
+ var PRELUDE_SOURCE = `(function (bridge, toolsJson, globalsJson, storeJson) {
653
+ "use strict";
654
+
655
+ // Freeze every object reachable from the built-in globals, plus the intrinsics that are only
656
+ // reachable from instances (iterator and generator prototypes, %TypedArray%).
657
+ //
658
+ // Freezing alone breaks ordinary code through the "override mistake": a data property that is
659
+ // read-only on a prototype cannot be assigned on an instance either, so
660
+ // this.name = "MyError" in an Error subclass would throw. Commonly overridden properties
661
+ // become accessors whose setter defines an own property on the instance instead.
662
+ (function lockdown() {
663
+ const OVERRIDABLE = new Set(["constructor", "name", "message", "toString", "toLocaleString", "valueOf", "toJSON"]);
664
+ const seen = new Set([globalThis]);
665
+ const queue = [];
666
+ const add = (value) => {
667
+ if ((typeof value === "object" && value !== null) || typeof value === "function") {
668
+ if (!seen.has(value)) {
669
+ seen.add(value);
670
+ queue.push(value);
671
+ }
672
+ }
673
+ };
674
+
675
+ // Accessors from an object literal have no own prototype object, unlike function expressions,
676
+ // whose prototype.constructor would be converted again without end.
677
+ function allowOverride(object, key, value, enumerable) {
678
+ const { get, set } = Object.getOwnPropertyDescriptor(
679
+ {
680
+ get accessor() {
681
+ return value;
682
+ },
683
+ set accessor(next) {
684
+ if (this === object) {
685
+ throw new TypeError("Cannot assign to read only property '" + String(key) + "' of a built-in");
686
+ }
687
+ if ((typeof this !== "object" || this === null) && typeof this !== "function") return;
688
+ Object.defineProperty(this, key, { value: next, writable: true, enumerable: true, configurable: true });
689
+ },
690
+ },
691
+ "accessor",
692
+ );
693
+ Object.defineProperty(object, key, { get, set, enumerable, configurable: false });
694
+ add(get);
695
+ add(set);
696
+ }
697
+
698
+ for (const key of Reflect.ownKeys(globalThis)) {
699
+ const descriptor = Object.getOwnPropertyDescriptor(globalThis, key);
700
+ add(descriptor.value);
701
+ add(descriptor.get);
702
+ add(descriptor.set);
703
+ if ("value" in descriptor && descriptor.configurable) {
704
+ Object.defineProperty(globalThis, key, { writable: false, configurable: false });
705
+ }
706
+ }
707
+ add(Object.getPrototypeOf(function* () {}));
708
+ add(Object.getPrototypeOf(async function () {}));
709
+ add(Object.getPrototypeOf(async function* () {}));
710
+ add(Object.getPrototypeOf(Int8Array));
711
+ add(Object.getPrototypeOf([][Symbol.iterator]()));
712
+ add(Object.getPrototypeOf(new Map()[Symbol.iterator]()));
713
+ add(Object.getPrototypeOf(new Set()[Symbol.iterator]()));
714
+ add(Object.getPrototypeOf(""[Symbol.iterator]()));
715
+ add(Object.getPrototypeOf(/a/[Symbol.matchAll]("")));
716
+ if (typeof Iterator === "function") {
717
+ if (typeof Iterator.prototype.map === "function") add(Object.getPrototypeOf([].values().map((x) => x)));
718
+ if (typeof Iterator.from === "function") add(Object.getPrototypeOf(Iterator.from({ next() {} })));
719
+ }
720
+
721
+ while (queue.length > 0) {
722
+ const object = queue.pop();
723
+ add(Object.getPrototypeOf(object));
724
+ const descriptors = Object.getOwnPropertyDescriptors(object);
725
+ for (const key of Reflect.ownKeys(descriptors)) {
726
+ const descriptor = descriptors[key];
727
+ if ("value" in descriptor) {
728
+ add(descriptor.value);
729
+ if (
730
+ descriptor.writable &&
731
+ descriptor.configurable &&
732
+ (object === Object.prototype || OVERRIDABLE.has(key))
733
+ ) {
734
+ allowOverride(object, key, descriptor.value, descriptor.enumerable);
735
+ }
736
+ } else {
737
+ add(descriptor.get);
738
+ add(descriptor.set);
739
+ }
740
+ }
741
+ Object.freeze(object);
742
+ }
743
+ })();
744
+ const stringify = JSON.stringify;
745
+ const parse = JSON.parse;
746
+ const promiseThen = Promise.prototype.then;
747
+ const ErrorCtor = Error;
748
+ const TypeErrorCtor = TypeError;
749
+ const RangeErrorCtor = RangeError;
750
+ const pending = new Map();
751
+ let nextId = 1;
752
+ let finished = false;
753
+ // Thrown by exit() to unwind the script after it already reported success.
754
+ const EXIT = Object.freeze({});
755
+
756
+ function done(ok, payload, writes) {
757
+ if (finished) return;
758
+ finished = true;
759
+ bridge("done", ok, payload, writes);
760
+ }
761
+
762
+ function serialize(value) {
763
+ return value === undefined ? undefined : stringify(value);
764
+ }
765
+
766
+ // QuickJS stacks list frames only. Prefix "Name: message" like V8 so the
767
+ // text reads the same as a Node error, and drop this prelude's frames.
768
+ function errorText(error) {
769
+ const head = error.message ? error.name + ": " + error.message : String(error.name);
770
+ const frames =
771
+ typeof error.stack === "string"
772
+ ? error.stack.split("\\n").filter((line) => line.trim() && !line.includes("codemode-prelude.js"))
773
+ : [];
774
+ return [head, ...frames].join("\\n");
775
+ }
776
+
777
+ function format(value) {
778
+ if (typeof value === "string") return value;
779
+ if (value instanceof ErrorCtor) return errorText(value);
780
+ try {
781
+ const json = stringify(value);
782
+ return json === undefined ? String(value) : json;
783
+ } catch {
784
+ return String(value);
785
+ }
786
+ }
787
+
788
+ // The host requires string fields. A script can set an error's name or message to anything, so
789
+ // they are coerced, and a value whose coercion throws gets a placeholder.
790
+ function describeError(error) {
791
+ try {
792
+ if (error instanceof ErrorCtor) {
793
+ return stringify({ name: String(error.name), message: String(error.message), stack: errorText(error) });
794
+ }
795
+ return stringify({ message: String(format(error)) });
796
+ } catch {
797
+ return stringify({ message: "The script threw a value that cannot be described" });
798
+ }
799
+ }
800
+
801
+ function caller(kind, name, spread) {
802
+ return (...args) =>
803
+ new Promise((resolve, reject) => {
804
+ let json;
805
+ try {
806
+ json = serialize(spread ? args : args[0]);
807
+ } catch (error) {
808
+ reject(error);
809
+ return;
810
+ }
811
+ const id = nextId++;
812
+ pending.set(id, { resolve, reject });
813
+ bridge(kind, id, name, json);
814
+ });
815
+ }
816
+
817
+ const tools = Object.create(null);
818
+ const allTools = [];
819
+ for (const { name, jsName, description } of parse(toolsJson)) {
820
+ const fn = caller("call", name);
821
+ // The first tool wins when two names normalize to the same identifier.
822
+ if (!(jsName in tools)) {
823
+ tools[jsName] = fn;
824
+ allTools.push(Object.freeze({ name: jsName, description }));
825
+ }
826
+ if (!(name in tools)) tools[name] = fn;
827
+ }
828
+ Object.freeze(tools);
829
+ Object.freeze(allTools);
830
+
831
+ // Reading a member that does not exist throws an error that names the close matches, instead of
832
+ // a later "not a function". \`in\` checks still work.
833
+ const comparable = (name) => name.toLowerCase().replace(/[^a-z0-9]/g, "");
834
+ function guard(target, label, names, hint) {
835
+ return new Proxy(target, {
836
+ get(object, property, receiver) {
837
+ if (typeof property !== "string" || property in object || property in Object.prototype || property === "then" || property === "toJSON") {
838
+ return Reflect.get(object, property, receiver);
839
+ }
840
+ const wanted = comparable(property);
841
+ const exact = names.filter((name) => comparable(name) === wanted);
842
+ const close = exact.length > 0 ? exact : names.filter((name) => wanted && (comparable(name).includes(wanted) || wanted.includes(comparable(name))));
843
+ let message = label + "." + property + " does not exist.";
844
+ if (close.length > 0) message += " Did you mean " + close.slice(0, 5).map((name) => label + "." + name).join(", ") + "?";
845
+ else if (names.length <= 20) message += " Available: " + names.join(", ") + ".";
846
+ if (hint) message += " " + hint;
847
+ message += ' Check for a member with "' + property + '" in ' + label + ".";
848
+ throw new TypeErrorCtor(message);
849
+ },
850
+ });
851
+ }
852
+ const toolsProxy = guard(
853
+ tools,
854
+ "tools",
855
+ allTools.map((tool) => tool.name),
856
+ "ALL_TOOLS lists every tool; searchTools(query) finds tools by topic.",
857
+ );
858
+
859
+ const namespaces = new Map();
860
+ for (const { name, spread } of parse(globalsJson)) {
861
+ const fn = caller("global", name, spread);
862
+ const dot = name.indexOf(".");
863
+ if (dot === -1) {
864
+ Object.defineProperty(globalThis, name, { value: fn, enumerable: true });
865
+ continue;
866
+ }
867
+ const namespace = name.slice(0, dot);
868
+ if (!namespaces.has(namespace)) namespaces.set(namespace, Object.create(null));
869
+ namespaces.get(namespace)[name.slice(dot + 1)] = fn;
870
+ }
871
+ for (const [namespace, members] of namespaces) {
872
+ Object.freeze(members);
873
+ const value = guard(members, namespace, Object.keys(members));
874
+ Object.defineProperty(globalThis, namespace, { value, enumerable: true });
875
+ }
876
+
877
+ // key -> JSON text. Sizes count key and JSON characters.
878
+ const stored = new Map(Object.entries(parse(storeJson)));
879
+ const writes = new Map();
880
+ let storedChars = 0;
881
+ for (const [key, json] of stored) storedChars += key.length + json.length;
882
+
883
+ const STORE_HINT =
884
+ "store() is for small state such as IDs or summaries. Show images with image(), keep large data in variables, or write it to a file with a tool.";
885
+
886
+ function checkKey(name, key) {
887
+ if (typeof key !== "string") throw new TypeError(name + "() key must be a string");
888
+ }
889
+
890
+ function store(key, value) {
891
+ checkKey("store", key);
892
+ const previous = stored.has(key) ? key.length + stored.get(key).length : 0;
893
+ if (value === undefined) {
894
+ stored.delete(key);
895
+ storedChars -= previous;
896
+ writes.set(key, undefined);
897
+ return;
898
+ }
899
+ let json;
900
+ try {
901
+ json = stringify(value);
902
+ } catch (error) {
903
+ throw new TypeError("store(" + stringify(key) + ") value is not JSON-serializable: " + format(error));
904
+ }
905
+ if (json === undefined) {
906
+ throw new TypeError("store(" + stringify(key) + ") value is not JSON-serializable");
907
+ }
908
+ if (json.length > ${MAX_STORE_VALUE_CHARS}) {
909
+ throw new RangeError(
910
+ "store(" + stringify(key) + ") value has " + json.length + " characters of JSON, more than the limit of ${MAX_STORE_VALUE_CHARS}. " +
911
+ STORE_HINT,
912
+ );
913
+ }
914
+ const next = storedChars - previous + key.length + json.length;
915
+ if (next > ${MAX_STORE_TOTAL_CHARS}) {
916
+ throw new RangeError(
917
+ "store is full: stored values would exceed ${MAX_STORE_TOTAL_CHARS} characters of JSON. Delete keys with store(key, undefined). " +
918
+ STORE_HINT,
919
+ );
920
+ }
921
+ stored.set(key, json);
922
+ storedChars = next;
923
+ writes.set(key, json);
924
+ }
925
+
926
+ function load(key) {
927
+ checkKey("load", key);
928
+ const json = stored.get(key);
929
+ return json === undefined ? undefined : parse(json);
930
+ }
931
+
932
+ function serializeWrites() {
933
+ const entries = [];
934
+ for (const [key, json] of writes) entries.push(json === undefined ? [key] : [key, json]);
935
+ return stringify(entries);
936
+ }
937
+
938
+ Object.defineProperty(globalThis, "store", { value: store, enumerable: true });
939
+ Object.defineProperty(globalThis, "load", { value: load, enumerable: true });
940
+
941
+ let outputChars = 0;
942
+ let outputItems = 0;
943
+
944
+ // Past the output limits the script fails: done() reports the error, so catching it does not
945
+ // resume output, and the host ends the script.
946
+ function output(kind, data, mimeType) {
947
+ if (finished) return;
948
+ outputChars += data.length;
949
+ outputItems++;
950
+ if (outputChars > ${MAX_OUTPUT_CHARS} || outputItems > ${MAX_OUTPUT_ITEMS}) {
951
+ const error = new RangeErrorCtor(
952
+ "script output exceeded the limit of ${MAX_OUTPUT_CHARS} characters or ${MAX_OUTPUT_ITEMS} text(), image(), and console calls. " +
953
+ "Print a summary instead, or write large data to a file with a tool.",
954
+ );
955
+ done(false, describeError(error));
956
+ throw error;
957
+ }
958
+ bridge("output", kind, data, mimeType);
959
+ }
960
+
961
+ // Primitives become their string form, everything else JSON.
962
+ function outputText(value) {
963
+ if (value === undefined || value === null || typeof value !== "object" && typeof value !== "function") {
964
+ return String(value);
965
+ }
966
+ const json = stringify(value);
967
+ return json === undefined ? String(value) : json;
968
+ }
969
+
970
+ function text(value) {
971
+ let rendered;
972
+ try {
973
+ rendered = outputText(value);
974
+ } catch (error) {
975
+ throw new TypeErrorCtor(error instanceof ErrorCtor ? error.message : String(error));
976
+ }
977
+ output("text", rendered);
978
+ }
979
+
980
+ function imageUrl(value) {
981
+ if (typeof value === "string") return value;
982
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
983
+ throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});
984
+ }
985
+ if (value.image_url !== undefined) {
986
+ if (typeof value.image_url !== "string") throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});
987
+ return value.image_url;
988
+ }
989
+ if (typeof value.type !== "string") throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});
990
+ if (value.type !== "image") {
991
+ throw new TypeErrorCtor('image only accepts image blocks, got "' + value.type + '"');
992
+ }
993
+ if (typeof value.data !== "string" || value.data === "") throw new TypeErrorCtor("image expected image block data");
994
+ if (value.data.toLowerCase().startsWith("data:")) return value.data;
995
+ return "data:;base64," + value.data;
996
+ }
997
+
998
+ // Base64 of the signatures of the formats providers accept inline (PNG, JPEG except
999
+ // JPEG-LS, GIF, "RIFF....WEBP"). Signatures start at byte 0, so their encodings are prefixes.
1000
+ const IMAGE_SIGNATURES = [
1001
+ ["image/png", /^iVBORw0KGg/],
1002
+ ["image/jpeg", /^[/]9j[/](?!9)/],
1003
+ ["image/gif", /^R0lGOD[dl]h/],
1004
+ ["image/webp", /^UklG.{8}RUJQ/],
1005
+ ];
1006
+
1007
+ function image(value) {
1008
+ const url = imageUrl(value);
1009
+ if (url === "") throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});
1010
+ const colon = url.indexOf(":");
1011
+ const scheme = colon === -1 ? "" : url.slice(0, colon).toLowerCase();
1012
+ if (scheme === "http" || scheme === "https") {
1013
+ throw new TypeErrorCtor("remote image URLs are not supported in tool outputs. Pass a base64 data URI instead");
1014
+ }
1015
+ const comma = url.indexOf(",");
1016
+ const header = comma === -1 ? [] : url.slice(colon + 1, comma).split(";");
1017
+ if (scheme !== "data" || comma === -1 || header.slice(1).every((part) => part.toLowerCase() !== "base64")) {
1018
+ throw new TypeErrorCtor("invalid image output. Pass a base64 data URI instead");
1019
+ }
1020
+ // Providers reject the whole request on a bad image, and a persisted image block would be
1021
+ // resent on every later turn. Line breaks from wrapped base64 are dropped. The declared type
1022
+ // is ignored in favor of the detected one, as providers also reject mismatches.
1023
+ const data = url.slice(comma + 1).replace(/\\s+/g, "");
1024
+ if (data.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(data)) {
1025
+ throw new TypeErrorCtor("invalid image output. The image data is not valid base64 (truncated or corrupted?)");
1026
+ }
1027
+ const head = data.slice(0, 16);
1028
+ const signature = IMAGE_SIGNATURES.find(([, pattern]) => pattern.test(head));
1029
+ if (!signature) {
1030
+ throw new TypeErrorCtor("invalid image output. The image data is not a PNG, JPEG, GIF, or WebP image");
1031
+ }
1032
+ output("image", data, signature[0]);
1033
+ }
1034
+
1035
+ function exit() {
1036
+ let writesJson;
1037
+ try {
1038
+ writesJson = serializeWrites();
1039
+ } catch (error) {
1040
+ done(false, describeError(error));
1041
+ throw EXIT;
1042
+ }
1043
+ done(true, undefined, writesJson);
1044
+ throw EXIT;
1045
+ }
1046
+
1047
+ const console = {};
1048
+ for (const level of ["log", "info", "warn", "error", "debug"]) {
1049
+ console[level] = (...args) => {
1050
+ output("console", args.map(format).join(" "));
1051
+ };
1052
+ }
1053
+ Object.freeze(console);
1054
+
1055
+ Object.defineProperty(globalThis, "tools", { value: toolsProxy, enumerable: true });
1056
+ Object.defineProperty(globalThis, "ALL_TOOLS", { value: allTools, enumerable: true });
1057
+ Object.defineProperty(globalThis, "console", { value: console, enumerable: true });
1058
+ Object.defineProperty(globalThis, "text", { value: text, enumerable: true });
1059
+ Object.defineProperty(globalThis, "image", { value: image, enumerable: true });
1060
+ Object.defineProperty(globalThis, "exit", { value: exit, enumerable: true });
1061
+
1062
+ return {
1063
+ settle(id, ok, payload, propertiesJson) {
1064
+ const entry = pending.get(id);
1065
+ if (!entry) return;
1066
+ pending.delete(id);
1067
+ if (!ok) {
1068
+ const error = new ErrorCtor(payload);
1069
+ if (propertiesJson !== undefined) {
1070
+ const properties = parse(propertiesJson);
1071
+ for (const key of Object.keys(properties)) {
1072
+ if (key === "name" || key === "message" || key === "stack") continue;
1073
+ Object.defineProperty(error, key, { value: properties[key], writable: true, enumerable: true, configurable: true });
1074
+ }
1075
+ }
1076
+ entry.reject(error);
1077
+ return;
1078
+ }
1079
+ let value;
1080
+ try {
1081
+ value = payload === undefined ? undefined : parse(payload);
1082
+ } catch (error) {
1083
+ entry.reject(error);
1084
+ return;
1085
+ }
1086
+ entry.resolve(value);
1087
+ },
1088
+ run(fn) {
1089
+ let promise;
1090
+ try {
1091
+ promise = fn(toolsProxy, console);
1092
+ } catch (error) {
1093
+ done(false, describeError(error));
1094
+ return;
1095
+ }
1096
+ promiseThen.call(
1097
+ promise,
1098
+ (value) => {
1099
+ let json;
1100
+ try {
1101
+ json = serialize(value);
1102
+ } catch (error) {
1103
+ done(false, describeError(error));
1104
+ return;
1105
+ }
1106
+ done(true, json, serializeWrites());
1107
+ },
1108
+ (error) => {
1109
+ done(false, describeError(error));
1110
+ },
1111
+ );
1112
+ },
1113
+ stalled() {
1114
+ if (finished || pending.size > 0) return false;
1115
+ done(
1116
+ false,
1117
+ stringify({
1118
+ name: "Error",
1119
+ message:
1120
+ "The script is waiting on a promise that can never settle: no tool call is pending, and timers do not exist here.",
1121
+ }),
1122
+ );
1123
+ return true;
1124
+ },
1125
+ };
1126
+ })`;
1127
+
1128
+ // node_modules/@earendil-works/pi-codemode/dist/runtime/vm.js
1129
+ function fnv1a(text) {
1130
+ let hash = 2166136261;
1131
+ for (let index = 0; index < text.length; index++) {
1132
+ hash ^= text.charCodeAt(index);
1133
+ hash = Math.imul(hash, 16777619);
1134
+ }
1135
+ return (hash >>> 0).toString(16).padStart(8, "0");
1136
+ }
1137
+ __name(fnv1a, "fnv1a");
1138
+ var PRELUDE_HASH = fnv1a(PRELUDE_SOURCE);
1139
+
1140
+ // node_modules/@earendil-works/pi-codemode/dist/runtime/inline.js
1141
+ var INLINE_MAX_STACK_SIZE = 256 * 1024;
1142
+
1143
+ // node_modules/@earendil-works/pi-codemode/dist/runtime/remote.js
1144
+ var FLUSH_CHARS = 1 << 20;
1145
+
1146
+ // node_modules/@earendil-works/pi-coding-agent/dist/extensions/codemode/execute.js
1147
+ var ARGS_PREVIEW_CHARS = 200;
1148
+ var ERROR_PREVIEW_CHARS = 500;
1149
+ var MAX_CONCURRENT_MODEL_CALLS = 4;
1150
+ var CODEMODE_MEMORY_LIMIT_BYTES = 256 * 1024 * 1024;
1151
+ var MAX_CONCURRENT_CODEMODE_WORKERS = 2;
1152
+ var activeCodemodeWorkers = 0;
1153
+ var MODEL_TYPES = /* @__PURE__ */ new Set(["chat", "image", "classifier"]);
1154
+ function truncateText(text, maxChars) {
1155
+ return text.length > maxChars ? `${text.slice(0, maxChars - 3)}...` : text;
1156
+ }
1157
+ __name(truncateText, "truncateText");
1158
+ function previewArgs(args) {
1159
+ if (args === void 0)
1160
+ return "";
1161
+ try {
1162
+ return truncateText(JSON.stringify(args) ?? "", ARGS_PREVIEW_CHARS);
1163
+ } catch {
1164
+ return "";
1165
+ }
1166
+ }
1167
+ __name(previewArgs, "previewArgs");
1168
+ function textOf(result) {
1169
+ return (result.content ?? []).filter((block) => block.type === "text").map((block) => block.text).join("\n");
1170
+ }
1171
+ __name(textOf, "textOf");
1172
+ function toModelType(value) {
1173
+ if (typeof value === "string" && MODEL_TYPES.has(value))
1174
+ return value;
1175
+ throw new Error(`Unknown model type ${JSON.stringify(value)}. Use "chat", "image", or "classifier".`);
1176
+ }
1177
+ __name(toModelType, "toModelType");
1178
+ function toProvider(value) {
1179
+ if (value === void 0 || value === null)
1180
+ return void 0;
1181
+ if (typeof value !== "string")
1182
+ throw new Error("provider must be a string");
1183
+ return value;
1184
+ }
1185
+ __name(toProvider, "toProvider");
1186
+ function toModelInfo(model) {
1187
+ const info = { ...model };
1188
+ delete info.headers;
1189
+ return info;
1190
+ }
1191
+ __name(toModelInfo, "toModelInfo");
1192
+ function withArticle(word) {
1193
+ return `${/^[aeiou]/.test(word) ? "an" : "a"} ${word}`;
1194
+ }
1195
+ __name(withArticle, "withArticle");
1196
+ function describeValue(value) {
1197
+ if (value === void 0 || value === null)
1198
+ return String(value);
1199
+ if (Array.isArray(value))
1200
+ return value.length === 0 ? "an empty array" : "an array";
1201
+ if (typeof value === "object") {
1202
+ const keys = Object.keys(value);
1203
+ if (keys.length === 0)
1204
+ return "{}";
1205
+ return `{ ${keys.slice(0, 6).join(", ")}${keys.length > 6 ? ", ..." : ""} }`;
1206
+ }
1207
+ return typeof value === "string" ? "a string" : `a ${typeof value}`;
1208
+ }
1209
+ __name(describeValue, "describeValue");
1210
+ var CLASSIFIER_CONTEXT_SHAPE = '{ state: { ... }, images?: [{ type: "image", data: <base64>, mimeType }], questions: { <id>: { type: "choice", instructions, criteria: { <label>: <meaning> } } | { type: "score", instructions, criteria: [<lowest level>, ..., <highest level>] } | { type: "bool", instructions, criteria: { true: <meaning>, false: <meaning> } } } }';
1211
+ function checkClassifierContext(context) {
1212
+ const fail = /* @__PURE__ */ __name((problem) => new Error(`models.classify() ${problem}. Expected context: ${CLASSIFIER_CONTEXT_SHAPE}. See "Classify" in ${CODEMODE_DOCS_PATH}.`), "fail");
1213
+ if (typeof context !== "object" || context === null || Array.isArray(context)) {
1214
+ throw fail(`expects a context object as its second argument, got ${describeValue(context)}`);
1215
+ }
1216
+ const { state, images, questions } = context;
1217
+ if (typeof state !== "object" || state === null || Array.isArray(state)) {
1218
+ throw fail(`context.state must be an object, got ${describeValue(state)}`);
1219
+ }
1220
+ if (images !== void 0) {
1221
+ if (!Array.isArray(images))
1222
+ throw fail(`context.images must be an array, got ${describeValue(images)}`);
1223
+ images.forEach((image, index) => {
1224
+ if (image?.type !== "image" || typeof image.data !== "string" || typeof image.mimeType !== "string") {
1225
+ throw fail(`context.images[${index}] must be an image block, got ${describeValue(image)}`);
1226
+ }
1227
+ });
1228
+ }
1229
+ if (typeof questions !== "object" || questions === null || Array.isArray(questions) || Object.keys(questions).length === 0) {
1230
+ throw fail(`context.questions must map question IDs to questions, got ${describeValue(questions)}`);
1231
+ }
1232
+ const isStrings = /* @__PURE__ */ __name((values) => values.length > 0 && values.every((value) => typeof value === "string"), "isStrings");
1233
+ for (const [id, question] of Object.entries(questions)) {
1234
+ const at = `context.questions.${id}`;
1235
+ if (typeof question !== "object" || question === null || Array.isArray(question)) {
1236
+ throw fail(`${at} must be a question object, got ${describeValue(question)}`);
1237
+ }
1238
+ const { type, instructions, criteria } = question;
1239
+ if (typeof instructions !== "string")
1240
+ throw fail(`${at}.instructions must be a string`);
1241
+ if (type === "choice") {
1242
+ if (typeof criteria !== "object" || criteria === null || Array.isArray(criteria) || !isStrings(Object.values(criteria))) {
1243
+ throw fail(`${at} is a "choice" question, so criteria must map each label to its meaning`);
1244
+ }
1245
+ } else if (type === "score") {
1246
+ if (!Array.isArray(criteria) || !isStrings(criteria)) {
1247
+ throw fail(`${at} is a "score" question, so criteria must list the levels as strings, lowest first`);
1248
+ }
1249
+ } else if (type === "bool") {
1250
+ const labels = criteria;
1251
+ if (typeof labels?.true !== "string" || typeof labels.false !== "string") {
1252
+ throw fail(`${at} is a "bool" question, so criteria must be { true: string, false: string }`);
1253
+ }
1254
+ } else {
1255
+ throw fail(`${at}.type must be "choice", "score", or "bool", got ${JSON.stringify(type)}`);
1256
+ }
1257
+ }
1258
+ return context;
1259
+ }
1260
+ __name(checkClassifierContext, "checkClassifierContext");
1261
+ function checkImagesContext(context) {
1262
+ const fail = /* @__PURE__ */ __name((problem) => new Error(`models.generateImages() ${problem}. Expected context: { input: [{ type: "text", text: <prompt> }, ...optional { type: "image", data: <base64>, mimeType } references] }. See "Generate images" in ${CODEMODE_DOCS_PATH}.`), "fail");
1263
+ if (typeof context !== "object" || context === null || Array.isArray(context)) {
1264
+ throw fail(`expects a context object as its second argument, got ${describeValue(context)}`);
1265
+ }
1266
+ const { input } = context;
1267
+ if (!Array.isArray(input) || input.length === 0) {
1268
+ throw fail(`context.input must be a non-empty array of blocks, got ${describeValue(input)}`);
1269
+ }
1270
+ input.forEach((block, index) => {
1271
+ if (block?.type === "text" && typeof block.text === "string")
1272
+ return;
1273
+ if (block?.type === "image" && typeof block.data === "string" && typeof block.mimeType === "string")
1274
+ return;
1275
+ throw fail(`context.input[${index}] must be a text or image block, got ${describeValue(block)}`);
1276
+ });
1277
+ return context;
1278
+ }
1279
+ __name(checkImagesContext, "checkImagesContext");
1280
+ function createLimiter(limit) {
1281
+ let active = 0;
1282
+ const waiting = [];
1283
+ return async (run) => {
1284
+ if (active >= limit)
1285
+ await new Promise((resolve) => waiting.push(resolve));
1286
+ active++;
1287
+ try {
1288
+ return await run();
1289
+ } finally {
1290
+ active--;
1291
+ waiting.shift()?.();
1292
+ }
1293
+ };
1294
+ }
1295
+ __name(createLimiter, "createLimiter");
1296
+ function isStoreEntryData(data) {
1297
+ if (typeof data !== "object" || data === null)
1298
+ return false;
1299
+ const { set, delete: deleted } = data;
1300
+ return typeof set === "object" && set !== null && Array.isArray(deleted) && deleted.every((key) => typeof key === "string");
1301
+ }
1302
+ __name(isStoreEntryData, "isStoreEntryData");
1303
+ function readCodemodeStore(branch) {
1304
+ const store = /* @__PURE__ */ new Map();
1305
+ for (const entry of branch) {
1306
+ if (entry.type !== "custom" || entry.customType !== CODEMODE_STORE_ENTRY_TYPE || !isStoreEntryData(entry.data)) {
1307
+ continue;
1308
+ }
1309
+ for (const key of entry.data.delete)
1310
+ store.delete(key);
1311
+ for (const [key, value] of Object.entries(entry.data.set))
1312
+ store.set(key, value);
1313
+ }
1314
+ return Object.fromEntries(store);
1315
+ }
1316
+ __name(readCodemodeStore, "readCodemodeStore");
1317
+ var DEFAULT_MAX_OUTPUT_TOKENS = 1e4;
1318
+ var CHARS_PER_TOKEN = 4;
1319
+ function valueText(value) {
1320
+ if (typeof value === "string")
1321
+ return value;
1322
+ return JSON.stringify(value) ?? String(value);
1323
+ }
1324
+ __name(valueText, "valueText");
1325
+ function formatOutput(output) {
1326
+ const total = output.filter((item) => item.type === "text" && !item.console).length;
1327
+ const items = [];
1328
+ const consoleLines = [];
1329
+ let index = 0;
1330
+ for (const item of output) {
1331
+ if (item.type === "image") {
1332
+ items.push(item);
1333
+ } else if (item.console) {
1334
+ consoleLines.push(item.text);
1335
+ } else {
1336
+ index++;
1337
+ items.push({ type: "text", text: total > 1 ? `==> text ${index}/${total} <==
1338
+ ${item.text}` : item.text });
1339
+ }
1340
+ }
1341
+ if (consoleLines.length > 0) {
1342
+ items.push({ type: "text", text: `<console_output>
1343
+ ${consoleLines.join("\n")}
1344
+ </console_output>` });
1345
+ }
1346
+ return items;
1347
+ }
1348
+ __name(formatOutput, "formatOutput");
1349
+ function joinAdjacentText(items) {
1350
+ const joined = [];
1351
+ let parts = [];
1352
+ let lastPart = "";
1353
+ const flush = /* @__PURE__ */ __name(() => {
1354
+ if (parts.length > 0)
1355
+ joined.push({ type: "text", text: parts.join("") });
1356
+ parts = [];
1357
+ lastPart = "";
1358
+ }, "flush");
1359
+ for (const item of items) {
1360
+ if (item.type !== "text") {
1361
+ flush();
1362
+ joined.push(item);
1363
+ continue;
1364
+ }
1365
+ if (lastPart !== "" && !lastPart.endsWith("\n")) {
1366
+ parts.push("\n");
1367
+ lastPart = "\n";
1368
+ }
1369
+ parts.push(item.text);
1370
+ if (item.text !== "")
1371
+ lastPart = item.text;
1372
+ }
1373
+ flush();
1374
+ return joined;
1375
+ }
1376
+ __name(joinAdjacentText, "joinAdjacentText");
1377
+ function formatCallSummary(calls) {
1378
+ if (calls.length === 0)
1379
+ return "No tool calls were made.";
1380
+ return `Tool calls made before the failure (they are not undone): ${calls.map((call) => `${call.name} (${call.status})`).join(", ")}`;
1381
+ }
1382
+ __name(formatCallSummary, "formatCallSummary");
1383
+ function formatError(result, calls) {
1384
+ const { error } = result;
1385
+ const head = error.kind === "script" ? error.stack ?? `${error.name ?? "Error"}: ${error.message}` : error.kind === "timeout" ? `Script timed out: ${error.message}` : error.kind === "aborted" ? `Script aborted: ${error.message}` : `Script sandbox failed: ${error.message}`;
1386
+ return `${head}
1387
+
1388
+ ${formatCallSummary(calls)}`;
1389
+ }
1390
+ __name(formatError, "formatError");
1391
+ async function spillOutput(text) {
1392
+ try {
1393
+ return { path: await writeOutputFile("pi-codemode", ".txt", text) };
1394
+ } catch (error) {
1395
+ return { error: error instanceof Error ? error.message : String(error) };
1396
+ }
1397
+ }
1398
+ __name(spillOutput, "spillOutput");
1399
+ var IMAGE_EXTENSIONS = {
1400
+ "image/png": ".png",
1401
+ "image/jpeg": ".jpg",
1402
+ "image/gif": ".gif",
1403
+ "image/webp": ".webp"
1404
+ };
1405
+ async function saveImages(items) {
1406
+ const labels = /* @__PURE__ */ new Map();
1407
+ const label = /* @__PURE__ */ __name(async ({ data, mimeType }) => {
1408
+ const bytes = Buffer.from(data, "base64");
1409
+ const kind = `${mimeType}, ${formatSize(bytes.length)}`;
1410
+ const extension = IMAGE_EXTENSIONS[mimeType];
1411
+ if (!extension)
1412
+ throw new Error(`No file extension for image type ${mimeType}`);
1413
+ try {
1414
+ const path = await writeOutputFile("pi-codemode", extension, bytes);
1415
+ return `[Image saved to ${path} (${kind})]`;
1416
+ } catch (error) {
1417
+ return `[Image (${kind}) could not be saved: ${error instanceof Error ? error.message : String(error)}]`;
1418
+ }
1419
+ }, "label");
1420
+ const result = await Promise.all(items.map(async (item) => {
1421
+ if (item.type !== "image")
1422
+ return [item];
1423
+ let pending = labels.get(item.data);
1424
+ if (!pending) {
1425
+ pending = label(item);
1426
+ labels.set(item.data, pending);
1427
+ }
1428
+ return [{ type: "text", text: await pending }, item];
1429
+ }));
1430
+ return result.flat();
1431
+ }
1432
+ __name(saveImages, "saveImages");
1433
+ async function truncateOutput(items, maxTokens) {
1434
+ const texts = items.filter((item) => item.type === "text").map((item) => item.text);
1435
+ const combined = texts.join("\n");
1436
+ const budget = maxTokens * CHARS_PER_TOKEN;
1437
+ if (texts.length === 0 || combined.length <= budget)
1438
+ return { items };
1439
+ const headChars = Math.floor(budget / 2);
1440
+ const tailChars = budget - headChars;
1441
+ const removed = combined.length - headChars - tailChars;
1442
+ const head = combined.slice(0, headChars);
1443
+ const tail = tailChars > 0 ? combined.slice(-tailChars) : "";
1444
+ let text = `Warning: truncated output (original token count: ${Math.ceil(combined.length / CHARS_PER_TOKEN)})
1445
+ Total output lines: ${combined.split("\n").length}
1446
+
1447
+ ${head}\u2026${Math.ceil(removed / CHARS_PER_TOKEN)} tokens truncated\u2026${tail}`;
1448
+ const spilled = await spillOutput(combined);
1449
+ text += "path" in spilled ? `
1450
+
1451
+ [Full output: ${spilled.path} (read with offset/limit)]` : `
1452
+
1453
+ [Could not save the full output: ${spilled.error}]`;
1454
+ return {
1455
+ items: [{ type: "text", text }, ...items.filter((item) => item.type === "image")],
1456
+ ..."path" in spilled ? { fullOutputPath: spilled.path } : {}
1457
+ };
1458
+ }
1459
+ __name(truncateOutput, "truncateOutput");
1460
+ function toScriptValue(tool, outcome) {
1461
+ const { result } = outcome;
1462
+ if (tool.outputSchema && result.structuredContent !== void 0)
1463
+ return result.structuredContent;
1464
+ const text = textOf(result);
1465
+ if (outcome.isError)
1466
+ throw new Error(text || `Tool "${tool.name}" failed`);
1467
+ return text;
1468
+ }
1469
+ __name(toScriptValue, "toScriptValue");
1470
+ async function executeCodemode(toolCallId, input, signal, onUpdate, ctx, options = {}) {
1471
+ const startedAt = performance.now();
1472
+ const { code, options: sourceOptions } = parseCodemodeSource(input.code);
1473
+ const calls = [];
1474
+ let modelUsage;
1475
+ let generatedImages = 0;
1476
+ const addGeneratedImages = /* @__PURE__ */ __name((count) => {
1477
+ generatedImages += count;
1478
+ }, "addGeneratedImages");
1479
+ const addModelUsage = /* @__PURE__ */ __name((usage) => {
1480
+ modelUsage = modelUsage ? combineUsage(modelUsage, usage) : usage;
1481
+ }, "addModelUsage");
1482
+ const snapshot = /* @__PURE__ */ __name(() => ({ calls: calls.map((call) => ({ ...call })) }), "snapshot");
1483
+ const publish = /* @__PURE__ */ __name(() => onUpdate?.({ content: [], details: snapshot() }), "publish");
1484
+ publish();
1485
+ const callable = ctx ? getCodemodeCallableTools(ctx.tools) : [];
1486
+ const guidelines = options.getToolGuidelines?.();
1487
+ const samples = new Map(callable.map((tool) => [tool.name, renderToolSample(toCodemodeDeclaration(tool, guidelines?.get(tool.name)))]));
1488
+ const sandboxTools = callable.map((tool) => ({
1489
+ name: tool.name,
1490
+ description: samples.get(tool.name),
1491
+ execute: /* @__PURE__ */ __name(async (args, { signal: callSignal }) => {
1492
+ const record = {
1493
+ id: `${toolCallId}/?`,
1494
+ name: tool.name,
1495
+ args: previewArgs(args),
1496
+ status: "running"
1497
+ };
1498
+ calls.push(record);
1499
+ publish();
1500
+ const callStartedAt = performance.now();
1501
+ if (!ctx)
1502
+ throw new Error("Tool calls need a session");
1503
+ const outcome = await ctx.executeTool(tool.name, args, { signal: callSignal });
1504
+ record.id = outcome.toolCall.id;
1505
+ record.durationMs = performance.now() - callStartedAt;
1506
+ if (outcome.isError) {
1507
+ record.status = callSignal.aborted ? "cancelled" : "error";
1508
+ record.error = truncateText(textOf(outcome.result) || `Tool "${tool.name}" failed`, ERROR_PREVIEW_CHARS);
1509
+ } else {
1510
+ record.status = "ok";
1511
+ }
1512
+ publish();
1513
+ return toScriptValue(tool, outcome);
1514
+ }, "execute")
1515
+ }));
1516
+ const sandbox = new CodemodeSandbox({
1517
+ tools: sandboxTools,
1518
+ globals: [
1519
+ ...createDiscoveryGlobals(callable, samples, options),
1520
+ ...options.models && ctx ? createModelGlobals(ctx.modelRegistry, toolCallId, calls, publish, addModelUsage, addGeneratedImages) : []
1521
+ ],
1522
+ timeoutMs: sourceOptions.timeoutMs ?? Number.POSITIVE_INFINITY,
1523
+ memoryLimitBytes: CODEMODE_MEMORY_LIMIT_BYTES,
1524
+ wasm: loadQuickJSWasm(getQuickJSWasmPath()),
1525
+ workerUrl: getCodemodeWorkerSpecifier(),
1526
+ acquireWorker: /* @__PURE__ */ __name(() => {
1527
+ if (activeCodemodeWorkers >= MAX_CONCURRENT_CODEMODE_WORKERS) {
1528
+ throw new Error(`Codemode worker limit reached (${MAX_CONCURRENT_CODEMODE_WORKERS} workers are still running or shutting down). Retry after they exit.`);
1529
+ }
1530
+ activeCodemodeWorkers++;
1531
+ return () => {
1532
+ activeCodemodeWorkers--;
1533
+ };
1534
+ }, "acquireWorker")
1535
+ });
1536
+ let result;
1537
+ try {
1538
+ const store = ctx ? readCodemodeStore(ctx.sessionManager.getBranch()) : {};
1539
+ result = await sandbox.execute(code, { signal, store });
1540
+ } finally {
1541
+ await sandbox.close();
1542
+ }
1543
+ for (const call of calls) {
1544
+ if (call.status === "running")
1545
+ call.status = "cancelled";
1546
+ }
1547
+ const scriptOutput = [...result.output];
1548
+ if (result.ok) {
1549
+ const { set, delete: deleted } = result.storeWrites;
1550
+ if (Object.keys(set).length > 0 || deleted.length > 0) {
1551
+ options.appendEntry?.(CODEMODE_STORE_ENTRY_TYPE, { set, delete: deleted });
1552
+ }
1553
+ if (result.value !== void 0)
1554
+ scriptOutput.push({ type: "text", text: valueText(result.value) });
1555
+ }
1556
+ const items = formatOutput(scriptOutput);
1557
+ if (!result.ok)
1558
+ items.push({ type: "text", text: `Script error:
1559
+ ${formatError(result, calls)}` });
1560
+ if (generatedImages > 0 && !items.some((item) => item.type === "image")) {
1561
+ items.push({
1562
+ type: "text",
1563
+ text: `Note: models.generateImages() returned ${generatedImages} image${generatedImages === 1 ? "" : "s"} that the script did not show. Show each image block of result.output with image(block).`
1564
+ });
1565
+ }
1566
+ const truncated = await truncateOutput(joinAdjacentText(items), sourceOptions.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS);
1567
+ const output = joinAdjacentText(await saveImages(truncated.items));
1568
+ const wallTime = ((performance.now() - startedAt) / 1e3).toFixed(1);
1569
+ const header = `${result.ok ? "Script completed" : "Script failed"}
1570
+ Wall time ${wallTime} seconds
1571
+ Output:
1572
+ `;
1573
+ const details = snapshot();
1574
+ if (truncated.fullOutputPath)
1575
+ details.fullOutputPath = truncated.fullOutputPath;
1576
+ return {
1577
+ content: [{ type: "text", text: header }, ...output],
1578
+ details,
1579
+ ...modelUsage ? { usage: modelUsage } : {},
1580
+ ...result.ok ? {} : { isError: true }
1581
+ };
1582
+ }
1583
+ __name(executeCodemode, "executeCodemode");
1584
+ function isNamespaceName(namespace, query) {
1585
+ const queryId = toCodemodeIdentifier(query);
1586
+ return [namespace.name, ...namespace.aliases ?? []].some((name) => name === query || toCodemodeIdentifier(name) === queryId);
1587
+ }
1588
+ __name(isNamespaceName, "isNamespaceName");
1589
+ function createDiscoveryGlobals(tools, samples, options) {
1590
+ const ranker = new Bm25Ranker();
1591
+ const entry = /* @__PURE__ */ __name((name) => ({ name: toCodemodeIdentifier(name), description: samples.get(name) ?? "" }), "entry");
1592
+ return [
1593
+ {
1594
+ name: "searchTools",
1595
+ spread: true,
1596
+ execute: /* @__PURE__ */ __name((args) => {
1597
+ const [query, searchOptions] = args;
1598
+ if (typeof query !== "string")
1599
+ throw new Error("searchTools() expects a query string");
1600
+ const limit = searchOptions?.limit ?? DEFAULT_TOOL_SEARCH_LIMIT;
1601
+ if (typeof limit !== "number" || !Number.isInteger(limit) || limit <= 0) {
1602
+ throw new Error("searchTools() limit must be a positive integer");
1603
+ }
1604
+ const namespace = searchOptions?.namespace;
1605
+ if (namespace !== void 0 && namespace !== null && typeof namespace !== "string") {
1606
+ throw new Error("searchTools() namespace must be a string");
1607
+ }
1608
+ const documents = tools.flatMap((tool) => {
1609
+ const toolNamespace = options.getToolNamespace?.(tool.name);
1610
+ if (namespace && (!toolNamespace || !isNamespaceName(toolNamespace, namespace)))
1611
+ return [];
1612
+ return [createToolSearchDocument(tool, toolNamespace)];
1613
+ });
1614
+ return ranker.rank(query, documents, limit).map((match) => entry(match.name));
1615
+ }, "execute")
1616
+ },
1617
+ {
1618
+ name: "describeTool",
1619
+ spread: true,
1620
+ execute: /* @__PURE__ */ __name((args) => {
1621
+ const [name] = args;
1622
+ if (typeof name !== "string")
1623
+ throw new Error("describeTool() expects a tool name");
1624
+ const tool = tools.find((candidate) => candidate.name === name || toCodemodeIdentifier(candidate.name) === name);
1625
+ return tool ? samples.get(tool.name) : void 0;
1626
+ }, "execute")
1627
+ },
1628
+ {
1629
+ name: "describeNamespace",
1630
+ spread: true,
1631
+ execute: /* @__PURE__ */ __name((args) => {
1632
+ const [name] = args;
1633
+ if (typeof name !== "string")
1634
+ throw new Error("describeNamespace() expects a namespace name");
1635
+ let namespace;
1636
+ const names = [];
1637
+ for (const tool of tools) {
1638
+ const toolNamespace = options.getToolNamespace?.(tool.name);
1639
+ if (!toolNamespace || !isNamespaceName(toolNamespace, name))
1640
+ continue;
1641
+ namespace ??= toolNamespace;
1642
+ names.push(toCodemodeIdentifier(tool.name));
1643
+ }
1644
+ if (!namespace)
1645
+ return void 0;
1646
+ return {
1647
+ name: namespace.name,
1648
+ ...namespace.description ? { description: namespace.description } : {},
1649
+ ...namespace.instructions ? { instructions: namespace.instructions } : {},
1650
+ tools: names
1651
+ };
1652
+ }, "execute")
1653
+ }
1654
+ ];
1655
+ }
1656
+ __name(createDiscoveryGlobals, "createDiscoveryGlobals");
1657
+ function createModelGlobals(models, toolCallId, calls, publish, addUsage, addGeneratedImages) {
1658
+ const limit = createLimiter(MAX_CONCURRENT_MODEL_CALLS);
1659
+ let callCount = 0;
1660
+ const runModelCall = /* @__PURE__ */ __name(async (name, type, [model, context], checkContext, run) => {
1661
+ const listHint = `List the ${type} models you can use with models.getAvailableOfType("${type}").`;
1662
+ const given = model;
1663
+ if (typeof given?.provider !== "string" || typeof given.id !== "string") {
1664
+ const undefinedHint = model === void 0 || model === null ? " models.getModelOfType() returns undefined for an unknown provider or id." : "";
1665
+ throw new Error(`${name}() expects ${withArticle(type)} model as its first argument, got ${describeValue(model)}.${undefinedHint} ${listHint}`);
1666
+ }
1667
+ const provider = given.provider;
1668
+ const id = given.id;
1669
+ const ref = `${provider}/${id}`;
1670
+ const resolved = models.getModelOfType(type, provider, id);
1671
+ if (!resolved) {
1672
+ const actualType = [...MODEL_TYPES].find((other) => other !== type && models.getModelOfType(other, provider, id) !== void 0);
1673
+ throw new Error(actualType ? `"${ref}" is ${withArticle(actualType)} model, not ${withArticle(type)} model. ${listHint}` : `Unknown ${type} model "${ref}". ${listHint}`);
1674
+ }
1675
+ const checked = checkContext(context);
1676
+ const record = {
1677
+ id: `${toolCallId}/${name}/${++callCount}`,
1678
+ name,
1679
+ args: `${resolved.provider}/${resolved.id}`,
1680
+ status: "running"
1681
+ };
1682
+ calls.push(record);
1683
+ publish();
1684
+ const startedAt = performance.now();
1685
+ const result = await limit(() => run(resolved, checked));
1686
+ record.durationMs = performance.now() - startedAt;
1687
+ record.status = result.stopReason === "stop" ? "ok" : result.stopReason === "aborted" ? "cancelled" : "error";
1688
+ if (result.errorMessage)
1689
+ record.error = truncateText(result.errorMessage, ERROR_PREVIEW_CHARS);
1690
+ if (result.usage) {
1691
+ record.cost = result.usage.cost.total;
1692
+ addUsage(result.usage);
1693
+ }
1694
+ publish();
1695
+ return result;
1696
+ }, "runModelCall");
1697
+ const implementations = {
1698
+ "models.getModelsOfType": /* @__PURE__ */ __name((args) => {
1699
+ const [type, provider] = args;
1700
+ return models.getModelsOfType(toModelType(type), toProvider(provider)).map(toModelInfo);
1701
+ }, "models.getModelsOfType"),
1702
+ "models.getAvailableOfType": /* @__PURE__ */ __name(async (args, { signal }) => {
1703
+ const [type, provider] = args;
1704
+ const available = await models.getAvailableOfType(toModelType(type), toProvider(provider), { signal });
1705
+ return available.map(toModelInfo);
1706
+ }, "models.getAvailableOfType"),
1707
+ "models.getModelOfType": /* @__PURE__ */ __name((args) => {
1708
+ const [type, provider, id] = args;
1709
+ if (typeof provider !== "string" || typeof id !== "string") {
1710
+ throw new Error(`models.getModelOfType(type, provider, id) expects three strings, got (${args.map(describeValue).join(", ")}). The provider and the id are separate arguments, for example models.getModelOfType("classifier", "typesafe", "jev-latest").`);
1711
+ }
1712
+ const model = models.getModelOfType(toModelType(type), provider, id);
1713
+ return model === void 0 ? void 0 : toModelInfo(model);
1714
+ }, "models.getModelOfType"),
1715
+ "models.classify": /* @__PURE__ */ __name((args, { signal }) => runModelCall("models.classify", "classifier", args, checkClassifierContext, (resolved, context) => models.classify(resolved, context, { signal })), "models.classify"),
1716
+ "models.generateImages": /* @__PURE__ */ __name((args, { signal }) => runModelCall("models.generateImages", "image", args, checkImagesContext, async (resolved, context) => {
1717
+ const result = await models.generateImages(resolved, context, { signal });
1718
+ addGeneratedImages(result.output.filter((block) => block.type === "image").length);
1719
+ return result;
1720
+ }), "models.generateImages")
1721
+ };
1722
+ return Object.entries(implementations).map(([name, execute]) => ({ name, spread: true, execute }));
1723
+ }
1724
+ __name(createModelGlobals, "createModelGlobals");
1725
+ export {
1726
+ executeCodemode,
1727
+ readCodemodeStore
1728
+ };