dal-code 1.0.28 → 1.0.30

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 (160) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dal-docs/README.md +1 -1
  3. package/dist/bundle/chunks/anthropic-messages-AZKHNVAG.js +5 -0
  4. package/dist/bundle/chunks/anthropic.js +74 -0
  5. package/dist/bundle/chunks/azure-openai-responses-LA3FYF3J.js +1 -0
  6. package/dist/bundle/chunks/bedrock-converse-stream.js +82 -0
  7. package/dist/bundle/chunks/chunk-4HEMJ3PG.js +1140 -0
  8. package/dist/bundle/chunks/chunk-4L3WN2XY.js +1 -0
  9. package/dist/bundle/chunks/chunk-4UTLMBZZ.js +13 -0
  10. package/dist/bundle/chunks/chunk-4XT6IQQ6.js +1 -0
  11. package/dist/bundle/chunks/chunk-5M7W2EDY.js +3 -0
  12. package/dist/bundle/chunks/chunk-5ULSWE2O.js +43 -0
  13. package/dist/bundle/chunks/chunk-6CYCI3EJ.js +11 -0
  14. package/dist/bundle/chunks/chunk-7ZC4UXSL.js +1 -0
  15. package/dist/bundle/chunks/chunk-ABVPQ2YN.js +14 -0
  16. package/dist/bundle/chunks/chunk-DRQDKNXA.js +1 -0
  17. package/dist/bundle/chunks/chunk-F5ZABL6Z.js +19 -0
  18. package/dist/bundle/chunks/chunk-GYI2XXNW.js +10 -0
  19. package/dist/bundle/chunks/chunk-H3QXYIF7.js +30 -0
  20. package/dist/bundle/chunks/chunk-HC56T2OZ.js +134 -0
  21. package/dist/bundle/chunks/chunk-HMFU7ZIF.js +1 -0
  22. package/dist/bundle/chunks/chunk-JEMNLK2O.js +10 -0
  23. package/dist/bundle/chunks/chunk-L2ZPNLYD.js +1 -0
  24. package/dist/bundle/chunks/chunk-LPXNMA2W.js +1 -0
  25. package/dist/bundle/chunks/chunk-PGXDEOVV.js +1 -0
  26. package/dist/bundle/chunks/chunk-PJACZCIR.js +1 -0
  27. package/dist/bundle/chunks/chunk-PMRZO46Y.js +1 -0
  28. package/dist/bundle/chunks/chunk-PRRNXB7S.js +1 -0
  29. package/dist/bundle/chunks/chunk-PRXLTI3Y.js +81 -0
  30. package/dist/bundle/chunks/chunk-Q6IMZXWD.js +129 -0
  31. package/dist/bundle/chunks/chunk-R4YWRKK4.js +7 -0
  32. package/dist/bundle/chunks/chunk-RDZVAGPR.js +1 -0
  33. package/dist/bundle/chunks/chunk-S3GGRYIO.js +5 -0
  34. package/dist/bundle/chunks/chunk-TEPMHNKQ.js +1 -0
  35. package/dist/bundle/chunks/chunk-TRDNDS6A.js +3 -0
  36. package/dist/bundle/chunks/chunk-USJZMAIR.js +1 -0
  37. package/dist/bundle/chunks/chunk-UTB4DTYQ.js +1 -0
  38. package/dist/bundle/chunks/chunk-WXULTH2D.js +1 -0
  39. package/dist/bundle/chunks/chunk-YKF7PQCJ.js +1 -0
  40. package/dist/bundle/chunks/chunk-YTERFI73.js +1 -0
  41. package/dist/bundle/chunks/chunk-ZBURYEWF.js +1 -0
  42. package/dist/bundle/chunks/chunk-ZKDITC7J.js +35 -0
  43. package/dist/bundle/chunks/cli-2LJMKSUZ.js +50 -0
  44. package/dist/bundle/chunks/cloudflare-workers-ai-system-one-6WEJUIW2.js +1 -0
  45. package/dist/bundle/chunks/codemode-worker.js +470 -0
  46. package/dist/bundle/chunks/dist-37IE4EWG.js +10 -0
  47. package/dist/bundle/chunks/easter-egg-3d-GHWWTBZN.js +1 -0
  48. package/dist/bundle/chunks/execute-JU22LJZT.js +489 -0
  49. package/dist/bundle/chunks/github-copilot.js +1 -0
  50. package/dist/bundle/chunks/google-generative-ai-RFPHNE43.js +1 -0
  51. package/dist/bundle/chunks/google-vertex-QDNCMHLE.js +1 -0
  52. package/dist/bundle/chunks/http-proxy-6TR4MP55.js +1 -0
  53. package/dist/bundle/chunks/https-proxy-agent-2VXB7436.js +12 -0
  54. package/dist/bundle/chunks/image-resize-worker.js +1 -0
  55. package/dist/bundle/chunks/jiti-loader-C3NU2SDH.js +20 -0
  56. package/dist/bundle/chunks/jiti-static-loader-E6ANQD5T.js +1 -0
  57. package/dist/bundle/chunks/kimi-coding.js +1 -0
  58. package/dist/bundle/chunks/lib-TEDK3E5I.js +8 -0
  59. package/dist/bundle/chunks/llama-cpp-classify-FYN623RH.js +21 -0
  60. package/dist/bundle/chunks/meta.js +1 -0
  61. package/dist/bundle/chunks/mistral-conversations-YHX5TRKG.js +4 -0
  62. package/dist/bundle/chunks/multipart-parser-SQ6GDJL7.js +2 -0
  63. package/dist/bundle/chunks/node-N5BSDOA5.js +15 -0
  64. package/dist/bundle/chunks/node-TWVVAGPO.js +1 -0
  65. package/dist/bundle/chunks/openai-chatgpt.js +74 -0
  66. package/dist/bundle/chunks/openai-codex-responses-UZEMMAYZ.js +9 -0
  67. package/dist/bundle/chunks/openai-codex.js +74 -0
  68. package/dist/bundle/chunks/openai-completions-H6WMELZZ.js +6 -0
  69. package/dist/bundle/chunks/openai-decisions-URHWCZPN.js +4 -0
  70. package/dist/bundle/chunks/openai-responses-7X65PCAB.js +2 -0
  71. package/dist/bundle/chunks/openrouter-images-DUPG5DZO.js +1 -0
  72. package/dist/bundle/chunks/openrouter.js +74 -0
  73. package/dist/bundle/chunks/pi-messages-YHKPQIHC.js +7 -0
  74. package/dist/bundle/chunks/radius.js +74 -0
  75. package/dist/bundle/chunks/runtime-LLITCT4N.js +1 -0
  76. package/dist/bundle/chunks/src-UK77SYZE.js +3 -0
  77. package/dist/bundle/chunks/typesafe-system-one-N7PKHI2N.js +1 -0
  78. package/dist/bundle/chunks/virtual-modules-H32OTUCD.js +1 -0
  79. package/dist/bundle/chunks/xai.js +1 -0
  80. package/dist/bundle/cli-runtime.js +2 -0
  81. package/dist/bundle/cli.js +2 -0
  82. package/dist/bundle/index.js +1 -0
  83. package/dist/bundle/rpc-entry.js +2 -0
  84. package/dist/core/key-id-schema.js +1 -0
  85. package/dist/core/keybindings-schema.js +1 -0
  86. package/dist/core/settings-defaults.js +1 -0
  87. package/dist/core/settings-schema.js +1 -0
  88. package/dist/core/system-prompt.js +9 -9
  89. package/dist/modes/interactive/components/daxnuts.js +1 -0
  90. package/dist/modes/interactive/interactive-mode.d.ts +3 -0
  91. package/dist/modes/interactive/interactive-mode.js +31 -31
  92. package/dist/modes/interactive/theme/theme-schema.js +12 -0
  93. package/dist/modes/interactive/theme/theme-tokens.js +1 -0
  94. package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
  95. package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
  96. package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
  97. package/dist/node_modules/@dalcode/dal-guard/src/index.js +1 -1
  98. package/dist/node_modules/@dalcode/dal-guard/src/mode.js +2 -0
  99. package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
  100. package/dist/node_modules/@dalcode/dal-interactive/package.json +2 -2
  101. package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
  102. package/dist/node_modules/@dalcode/dal-lsp/package.json +3 -3
  103. package/dist/node_modules/@dalcode/dal-mcp/package.json +5 -5
  104. package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
  105. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +1 -1
  106. package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
  107. package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +1 -1
  108. package/dist/node_modules/@dalcode/dal-plugins/package.json +2 -2
  109. package/dist/node_modules/@dalcode/dal-review/package.json +3 -3
  110. package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
  111. package/dist/node_modules/@dalcode/dal-router/package.json +4 -4
  112. package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
  113. package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
  114. package/dist/node_modules/@dalcode/dal-telemetry/package.json +2 -2
  115. package/dist/node_modules/@dalcode/dal-terminal/package.json +2 -2
  116. package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
  117. package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
  118. package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
  119. package/dist/node_modules/@dalcode/dal-workflow/src/check-in.js +2 -0
  120. package/dist/node_modules/@dalcode/dal-workflow/src/index.js +4 -4
  121. package/dist/node_modules/@dalcode/dal-workflow/src/todo.js +2 -2
  122. package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
  123. package/dist/node_modules/@earendil-works/chord/package.json +1 -1
  124. package/dist/node_modules/@earendil-works/pi-agent-core/package.json +2 -2
  125. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/compat-schema.js +1 -0
  126. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  127. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/huggingface.json +1 -1
  128. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  129. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  130. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/model-schema.js +1 -0
  131. package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
  132. package/dist/node_modules/@earendil-works/pi-client/package.json +3 -3
  133. package/dist/node_modules/@earendil-works/pi-codemode/package.json +1 -1
  134. package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
  135. package/dist/node_modules/@earendil-works/pi-mcp/package.json +1 -1
  136. package/dist/node_modules/@earendil-works/pi-protocol/package.json +2 -2
  137. package/dist/node_modules/@earendil-works/pi-server/package.json +3 -3
  138. package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  139. package/dist/node_modules/@earendil-works/pi-tui/native/darwin/prebuilds/darwin-arm64/darwin-platform.node +0 -0
  140. package/dist/node_modules/@earendil-works/pi-tui/native/darwin/prebuilds/darwin-x64/darwin-platform.node +0 -0
  141. package/dist/node_modules/@earendil-works/pi-tui/native/darwin/src/darwin-platform.m +132 -0
  142. package/dist/node_modules/@earendil-works/pi-tui/native/linux/prebuilds/linux-arm64/linux-platform-x11.node +0 -0
  143. package/dist/node_modules/@earendil-works/pi-tui/native/linux/prebuilds/linux-x64/linux-platform-x11.node +0 -0
  144. package/dist/node_modules/@earendil-works/pi-tui/native/linux/src/clipboard-worker.h +70 -0
  145. package/dist/node_modules/@earendil-works/pi-tui/native/linux/src/linux-platform-x11.c +274 -0
  146. package/dist/node_modules/@earendil-works/pi-tui/native/win32/prebuilds/win32-arm64/win32-platform.node +0 -0
  147. package/dist/node_modules/@earendil-works/pi-tui/native/win32/prebuilds/win32-x64/win32-platform.node +0 -0
  148. package/dist/node_modules/@earendil-works/pi-tui/native/win32/src/win32-platform.c +241 -0
  149. package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
  150. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  151. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  152. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  153. package/examples/extensions/gondolin/package-lock.json +2 -2
  154. package/examples/extensions/gondolin/package.json +1 -1
  155. package/examples/extensions/sandbox/package-lock.json +2 -2
  156. package/examples/extensions/sandbox/package.json +1 -1
  157. package/examples/extensions/with-deps/package-lock.json +2 -2
  158. package/examples/extensions/with-deps/package.json +1 -1
  159. package/npm-shrinkwrap.json +2 -2
  160. package/package.json +1 -1
@@ -0,0 +1,50 @@
1
+ var H=Object.defineProperty;var v=(n,r)=>H(n,"name",{value:r,configurable:!0});import{createRequire as F}from"node:module";const me=F(import.meta.url);import{McpOAuthCredentialStore as q,McpServerConnection as Y,McpServerLog as z,McpSignInCancelledError as V,createDefaultTransport as B,signInMcpServer as K}from"./chunk-PRXLTI3Y.js";import{ProjectTrustStore as k,addMcpServerConfig as W,loadMcpConfig as I,openBrowser as G,removeMcpServerConfig as J}from"./chunk-5M7W2EDY.js";import{getMcpToolExposure as Q,validateMcpServerConfig as X}from"./chunk-ABVPQ2YN.js";import"./chunk-ZKDITC7J.js";import{APP_NAME as f,CONFIG_DIR_NAME as A,source_default as N}from"./chunk-HC56T2OZ.js";import"./chunk-S3GGRYIO.js";import"./chunk-4L3WN2XY.js";import{existsSync as Z}from"node:fs";import{join as P}from"node:path";import{createInterface as ee}from"node:readline/promises";var re=`${N.bold("Usage:")}
2
+ ${f} mcp add <server> [options] -- <command> [args...]
3
+ ${f} mcp add <server> [options] --url <url>
4
+ ${f} mcp remove <server> [-l]
5
+ ${f} mcp list [--json]
6
+ ${f} mcp login <server> [--timeout <seconds>]
7
+ ${f} mcp logout <server>
8
+
9
+ Configure and check MCP servers and sign in to OAuth servers without starting a session.
10
+ Reads ~/${A}/agent/mcp.json and, in trusted projects, ${A}/mcp.json.
11
+
12
+ Commands:
13
+ add <server> Add or replace a server in mcp.json
14
+ remove <server> Remove a server from mcp.json
15
+ list Show state, tools, and errors (exits 1 on failure)
16
+ login <server> Sign in through the browser
17
+ logout <server> Delete the stored OAuth credentials
18
+
19
+ Options for add and remove:
20
+ -l, --local Use ${A}/mcp.json in the current project instead of the global file
21
+
22
+ Options for add:
23
+ --url <url> Streamable HTTP server URL (instead of a command)
24
+ --env <KEY=VALUE> Environment variable for a stdio server (repeatable)
25
+ --cwd <dir> Working directory for a stdio server
26
+ --header <KEY=VALUE> HTTP header (repeatable)
27
+ --bearer-token-env-var <NAME>
28
+ Send "Authorization: Bearer \${NAME}"
29
+ --oauth-client-id <id> Pre-registered OAuth client id
30
+ --oauth-client-secret <secret>
31
+ OAuth client secret (may be \${NAME} or !command)
32
+ --oauth-callback-port <port>
33
+ Fixed OAuth callback port
34
+ --oauth-client-name <name>
35
+ Client name sent when registering with the OAuth server
36
+ --exposure <mode> codemode (default), deferred, direct, or hidden
37
+ --description <text> What the server offers, shown in the system prompt
38
+
39
+ Other options:
40
+ --json Print the list as JSON
41
+ --timeout <seconds> How long login waits for the browser (default: 300)`,M=N.dim(`Use "${f} mcp --help" for usage.`),te=300;function T(n){return n instanceof Error?n.message:String(n)}v(T,"errorMessage");function oe(n){let{config:r}=n;return"url"in r?r.url:[r.command,...r.args??[]].join(" ")}v(oe,"describeTransport");function D(n,r,s){return new Y({entry:n,cwd:r.cwd,createTransport:B,credentials:s,log:new z(P(r.agentDir,"mcp.log")),onTools:v(()=>{},"onTools")})}v(D,"createConnection");var ne=new Map([["-l","--local"]]);function O(n,r,s,l=Number.POSITIVE_INFINITY){let o=[],i=new Map,d=new Map;for(let p=0;p<n.length;p++){let e=ne.get(n[p])??n[p];if(e==="--"||o.length>=l){o.push(...n.slice(e==="--"?p+1:p));break}if(!e.startsWith("--")){o.push(e);continue}let c=e.slice(2),a=r[c];if(!a){s(`Unknown option ${e}.
42
+ ${M}`);return}if(a==="flag"){i.set(c,!0);continue}let t=n[++p];if(t===void 0){s(`${e} needs a value.`);return}a==="list"?d.set(c,[...d.get(c)??[],t]):i.set(c,t)}return{positional:o,values:i,lists:d}}v(O,"parseOptions");async function ae(n,r){let s=r.log??(t=>console.log(t)),l=r.error??(t=>console.error(t)),[o,...i]=n;if(o===void 0||o==="help"||n.includes("--help")||n.includes("-h"))return s(re),0;let d=P(r.cwd,A,"mcp.json");if(o==="add"||o==="remove")return o==="add"?se(i,d,r,s,l):ie(i,d,r,s,l);let p=new k(r.agentDir).get(r.cwd)===!0,e=I({agentDir:r.agentDir,cwd:r.cwd,projectTrusted:p}),c=!p&&Z(d)?`${d} is ignored because the project is not trusted. Start ${f} in the project to trust it.`:void 0,a=r.credentials??new q;switch(o){case"list":{let t=O(i,{json:"flag"},l);return t?t.positional.length>0?(l(`Usage: ${f} mcp list [--json]
43
+ ${M}`),1):le(e,t.values.has("json"),c,r,a,s):1}case"login":case"logout":{let t=O(i,o==="login"?{timeout:"value"}:{},l);if(!t)return 1;let[u,...m]=t.positional;if(!u||m.length>0)return l(`Usage: ${f} mcp ${o} <server>
44
+ ${M}`),1;let g=e.servers.find($=>$.name===u);if(!g)return l(`No MCP server named "${u}".${c?` ${c}`:""} Configured: ${e.servers.map($=>$.name).join(", ")||"none"}.`),1;let j=D(g,r,a),w=j.oauthUrl;if(!w)return l(`MCP server "${u}" does not use OAuth. Only HTTP servers without an Authorization header do.`),1;if(o==="logout"){let $=a.remove(u,w);return s($?`Signed out of MCP server "${u}".`:`No stored credentials for MCP server "${u}".`),0}let C=Number(t.values.get("timeout")??te);if(!Number.isFinite(C)||C<=0)return l("--timeout must be a positive number of seconds."),1;try{return await ce(g,j,w,C*1e3,r,a,s,l)}finally{await j.close()}}default:return l(`Unknown mcp command "${o}".
45
+ ${M}`),1}}v(ae,"runMcpCommand");function L(n,r,s){if(!r)return{};let l={};for(let o of r){let i=o.indexOf("=");if(i<=0){s(`--${n} expects KEY=VALUE, got "${o}".`);return}l[o.slice(0,i)]=o.slice(i+1)}return l}v(L,"parsePairs");function se(n,r,s,l,o){let i=`Usage: ${f} mcp add <server> [options] (--url <url> | -- <command> [args...])
46
+ ${M}`,d=O(n,{local:"flag",url:"value",env:"list",cwd:"value",header:"list","bearer-token-env-var":"value","oauth-client-id":"value","oauth-client-secret":"value","oauth-callback-port":"value","oauth-client-name":"value",exposure:"value",description:"value"},o,2);if(!d)return 1;let{positional:p,values:e,lists:c}=d,[a,...t]=p,u=e.get("url");if(!a||u===void 0==(t.length===0))return o(i),1;let m=v(h=>{let b=e.get(h);return typeof b=="string"?b:void 0},"value"),g=m("exposure"),j=(u===void 0?["header","bearer-token-env-var","oauth-client-id","oauth-client-secret","oauth-callback-port","oauth-client-name"]:["env","cwd"]).find(h=>e.has(h)||c.has(h));if(j)return o(`--${j} only applies to ${u===void 0?"HTTP servers (--url)":"stdio servers"}.`),1;let w;if(typeof u=="string"){let h=L("header",c.get("header"),o);if(!h)return 1;let b=m("bearer-token-env-var");b!==void 0&&(h.Authorization=`Bearer \${${b}}`);let S=m("oauth-callback-port"),U={...m("oauth-client-id")===void 0?{}:{clientId:m("oauth-client-id")},...m("oauth-client-secret")===void 0?{}:{clientSecret:m("oauth-client-secret")},...S===void 0?{}:{callbackPort:Number(S)},...m("oauth-client-name")===void 0?{}:{clientName:m("oauth-client-name")}};w={url:u,...Object.keys(h).length>0?{headers:h}:{},...Object.keys(U).length>0?{oauth:U}:{}}}else{let h=L("env",c.get("env"),o);if(!h)return 1;let[b,...S]=t;w={command:b,...S.length>0?{args:S}:{},...Object.keys(h).length>0?{env:h}:{},...m("cwd")===void 0?{}:{cwd:m("cwd")}}}g!==void 0&&(w.exposure=g);let C=m("description");C!==void 0&&(w.description=C);let $=X(a,w);if(typeof $=="string")return o($),1;let x=e.has("local"),E=x?r:P(s.agentDir,"mcp.json"),R=x?"project":"global",y;try{y=W(E,a,$)}catch(h){return o(`Could not update ${E}: ${T(h)}`),1}l(`${y?"Replaced":"Added"} ${R} MCP server "${a}" in ${E}.`),x&&new k(s.agentDir).get(s.cwd)!==!0&&l(`The project is not trusted, so ${E} is ignored until you start ${f} in the project and trust it.`);let _="url"in $&&!Object.keys($.headers??{}).some(h=>h.toLowerCase()==="authorization");return l(`Check it with: ${f} mcp list${_?`. If it requires sign-in: ${f} mcp login ${a}`:""}`),0}v(se,"add");function ie(n,r,s,l,o){let i=O(n,{local:"flag"},o);if(!i)return 1;let[d,...p]=i.positional;if(!d||p.length>0)return o(`Usage: ${f} mcp remove <server> [-l]
47
+ ${M}`),1;let e=i.values.has("local"),c=P(s.agentDir,"mcp.json"),a=e?r:c,t=e?"project":"global",u;try{u=J(a,d)}catch(g){return o(`Could not update ${a}: ${T(g)}`),1}if(u)return l(`Removed ${t} MCP server "${d}" from ${a}.`),0;let m=I({agentDir:s.agentDir,cwd:s.cwd,projectTrusted:!0}).servers.find(g=>g.name===d&&g.scope!==t);return o(`No ${t} MCP server named "${d}" in ${a}.${m?` It is defined in ${m.source}${m.scope==="project"?"; use --local":"; omit --local"}.`:""}`),1}v(ie,"remove");async function le(n,r,s,l,o,i){let d=await Promise.all(n.servers.map(async e=>{let c={name:e.name,scope:e.scope??"global",source:e.source,...e.override?{override:e.override}:{},enabled:e.config.enabled!==!1,exposure:e.config.exposure??"codemode",transport:oe(e),state:"disabled",tools:[]};if(!c.enabled)return c;let a=D(e,l,o);try{await a.getClient()}catch{}c.state=a.state,c.tools=a.tools.map(u=>u.name);let t=a.tools.flatMap(u=>{let m=Q(e.config,u.name);return m===c.exposure?[]:[[u.name,m]]});return t.length>0&&(c.toolExposure=Object.fromEntries(t)),a.hasResources&&(c.resources=a.resources.length,c.resourceTemplates=a.resourceTemplates.length),a.state!=="connected"&&a.error&&(c.error=a.error),await a.close(),c})),p=n.errors.length>0||d.some(e=>e.enabled&&e.state!=="connected");if(r)return i(JSON.stringify({servers:d,errors:n.errors,...s?{note:s}:{}},null,2)),p?1:0;d.length===0&&n.errors.length===0&&i(`No MCP servers configured. Add them to ${P(l.agentDir,"mcp.json")} or .pi/mcp.json.`);for(let e of d){let c=e.state==="connected"?`connected, ${e.tools.length} tool${e.tools.length===1?"":"s"}`:e.state==="needs-auth"?"needs sign-in":e.state;if(i(`${e.name}: ${c} (${e.exposure}, ${e.scope})`),i(` ${e.transport}`),e.override&&i(` project override: ${e.override}`),e.state==="needs-auth"&&i(` sign in with: ${f} mcp login ${e.name}`),e.tools.length>0){let a=e.tools.map(t=>{let u=e.toolExposure?.[t];return u?`${t} [${u}]`:t});i(` tools: ${a.join(", ")}`)}e.resources!==void 0&&i(` resources: ${e.resources}, URI templates: ${e.resourceTemplates??0}`),e.error&&i(` ${e.error.split(`
48
+ `).join(`
49
+ `)}`)}for(let e of n.errors)i(`config error: ${e}`);return s&&i(s),p?1:0}v(le,"list");async function ce(n,r,s,l,o,i,d,p){let{name:e}=n;try{return await r.getClient(),d(`Already signed in to MCP server "${e}" (${r.tools.length} tools).`),0}catch{if(r.state!=="needs-auth")return p(`MCP server "${e}" failed to connect: ${r.error??"unknown error"}`),1}let c=o.openUrl??G,a=process.stdin.isTTY===!0&&o.openUrl===void 0;try{await K({serverUrl:s,store:i.forServer(e,s),settings:r.oauthSettings(),challenge:r.challenge,prompt:{showAuthorizationUrl:v(t=>{d(`Sign in to MCP server "${e}" in your browser:
50
+ ${t.href}`),c(t.href)},"showAuthorizationUrl"),promptForRedirectUrl:v(t=>de(t,a),"promptForRedirectUrl")},signal:AbortSignal.timeout(l)})}catch(t){return p(t instanceof V?`Sign-in to MCP server "${e}" was cancelled or not completed within ${Math.round(l/1e3)} seconds.`:`Sign-in to MCP server "${e}" failed: ${T(t)}`),1}r.challenge=void 0;try{await r.reconnect()}catch(t){return p(`Signed in, but ${T(t)}`),1}return d(`Signed in to MCP server "${e}" (${r.tools.length} tools).`),0}v(ce,"login");async function de(n,r){if(!r){n.aborted||await new Promise(l=>n.addEventListener("abort",l,{once:!0}));return}let s=ee({input:process.stdin,output:process.stderr});try{return await s.question("If the browser cannot reach this machine, paste the URL it was redirected to: ",{signal:n})}catch{return}finally{s.close()}}v(de,"waitForRedirectUrl");export{ae as runMcpCommand};
@@ -0,0 +1 @@
1
+ var n=Object.defineProperty;var s=(e,r)=>n(e,"name",{value:r,configurable:!0});import{createRequire as a}from"node:module";const c=a(import.meta.url);import{classifySystemOne as u}from"./chunk-YTERFI73.js";import{isRecord as i}from"./chunk-HMFU7ZIF.js";import"./chunk-TEPMHNKQ.js";import"./chunk-PMRZO46Y.js";import"./chunk-UTB4DTYQ.js";import"./chunk-GYI2XXNW.js";import"./chunk-LPXNMA2W.js";import"./chunk-4L3WN2XY.js";var o="Cloudflare Workers AI";function p(e){if(Array.isArray(e)){let r=e.map(t=>i(t)&&typeof t.message=="string"?t.message:void 0).filter(t=>t!==void 0);if(r.length>0)return`${o} error: ${r.join("; ")}`}return`${o} request failed`}s(p,"cloudflareErrorMessage");var l={api:"cloudflare-workers-ai-system-one",label:o,url:s(e=>new URL("run",`${e.baseUrl.replace(/\/+$/u,"")}/`),"url"),payload:s((e,r)=>({model:e.id,input:r}),"payload"),output:s(e=>{if(!i(e))throw new Error(`${o} returned an unexpected response`);if(e.success===!1)throw new Error(p(e.errors));let r=e.result;if(!i(r))throw new Error(`${o} returned an unexpected response`);if("answers"in r)return r;if(r.state!=="Completed")throw new Error(`${o} run did not complete (state: ${String(r.state)})`);if(!i(r.result))throw new Error(`${o} returned an unexpected response`);return r.result},"output")},m=s((e,r,t)=>u(l,e,r,t),"classify");export{m as classify};
@@ -0,0 +1,470 @@
1
+ var W=Object.defineProperty;var _=(o,e)=>W(o,"name",{value:e,configurable:!0});import{parentPort as F,workerData as G}from"node:worker_threads";function V(o){return{clock_time_get(e,t,r){let s=o(),i=new DataView(s.buffer);if(e===0||e===1){let n=BigInt(Date.now())*1000000n;return i.setBigUint64(r,n,!0),0}return 52},fd_write(e,t,r,s){let i=o(),n=new DataView(i.buffer),a=new Uint8Array(i.buffer),p=0;if(e!==1&&e!==2)return 8;for(let u=0;u<r;u++){let l=n.getUint32(t+u*8,!0),c=n.getUint32(t+u*8+4,!0),f=a.slice(l,l+c),d=new TextDecoder().decode(f);e===1?typeof process<"u"&&process.stdout?process.stdout.write(d):console.log(d):typeof process<"u"&&process.stderr?process.stderr.write(d):console.error(d),p+=c}return n.setUint32(s,p,!0),0},fd_close(e){return 52},fd_fdstat_get(e,t){let r=o(),s=new DataView(r.buffer);return e===1||e===2?(s.setUint8(t,2),s.setUint16(t+2,0,!0),s.setBigUint64(t+8,0n,!0),s.setBigUint64(t+16,0n,!0),0):8},fd_seek(e,t,r,s){return 52},random_get(e,t){let r=o(),s=new Uint8Array(r.buffer,e,t);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(s);else for(let i=0;i<t;i++)s[i]=Math.floor(Math.random()*256);return 0}}}_(V,"createWasiShim");var K=new TextDecoder;function Q(o,e){let t=new Uint8Array(o.buffer),r=e;for(;t[r]!==0;)r++;if(r===e)return{};let s=K.decode(t.slice(e,r)),i={};for(let n of s.split(`
2
+ `)){let a=n.indexOf("=");a>0&&(i[n.slice(0,a)]=n.slice(a+1))}return i}_(Q,"parseVersionString");function X(o,e){let t=`qjs_ext_${o.name.replace(/-/g,"_")}_versions`,r=o.instance.exports[t];if(typeof r!="function")return;let s=r();if(s!==0)return Q(e,s)}_(X,"extractExtensionVersions");function k(o,e){let t=0,r=0;for(;e.value<o.length;){let s=o[e.value++];if(t|=(s&127)<<r,(s&128)===0)break;r+=7}return t}_(k,"readULEB128");function Z(o){let e=WebAssembly.Module.customSections(o,"dylink.0");if(e.length===0)return null;let t=new Uint8Array(e[0]),r={value:0},s={memorySize:0,memoryAlignment:0,tableSize:0,tableAlignment:0,needed:[]};for(;r.value<t.length;){let i=k(t,r),n=k(t,r),a=r.value+n;if(i===1)s.memorySize=k(t,r),s.memoryAlignment=k(t,r),s.tableSize=k(t,r),s.tableAlignment=k(t,r);else if(i===2){let p=k(t,r);for(let u=0;u<p;u++){let l=k(t,r),c=new TextDecoder().decode(t.slice(r.value,r.value+l));r.value+=l,s.needed.push(c)}}r.value=a}return s}_(Z,"parseDylink");async function J(o,e,t,r,s,i){let n;o.wasm instanceof WebAssembly.Module?n=o.wasm:n=await WebAssembly.compile(o.wasm);let a=Z(n);if(!a)throw new Error(`Extension "${o.name}" is not a WASM shared library (missing dylink.0 section)`);let p=e.memory,u=e.__indirect_function_table,l=e.__stack_pointer,c=e.malloc;if(!p)throw new Error("Main module does not export memory");if(!u)throw new Error("Main module does not export __indirect_function_table");if(!c)throw new Error("Main module does not export malloc");let f,d;if(i)f=i.memoryBase,d=i.tableBase;else if(a.memorySize>0){if(f=c(a.memorySize),f===0)throw new Error(`Failed to allocate ${a.memorySize} bytes for extension "${o.name}"`);new Uint8Array(p.buffer,f,a.memorySize).fill(0)}else f=0;i?(d=i.tableBase,d+a.tableSize>u.length&&u.grow(d+a.tableSize-u.length)):(d=u.length,a.tableSize>0&&u.grow(a.tableSize));let y=WebAssembly.Module.imports(n),g={env:{},"GOT.mem":{},"GOT.func":{}};if(y.some(m=>m.module==="wasi_snapshot_preview1")){let m=o.wasi&&s?o.wasi(s):void 0;g.wasi_snapshot_preview1={...t,...m,...r}}let T=new Set(WebAssembly.Module.exports(n).filter(m=>m.kind==="function").map(m=>m.name)),q=new Set;for(let m of y)if(m.module==="env"){if(m.name==="memory"&&m.kind==="memory")g.env.memory=p;else if(m.name==="__indirect_function_table"&&m.kind==="table")g.env.__indirect_function_table=u;else if(m.name==="__memory_base"&&m.kind==="global")g.env.__memory_base=new WebAssembly.Global({value:"i32",mutable:!1},f);else if(m.name==="__table_base"&&m.kind==="global")g.env.__table_base=new WebAssembly.Global({value:"i32",mutable:!1},d);else if(m.name==="__stack_pointer"&&m.kind==="global")g.env.__stack_pointer=l;else if(m.kind==="function"){let v=e[m.name];v&&typeof v=="function"?g.env[m.name]=v:(q.add(m.name),g.env[m.name]=()=>{throw new Error(`Extension "${o.name}" called unresolved symbol: env.${m.name}`)})}else if(m.kind==="global"){let v=e[m.name];v instanceof WebAssembly.Global?g.env[m.name]=v:g.env[m.name]=new WebAssembly.Global({value:"i32",mutable:!0},0)}}else if(m.module==="GOT.mem"&&m.kind==="global")g["GOT.mem"][m.name]=new WebAssembly.Global({value:"i32",mutable:!0},0);else if(m.module==="GOT.func"&&m.kind==="global"){let v=e[m.name];if(v&&typeof v=="function"){let H=u.length;u.grow(1),u.set(H,v),g["GOT.func"][m.name]=new WebAssembly.Global({value:"i32",mutable:!0},H)}else g["GOT.func"][m.name]=new WebAssembly.Global({value:"i32",mutable:!0},0)}let w=[...q].filter(m=>T.has(m)),b={};for(let m of w){let v={target:null};b[m]=v,g.env[m]=(...H)=>{if(!v.target)throw new Error(`Extension "${o.name}" called unresolved symbol during init: env.${m}`);return v.target(...H)}}let j=await WebAssembly.instantiate(n,g),x=j.exports;for(let m of w){let v=x[m];typeof v=="function"&&(b[m].target=v)}typeof x.__wasm_apply_data_relocs=="function"&&x.__wasm_apply_data_relocs(),typeof x.__wasm_call_ctors=="function"&&x.__wasm_call_ctors();let E=o.initFn??`qjs_ext_${o.name.replace(/-/g,"_")}_init`,C={name:o.name,module:n,instance:j,dylink:a,memoryBase:f,tableBase:d,initFn:E};return C.versions=X(C,p),C}_(J,"loadExtension");function Y(o,e){let t=o.instance.exports[o.initFn];if(typeof t!="function")throw new Error(`Extension "${o.name}" does not export init function "${o.initFn}"`);let r=e.qjs_get_context_ptr(),s=e.qjs_get_runtime_ptr(),i=t(r,s);if(i!==0)throw new Error(`Extension "${o.name}" init function returned error code ${i}`)}_(Y,"initExtension");async function ee(o,e,t,r,s,i){let n=[];for(let a of e){let p=o.find(l=>l.name===a.name);if(!p)throw new Error(`Extension "${a.name}" required by snapshot but not provided`);let u=await J(p,t,r,s,i,{memoryBase:a.memoryBase,tableBase:a.tableBase});u.initFn=a.initFn,n.push(u)}return n}_(ee,"restoreExtensions");var te="3.6.2",O=_(function(o,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var r,s;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=e[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=e[Symbol.dispose],t&&(s=r)}if(typeof r!="function")throw new TypeError("Object not disposable.");s&&(r=_(function(){try{s.call(this)}catch(i){return Promise.reject(i)}},"dispose")),o.stack.push({value:e,dispose:r,async:t})}else t&&o.stack.push({async:!0});return e},"__addDisposableResource"),N=(function(o){return function(e){function t(n){e.error=e.hasError?new o(n,e.error,"An error was suppressed during disposal."):n,e.hasError=!0}_(t,"fail");var r,s=0;function i(){for(;r=e.stack.pop();)try{if(!r.async&&s===1)return s=0,e.stack.push(r),Promise.resolve().then(i);if(r.dispose){var n=r.dispose.call(r.value);if(r.async)return s|=2,Promise.resolve(n).then(i,function(a){return t(a),i()})}else s|=1}catch(a){t(a)}if(s===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return _(i,"next"),i()}})(typeof SuppressedError=="function"?SuppressedError:function(o,e,t){var r=new Error(t);return r.name="SuppressedError",r.error=o,r.suppressed=e,r}),B=512*1024,L=1363825491,R=2,z=24,re=class P{static{_(this,"_QuickJS")}exports;module;instance;encoder=new TextEncoder;decoder=new TextDecoder;disposed=!1;hostCallbacks=new Map;nextInternalId=1;interruptHandler=null;unhandledRejectionHandler=null;moduleNormalizeHandler=null;moduleLoadHandler=null;timezoneOffsetHandler=null;_global=null;_versions=null;_undefined=null;_null=null;_true=null;_false=null;_ownedHandles=new Set;_activeScope=null;loadedExtensions=[];constructor(e){this.module=e,this.instance=null,this.exports=null}setInstance(e){this.instance=e,this.exports=e.exports}get versions(){if(this.assertNotDisposed(),!this._versions){let e={"quickjs-wasi":te,quickjs:this.readCString(this.exports.qjs_get_quickjs_version())};for(let t of this.loadedExtensions)t.versions&&Object.assign(e,t.versions);this._versions=e}return this._versions}get global(){return this._global||(this._global=new h(this,this.exports.qjs_get_global(),!0)),this._global}get undefined(){return this._undefined||(this._undefined=new h(this,this.exports.qjs_get_undefined(),!0)),this._undefined}get null(){return this._null||(this._null=new h(this,this.exports.qjs_get_null(),!0)),this._null}get true(){return this._true||(this._true=new h(this,this.exports.qjs_get_true(),!0)),this._true}get false(){return this._false||(this._false=new h(this,this.exports.qjs_get_false(),!0)),this._false}static async create(e){let t=P.normalizeOptions(e),r=await P.resolveModule(t.wasm),s=new P(r),{instance:i,wasiBuiltins:n,wasiUserOverrides:a,memoryProxy:p}=await P.instantiate(r,s,t.wasi);if(s.setInstance(i),s.exports._initialize(),(t.intrinsics!==void 0?s.exports.qjs_init2(t.intrinsics):s.exports.qjs_init())!==0)throw new Error("Failed to initialize QuickJS runtime");if(t.extensions){let u=i.exports;for(let l of t.extensions){let c=await J(l,u,n,a,p);s.loadedExtensions.push(c),Y(c,u)}}return P.applyLimits(s,t),s}static async restore(e,t){let r=P.normalizeOptions(t),s=await P.resolveModule(r.wasm),i=new P(s),{instance:n,wasiBuiltins:a,wasiUserOverrides:p,memoryProxy:u}=await P.instantiate(s,i,r.wasi);i.setInstance(n);let l=n.exports,c=i.exports.memory,f=c.buffer.byteLength/65536,d=Math.ceil(e.memory.byteLength/65536);if(d>f&&c.grow(d-f),e.extensions.length>0){let y=r.extensions??[];i.loadedExtensions=await ee(y,e.extensions,l,a,p,u)}return new Uint8Array(c.buffer).set(e.memory),i.exports.qjs_set_runtime_and_context(e.runtimePtr,e.contextPtr),i.exports.__stack_pointer.value=e.stackPointer,P.applyLimits(i,r),i}static serializeSnapshot(e){let t=new TextEncoder,r=4,s=[],i=[];for(let c of e.extensions){let f=t.encode(c.name),d=t.encode(c.initFn);s.push(f),i.push(d),r+=4+f.length+4+4+4+d.length}let n=z+r+e.memory.byteLength,a=new ArrayBuffer(n),p=new DataView(a),u=new Uint8Array(a);p.setUint32(0,L,!1),p.setUint8(4,R),p.setUint32(8,e.memory.byteLength,!0),p.setUint32(12,e.stackPointer,!0),p.setUint32(16,e.runtimePtr,!0),p.setUint32(20,e.contextPtr,!0);let l=z;p.setUint32(l,e.extensions.length,!0),l+=4;for(let c=0;c<e.extensions.length;c++){let f=e.extensions[c],d=s[c],y=i[c];p.setUint32(l,d.length,!0),l+=4,u.set(d,l),l+=d.length,p.setUint32(l,f.memoryBase,!0),l+=4,p.setUint32(l,f.tableBase,!0),l+=4,p.setUint32(l,y.length,!0),l+=4,u.set(y,l),l+=y.length}return u.set(e.memory,l),u}static deserializeSnapshot(e){if(e.length<z)throw new Error("Invalid snapshot: too small");let t=new DataView(e.buffer,e.byteOffset,e.byteLength),r=t.getUint32(0,!1);if(r!==L)throw new Error(`Invalid snapshot: bad magic (expected 0x${L.toString(16)}, got 0x${r.toString(16)})`);let s=t.getUint8(4);if(s!==R&&s!==1)throw new Error(`Unsupported snapshot version: ${s} (expected ${R})`);let i=t.getUint32(8,!0),n=t.getUint32(12,!0),a=t.getUint32(16,!0),p=t.getUint32(20,!0),u=[],l=z;if(s>=2){let f=t.getUint32(24,!0),d=28,y=new TextDecoder;for(let g=0;g<f;g++){let T=t.getUint32(d,!0);d+=4;let q=y.decode(e.slice(d,d+T));d+=T;let w=t.getUint32(d,!0);d+=4;let b=t.getUint32(d,!0);d+=4;let j=t.getUint32(d,!0);d+=4;let x=y.decode(e.slice(d,d+j));d+=j,u.push({name:q,memoryBase:w,tableBase:b,initFn:x})}l=d}let c=l+i;if(e.length<c)throw new Error(`Invalid snapshot: expected ${c} bytes, got ${e.length}`);return{memory:e.slice(l,l+i),stackPointer:n,runtimePtr:a,contextPtr:p,extensions:u}}static normalizeOptions(e){if(!e)return{wasm:void 0};if(e instanceof WebAssembly.Module)return{wasm:e};if(typeof e=="object"&&("wasm"in e||"wasi"in e||"memoryLimit"in e||"maxStackSize"in e||"interruptHandler"in e||"onUnhandledRejection"in e||"moduleLoader"in e||"intrinsics"in e||"extensions"in e||"timezoneOffset"in e)){let t=e;if(t.maxStackSize!==void 0&&(!Number.isInteger(t.maxStackSize)||t.maxStackSize<0||t.maxStackSize>B))throw new RangeError(`maxStackSize must be an integer between 0 and ${B}`);return t}return{wasm:e}}static applyLimits(e,t){t.memoryLimit!==void 0&&e.exports.qjs_set_memory_limit(t.memoryLimit),t.maxStackSize!==void 0&&e.exports.qjs_set_max_stack_size(t.maxStackSize),t.interruptHandler&&(e.interruptHandler=t.interruptHandler,e.exports.qjs_set_interrupt_handler(1)),t.onUnhandledRejection&&(e.unhandledRejectionHandler=t.onUnhandledRejection,e.exports.qjs_set_promise_rejection_handler(1)),t.moduleLoader&&(e.moduleLoadHandler=t.moduleLoader.load,e.moduleNormalizeHandler=t.moduleLoader.normalize??null,e.exports.qjs_set_module_loader(1));let r=t.timezoneOffset;if(typeof r=="function")e.timezoneOffsetHandler=s=>-r(s)*60;else if(typeof r=="number"){let s=-r*60;e.timezoneOffsetHandler=()=>s}else e.timezoneOffsetHandler=s=>-new Date(s*1e3).getTimezoneOffset()*60}static async resolveModule(e){if(e instanceof WebAssembly.Module)return e;if(e)return WebAssembly.compile(e);throw new TypeError("QuickJS: `wasm` option is required. Provide WASM bytes or a compiled `WebAssembly.Module`. The binary is shipped at `quickjs-wasi/quickjs.wasm` and can be loaded via your environment's preferred mechanism (e.g. `fetch()`, `node:fs/promises`, or a bundler import like Vite's `?url`).")}static async instantiate(e,t,r){let s=null,i=new Proxy({},{get(w,b){return s[b]}}),n=V(()=>s),a=r?r(i):void 0,p={...n,...a},u=_((w,b,j,x,E)=>t.handleHostCall(w,b,j,x,E),"hostCall"),l=_(()=>t.interruptHandler&&t.interruptHandler()?1:0,"hostInterrupt"),c=_((w,b,j)=>{if(!t.unhandledRejectionHandler){t.exports.qjs_free_value(w),t.exports.qjs_free_value(b);return}let x=new h(t,w),E=new h(t,b);try{t.unhandledRejectionHandler(x,E,j!==0)}finally{x.dispose(),E.dispose()}},"hostPromiseRejection"),f=_(w=>{let b=t.newError(w instanceof Error?w:String(w));t.exports.qjs_throw(b.ptr),b.dispose()},"throwIntoContext"),d=_((w,b)=>{if(typeof w=="string")return w;let j=w!==null&&typeof w=="object"&&typeof w.then=="function"?"a Promise":`type ${typeof w}`;throw new TypeError(`moduleLoader.${b} must synchronously return a string (got ${j}). Async module loading is not supported. Pre-fetch module sources instead (see the "ES Modules" section of the quickjs-wasi README).`)},"assertSyncString"),y=_((w,b)=>{if(!t.moduleNormalizeHandler){let E=t.readCString(b);return t.writeString(E).ptr}let j=t.readCString(w),x=t.readCString(b);try{let E=d(t.moduleNormalizeHandler(j,x),"normalize");return t.writeString(E).ptr}catch(E){return f(E),0}},"hostModuleNormalize"),g=_((w,b)=>{if(!t.moduleLoadHandler)return 0;let j=t.readCString(w);try{let x=d(t.moduleLoadHandler(j),"load"),{ptr:E,len:C}=t.writeString(x);return new Uint32Array(t.exports.memory.buffer,b,1)[0]=C,E}catch(x){return f(x),0}},"hostModuleLoad"),T=_((w,b)=>{let j=Number(BigInt(w)<<32n|BigInt(b>>>0));return t.timezoneOffsetHandler?t.timezoneOffsetHandler(j):0},"hostGetTimezoneOffset"),q=await WebAssembly.instantiate(e,{env:{host_call:u,host_interrupt:l,host_promise_rejection:c,host_module_normalize:y,host_module_load:g,host_get_timezone_offset:T},wasi_snapshot_preview1:p});return s=q.exports.memory,{instance:q,wasiBuiltins:n,wasiUserOverrides:a,memoryProxy:i}}handleHostCall(e,t,r,s,i){let n=this.decoder.decode(new Uint8Array(this.exports.memory.buffer,e,t)),a=this.hostCallbacks.get(n);if(!a){let l=this.newError(`Host callback "${n}" is not registered: it was unregistered, its ephemeral function handle was disposed, or it was never re-registered after a snapshot restore.`);return this.exports.qjs_throw(l.ptr),l.dispose(),0}let p=new h(this,r,!1,!0),u=[];if(s>0&&i!==0){let l=new DataView(this.exports.memory.buffer);for(let c=0;c<s;c++){let f=l.getUint32(i+c*4,!0);u.push(new h(this,f,!1,!0))}}try{let l=a.call(p,...u);return this.exports.qjs_dup_value(l.ptr)}catch(l){let c=this.newError(l instanceof Error?l:String(l));return this.exports.qjs_throw(c.ptr),c.dispose(),0}}writeString(e){let t=ne(e),r=this.exports.wasm_malloc(t.length+1);if(r===0)throw new Error("wasm_malloc failed");let s=new Uint8Array(this.exports.memory.buffer);return s.set(t,r),s[r+t.length]=0,{ptr:r,len:t.length}}readCString(e){let t=new Uint8Array(this.exports.memory.buffer),r=e;for(;t[r]!==0;)r++;return this.decoder.decode(t.slice(e,r))}throwIfException(e){if(this.exports.qjs_is_exception(e.ptr)!==0){let t=this.getException();throw e.dispose(),this._ownedHandles.add(t),new U(t)}return e}evalCode(e,t="<eval>",r=0){this.assertNotDisposed();let s=this.writeString(e),i=this.writeString(t),n=this.exports.qjs_eval(s.ptr,s.len,i.ptr,r);return this.exports.wasm_free(s.ptr),this.exports.wasm_free(i.ptr),this.throwIfException(new h(this,n))}compile(e,t="<compile>",r=0,s=0){this.assertNotDisposed();let i=this.writeString(e),n=this.writeString(t),a=this.exports.wasm_malloc(4),p=this.exports.qjs_compile(i.ptr,i.len,n.ptr,r,s,a);if(this.exports.wasm_free(i.ptr),this.exports.wasm_free(n.ptr),p===0){this.exports.wasm_free(a);let c=this.getException();throw new Error(`Compilation error: ${c.toString()}`)}let u=new Uint32Array(this.exports.memory.buffer,a,1)[0];this.exports.wasm_free(a);let l=new Uint8Array(this.exports.memory.buffer,p,u).slice();return this.exports.wasm_free(p),l}evalBytecode(e){this.assertNotDisposed();let t=this.exports.wasm_malloc(e.byteLength);new Uint8Array(this.exports.memory.buffer,t,e.byteLength).set(e);let r=this.exports.qjs_eval_bytecode(t,e.byteLength);return this.exports.wasm_free(t),this.throwIfException(new h(this,r))}executePendingJobs(){this.assertNotDisposed();let e=0;for(;this.exports.qjs_is_job_pending();){if(this.exports.qjs_execute_pending_job()<0){let t=this.getException();throw new Error(`Job execution error: ${t.toString()}`)}e++}return e}runGC(){this.assertNotDisposed(),this.exports.qjs_run_gc()}get gcThreshold(){return this.assertNotDisposed(),this.exports.qjs_get_gc_threshold()}set gcThreshold(e){this.assertNotDisposed(),this.exports.qjs_set_gc_threshold(e)}getMemoryUsage(){this.assertNotDisposed();let e=this.exports.wasm_malloc(208);this.exports.qjs_compute_memory_usage(e);let t=new BigInt64Array(this.exports.memory.buffer,e,26),r={mallocSize:Number(t[0]),mallocLimit:Number(t[1]),memoryUsedSize:Number(t[2]),mallocCount:Number(t[3]),memoryUsedCount:Number(t[4]),atomCount:Number(t[5]),atomSize:Number(t[6]),strCount:Number(t[7]),strSize:Number(t[8]),objCount:Number(t[9]),objSize:Number(t[10]),propCount:Number(t[11]),propSize:Number(t[12]),shapeCount:Number(t[13]),shapeSize:Number(t[14]),jsFuncCount:Number(t[15]),jsFuncSize:Number(t[16]),jsFuncCodeSize:Number(t[17]),jsFuncPc2lineCount:Number(t[18]),jsFuncPc2lineSize:Number(t[19]),cFuncCount:Number(t[20]),arrayCount:Number(t[21]),fastArrayCount:Number(t[22]),fastArrayElements:Number(t[23]),binaryObjectCount:Number(t[24]),binaryObjectSize:Number(t[25])};return this.exports.wasm_free(e),r}getGlobal(){return this.assertNotDisposed(),new h(this,this.exports.qjs_get_global())}newString(e){this.assertNotDisposed();let{ptr:t,len:r}=this.writeString(e),s=this.exports.qjs_new_string(t,r);return this.exports.wasm_free(t),new h(this,s)}newNumber(e){return this.assertNotDisposed(),new h(this,this.exports.qjs_new_number(e))}newBigInt(e){this.assertNotDisposed();let t=Number(e&0xffffffffn),r=Number(e>>32n&0xffffffffn);return new h(this,this.exports.qjs_new_big_int64(t,r))}newObject(){return this.assertNotDisposed(),new h(this,this.exports.qjs_new_object())}newArray(){return this.assertNotDisposed(),new h(this,this.exports.qjs_new_array())}newSymbolFor(e){this.assertNotDisposed();let{ptr:t,len:r}=this.writeString(e),s=new h(this,this.exports.qjs_new_symbol(t,r,1));return this.exports.wasm_free(t),s}newArrayBuffer(e){this.assertNotDisposed();let t=e instanceof ArrayBuffer?new Uint8Array(e):e,r=this.exports.wasm_malloc(t.length);if(r===0)throw new Error("wasm_malloc failed");new Uint8Array(this.exports.memory.buffer).set(t,r);let s=new h(this,this.exports.qjs_new_array_buffer(r,t.length));return this.exports.wasm_free(r),s}newUint8Array(e){this.assertNotDisposed();let t=this.exports.wasm_malloc(e.length);if(t===0)throw new Error("wasm_malloc failed");new Uint8Array(this.exports.memory.buffer).set(e,t);let r=new h(this,this.exports.qjs_new_uint8_array(t,e.length));return this.exports.wasm_free(t),r}getUndefined(){return this.assertNotDisposed(),new h(this,this.exports.qjs_get_undefined())}getNull(){return this.assertNotDisposed(),new h(this,this.exports.qjs_get_null())}getTrue(){return this.assertNotDisposed(),new h(this,this.exports.qjs_get_true())}getFalse(){return this.assertNotDisposed(),new h(this,this.exports.qjs_get_false())}newFunction(e,t){if(this.assertNotDisposed(),this.hostCallbacks.has(e))throw new Error(`Host callback with name "${e}" is already registered`);this.hostCallbacks.set(e,t);let{ptr:r,len:s}=this.writeString(e),i=this.exports.qjs_new_host_function(r,s,0);return this.exports.wasm_free(r),new h(this,i)}withScope(e){this.assertNotDisposed();let t=this._activeScope,r=new Set;this._activeScope=r;let s={escape:_(i=>(r.delete(i),t?.add(i),i),"escape")};try{return e(s)}finally{this._activeScope=t;for(let i of r)i.dispose()}}exportHandle(e){if(this.assertNotDisposed(),e.vm!==this)throw new Error("exportHandle: handle belongs to a different VM");if(e.disposed)throw new Error("exportHandle: handle is disposed");if(e._isBorrowed)throw new Error("exportHandle: cannot export a borrowed handle (host-callback this/argument); its box is freed when the callback returns. dup() it and export the duplicate.");return e.ptr}importHandle(e){if(this.assertNotDisposed(),!Number.isInteger(e)||e<=0||e>=this.exports.memory.buffer.byteLength)throw new Error(`importHandle: invalid token ${e}`);return new h(this,this.exports.qjs_dup_value(e))}newEphemeralFunction(e){this.assertNotDisposed();let t=`__ephemeral:${this.nextInternalId++}`;this.hostCallbacks.set(t,e);let{ptr:r,len:s}=this.writeString(t),i=this.exports.qjs_new_host_function(r,s,0);this.exports.wasm_free(r);let n=new h(this,i);return n._onDispose=()=>{this.hostCallbacks.delete(t)},n}unregisterHostCallback(e){return this.hostCallbacks.delete(e)}newInternalFunction(e,t){this.hostCallbacks.set(e,t);let{ptr:r,len:s}=this.writeString(e),i=this.exports.qjs_new_host_function(r,s,0);return this.exports.wasm_free(r),new h(this,i)}newPromise(){this.assertNotDisposed();let e=this.exports.wasm_malloc(4),t=this.exports.wasm_malloc(4),r=this.exports.qjs_new_promise(e,t),s=new DataView(this.exports.memory.buffer),i=s.getUint32(e,!0),n=s.getUint32(t,!0);this.exports.wasm_free(e),this.exports.wasm_free(t);let a=new h(this,r),p=new h(this,i),u=new h(this,n),l=this;l._ownedHandles.add(p),l._ownedHandles.add(u);let c=null;return{handle:a,get settled(){if(!c){let f;c=new Promise(g=>{f=g});let d=`__settle:${l.nextInternalId++}`,y=l.newInternalFunction(d,()=>(f(),l.hostCallbacks.delete(d),l.undefined));l.promiseThenRaw(a,y,y).dispose(),y.dispose()}return c},resolve(f){l.callFunctionRaw(p,l.undefined,f).dispose(),l._ownedHandles.delete(p),p.dispose()},reject(f){l.callFunctionRaw(u,l.undefined,f).dispose(),l._ownedHandles.delete(u),u.dispose()}}}resolvePromise(e){if(this.assertNotDisposed(),!this.exports.qjs_is_promise(e.ptr))return Promise.resolve({value:e.dup()});let t=this.exports.qjs_promise_state(e.ptr);return t===1?Promise.resolve({value:new h(this,this.exports.qjs_promise_result(e.ptr))}):t===2?Promise.resolve({error:new h(this,this.exports.qjs_promise_result(e.ptr))}):new Promise(r=>{let s=this.nextInternalId++,i=`__onFulfilled:${s}`,n=`__onRejected:${s}`,a=this.newInternalFunction(i,(...u)=>{let l=u[0]?.dup()??this.undefined;return this.hostCallbacks.delete(i),this.hostCallbacks.delete(n),r({value:l}),this.undefined}),p=this.newInternalFunction(n,(...u)=>{let l=u[0]?.dup()??this.undefined;return this.hostCallbacks.delete(i),this.hostCallbacks.delete(n),r({error:l}),this.undefined});this.promiseThenRaw(e,a,p).dispose(),a.dispose(),p.dispose()})}promiseThenRaw(e,t,r){return new h(this,this.exports.qjs_promise_then(e.ptr,t.ptr,r.ptr))}markPromiseHandled(e){this.assertNotDisposed(),this.exports.qjs_promise_mark_as_handled(e.ptr)}callFunction(e,t,...r){return this.throwIfException(this.callFunctionRaw(e,t,...r))}construct(e,...t){this.assertNotDisposed();let r=t.length,s=0;if(r>0){s=this.exports.wasm_malloc(r*4);let n=new DataView(this.exports.memory.buffer);for(let a=0;a<r;a++)n.setUint32(s+a*4,t[a].ptr,!0)}let i=this.exports.qjs_call_constructor(e.ptr,r,s);return s&&this.exports.wasm_free(s),this.throwIfException(new h(this,i))}callFunctionRaw(e,t,...r){this.assertNotDisposed();let s=r.length,i=0;if(s>0){i=this.exports.wasm_malloc(s*4);let a=new DataView(this.exports.memory.buffer);for(let p=0;p<s;p++)a.setUint32(i+p*4,r[p].ptr,!0)}let n=this.exports.qjs_call(e.ptr,t.ptr,s,i);return i&&this.exports.wasm_free(i),new h(this,n)}setProp(e,t,r){if(this.assertNotDisposed(),typeof t=="string"){let{ptr:s}=this.writeString(t);this.exports.qjs_set_prop_string(e.ptr,s,r.ptr),this.exports.wasm_free(s)}else this.exports.qjs_set_prop_value(e.ptr,t.ptr,r.ptr)}defineProp(e,t,r,s){this.assertNotDisposed();let i=0;if(s?.configurable&&(i|=1),s?.writable&&(i|=2),s?.enumerable&&(i|=4),typeof t=="string"){let{ptr:n}=this.writeString(t);this.exports.qjs_define_prop_string(e.ptr,n,r.ptr,i),this.exports.wasm_free(n)}else this.exports.qjs_define_prop_value(e.ptr,t.ptr,r.ptr,i)}getProp(e,t){return this.assertNotDisposed(),new h(this,this.exports.qjs_get_prop_value(e.ptr,t.ptr))}getException(){return this.assertNotDisposed(),new h(this,this.exports.qjs_get_exception())}newError(e){this.assertNotDisposed();let t=this.exports.qjs_new_error(),r=new h(this,t);if(typeof e=="string"){let s=this.newString(e);r.setProp("message",s),s.dispose()}else{let s=this.newString(e.message);if(r.setProp("message",s),s.dispose(),e.name){let i=this.newString(e.name);r.setProp("name",i),i.dispose()}if(e.stack){let i=this.newString(e.stack);r.setProp("stack",i),i.dispose()}}return r}typeof(e){this.assertNotDisposed();let t=this.exports;return t.qjs_is_undefined(e.ptr)?"undefined":t.qjs_is_null(e.ptr)?"object":t.qjs_is_bool(e.ptr)?"boolean":t.qjs_is_number(e.ptr)?"number":t.qjs_is_big_int(e.ptr)?"bigint":t.qjs_is_string(e.ptr)?"string":t.qjs_is_symbol(e.ptr)?"symbol":t.qjs_is_function(e.ptr)?"function":t.qjs_is_object(e.ptr)?"object":"unknown"}dump(e){return this.assertNotDisposed(),this._dump(e,new Map)}_dump(e,t){let r=this.exports;if(!r.qjs_is_undefined(e.ptr)){if(r.qjs_is_null(e.ptr))return null;if(r.qjs_is_bool(e.ptr))return r.qjs_get_bool(e.ptr)!==0;if(r.qjs_is_number(e.ptr))return r.qjs_get_float64(e.ptr);if(r.qjs_is_string(e.ptr))return e.toString();if(r.qjs_is_big_int(e.ptr))return e.toBigInt();if(r.qjs_is_symbol(e.ptr)){let s=r.wasm_malloc(4),i=r.qjs_get_symbol_description(e.ptr,s),n=new DataView(r.memory.buffer).getUint32(s,!0);if(r.wasm_free(s),i===1){let a=new h(this,n),p=a.toString();return a.dispose(),Symbol.for(p)}else if(i===2){new h(this,n).dispose();return}return}if(r.qjs_is_array_buffer(e.ptr))return e.toArrayBuffer();if(r.qjs_is_exception(e.ptr)){let s=this.getException(),i=s.toString();return s.dispose(),new Error(i)}if(!r.qjs_is_function(e.ptr)){if(r.qjs_is_object(e.ptr)){let s=r.qjs_get_value_ptr(e.ptr);if(s){let i=t.get(s);if(i!==void 0)return i}}if(r.qjs_is_object(e.ptr)){let s=r.wasm_malloc(4),i=r.wasm_malloc(4),n=r.wasm_malloc(4),a=r.qjs_get_typed_array_buffer(e.ptr,s,i,n),p=new h(this,a);if(r.qjs_is_exception(p.ptr)===0){let u=new DataView(r.memory.buffer),l=u.getUint32(s,!0),c=u.getUint32(i,!0),f=u.getUint32(n,!0);r.wasm_free(s),r.wasm_free(i),r.wasm_free(n);let d=r.wasm_malloc(4),y=r.qjs_get_array_buffer(p.ptr,d);if(r.wasm_free(d),p.dispose(),y!==0){let g=new Uint8Array(r.memory.buffer,y+l,c).slice();switch(f){case 1:return g;case 2:return new Uint16Array(g.buffer);case 4:return new Uint32Array(g.buffer);case 8:return new Float64Array(g.buffer);default:return g}}}else p.dispose(),r.wasm_free(s),r.wasm_free(i),r.wasm_free(n)}if(r.qjs_is_array(e.ptr)){let s=e.getProp("length"),i=r.qjs_get_float64(s.ptr);s.dispose();let n=[],a=r.qjs_get_value_ptr(e.ptr);a&&t.set(a,n);for(let p=0;p<i;p++){let u=r.qjs_get_prop_uint32(e.ptr,p),l=new h(this,u);n.push(this._dump(l,t)),l.dispose()}return n}if(r.qjs_is_error(e.ptr)){let s=e.getProp("name"),i=e.getProp("message"),n=e.getProp("stack"),a=s.isUndefined?"Error":s.toString(),p=i.isUndefined?"":i.toString(),u=n.isUndefined?void 0:n.toString();s.dispose(),i.dispose(),n.dispose();let l=new Error(p);return l.name=a,u!==void 0&&(l.stack=u),l}if(r.qjs_is_object(e.ptr)){let s=r.qjs_get_own_property_names(e.ptr),i=new h(this,s);if(r.qjs_is_exception(i.ptr)!==0)return i.dispose(),{};let n=i.getProp("length"),a=r.qjs_get_float64(n.ptr);n.dispose();let p={},u=r.qjs_get_value_ptr(e.ptr);u&&t.set(u,p);for(let l=0;l<a;l++){let c=r.qjs_get_prop_uint32(i.ptr,l),f=new h(this,c),d=f.toString();f.dispose();let y=e.getProp(d);p[d]=this._dump(y,t),y.dispose()}return i.dispose(),p}}}}hostToHandle(e){if(this.assertNotDisposed(),e===void 0)return this.undefined;if(e===null)return this.null;if(e===!0)return this.true;if(e===!1)return this.false;if(typeof e=="number")return this.newNumber(e);if(typeof e=="string")return this.newString(e);if(typeof e=="bigint")return this.newBigInt(e);if(typeof e=="symbol"){let t=Symbol.keyFor(e);if(t!==void 0)return this.newSymbolFor(t);throw new Error("Cannot convert local symbol to QuickJS handle. Use Symbol.for() for cross-boundary symbols.")}if(e instanceof Promise){let t=this.newPromise();return e.then(r=>{t.resolve(this.hostToHandle(r)),this.executePendingJobs()},r=>{t.reject(this.hostToHandle(r)),this.executePendingJobs()}),t.handle}if(e instanceof Error)return this.newError(e);if(e instanceof ArrayBuffer)return this.newArrayBuffer(e);if(e instanceof Uint8Array)return this.newUint8Array(e);if(ArrayBuffer.isView(e))return this.newArrayBuffer(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));if(Array.isArray(e)){let t=this.newArray();for(let r=0;r<e.length;r++){let s=this.hostToHandle(e[r]);this.exports.qjs_set_prop_uint32(t.ptr,r,s.ptr),s.dispose()}return t}if(typeof e=="object"&&e!==null){let t=this.newObject();for(let[r,s]of Object.entries(e)){let i=this.hostToHandle(s);t.setProp(r,i),i.dispose()}return t}return this.undefined}snapshot(){return this.assertNotDisposed(),{memory:new Uint8Array(this.exports.memory.buffer).slice(),stackPointer:this.exports.__stack_pointer.value,runtimePtr:this.exports.qjs_get_runtime_ptr(),contextPtr:this.exports.qjs_get_context_ptr(),extensions:this.loadedExtensions.map(e=>({name:e.name,memoryBase:e.memoryBase,tableBase:e.tableBase,initFn:e.initFn}))}}registerHostCallback(e,t){this.hostCallbacks.set(e,t)}dispose(){this.disposed||(this.disposed=!0,this._global=null,this._undefined=null,this._null=null,this._true=null,this._false=null,this._ownedHandles.clear(),this.hostCallbacks.clear(),this._activeScope=null,this.exports=null,this.instance=null,this.module=null)}[Symbol.dispose](){this.dispose()}assertNotDisposed(){if(this.disposed)throw new Error("QuickJS instance has been disposed")}_getExports(){return this.exports}_getMemory(){return this.exports.memory}_writeString(e){return this.writeString(e)}_readCString(e){return this.readCString(e)}};function D(o){return o.includes("\0")||M.test(o)}_(D,"stringKeyNeedsValuePath");var se=new TextDecoder,ie=new TextEncoder,M=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF]))|(?:(?<![\uD800-\uDBFF])[\uDC00-\uDFFF])/;function ne(o){if(!M.test(o))return ie.encode(o);let e=[];for(let t=0;t<o.length;t++){let r=o.charCodeAt(t);if(r<128)e.push(r);else if(r<2048)e.push(192|r>>6,128|r&63);else if(r>=55296&&r<=56319&&t+1<o.length){let s=o.charCodeAt(t+1);if(s>=56320&&s<=57343){let i=65536+(r-55296<<10)+(s-56320);e.push(240|i>>18,128|i>>12&63,128|i>>6&63,128|i&63),t++;continue}e.push(224|r>>12,128|r>>6&63,128|r&63)}else e.push(224|r>>12,128|r>>6&63,128|r&63)}return new Uint8Array(e)}_(ne,"encodeWtf8");function oe(o){let e=!1;for(let s=0;s<o.length-1;s++)if(o[s]===237&&o[s+1]>=160&&o[s+1]<=191){e=!0;break}if(!e)return se.decode(o);let t="",r=0;for(;r<o.length;){let s=o[r];if(s<128)t+=String.fromCharCode(s),r+=1;else if(s<224)t+=String.fromCharCode((s&31)<<6|o[r+1]&63),r+=2;else if(s<240)t+=String.fromCharCode((s&15)<<12|(o[r+1]&63)<<6|o[r+2]&63),r+=3;else{let i=(s&7)<<18|(o[r+1]&63)<<12|(o[r+2]&63)<<6|o[r+3]&63;t+=String.fromCodePoint(i),r+=4}}return t}_(oe,"decodeWtf8");var U=class extends Error{static{_(this,"JSException")}handle;#e;#t;#r;constructor(o){let e={stack:[],error:void 0,hasError:!1};try{super(),this.handle=o,delete this.stack;let t=O(e,o.getProp("message"),!1);this.#e=o.getProp("name").consume(r=>r.isUndefined?"Error":r.toString()),this.#t=t.isUndefined?o.toString():t.toString(),this.#r=o.getProp("stack").consume(r=>r.isUndefined?void 0:r.toString())}catch(t){e.error=t,e.hasError=!0}finally{N(e)}}get name(){return this.#e}set name(o){this.#e=o}get message(){return this.#t}set message(o){this.#t=o}get stack(){return this.#r}set stack(o){this.#r=o}dispose(){this.handle.dispose()}[Symbol.dispose](){this.handle.dispose()}},h=class S{static{_(this,"_JSValueHandle")}vm;ptr;disposed_=!1;singleton;borrowed;_onDispose;constructor(e,t,r=!1,s=!1){this.vm=e,this.ptr=t,this.singleton=r,this.borrowed=s,!r&&!s&&e._activeScope?.add(this)}get _isBorrowed(){return this.borrowed}get disposed(){return this.disposed_}get isUndefined(){return this.vm._getExports().qjs_is_undefined(this.ptr)!==0}get isNull(){return this.vm._getExports().qjs_is_null(this.ptr)!==0}get isBool(){return this.vm._getExports().qjs_is_bool(this.ptr)!==0}get isNumber(){return this.vm._getExports().qjs_is_number(this.ptr)!==0}get isString(){return this.vm._getExports().qjs_is_string(this.ptr)!==0}get isSymbol(){return this.vm._getExports().qjs_is_symbol(this.ptr)!==0}get isBigInt(){return this.vm._getExports().qjs_is_big_int(this.ptr)!==0}get isObject(){return this.vm._getExports().qjs_is_object(this.ptr)!==0}get isArray(){return this.vm._getExports().qjs_is_array(this.ptr)!==0}get isFunction(){return this.vm._getExports().qjs_is_function(this.ptr)!==0}get isError(){return this.vm._getExports().qjs_is_error(this.ptr)!==0}get isPromise(){return this.vm._getExports().qjs_is_promise(this.ptr)!==0}get isArrayBuffer(){return this.vm._getExports().qjs_is_array_buffer(this.ptr)!==0}get isProxy(){return this.vm._getExports().qjs_is_proxy(this.ptr)!==0}get isMap(){return this.vm._getExports().qjs_is_map(this.ptr)!==0}get isSet(){return this.vm._getExports().qjs_is_set(this.ptr)!==0}get isDate(){return this.vm._getExports().qjs_is_date(this.ptr)!==0}get isRegExp(){return this.vm._getExports().qjs_is_regexp(this.ptr)!==0}get isWeakRef(){return this.vm._getExports().qjs_is_weak_ref(this.ptr)!==0}get isWeakMap(){return this.vm._getExports().qjs_is_weak_map(this.ptr)!==0}get isWeakSet(){return this.vm._getExports().qjs_is_weak_set(this.ptr)!==0}get isDataView(){return this.vm._getExports().qjs_is_data_view(this.ptr)!==0}get identity(){return this.vm._getExports().qjs_get_value_ptr(this.ptr)}toBoolean(){return this.vm._getExports().qjs_get_bool(this.ptr)!==0}get classId(){return this.vm._getExports().qjs_get_class_id(this.ptr)}get className(){let e=new S(this.vm,this.vm._getExports().qjs_get_class_name(this.ptr));if(this.vm._getExports().qjs_is_exception(e.ptr)!==0)throw e.dispose(),new U(this.vm.getException());try{return e.isUndefined?void 0:e.toString()}finally{e.dispose()}}get promiseState(){return this.vm._getExports().qjs_promise_state(this.ptr)}get typeof(){return this.vm.typeof(this)}get length(){let e=this.getProp("length"),t=e.toNumber();return e.dispose(),t}get constructorName(){let e=this.getProp("constructor");if(e.isUndefined||e.isNull){e.dispose();return}let t=e.getProp("name");if(e.dispose(),t.isUndefined||t.isNull){t.dispose();return}let r=t.toString();return t.dispose(),r}keys(){let e=this.vm._getExports(),t=e.qjs_get_own_property_names(this.ptr),r=new S(this.vm,t);if(e.qjs_is_exception(r.ptr)!==0)return r.dispose(),[];let s=r.getProp("length"),i=e.qjs_get_float64(s.ptr);s.dispose();let n=[];for(let a=0;a<i;a++){let p=e.qjs_get_prop_uint32(r.ptr,a),u=new S(this.vm,p);n.push(u.toString()),u.dispose()}return r.dispose(),n}getOwnPropertyNames(){let e=this.vm._getExports(),t=e.qjs_get_own_property_names_all(this.ptr),r=new S(this.vm,t);if(e.qjs_is_exception(r.ptr)!==0)return r.dispose(),[];let s=r.getProp("length"),i=e.qjs_get_float64(s.ptr);s.dispose();let n=[];for(let a=0;a<i;a++){let p=e.qjs_get_prop_uint32(r.ptr,a),u=new S(this.vm,p);n.push(u.toString()),u.dispose()}return r.dispose(),n}getOwnPropertyKeys(){let e=this.vm._getExports(),t=e.qjs_get_own_property_keys(this.ptr),r=new S(this.vm,t);if(e.qjs_is_exception(r.ptr)!==0)return r.dispose(),[];let s=r.getProp("length"),i=e.qjs_get_float64(s.ptr);s.dispose();let n=[];for(let a=0;a<i;a++){let p=e.qjs_get_prop_uint32(r.ptr,a),u=new S(this.vm,p);u.isSymbol?n.push(u):(n.push(u.toString()),u.dispose())}return r.dispose(),n}getOwnPropertyDescriptor(e){let t={stack:[],error:void 0,hasError:!1};try{let r=this.vm._getExports(),s,i;typeof e=="string"?(s=this.vm.newString(e),i=s.ptr):i=e.ptr;let n=r.qjs_get_own_property_descriptor(this.ptr,i);if(s?.dispose(),n===0)return;let a=O(t,new S(this.vm,n),!1);if(r.qjs_is_exception(a.ptr)!==0)throw new U(this.vm.getException());let p=a.getProp("enumerable").consume(l=>r.qjs_get_bool(l.ptr)!==0),u=a.getProp("configurable").consume(l=>r.qjs_get_bool(l.ptr)!==0);return a.hasOwnProperty("value")?{value:a.getProp("value"),writable:a.getProp("writable").consume(l=>r.qjs_get_bool(l.ptr)!==0),enumerable:p,configurable:u}:{get:a.getProp("get"),set:a.getProp("set"),enumerable:p,configurable:u}}catch(r){t.error=r,t.hasError=!0}finally{N(t)}}hasOwnProperty(e){if(D(e)){let s={stack:[],error:void 0,hasError:!1};try{let i=O(s,this.vm.newString(e),!1);return this.vm._getExports().qjs_has_own_property_value(this.ptr,i.ptr)===1}catch(i){s.error=i,s.hasError=!0}finally{N(s)}}let{ptr:t}=this.vm._writeString(e),r=this.vm._getExports().qjs_has_own_property(this.ptr,t);return this.vm._getExports().wasm_free(t),r===1}propertyIsEnumerable(e){if(D(e)){let s={stack:[],error:void 0,hasError:!1};try{let i=O(s,this.vm.newString(e),!1);return this.vm._getExports().qjs_property_is_enumerable_value(this.ptr,i.ptr)===1}catch(i){s.error=i,s.hasError=!0}finally{N(s)}}let{ptr:t}=this.vm._writeString(e),r=this.vm._getExports().qjs_property_is_enumerable(this.ptr,t);return this.vm._getExports().wasm_free(t),r===1}getPrototypeOf(){let e=this.vm._getExports().qjs_get_prototype_of(this.ptr);return new S(this.vm,e)}getProxyTarget(){let e=this.vm._getExports().qjs_get_proxy_target(this.ptr),t=new S(this.vm,e);if(this.vm._getExports().qjs_is_exception(t.ptr)!==0)throw t.dispose(),new U(this.vm.getException());return t}getProxyHandler(){let e=this.vm._getExports().qjs_get_proxy_handler(this.ptr),t=new S(this.vm,e);if(this.vm._getExports().qjs_is_exception(t.ptr)!==0)throw t.dispose(),new U(this.vm.getException());return t}getProp(e){if(D(e)){let s={stack:[],error:void 0,hasError:!1};try{let i=O(s,this.vm.newString(e),!1);return this.vm.getProp(this,i)}catch(i){s.error=i,s.hasError=!0}finally{N(s)}}let{ptr:t}=this.vm._writeString(e),r=this.vm._getExports().qjs_get_prop_string(this.ptr,t);return this.vm._getExports().wasm_free(t),new S(this.vm,r)}setProp(e,t){if(D(e)){let s={stack:[],error:void 0,hasError:!1};try{let i=O(s,this.vm.newString(e),!1);this.vm.setProp(this,i,t);return}catch(i){s.error=i,s.hasError=!0}finally{N(s)}}let{ptr:r}=this.vm._writeString(e);this.vm._getExports().qjs_set_prop_string(this.ptr,r,t.ptr),this.vm._getExports().wasm_free(r)}defineProp(e,t,r){let s=0;if(r?.configurable&&(s|=1),r?.writable&&(s|=2),r?.enumerable&&(s|=4),typeof e=="string"){if(D(e)){let n={stack:[],error:void 0,hasError:!1};try{let a=O(n,this.vm.newString(e),!1);this.vm._getExports().qjs_define_prop_value(this.ptr,a.ptr,t.ptr,s);return}catch(a){n.error=a,n.hasError=!0}finally{N(n)}}let{ptr:i}=this.vm._writeString(e);this.vm._getExports().qjs_define_prop_string(this.ptr,i,t.ptr,s),this.vm._getExports().wasm_free(i)}else this.vm._getExports().qjs_define_prop_value(this.ptr,e.ptr,t.ptr,s)}toNumber(){return this.vm._getExports().qjs_get_float64(this.ptr)}toBigInt(){let e=this.vm._getExports(),t=e.wasm_malloc(4),r=e.wasm_malloc(4);if(e.qjs_get_big_int64(this.ptr,t,r)!==0)throw e.wasm_free(t),e.wasm_free(r),new Error("Failed to convert value to BigInt");let s=new DataView(e.memory.buffer),i=s.getUint32(t,!0),n=s.getInt32(r,!0);return e.wasm_free(t),e.wasm_free(r),BigInt(n)<<32n|BigInt(i)}toArrayBuffer(){let e=this.vm._getExports(),t=e.wasm_malloc(4);if(e.qjs_is_array_buffer(this.ptr)){let d=e.qjs_get_array_buffer(this.ptr,t);if(d===0)throw e.wasm_free(t),new Error("Failed to get ArrayBuffer data");let y=new DataView(e.memory.buffer).getUint32(t,!0);return e.wasm_free(t),new Uint8Array(e.memory.buffer,d,y).slice().buffer}e.wasm_free(t);let r=e.wasm_malloc(4),s=e.wasm_malloc(4),i=e.wasm_malloc(4),n=e.qjs_get_typed_array_buffer(this.ptr,r,s,i),a=new S(this.vm,n);if(this.vm._getExports().qjs_is_exception(a.ptr)!==0)throw a.dispose(),e.wasm_free(r),e.wasm_free(s),e.wasm_free(i),new Error("Value is not an ArrayBuffer or typed array");let p=new DataView(e.memory.buffer),u=p.getUint32(r,!0),l=p.getUint32(s,!0);e.wasm_free(r),e.wasm_free(s),e.wasm_free(i);let c=e.wasm_malloc(4),f=e.qjs_get_array_buffer(a.ptr,c);if(e.wasm_free(c),a.dispose(),f===0)throw new Error("Failed to get ArrayBuffer data from typed array");return new Uint8Array(e.memory.buffer,f+u,l).slice().buffer}toUint8Array(){return new Uint8Array(this.toArrayBuffer())}toString(){let e=this.vm._getExports(),t=e.wasm_malloc(4);if(t===0)throw new Error("wasm_malloc failed");try{let r=e.qjs_get_string_len(this.ptr,t);if(r===0)return"<null>";let s=new DataView(e.memory.buffer).getUint32(t,!0),i=new Uint8Array(e.memory.buffer,r,s),n=oe(i);return e.qjs_free_cstring(r),n}finally{e.wasm_free(t)}}consume(e){try{return e(this)}finally{this.dispose()}}dup(){return new S(this.vm,this.vm._getExports().qjs_dup_value(this.ptr))}dispose(){if(!(this.singleton||this.borrowed)&&!this.disposed_){this.disposed_=!0,this._onDispose?.(),this._onDispose=void 0;let e=this.vm._getExports();e&&e.qjs_free_value(this.ptr)}}[Symbol.dispose](){this.dispose()}},I="image expects a non-empty image URL string, an object with image_url, or a raw MCP image block",ae=`(function (bridge, toolsJson, globalsJson, storeJson) {
3
+ "use strict";
4
+
5
+ // Freeze every object reachable from the built-in globals, plus the intrinsics that are only
6
+ // reachable from instances (iterator and generator prototypes, %TypedArray%).
7
+ //
8
+ // Freezing alone breaks ordinary code through the "override mistake": a data property that is
9
+ // read-only on a prototype cannot be assigned on an instance either, so
10
+ // this.name = "MyError" in an Error subclass would throw. Commonly overridden properties
11
+ // become accessors whose setter defines an own property on the instance instead.
12
+ (function lockdown() {
13
+ const OVERRIDABLE = new Set(["constructor", "name", "message", "toString", "toLocaleString", "valueOf", "toJSON"]);
14
+ const seen = new Set([globalThis]);
15
+ const queue = [];
16
+ const add = (value) => {
17
+ if ((typeof value === "object" && value !== null) || typeof value === "function") {
18
+ if (!seen.has(value)) {
19
+ seen.add(value);
20
+ queue.push(value);
21
+ }
22
+ }
23
+ };
24
+
25
+ // Accessors from an object literal have no own prototype object, unlike function expressions,
26
+ // whose prototype.constructor would be converted again without end.
27
+ function allowOverride(object, key, value, enumerable) {
28
+ const { get, set } = Object.getOwnPropertyDescriptor(
29
+ {
30
+ get accessor() {
31
+ return value;
32
+ },
33
+ set accessor(next) {
34
+ if (this === object) {
35
+ throw new TypeError("Cannot assign to read only property '" + String(key) + "' of a built-in");
36
+ }
37
+ if ((typeof this !== "object" || this === null) && typeof this !== "function") return;
38
+ Object.defineProperty(this, key, { value: next, writable: true, enumerable: true, configurable: true });
39
+ },
40
+ },
41
+ "accessor",
42
+ );
43
+ Object.defineProperty(object, key, { get, set, enumerable, configurable: false });
44
+ add(get);
45
+ add(set);
46
+ }
47
+
48
+ for (const key of Reflect.ownKeys(globalThis)) {
49
+ const descriptor = Object.getOwnPropertyDescriptor(globalThis, key);
50
+ add(descriptor.value);
51
+ add(descriptor.get);
52
+ add(descriptor.set);
53
+ if ("value" in descriptor && descriptor.configurable) {
54
+ Object.defineProperty(globalThis, key, { writable: false, configurable: false });
55
+ }
56
+ }
57
+ add(Object.getPrototypeOf(function* () {}));
58
+ add(Object.getPrototypeOf(async function () {}));
59
+ add(Object.getPrototypeOf(async function* () {}));
60
+ add(Object.getPrototypeOf(Int8Array));
61
+ add(Object.getPrototypeOf([][Symbol.iterator]()));
62
+ add(Object.getPrototypeOf(new Map()[Symbol.iterator]()));
63
+ add(Object.getPrototypeOf(new Set()[Symbol.iterator]()));
64
+ add(Object.getPrototypeOf(""[Symbol.iterator]()));
65
+ add(Object.getPrototypeOf(/a/[Symbol.matchAll]("")));
66
+ if (typeof Iterator === "function") {
67
+ if (typeof Iterator.prototype.map === "function") add(Object.getPrototypeOf([].values().map((x) => x)));
68
+ if (typeof Iterator.from === "function") add(Object.getPrototypeOf(Iterator.from({ next() {} })));
69
+ }
70
+
71
+ while (queue.length > 0) {
72
+ const object = queue.pop();
73
+ add(Object.getPrototypeOf(object));
74
+ const descriptors = Object.getOwnPropertyDescriptors(object);
75
+ for (const key of Reflect.ownKeys(descriptors)) {
76
+ const descriptor = descriptors[key];
77
+ if ("value" in descriptor) {
78
+ add(descriptor.value);
79
+ if (
80
+ descriptor.writable &&
81
+ descriptor.configurable &&
82
+ (object === Object.prototype || OVERRIDABLE.has(key))
83
+ ) {
84
+ allowOverride(object, key, descriptor.value, descriptor.enumerable);
85
+ }
86
+ } else {
87
+ add(descriptor.get);
88
+ add(descriptor.set);
89
+ }
90
+ }
91
+ Object.freeze(object);
92
+ }
93
+ })();
94
+ const stringify = JSON.stringify;
95
+ const parse = JSON.parse;
96
+ const promiseThen = Promise.prototype.then;
97
+ const ErrorCtor = Error;
98
+ const TypeErrorCtor = TypeError;
99
+ const RangeErrorCtor = RangeError;
100
+ const pending = new Map();
101
+ let nextId = 1;
102
+ let finished = false;
103
+ // Thrown by exit() to unwind the script after it already reported success.
104
+ const EXIT = Object.freeze({});
105
+
106
+ function done(ok, payload, writes) {
107
+ if (finished) return;
108
+ finished = true;
109
+ bridge("done", ok, payload, writes);
110
+ }
111
+
112
+ function serialize(value) {
113
+ return value === undefined ? undefined : stringify(value);
114
+ }
115
+
116
+ // QuickJS stacks list frames only. Prefix "Name: message" like V8 so the
117
+ // text reads the same as a Node error, and drop this prelude's frames.
118
+ function errorText(error) {
119
+ const head = error.message ? error.name + ": " + error.message : String(error.name);
120
+ const frames =
121
+ typeof error.stack === "string"
122
+ ? error.stack.split("\\n").filter((line) => line.trim() && !line.includes("codemode-prelude.js"))
123
+ : [];
124
+ return [head, ...frames].join("\\n");
125
+ }
126
+
127
+ function format(value) {
128
+ if (typeof value === "string") return value;
129
+ if (value instanceof ErrorCtor) return errorText(value);
130
+ try {
131
+ const json = stringify(value);
132
+ return json === undefined ? String(value) : json;
133
+ } catch {
134
+ return String(value);
135
+ }
136
+ }
137
+
138
+ // The host requires string fields. A script can set an error's name or message to anything, so
139
+ // they are coerced, and a value whose coercion throws gets a placeholder.
140
+ function describeError(error) {
141
+ try {
142
+ if (error instanceof ErrorCtor) {
143
+ return stringify({ name: String(error.name), message: String(error.message), stack: errorText(error) });
144
+ }
145
+ return stringify({ message: String(format(error)) });
146
+ } catch {
147
+ return stringify({ message: "The script threw a value that cannot be described" });
148
+ }
149
+ }
150
+
151
+ function caller(kind, name, spread) {
152
+ return (...args) =>
153
+ new Promise((resolve, reject) => {
154
+ let json;
155
+ try {
156
+ json = serialize(spread ? args : args[0]);
157
+ } catch (error) {
158
+ reject(error);
159
+ return;
160
+ }
161
+ const id = nextId++;
162
+ pending.set(id, { resolve, reject });
163
+ bridge(kind, id, name, json);
164
+ });
165
+ }
166
+
167
+ const tools = Object.create(null);
168
+ const allTools = [];
169
+ for (const { name, jsName, description } of parse(toolsJson)) {
170
+ const fn = caller("call", name);
171
+ // The first tool wins when two names normalize to the same identifier.
172
+ if (!(jsName in tools)) {
173
+ tools[jsName] = fn;
174
+ allTools.push(Object.freeze({ name: jsName, description }));
175
+ }
176
+ if (!(name in tools)) tools[name] = fn;
177
+ }
178
+ Object.freeze(tools);
179
+ Object.freeze(allTools);
180
+
181
+ // Reading a member that does not exist throws an error that names the close matches, instead of
182
+ // a later "not a function". \`in\` checks still work.
183
+ const comparable = (name) => name.toLowerCase().replace(/[^a-z0-9]/g, "");
184
+ function guard(target, label, names, hint) {
185
+ return new Proxy(target, {
186
+ get(object, property, receiver) {
187
+ if (typeof property !== "string" || property in object || property in Object.prototype || property === "then" || property === "toJSON") {
188
+ return Reflect.get(object, property, receiver);
189
+ }
190
+ const wanted = comparable(property);
191
+ const exact = names.filter((name) => comparable(name) === wanted);
192
+ const close = exact.length > 0 ? exact : names.filter((name) => wanted && (comparable(name).includes(wanted) || wanted.includes(comparable(name))));
193
+ let message = label + "." + property + " does not exist.";
194
+ if (close.length > 0) message += " Did you mean " + close.slice(0, 5).map((name) => label + "." + name).join(", ") + "?";
195
+ else if (names.length <= 20) message += " Available: " + names.join(", ") + ".";
196
+ if (hint) message += " " + hint;
197
+ message += ' Check for a member with "' + property + '" in ' + label + ".";
198
+ throw new TypeErrorCtor(message);
199
+ },
200
+ });
201
+ }
202
+ const toolsProxy = guard(
203
+ tools,
204
+ "tools",
205
+ allTools.map((tool) => tool.name),
206
+ "ALL_TOOLS lists every tool; searchTools(query) finds tools by topic.",
207
+ );
208
+
209
+ const namespaces = new Map();
210
+ for (const { name, spread } of parse(globalsJson)) {
211
+ const fn = caller("global", name, spread);
212
+ const dot = name.indexOf(".");
213
+ if (dot === -1) {
214
+ Object.defineProperty(globalThis, name, { value: fn, enumerable: true });
215
+ continue;
216
+ }
217
+ const namespace = name.slice(0, dot);
218
+ if (!namespaces.has(namespace)) namespaces.set(namespace, Object.create(null));
219
+ namespaces.get(namespace)[name.slice(dot + 1)] = fn;
220
+ }
221
+ for (const [namespace, members] of namespaces) {
222
+ Object.freeze(members);
223
+ const value = guard(members, namespace, Object.keys(members));
224
+ Object.defineProperty(globalThis, namespace, { value, enumerable: true });
225
+ }
226
+
227
+ // key -> JSON text. Sizes count key and JSON characters.
228
+ const stored = new Map(Object.entries(parse(storeJson)));
229
+ const writes = new Map();
230
+ let storedChars = 0;
231
+ for (const [key, json] of stored) storedChars += key.length + json.length;
232
+
233
+ const STORE_HINT =
234
+ "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.";
235
+
236
+ function checkKey(name, key) {
237
+ if (typeof key !== "string") throw new TypeError(name + "() key must be a string");
238
+ }
239
+
240
+ function store(key, value) {
241
+ checkKey("store", key);
242
+ const previous = stored.has(key) ? key.length + stored.get(key).length : 0;
243
+ if (value === undefined) {
244
+ stored.delete(key);
245
+ storedChars -= previous;
246
+ writes.set(key, undefined);
247
+ return;
248
+ }
249
+ let json;
250
+ try {
251
+ json = stringify(value);
252
+ } catch (error) {
253
+ throw new TypeError("store(" + stringify(key) + ") value is not JSON-serializable: " + format(error));
254
+ }
255
+ if (json === undefined) {
256
+ throw new TypeError("store(" + stringify(key) + ") value is not JSON-serializable");
257
+ }
258
+ if (json.length > 262144) {
259
+ throw new RangeError(
260
+ "store(" + stringify(key) + ") value has " + json.length + " characters of JSON, more than the limit of 262144. " +
261
+ STORE_HINT,
262
+ );
263
+ }
264
+ const next = storedChars - previous + key.length + json.length;
265
+ if (next > 1048576) {
266
+ throw new RangeError(
267
+ "store is full: stored values would exceed 1048576 characters of JSON. Delete keys with store(key, undefined). " +
268
+ STORE_HINT,
269
+ );
270
+ }
271
+ stored.set(key, json);
272
+ storedChars = next;
273
+ writes.set(key, json);
274
+ }
275
+
276
+ function load(key) {
277
+ checkKey("load", key);
278
+ const json = stored.get(key);
279
+ return json === undefined ? undefined : parse(json);
280
+ }
281
+
282
+ function serializeWrites() {
283
+ const entries = [];
284
+ for (const [key, json] of writes) entries.push(json === undefined ? [key] : [key, json]);
285
+ return stringify(entries);
286
+ }
287
+
288
+ Object.defineProperty(globalThis, "store", { value: store, enumerable: true });
289
+ Object.defineProperty(globalThis, "load", { value: load, enumerable: true });
290
+
291
+ let outputChars = 0;
292
+ let outputItems = 0;
293
+
294
+ // Past the output limits the script fails: done() reports the error, so catching it does not
295
+ // resume output, and the host ends the script.
296
+ function output(kind, data, mimeType) {
297
+ if (finished) return;
298
+ outputChars += data.length;
299
+ outputItems++;
300
+ if (outputChars > 16777216 || outputItems > 100000) {
301
+ const error = new RangeErrorCtor(
302
+ "script output exceeded the limit of 16777216 characters or 100000 text(), image(), and console calls. " +
303
+ "Print a summary instead, or write large data to a file with a tool.",
304
+ );
305
+ done(false, describeError(error));
306
+ throw error;
307
+ }
308
+ bridge("output", kind, data, mimeType);
309
+ }
310
+
311
+ // Primitives become their string form, everything else JSON.
312
+ function outputText(value) {
313
+ if (value === undefined || value === null || typeof value !== "object" && typeof value !== "function") {
314
+ return String(value);
315
+ }
316
+ const json = stringify(value);
317
+ return json === undefined ? String(value) : json;
318
+ }
319
+
320
+ function text(value) {
321
+ let rendered;
322
+ try {
323
+ rendered = outputText(value);
324
+ } catch (error) {
325
+ throw new TypeErrorCtor(error instanceof ErrorCtor ? error.message : String(error));
326
+ }
327
+ output("text", rendered);
328
+ }
329
+
330
+ function imageUrl(value) {
331
+ if (typeof value === "string") return value;
332
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
333
+ throw new TypeErrorCtor(${JSON.stringify(I)});
334
+ }
335
+ if (value.image_url !== undefined) {
336
+ if (typeof value.image_url !== "string") throw new TypeErrorCtor(${JSON.stringify(I)});
337
+ return value.image_url;
338
+ }
339
+ if (typeof value.type !== "string") throw new TypeErrorCtor(${JSON.stringify(I)});
340
+ if (value.type !== "image") {
341
+ throw new TypeErrorCtor('image only accepts MCP image blocks, got "' + value.type + '"');
342
+ }
343
+ if (typeof value.data !== "string" || value.data === "") throw new TypeErrorCtor("image expected MCP image data");
344
+ if (value.data.toLowerCase().startsWith("data:")) return value.data;
345
+ return "data:;base64," + value.data;
346
+ }
347
+
348
+ // Base64 of the signatures of the formats providers accept inline (PNG, JPEG except
349
+ // JPEG-LS, GIF, "RIFF....WEBP"). Signatures start at byte 0, so their encodings are prefixes.
350
+ const IMAGE_SIGNATURES = [
351
+ ["image/png", /^iVBORw0KGg/],
352
+ ["image/jpeg", /^[/]9j[/](?!9)/],
353
+ ["image/gif", /^R0lGOD[dl]h/],
354
+ ["image/webp", /^UklG.{8}RUJQ/],
355
+ ];
356
+
357
+ function image(value) {
358
+ const url = imageUrl(value);
359
+ if (url === "") throw new TypeErrorCtor(${JSON.stringify(I)});
360
+ const colon = url.indexOf(":");
361
+ const scheme = colon === -1 ? "" : url.slice(0, colon).toLowerCase();
362
+ if (scheme === "http" || scheme === "https") {
363
+ throw new TypeErrorCtor("remote image URLs are not supported in tool outputs. Pass a base64 data URI instead");
364
+ }
365
+ const comma = url.indexOf(",");
366
+ const header = comma === -1 ? [] : url.slice(colon + 1, comma).split(";");
367
+ if (scheme !== "data" || comma === -1 || header.slice(1).every((part) => part.toLowerCase() !== "base64")) {
368
+ throw new TypeErrorCtor("invalid image output. Pass a base64 data URI instead");
369
+ }
370
+ // Providers reject the whole request on a bad image, and a persisted image block would be
371
+ // resent on every later turn. Line breaks from wrapped base64 are dropped. The declared type
372
+ // is ignored in favor of the detected one, as providers also reject mismatches.
373
+ const data = url.slice(comma + 1).replace(/\\s+/g, "");
374
+ if (data.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(data)) {
375
+ throw new TypeErrorCtor("invalid image output. The image data is not valid base64 (truncated or corrupted?)");
376
+ }
377
+ const head = data.slice(0, 16);
378
+ const signature = IMAGE_SIGNATURES.find(([, pattern]) => pattern.test(head));
379
+ if (!signature) {
380
+ throw new TypeErrorCtor("invalid image output. The image data is not a PNG, JPEG, GIF, or WebP image");
381
+ }
382
+ output("image", data, signature[0]);
383
+ }
384
+
385
+ function exit() {
386
+ let writesJson;
387
+ try {
388
+ writesJson = serializeWrites();
389
+ } catch (error) {
390
+ done(false, describeError(error));
391
+ throw EXIT;
392
+ }
393
+ done(true, undefined, writesJson);
394
+ throw EXIT;
395
+ }
396
+
397
+ const console = {};
398
+ for (const level of ["log", "info", "warn", "error", "debug"]) {
399
+ console[level] = (...args) => {
400
+ output("console", args.map(format).join(" "));
401
+ };
402
+ }
403
+ Object.freeze(console);
404
+
405
+ Object.defineProperty(globalThis, "tools", { value: toolsProxy, enumerable: true });
406
+ Object.defineProperty(globalThis, "ALL_TOOLS", { value: allTools, enumerable: true });
407
+ Object.defineProperty(globalThis, "console", { value: console, enumerable: true });
408
+ Object.defineProperty(globalThis, "text", { value: text, enumerable: true });
409
+ Object.defineProperty(globalThis, "image", { value: image, enumerable: true });
410
+ Object.defineProperty(globalThis, "exit", { value: exit, enumerable: true });
411
+
412
+ return {
413
+ settle(id, ok, payload) {
414
+ const entry = pending.get(id);
415
+ if (!entry) return;
416
+ pending.delete(id);
417
+ if (!ok) {
418
+ entry.reject(new ErrorCtor(payload));
419
+ return;
420
+ }
421
+ let value;
422
+ try {
423
+ value = payload === undefined ? undefined : parse(payload);
424
+ } catch (error) {
425
+ entry.reject(error);
426
+ return;
427
+ }
428
+ entry.resolve(value);
429
+ },
430
+ run(fn) {
431
+ let promise;
432
+ try {
433
+ promise = fn(toolsProxy, console);
434
+ } catch (error) {
435
+ done(false, describeError(error));
436
+ return;
437
+ }
438
+ promiseThen.call(
439
+ promise,
440
+ (value) => {
441
+ let json;
442
+ try {
443
+ json = serialize(value);
444
+ } catch (error) {
445
+ done(false, describeError(error));
446
+ return;
447
+ }
448
+ done(true, json, serializeWrites());
449
+ },
450
+ (error) => {
451
+ done(false, describeError(error));
452
+ },
453
+ );
454
+ },
455
+ stalled() {
456
+ if (finished || pending.size > 0) return false;
457
+ done(
458
+ false,
459
+ stringify({
460
+ name: "Error",
461
+ message:
462
+ "The script is waiting on a promise that can never settle: no tool call is pending, and timers do not exist here.",
463
+ }),
464
+ );
465
+ return true;
466
+ },
467
+ };
468
+ })`;function le(o){return typeof o=="object"&&o!==null&&o.type==="result"}_(le,"isHostToWorkerMessage");function A(o){F?.postMessage(o)}_(A,"post");function $(o){A({type:"crash",message:o instanceof Error?`${o.name}: ${o.message}`:String(o)})}_($,"crash");function pe(o){return{fd_write(e,t,r,s){let i=new DataView(o.buffer),n=0;for(let a=0;a<r;a++)n+=i.getUint32(t+a*8+4,!0);return i.setUint32(s,n,!0),0}}}_(pe,"discardOutput");function ue(o){let e=o.message?`${o.name}: ${o.message}`:o.name,t=o.stack?.trimEnd();return JSON.stringify({name:o.name,message:o.message,stack:t?`${e}
469
+ ${t}`:e})}_(ue,"describeException");async function de(o){let e=new Int32Array(o.interrupt),t=await re.create({wasm:o.wasm,memoryLimit:o.memoryLimitBytes,maxStackSize:B,interruptHandler:_(()=>Atomics.load(e,0)!==0,"interruptHandler"),wasi:pe}),r=t.newFunction("bridge",(l,c,f,d)=>{switch(l.toString()){case"call":case"global":A({type:"call",id:c.toNumber(),target:l.toString()==="call"?"tool":"global",name:f.toString(),args:d===void 0||d.isUndefined?void 0:d.toString()});break;case"output":A({type:"output",item:c.toString()==="image"?{type:"image",data:f.toString(),mimeType:d.toString()}:c.toString()==="console"?{type:"text",text:f.toString(),console:!0}:{type:"text",text:f.toString()}});break;case"done":c.toBoolean()?A({type:"done",ok:!0,value:f===void 0||f.isUndefined?void 0:f.toString(),writes:d.toString()}):A({type:"done",ok:!1,error:f.toString()});break}return t.undefined}),s=t.withScope(l=>l.escape(t.callFunction(t.evalCode(ae,"codemode-prelude.js"),t.undefined,r,t.newString(JSON.stringify(o.tools)),t.newString(JSON.stringify(o.globals)),t.newString(JSON.stringify(o.store))))),i=s.getProp("settle"),n=s.getProp("run"),a=s.getProp("stalled"),p=_(()=>{t.executePendingJobs(),t.callFunction(a,s).dispose()},"drain");F?.on("message",l=>{if(le(l))try{t.withScope(()=>{t.callFunction(i,s,t.newNumber(l.id),l.ok?t.true:t.false,l.payload===void 0?t.undefined:t.newString(l.payload))}),p()}catch(c){$(c)}});let u;try{u=t.evalCode(`(async (tools, console) => {${o.code}
470
+ })`,"codemode.js")}catch(l){if(!(l instanceof U))throw l;A({type:"done",ok:!1,error:ue(l)});return}t.callFunction(n,s,u).dispose(),u.dispose(),p()}_(de,"main"),F&&de(G).catch($);