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,489 @@
1
+ var ae=Object.defineProperty;var a=(e,t)=>ae(e,"name",{value:t,configurable:!0});import{createRequire as ie}from"node:module";const rt=ie(import.meta.url);import{Bm25Ranker as le,CODEMODE_DOCS_PATH as F,CODEMODE_STORE_ENTRY_TYPE as H,DEFAULT_TOOL_SEARCH_LIMIT as ce,combineUsage as ue,createToolSearchDocument as de,getCodemodeCallableTools as pe,parseCodemodeSource as fe,renderToolSample as me,toCodemodeDeclaration as ge,toCodemodeIdentifier as S}from"./chunk-Q6IMZXWD.js";import{formatSize as he,writeOutputFile as V}from"./chunk-ZKDITC7J.js";import{getCodemodeWorkerSpecifier as ye,getQuickJSWasmPath as be}from"./chunk-HC56T2OZ.js";import"./chunk-S3GGRYIO.js";import"./chunk-4L3WN2XY.js";import{Worker as we}from"node:worker_threads";import{readFile as ve}from"node:fs/promises";import{createRequire as Oe}from"node:module";var J=new Map;function K(e){let t=e??Oe(import.meta.url).resolve("quickjs-wasi/quickjs.wasm"),r=J.get(t);if(!r){let{WebAssembly:o}=globalThis;r=ve(t).then(s=>o.compile(s)).catch(s=>{throw J.delete(t),s}),J.set(t,r)}return r}a(K,"loadQuickJSWasm");function ke(e){if(typeof e!="object"||e===null)return!1;let t=e.type;return t==="call"||t==="output"||t==="done"||t==="crash"}a(ke,"isWorkerToHostMessage");var Ee=3e5,Te=/^[A-Za-z_$][A-Za-z0-9_$]*$/,je=new Set(["tools","ALL_TOOLS","console","text","image","exit","globalThis","store","load"]);function M(e){return e instanceof Error?e.message:String(e)}a(M,"errorMessage");function xe(e){let t={};for(let[r,o]of Object.entries(e??{})){let s=JSON.stringify(o);s!==void 0&&(t[r]=s)}return t}a(xe,"serializeStore");var O=class extends Error{static{a(this,"BridgeError")}};function _(e,t){try{return JSON.parse(e)}catch{throw new O(`${t} is not valid JSON`)}}a(_,"parseBridgeJson");function Se(e){let t=_(e,"store writes");if(!Array.isArray(t))throw new O("store writes are not an array");let r={set:{},delete:[]};for(let o of t){if(!Array.isArray(o)||typeof o[0]!="string"||(o.length===2?typeof o[1]!="string":o.length!==1))throw new O("store writes contain a malformed entry");let[s,n]=o;n===void 0?r.delete.push(s):r.set[s]=_(n,`store value for ${JSON.stringify(s)}`)}return r}a(Se,"parseStoreWrites");function $e(e){let t=_(e,"script error");if(typeof t!="object"||t===null)throw new O("script error is not an object");let{name:r,message:o,stack:s}=t;if(typeof o!="string"||r!==void 0&&typeof r!="string"||s!==void 0&&typeof s!="string")throw new O("script error is malformed");return{kind:"script",name:r,message:o,stack:s}}a($e,"parseScriptError");function Ce(){return new URL(import.meta.url.endsWith(".ts")?"./worker.ts":"./worker.js",import.meta.url)}a(Ce,"defaultWorkerUrl");var Ne=class{static{a(this,"Execution")}promise;resolveResult;worker;interrupt=new SharedArrayBuffer(4);tools;globals;signal;timer;output=[];calls=[];pending=new Map;finished=!1;constructor(e){this.promise=new Promise(t=>{this.resolveResult=t}),this.tools=e.tools,this.globals=e.globals,this.signal=e.signal,Number.isFinite(e.timeoutMs)&&(this.timer=setTimeout(()=>{this.finish({kind:"timeout",message:`Execution timed out after ${e.timeoutMs} ms`})},e.timeoutMs)),e.signal&&(e.signal.aborted?this.onAbort():e.signal.addEventListener("abort",this.onAbort,{once:!0})),e.wasm.then(t=>this.start(e,t),t=>{this.finish({kind:"sandbox",message:`Failed to load QuickJS: ${M(t)}`})})}abort(e){return this.finish({kind:"aborted",message:e}),this.promise}start(e,t){if(this.finished)return;let r={code:e.code,tools:[...e.tools.values()].map(s=>({name:s.name,jsName:S(s.name),description:s.description??""})),globals:[...e.globals.values()].map(s=>({name:s.name,spread:s.spread===!0})),wasm:t,memoryLimitBytes:e.memoryLimitBytes,store:e.store,interrupt:this.interrupt},o;try{o=new we(e.workerUrl,{workerData:r})}catch(s){this.finish({kind:"sandbox",message:`Failed to start worker: ${M(s)}`});return}this.worker=o,o.on("message",s=>{try{this.handleMessage(s)}catch(n){this.finish({kind:"sandbox",message:n instanceof O?`Sandbox bridge broken: ${n.message}. The script may have modified built-ins such as a prototype's toJSON.`:`Sandbox host failed: ${M(n)}`})}}),o.on("error",s=>{this.finish({kind:"sandbox",name:s instanceof Error?s.name:void 0,message:M(s)})}),o.on("exit",s=>{this.finish({kind:"sandbox",message:`Worker exited with code ${s} before the script settled`})})}onAbort=a(()=>{let e=this.signal?.reason;this.finish({kind:"aborted",message:e instanceof Error?e.message:"Execution aborted"})},"onAbort");post(e){this.worker?.postMessage(e)}handleMessage(e){if(!this.finished){if(!ke(e))throw new O("unknown message from the worker");switch(e.type){case"output":this.output.push(e.item);break;case"call":if(this.pending.has(e.id))throw new O(`duplicate call id ${e.id}`);this.handleCall(e);break;case"done":this.handleDone(e);break;case"crash":this.finish({kind:"sandbox",message:e.message});break}}}handleDone(e){if(!e.ok){this.finish($e(e.error));return}let t=e.value===void 0?void 0:_(e.value,"return value");this.finish(void 0,t,Se(e.writes))}async handleCall(e){let{id:t,name:r}=e,o=e.target==="tool",s=o?{name:r,status:"cancelled",durationMs:0}:void 0;s&&this.calls.push(s);let n={record:s,startedAt:performance.now(),controller:new AbortController};this.pending.set(t,n);let i,d;try{let c=(o?this.tools:this.globals).get(r);if(!c)throw new Error(`Unknown ${o?"tool":"global"} "${r}"`);let u=e.args===void 0?void 0:JSON.parse(e.args),l=await c.execute(u,{signal:n.controller.signal});d={type:"result",id:t,ok:!0,payload:l===void 0?void 0:JSON.stringify(l)},i="ok"}catch(c){d={type:"result",id:t,ok:!1,payload:M(c)},i="error"}this.pending.delete(t)&&(s&&(s.status=i,s.durationMs=performance.now()-n.startedAt),this.post(d))}finish(e,t,r){if(this.finished)return;this.finished=!0,clearTimeout(this.timer),this.signal?.removeEventListener("abort",this.onAbort);let o=performance.now();for(let n of this.pending.values())n.record&&(n.record.durationMs=o-n.startedAt),n.controller.abort();this.pending.clear();let s=e?{ok:!1,error:e,output:this.output,calls:this.calls}:{ok:!0,value:t,output:this.output,calls:this.calls,storeWrites:r??{set:{},delete:[]}};if(!this.worker){this.resolveResult(s);return}Atomics.store(new Int32Array(this.interrupt),0,1),this.worker.terminate().catch(()=>{}).then(()=>this.resolveResult(s))}},Me=class{static{a(this,"CodemodeSandbox")}toolsByName=new Map;globalsByName=new Map;timeoutMs;memoryLimitBytes;wasm;workerUrl;running=new Set;closed=!1;constructor(e={}){this.timeoutMs=e.timeoutMs??Ee,this.memoryLimitBytes=e.memoryLimitBytes,this.wasm=e.wasm,this.workerUrl=e.workerUrl??Ce();for(let r of e.tools??[])this.registerTool(r);let t=new Set;for(let r of e.globals??[]){let o=r.name.split(".");if(o.length>2||!o.every(s=>Te.test(s))||je.has(o[0]))throw new Error(`Invalid global name "${r.name}"`);if(this.globalsByName.has(r.name))throw new Error(`Global "${r.name}" is already registered`);o.length===2&&t.add(o[0]),this.globalsByName.set(r.name,r)}for(let r of t)if(this.globalsByName.has(r))throw new Error(`Global "${r}" conflicts with the namespace "${r}"`)}registerTool(e){if(this.toolsByName.has(e.name))throw new Error(`Tool "${e.name}" is already registered`);this.toolsByName.set(e.name,e)}unregisterTool(e){return this.toolsByName.delete(e)}get tools(){return[...this.toolsByName.values()]}get globals(){return[...this.globalsByName.values()]}execute(e,t={}){if(this.closed)return Promise.reject(new Error("Sandbox is closed"));let r=new Ne({code:e,tools:new Map(this.toolsByName),globals:this.globalsByName,timeoutMs:t.timeoutMs??this.timeoutMs,signal:t.signal,memoryLimitBytes:this.memoryLimitBytes,store:xe(t.store),wasm:this.wasm===void 0?K():Promise.resolve(this.wasm),workerUrl:this.workerUrl});return this.running.add(r),r.promise.finally(()=>this.running.delete(r))}async close(){this.closed=!0,await Promise.all([...this.running].map(e=>e.abort("Sandbox closed")))}},L="image expects a non-empty image URL string, an object with image_url, or a raw MCP image block",dt=`(function (bridge, toolsJson, globalsJson, storeJson) {
2
+ "use strict";
3
+
4
+ // Freeze every object reachable from the built-in globals, plus the intrinsics that are only
5
+ // reachable from instances (iterator and generator prototypes, %TypedArray%).
6
+ //
7
+ // Freezing alone breaks ordinary code through the "override mistake": a data property that is
8
+ // read-only on a prototype cannot be assigned on an instance either, so
9
+ // this.name = "MyError" in an Error subclass would throw. Commonly overridden properties
10
+ // become accessors whose setter defines an own property on the instance instead.
11
+ (function lockdown() {
12
+ const OVERRIDABLE = new Set(["constructor", "name", "message", "toString", "toLocaleString", "valueOf", "toJSON"]);
13
+ const seen = new Set([globalThis]);
14
+ const queue = [];
15
+ const add = (value) => {
16
+ if ((typeof value === "object" && value !== null) || typeof value === "function") {
17
+ if (!seen.has(value)) {
18
+ seen.add(value);
19
+ queue.push(value);
20
+ }
21
+ }
22
+ };
23
+
24
+ // Accessors from an object literal have no own prototype object, unlike function expressions,
25
+ // whose prototype.constructor would be converted again without end.
26
+ function allowOverride(object, key, value, enumerable) {
27
+ const { get, set } = Object.getOwnPropertyDescriptor(
28
+ {
29
+ get accessor() {
30
+ return value;
31
+ },
32
+ set accessor(next) {
33
+ if (this === object) {
34
+ throw new TypeError("Cannot assign to read only property '" + String(key) + "' of a built-in");
35
+ }
36
+ if ((typeof this !== "object" || this === null) && typeof this !== "function") return;
37
+ Object.defineProperty(this, key, { value: next, writable: true, enumerable: true, configurable: true });
38
+ },
39
+ },
40
+ "accessor",
41
+ );
42
+ Object.defineProperty(object, key, { get, set, enumerable, configurable: false });
43
+ add(get);
44
+ add(set);
45
+ }
46
+
47
+ for (const key of Reflect.ownKeys(globalThis)) {
48
+ const descriptor = Object.getOwnPropertyDescriptor(globalThis, key);
49
+ add(descriptor.value);
50
+ add(descriptor.get);
51
+ add(descriptor.set);
52
+ if ("value" in descriptor && descriptor.configurable) {
53
+ Object.defineProperty(globalThis, key, { writable: false, configurable: false });
54
+ }
55
+ }
56
+ add(Object.getPrototypeOf(function* () {}));
57
+ add(Object.getPrototypeOf(async function () {}));
58
+ add(Object.getPrototypeOf(async function* () {}));
59
+ add(Object.getPrototypeOf(Int8Array));
60
+ add(Object.getPrototypeOf([][Symbol.iterator]()));
61
+ add(Object.getPrototypeOf(new Map()[Symbol.iterator]()));
62
+ add(Object.getPrototypeOf(new Set()[Symbol.iterator]()));
63
+ add(Object.getPrototypeOf(""[Symbol.iterator]()));
64
+ add(Object.getPrototypeOf(/a/[Symbol.matchAll]("")));
65
+ if (typeof Iterator === "function") {
66
+ if (typeof Iterator.prototype.map === "function") add(Object.getPrototypeOf([].values().map((x) => x)));
67
+ if (typeof Iterator.from === "function") add(Object.getPrototypeOf(Iterator.from({ next() {} })));
68
+ }
69
+
70
+ while (queue.length > 0) {
71
+ const object = queue.pop();
72
+ add(Object.getPrototypeOf(object));
73
+ const descriptors = Object.getOwnPropertyDescriptors(object);
74
+ for (const key of Reflect.ownKeys(descriptors)) {
75
+ const descriptor = descriptors[key];
76
+ if ("value" in descriptor) {
77
+ add(descriptor.value);
78
+ if (
79
+ descriptor.writable &&
80
+ descriptor.configurable &&
81
+ (object === Object.prototype || OVERRIDABLE.has(key))
82
+ ) {
83
+ allowOverride(object, key, descriptor.value, descriptor.enumerable);
84
+ }
85
+ } else {
86
+ add(descriptor.get);
87
+ add(descriptor.set);
88
+ }
89
+ }
90
+ Object.freeze(object);
91
+ }
92
+ })();
93
+ const stringify = JSON.stringify;
94
+ const parse = JSON.parse;
95
+ const promiseThen = Promise.prototype.then;
96
+ const ErrorCtor = Error;
97
+ const TypeErrorCtor = TypeError;
98
+ const RangeErrorCtor = RangeError;
99
+ const pending = new Map();
100
+ let nextId = 1;
101
+ let finished = false;
102
+ // Thrown by exit() to unwind the script after it already reported success.
103
+ const EXIT = Object.freeze({});
104
+
105
+ function done(ok, payload, writes) {
106
+ if (finished) return;
107
+ finished = true;
108
+ bridge("done", ok, payload, writes);
109
+ }
110
+
111
+ function serialize(value) {
112
+ return value === undefined ? undefined : stringify(value);
113
+ }
114
+
115
+ // QuickJS stacks list frames only. Prefix "Name: message" like V8 so the
116
+ // text reads the same as a Node error, and drop this prelude's frames.
117
+ function errorText(error) {
118
+ const head = error.message ? error.name + ": " + error.message : String(error.name);
119
+ const frames =
120
+ typeof error.stack === "string"
121
+ ? error.stack.split("\\n").filter((line) => line.trim() && !line.includes("codemode-prelude.js"))
122
+ : [];
123
+ return [head, ...frames].join("\\n");
124
+ }
125
+
126
+ function format(value) {
127
+ if (typeof value === "string") return value;
128
+ if (value instanceof ErrorCtor) return errorText(value);
129
+ try {
130
+ const json = stringify(value);
131
+ return json === undefined ? String(value) : json;
132
+ } catch {
133
+ return String(value);
134
+ }
135
+ }
136
+
137
+ // The host requires string fields. A script can set an error's name or message to anything, so
138
+ // they are coerced, and a value whose coercion throws gets a placeholder.
139
+ function describeError(error) {
140
+ try {
141
+ if (error instanceof ErrorCtor) {
142
+ return stringify({ name: String(error.name), message: String(error.message), stack: errorText(error) });
143
+ }
144
+ return stringify({ message: String(format(error)) });
145
+ } catch {
146
+ return stringify({ message: "The script threw a value that cannot be described" });
147
+ }
148
+ }
149
+
150
+ function caller(kind, name, spread) {
151
+ return (...args) =>
152
+ new Promise((resolve, reject) => {
153
+ let json;
154
+ try {
155
+ json = serialize(spread ? args : args[0]);
156
+ } catch (error) {
157
+ reject(error);
158
+ return;
159
+ }
160
+ const id = nextId++;
161
+ pending.set(id, { resolve, reject });
162
+ bridge(kind, id, name, json);
163
+ });
164
+ }
165
+
166
+ const tools = Object.create(null);
167
+ const allTools = [];
168
+ for (const { name, jsName, description } of parse(toolsJson)) {
169
+ const fn = caller("call", name);
170
+ // The first tool wins when two names normalize to the same identifier.
171
+ if (!(jsName in tools)) {
172
+ tools[jsName] = fn;
173
+ allTools.push(Object.freeze({ name: jsName, description }));
174
+ }
175
+ if (!(name in tools)) tools[name] = fn;
176
+ }
177
+ Object.freeze(tools);
178
+ Object.freeze(allTools);
179
+
180
+ // Reading a member that does not exist throws an error that names the close matches, instead of
181
+ // a later "not a function". \`in\` checks still work.
182
+ const comparable = (name) => name.toLowerCase().replace(/[^a-z0-9]/g, "");
183
+ function guard(target, label, names, hint) {
184
+ return new Proxy(target, {
185
+ get(object, property, receiver) {
186
+ if (typeof property !== "string" || property in object || property in Object.prototype || property === "then" || property === "toJSON") {
187
+ return Reflect.get(object, property, receiver);
188
+ }
189
+ const wanted = comparable(property);
190
+ const exact = names.filter((name) => comparable(name) === wanted);
191
+ const close = exact.length > 0 ? exact : names.filter((name) => wanted && (comparable(name).includes(wanted) || wanted.includes(comparable(name))));
192
+ let message = label + "." + property + " does not exist.";
193
+ if (close.length > 0) message += " Did you mean " + close.slice(0, 5).map((name) => label + "." + name).join(", ") + "?";
194
+ else if (names.length <= 20) message += " Available: " + names.join(", ") + ".";
195
+ if (hint) message += " " + hint;
196
+ message += ' Check for a member with "' + property + '" in ' + label + ".";
197
+ throw new TypeErrorCtor(message);
198
+ },
199
+ });
200
+ }
201
+ const toolsProxy = guard(
202
+ tools,
203
+ "tools",
204
+ allTools.map((tool) => tool.name),
205
+ "ALL_TOOLS lists every tool; searchTools(query) finds tools by topic.",
206
+ );
207
+
208
+ const namespaces = new Map();
209
+ for (const { name, spread } of parse(globalsJson)) {
210
+ const fn = caller("global", name, spread);
211
+ const dot = name.indexOf(".");
212
+ if (dot === -1) {
213
+ Object.defineProperty(globalThis, name, { value: fn, enumerable: true });
214
+ continue;
215
+ }
216
+ const namespace = name.slice(0, dot);
217
+ if (!namespaces.has(namespace)) namespaces.set(namespace, Object.create(null));
218
+ namespaces.get(namespace)[name.slice(dot + 1)] = fn;
219
+ }
220
+ for (const [namespace, members] of namespaces) {
221
+ Object.freeze(members);
222
+ const value = guard(members, namespace, Object.keys(members));
223
+ Object.defineProperty(globalThis, namespace, { value, enumerable: true });
224
+ }
225
+
226
+ // key -> JSON text. Sizes count key and JSON characters.
227
+ const stored = new Map(Object.entries(parse(storeJson)));
228
+ const writes = new Map();
229
+ let storedChars = 0;
230
+ for (const [key, json] of stored) storedChars += key.length + json.length;
231
+
232
+ const STORE_HINT =
233
+ "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.";
234
+
235
+ function checkKey(name, key) {
236
+ if (typeof key !== "string") throw new TypeError(name + "() key must be a string");
237
+ }
238
+
239
+ function store(key, value) {
240
+ checkKey("store", key);
241
+ const previous = stored.has(key) ? key.length + stored.get(key).length : 0;
242
+ if (value === undefined) {
243
+ stored.delete(key);
244
+ storedChars -= previous;
245
+ writes.set(key, undefined);
246
+ return;
247
+ }
248
+ let json;
249
+ try {
250
+ json = stringify(value);
251
+ } catch (error) {
252
+ throw new TypeError("store(" + stringify(key) + ") value is not JSON-serializable: " + format(error));
253
+ }
254
+ if (json === undefined) {
255
+ throw new TypeError("store(" + stringify(key) + ") value is not JSON-serializable");
256
+ }
257
+ if (json.length > 262144) {
258
+ throw new RangeError(
259
+ "store(" + stringify(key) + ") value has " + json.length + " characters of JSON, more than the limit of 262144. " +
260
+ STORE_HINT,
261
+ );
262
+ }
263
+ const next = storedChars - previous + key.length + json.length;
264
+ if (next > 1048576) {
265
+ throw new RangeError(
266
+ "store is full: stored values would exceed 1048576 characters of JSON. Delete keys with store(key, undefined). " +
267
+ STORE_HINT,
268
+ );
269
+ }
270
+ stored.set(key, json);
271
+ storedChars = next;
272
+ writes.set(key, json);
273
+ }
274
+
275
+ function load(key) {
276
+ checkKey("load", key);
277
+ const json = stored.get(key);
278
+ return json === undefined ? undefined : parse(json);
279
+ }
280
+
281
+ function serializeWrites() {
282
+ const entries = [];
283
+ for (const [key, json] of writes) entries.push(json === undefined ? [key] : [key, json]);
284
+ return stringify(entries);
285
+ }
286
+
287
+ Object.defineProperty(globalThis, "store", { value: store, enumerable: true });
288
+ Object.defineProperty(globalThis, "load", { value: load, enumerable: true });
289
+
290
+ let outputChars = 0;
291
+ let outputItems = 0;
292
+
293
+ // Past the output limits the script fails: done() reports the error, so catching it does not
294
+ // resume output, and the host ends the script.
295
+ function output(kind, data, mimeType) {
296
+ if (finished) return;
297
+ outputChars += data.length;
298
+ outputItems++;
299
+ if (outputChars > 16777216 || outputItems > 100000) {
300
+ const error = new RangeErrorCtor(
301
+ "script output exceeded the limit of 16777216 characters or 100000 text(), image(), and console calls. " +
302
+ "Print a summary instead, or write large data to a file with a tool.",
303
+ );
304
+ done(false, describeError(error));
305
+ throw error;
306
+ }
307
+ bridge("output", kind, data, mimeType);
308
+ }
309
+
310
+ // Primitives become their string form, everything else JSON.
311
+ function outputText(value) {
312
+ if (value === undefined || value === null || typeof value !== "object" && typeof value !== "function") {
313
+ return String(value);
314
+ }
315
+ const json = stringify(value);
316
+ return json === undefined ? String(value) : json;
317
+ }
318
+
319
+ function text(value) {
320
+ let rendered;
321
+ try {
322
+ rendered = outputText(value);
323
+ } catch (error) {
324
+ throw new TypeErrorCtor(error instanceof ErrorCtor ? error.message : String(error));
325
+ }
326
+ output("text", rendered);
327
+ }
328
+
329
+ function imageUrl(value) {
330
+ if (typeof value === "string") return value;
331
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
332
+ throw new TypeErrorCtor(${JSON.stringify(L)});
333
+ }
334
+ if (value.image_url !== undefined) {
335
+ if (typeof value.image_url !== "string") throw new TypeErrorCtor(${JSON.stringify(L)});
336
+ return value.image_url;
337
+ }
338
+ if (typeof value.type !== "string") throw new TypeErrorCtor(${JSON.stringify(L)});
339
+ if (value.type !== "image") {
340
+ throw new TypeErrorCtor('image only accepts MCP image blocks, got "' + value.type + '"');
341
+ }
342
+ if (typeof value.data !== "string" || value.data === "") throw new TypeErrorCtor("image expected MCP image data");
343
+ if (value.data.toLowerCase().startsWith("data:")) return value.data;
344
+ return "data:;base64," + value.data;
345
+ }
346
+
347
+ // Base64 of the signatures of the formats providers accept inline (PNG, JPEG except
348
+ // JPEG-LS, GIF, "RIFF....WEBP"). Signatures start at byte 0, so their encodings are prefixes.
349
+ const IMAGE_SIGNATURES = [
350
+ ["image/png", /^iVBORw0KGg/],
351
+ ["image/jpeg", /^[/]9j[/](?!9)/],
352
+ ["image/gif", /^R0lGOD[dl]h/],
353
+ ["image/webp", /^UklG.{8}RUJQ/],
354
+ ];
355
+
356
+ function image(value) {
357
+ const url = imageUrl(value);
358
+ if (url === "") throw new TypeErrorCtor(${JSON.stringify(L)});
359
+ const colon = url.indexOf(":");
360
+ const scheme = colon === -1 ? "" : url.slice(0, colon).toLowerCase();
361
+ if (scheme === "http" || scheme === "https") {
362
+ throw new TypeErrorCtor("remote image URLs are not supported in tool outputs. Pass a base64 data URI instead");
363
+ }
364
+ const comma = url.indexOf(",");
365
+ const header = comma === -1 ? [] : url.slice(colon + 1, comma).split(";");
366
+ if (scheme !== "data" || comma === -1 || header.slice(1).every((part) => part.toLowerCase() !== "base64")) {
367
+ throw new TypeErrorCtor("invalid image output. Pass a base64 data URI instead");
368
+ }
369
+ // Providers reject the whole request on a bad image, and a persisted image block would be
370
+ // resent on every later turn. Line breaks from wrapped base64 are dropped. The declared type
371
+ // is ignored in favor of the detected one, as providers also reject mismatches.
372
+ const data = url.slice(comma + 1).replace(/\\s+/g, "");
373
+ if (data.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(data)) {
374
+ throw new TypeErrorCtor("invalid image output. The image data is not valid base64 (truncated or corrupted?)");
375
+ }
376
+ const head = data.slice(0, 16);
377
+ const signature = IMAGE_SIGNATURES.find(([, pattern]) => pattern.test(head));
378
+ if (!signature) {
379
+ throw new TypeErrorCtor("invalid image output. The image data is not a PNG, JPEG, GIF, or WebP image");
380
+ }
381
+ output("image", data, signature[0]);
382
+ }
383
+
384
+ function exit() {
385
+ let writesJson;
386
+ try {
387
+ writesJson = serializeWrites();
388
+ } catch (error) {
389
+ done(false, describeError(error));
390
+ throw EXIT;
391
+ }
392
+ done(true, undefined, writesJson);
393
+ throw EXIT;
394
+ }
395
+
396
+ const console = {};
397
+ for (const level of ["log", "info", "warn", "error", "debug"]) {
398
+ console[level] = (...args) => {
399
+ output("console", args.map(format).join(" "));
400
+ };
401
+ }
402
+ Object.freeze(console);
403
+
404
+ Object.defineProperty(globalThis, "tools", { value: toolsProxy, enumerable: true });
405
+ Object.defineProperty(globalThis, "ALL_TOOLS", { value: allTools, enumerable: true });
406
+ Object.defineProperty(globalThis, "console", { value: console, enumerable: true });
407
+ Object.defineProperty(globalThis, "text", { value: text, enumerable: true });
408
+ Object.defineProperty(globalThis, "image", { value: image, enumerable: true });
409
+ Object.defineProperty(globalThis, "exit", { value: exit, enumerable: true });
410
+
411
+ return {
412
+ settle(id, ok, payload) {
413
+ const entry = pending.get(id);
414
+ if (!entry) return;
415
+ pending.delete(id);
416
+ if (!ok) {
417
+ entry.reject(new ErrorCtor(payload));
418
+ return;
419
+ }
420
+ let value;
421
+ try {
422
+ value = payload === undefined ? undefined : parse(payload);
423
+ } catch (error) {
424
+ entry.reject(error);
425
+ return;
426
+ }
427
+ entry.resolve(value);
428
+ },
429
+ run(fn) {
430
+ let promise;
431
+ try {
432
+ promise = fn(toolsProxy, console);
433
+ } catch (error) {
434
+ done(false, describeError(error));
435
+ return;
436
+ }
437
+ promiseThen.call(
438
+ promise,
439
+ (value) => {
440
+ let json;
441
+ try {
442
+ json = serialize(value);
443
+ } catch (error) {
444
+ done(false, describeError(error));
445
+ return;
446
+ }
447
+ done(true, json, serializeWrites());
448
+ },
449
+ (error) => {
450
+ done(false, describeError(error));
451
+ },
452
+ );
453
+ },
454
+ stalled() {
455
+ if (finished || pending.size > 0) return false;
456
+ done(
457
+ false,
458
+ stringify({
459
+ name: "Error",
460
+ message:
461
+ "The script is waiting on a promise that can never settle: no tool call is pending, and timers do not exist here.",
462
+ }),
463
+ );
464
+ return true;
465
+ },
466
+ };
467
+ })`,Pe=200,X=500,Ae=4,Ie=256*1024*1024,Y=new Set(["chat","image","classifier"]);function U(e,t){return e.length>t?`${e.slice(0,t-3)}...`:e}a(U,"truncateText");function Re(e){if(e===void 0)return"";try{return U(JSON.stringify(e)??"",Pe)}catch{return""}}a(Re,"previewArgs");function Q(e){return(e.content??[]).filter(t=>t.type==="text").map(t=>t.text).join(`
468
+ `)}a(Q,"textOf");function B(e){if(typeof e=="string"&&Y.has(e))return e;throw new Error(`Unknown model type ${JSON.stringify(e)}. Use "chat", "image", or "classifier".`)}a(B,"toModelType");function Z(e){if(e!=null){if(typeof e!="string")throw new Error("provider must be a string");return e}}a(Z,"toProvider");function D(e){let t={...e};return delete t.headers,t}a(D,"toModelInfo");function z(e){return`${/^[aeiou]/.test(e)?"an":"a"} ${e}`}a(z,"withArticle");function y(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(y,"isRecord");function b(e){if(e==null)return String(e);if(Array.isArray(e))return e.length===0?"an empty array":"an array";if(typeof e=="object"){let t=Object.keys(e);return t.length===0?"{}":`{ ${t.slice(0,6).join(", ")}${t.length>6?", ...":""} }`}return typeof e=="string"?"a string":`a ${typeof e}`}a(b,"describeValue");var _e='{ 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> } } } }';function Le(e){let t=a(n=>new Error(`models.classify() ${n}. Expected context: ${_e}. See "Classify" in ${F}.`),"fail");if(!y(e))throw t(`expects a context object as its second argument, got ${b(e)}`);if(!y(e.state))throw t(`context.state must be an object, got ${b(e.state)}`);let{images:r}=e;if(r!==void 0){if(!Array.isArray(r))throw t(`context.images must be an array, got ${b(r)}`);r.forEach((n,i)=>{if(!y(n)||n.type!=="image"||typeof n.data!="string"||typeof n.mimeType!="string")throw t(`context.images[${i}] must be an image block, got ${b(n)}`)})}let{questions:o}=e;if(!y(o)||Object.keys(o).length===0)throw t(`context.questions must map question IDs to questions, got ${b(o)}`);let s=a(n=>n.length>0&&n.every(i=>typeof i=="string"),"isStrings");for(let[n,i]of Object.entries(o)){let d=`context.questions.${n}`;if(!y(i))throw t(`${d} must be a question object, got ${b(i)}`);if(typeof i.instructions!="string")throw t(`${d}.instructions must be a string`);let{criteria:c}=i;if(i.type==="choice"){if(!y(c)||!s(Object.values(c)))throw t(`${d} is a "choice" question, so criteria must map each label to its meaning`)}else if(i.type==="score"){if(!Array.isArray(c)||!s(c))throw t(`${d} is a "score" question, so criteria must list the levels as strings, lowest first`)}else if(i.type==="bool"){if(!y(c)||typeof c.true!="string"||typeof c.false!="string")throw t(`${d} is a "bool" question, so criteria must be { true: string, false: string }`)}else throw t(`${d}.type must be "choice", "score", or "bool", got ${JSON.stringify(i.type)}`)}return e}a(Le,"checkClassifierContext");function Je(e){let t=a(o=>new Error(`models.generateImages() ${o}. Expected context: { input: [{ type: "text", text: <prompt> }, ...optional { type: "image", data: <base64>, mimeType } references] }. See "Generate images" in ${F}.`),"fail");if(!y(e))throw t(`expects a context object as its second argument, got ${b(e)}`);let{input:r}=e;if(!Array.isArray(r)||r.length===0)throw t(`context.input must be a non-empty array of blocks, got ${b(r)}`);return r.forEach((o,s)=>{if(!(y(o)&&o.type==="text"&&typeof o.text=="string")&&!(y(o)&&o.type==="image"&&typeof o.data=="string"&&typeof o.mimeType=="string"))throw t(`context.input[${s}] must be a text or image block, got ${b(o)}`)}),e}a(Je,"checkImagesContext");function Ue(e){let t=0,r=[];return async o=>{t>=e&&await new Promise(s=>r.push(s)),t++;try{return await o()}finally{t--,r.shift()?.()}}}a(Ue,"createLimiter");function Be(e){if(typeof e!="object"||e===null)return!1;let{set:t,delete:r}=e;return typeof t=="object"&&t!==null&&Array.isArray(r)&&r.every(o=>typeof o=="string")}a(Be,"isStoreEntryData");function ee(e){let t=new Map;for(let r of e)if(!(r.type!=="custom"||r.customType!==H||!Be(r.data))){for(let o of r.data.delete)t.delete(o);for(let[o,s]of Object.entries(r.data.set))t.set(o,s)}return Object.fromEntries(t)}a(ee,"readCodemodeStore");var De=1e4,q=4;function ze(e){return typeof e=="string"?e:JSON.stringify(e)??String(e)}a(ze,"valueText");function qe(e){let t=e.filter(n=>n.type==="text"&&!n.console).length,r=[],o=[],s=0;for(let n of e)n.type==="image"?r.push(n):n.console?o.push(n.text):(s++,r.push({type:"text",text:t>1?`==> text ${s}/${t} <==
469
+ ${n.text}`:n.text}));return o.length>0&&r.push({type:"text",text:`<console_output>
470
+ ${o.join(`
471
+ `)}
472
+ </console_output>`}),r}a(qe,"formatOutput");function te(e){let t=[];for(let r of e){let o=t.at(-1);if(r.type==="text"&&o?.type==="text"){let s=o.text===""||o.text.endsWith(`
473
+ `)?"":`
474
+ `;t[t.length-1]={type:"text",text:`${o.text}${s}${r.text}`}}else t.push(r)}return t}a(te,"joinAdjacentText");function Ge(e){return e.length===0?"No tool calls were made.":`Tool calls made before the failure (they are not undone): ${e.map(t=>`${t.name} (${t.status})`).join(", ")}`}a(Ge,"formatCallSummary");function We(e,t){let{error:r}=e;return`${r.kind==="script"?r.stack??`${r.name??"Error"}: ${r.message}`:r.kind==="timeout"?`Script timed out: ${r.message}`:r.kind==="aborted"?`Script aborted: ${r.message}`:`Script sandbox failed: ${r.message}`}
475
+
476
+ ${Ge(t)}`}a(We,"formatError");async function Fe(e){try{return{path:await V("pi-codemode",".txt",e)}}catch(t){return{error:t instanceof Error?t.message:String(t)}}}a(Fe,"spillOutput");var He={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp"};async function Ve(e){let t=new Map,r=a(async({data:o,mimeType:s})=>{let n=Buffer.from(o,"base64"),i=`${s}, ${he(n.length)}`,d=He[s];if(!d)throw new Error(`No file extension for image type ${s}`);try{return`[Image saved to ${await V("pi-codemode",d,n)} (${i})]`}catch(c){return`[Image (${i}) could not be saved: ${c instanceof Error?c.message:String(c)}]`}},"label");return(await Promise.all(e.map(async o=>{if(o.type!=="image")return[o];let s=t.get(o.data);return s||(s=r(o),t.set(o.data,s)),[{type:"text",text:await s},o]}))).flat()}a(Ve,"saveImages");async function Ke(e,t){let r=e.filter(m=>m.type==="text").map(m=>m.text),o=r.join(`
477
+ `),s=t*q;if(r.length===0||o.length<=s)return{items:e};let n=Math.floor(s/2),i=s-n,d=o.length-n-i,c=o.slice(0,n),u=i>0?o.slice(-i):"",l=`Warning: truncated output (original token count: ${Math.ceil(o.length/q)})
478
+ Total output lines: ${o.split(`
479
+ `).length}
480
+
481
+ ${c}\u2026${Math.ceil(d/q)} tokens truncated\u2026${u}`,p=await Fe(o);return l+="path"in p?`
482
+
483
+ [Full output: ${p.path} (read with offset/limit)]`:`
484
+
485
+ [Could not save the full output: ${p.error}]`,{items:[{type:"text",text:l},...e.filter(m=>m.type==="image")],..."path"in p?{fullOutputPath:p.path}:{}}}a(Ke,"truncateOutput");function Xe(e,t){let{result:r}=t;if(e.outputSchema&&r.structuredContent!==void 0)return r.structuredContent;let o=Q(r);if(t.isError)throw new Error(o||`Tool "${e.name}" failed`);return o}a(Xe,"toScriptValue");async function Ye(e,t,r,o,s,n={}){let i=performance.now(),{code:d,options:c}=fe(t.code),u=[],l,p=0,m=a(f=>{p+=f},"addGeneratedImages"),w=a(f=>{l=l?ue(l,f):f},"addModelUsage"),T=a(()=>({calls:u.map(f=>({...f}))}),"snapshot"),k=a(()=>o?.({content:[],details:T()}),"publish"),E=s?pe(s.tools):[],$=n.getToolGuidelines?.(),C=new Map(E.map(f=>[f.name,me(ge(f,$?.get(f.name)))])),j=E.map(f=>({name:f.name,description:C.get(f.name),execute:a(async(N,{signal:W})=>{let x={id:`${e}/?`,name:f.name,args:Re(N),status:"running"};u.push(x),k();let ne=performance.now();if(!s)throw new Error("Tool calls need a session");let R=await s.executeTool(f.name,N,{signal:W});return x.id=R.toolCall.id,x.durationMs=performance.now()-ne,R.isError?(x.status=W.aborted?"cancelled":"error",x.error=U(Q(R.result)||`Tool "${f.name}" failed`,X)):x.status="ok",k(),Xe(f,R)},"execute")})),P=new Me({tools:j,globals:[...Qe(E,C,n),...n.models&&s?Ze(s.modelRegistry,e,u,k,w,m):[]],timeoutMs:c.timeoutMs??Number.POSITIVE_INFINITY,memoryLimitBytes:Ie,wasm:K(be()),workerUrl:ye()}),g;try{let f=s?ee(s.sessionManager.getBranch()):{};g=await P.execute(d,{signal:r,store:f})}finally{await P.close()}for(let f of u)f.status==="running"&&(f.status="cancelled");let A=[...g.output];if(g.ok){let{set:f,delete:N}=g.storeWrites;(Object.keys(f).length>0||N.length>0)&&n.appendEntry?.(H,{set:f,delete:N}),g.value!==void 0&&A.push({type:"text",text:ze(g.value)})}let h=qe(A);g.ok||h.push({type:"text",text:`Script error:
486
+ ${We(g,u)}`}),p>0&&!h.some(f=>f.type==="image")&&h.push({type:"text",text:`Note: models.generateImages() returned ${p} image${p===1?"":"s"} that the script did not show. Show each image block of result.output with image(block).`});let v=await Ke(te(h),c.maxOutputTokens??De),I=te(await Ve(v.items)),oe=((performance.now()-i)/1e3).toFixed(1),se=`${g.ok?"Script completed":"Script failed"}
487
+ Wall time ${oe} seconds
488
+ Output:
489
+ `,G=T();return v.fullOutputPath&&(G.fullOutputPath=v.fullOutputPath),{content:[{type:"text",text:se},...I],details:G,...l?{usage:l}:{},...g.ok?{}:{isError:!0}}}a(Ye,"executeCodemode");function re(e,t){let r=S(e),o=S(t),s=a(n=>n.includes("__")?n.slice(n.lastIndexOf("__")+2):void 0,"suffix");return e===t||r===o||s(e)===t||s(r)===o}a(re,"isNamespaceName");function Qe(e,t,r){let o=new le,s=a(n=>({name:S(n),description:t.get(n)??""}),"entry");return[{name:"searchTools",spread:!0,execute:a(n=>{let[i,d]=n;if(typeof i!="string")throw new Error("searchTools() expects a query string");let c=d?.limit??ce;if(typeof c!="number"||!Number.isInteger(c)||c<=0)throw new Error("searchTools() limit must be a positive integer");let u=d?.namespace;if(u!=null&&typeof u!="string")throw new Error("searchTools() namespace must be a string");let l=e.flatMap(p=>{let m=r.getToolNamespace?.(p.name);return u&&(!m||!re(m.name,u))?[]:[de(p,m)]});return o.rank(i,l,c).map(p=>s(p.name))},"execute")},{name:"describeTool",spread:!0,execute:a(n=>{let[i]=n;if(typeof i!="string")throw new Error("describeTool() expects a tool name");let d=e.find(c=>c.name===i||S(c.name)===i);return d?t.get(d.name):void 0},"execute")},{name:"describeNamespace",spread:!0,execute:a(n=>{let[i]=n;if(typeof i!="string")throw new Error("describeNamespace() expects a namespace name");let d,c=[];for(let u of e){let l=r.getToolNamespace?.(u.name);!l||!re(l.name,i)||(d??=l,c.push(S(u.name)))}if(d)return{name:d.name,...d.description?{description:d.description}:{},...d.instructions?{instructions:d.instructions}:{},tools:c}},"execute")}]}a(Qe,"createDiscoveryGlobals");function Ze(e,t,r,o,s,n){let i=Ue(Ae),d=0,c=a(async(u,l,[p,m],w,T)=>{let k=`List the ${l} models you can use with models.getAvailableOfType("${l}").`;if(!y(p)||typeof p.provider!="string"||typeof p.id!="string"){let v=p==null?" models.getModelOfType() returns undefined for an unknown provider or id.":"";throw new Error(`${u}() expects ${z(l)} model as its first argument, got ${b(p)}.${v} ${k}`)}let{provider:E,id:$}=p,C=`${E}/${$}`,j=e.getModelOfType(l,E,$);if(!j){let v=[...Y].find(I=>I!==l&&e.getModelOfType(I,E,$)!==void 0);throw new Error(v?`"${C}" is ${z(v)} model, not ${z(l)} model. ${k}`:`Unknown ${l} model "${C}". ${k}`)}let P=w(m),g={id:`${t}/${u}/${++d}`,name:u,args:`${j.provider}/${j.id}`,status:"running"};r.push(g),o();let A=performance.now(),h=await i(()=>T(j,P));return g.durationMs=performance.now()-A,g.status=h.stopReason==="stop"?"ok":h.stopReason==="aborted"?"cancelled":"error",h.errorMessage&&(g.error=U(h.errorMessage,X)),h.usage&&(g.cost=h.usage.cost.total,s(h.usage)),o(),h},"runModelCall");return Object.entries({"models.getModelsOfType":a(u=>{let[l,p]=u;return e.getModelsOfType(B(l),Z(p)).map(D)},"models.getModelsOfType"),"models.getAvailableOfType":a(async(u,{signal:l})=>{let[p,m]=u;return(await e.getAvailableOfType(B(p),Z(m),{signal:l})).map(D)},"models.getAvailableOfType"),"models.getModelOfType":a(u=>{let[l,p,m]=u;if(typeof p!="string"||typeof m!="string")throw new Error(`models.getModelOfType(type, provider, id) expects three strings, got (${u.map(b).join(", ")}). The provider and the id are separate arguments, for example models.getModelOfType("classifier", "typesafe", "jev-latest").`);let w=e.getModelOfType(B(l),p,m);return w===void 0?void 0:D(w)},"models.getModelOfType"),"models.classify":a((u,{signal:l})=>c("models.classify","classifier",u,Le,(p,m)=>e.classify(p,m,{signal:l})),"models.classify"),"models.generateImages":a((u,{signal:l})=>c("models.generateImages","image",u,Je,async(p,m)=>{let w=await e.generateImages(p,m,{signal:l});return n(w.output.filter(T=>T.type==="image").length),w}),"models.generateImages")}).map(([u,l])=>({name:u,spread:!0,execute:l}))}a(Ze,"createModelGlobals");export{Ye as executeCodemode,ee as readCodemodeStore};
@@ -0,0 +1 @@
1
+ var W=Object.defineProperty;var r=(e,t)=>W(e,"name",{value:t,configurable:!0});import{createRequire as A}from"node:module";const J=A(import.meta.url);var m={"anthropic-messages":{"chat:claude-fable-5":{id:"claude-fable-5",name:"Claude Fable 5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:10,output:50,cacheRead:1,cacheWrite:12.5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,forceAdaptiveThinking:!0},thinkingLevelMap:{off:null,xhigh:"xhigh",max:"max"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-fable-5.1":{id:"claude-fable-5.1",name:"Claude Fable 5.1",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:10,output:50,cacheRead:.25,cacheWrite:12.5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,forceAdaptiveThinking:!0},thinkingLevelMap:{off:null,xhigh:"xhigh",max:"max"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-haiku-4.5":{id:"claude-haiku-4.5",name:"Claude Haiku 4.5 (latest)",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:1,output:5,cacheRead:.1,cacheWrite:1.25},contextWindow:2e5,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsEagerToolInputStreaming:!1},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-haiku-5.5":{id:"claude-haiku-5.5",name:"Claude Haiku 5.5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.1,output:.5,cacheRead:.01,cacheWrite:.125,tiers:[{inputTokensAbove:1e5,input:.5,output:2.5,cacheRead:.05,cacheWrite:.625}]},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,forceAdaptiveThinking:!0,supportsTemperature:!1},thinkingLevelMap:{xhigh:"xhigh",max:"max"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-opus-4.7":{id:"claude-opus-4.7",name:"Claude Opus 4.7",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:32e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{xhigh:"xhigh",max:"max",minimal:"low"},compat:{forceAdaptiveThinking:!0,supportsTemperature:!1},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-opus-4.8":{id:"claude-opus-4.8",name:"Claude Opus 4.8",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,forceAdaptiveThinking:!0,supportsTemperature:!1},thinkingLevelMap:{xhigh:"xhigh",max:"max",minimal:"low"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-opus-5":{id:"claude-opus-5",name:"Claude Opus 5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,forceAdaptiveThinking:!0,supportsTemperature:!1},thinkingLevelMap:{xhigh:"xhigh",max:"max",minimal:"low"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-opus-5.5":{id:"claude-opus-5.5",name:"Claude Opus 5.5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:4,output:20,cacheRead:.2,cacheWrite:5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,forceAdaptiveThinking:!0,supportsTemperature:!1},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-sonnet-4.6":{id:"claude-sonnet-4.6",name:"Claude Sonnet 4.6",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:1e6,maxTokens:32e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{max:"max",minimal:"low"},compat:{forceAdaptiveThinking:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-sonnet-5":{id:"claude-sonnet-5",name:"Claude Sonnet 5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.2,cacheWrite:2.5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{xhigh:"xhigh",max:"max"},compat:{forceAdaptiveThinking:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-sonnet-5.5":{id:"claude-sonnet-5.5",name:"Claude Sonnet 5.5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.1,cacheWrite:2.5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,forceAdaptiveThinking:!0,supportsTemperature:!1},thinkingLevelMap:{xhigh:"xhigh",max:"max"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"}},"openai-completions":{"chat:gemini-3.5-flash":{id:"gemini-3.5-flash",name:"Gemini 3.5 Flash",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:1.5,output:9,cacheRead:.15,cacheWrite:0},contextWindow:2e5,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStrictMode:!0,supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gemini-3.6-flash":{id:"gemini-3.6-flash",name:"Gemini 3.6 Flash",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.75,output:3.75,cacheRead:.075,cacheWrite:0},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStrictMode:!0,supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gemini-3.7-flash":{id:"gemini-3.7-flash",name:"Gemini 3.7 Flash",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.75,output:3.75,cacheRead:.075,cacheWrite:0},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStrictMode:!0,supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gemini-3.8-flash":{id:"gemini-3.8-flash",name:"Gemini 3.8 Flash",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.75,output:3.75,cacheRead:.075,cacheWrite:0},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStrictMode:!0,supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:kimi-k2.7-code":{id:"kimi-k2.7-code",name:"Kimi K2.7 Code",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.95,output:4,cacheRead:.19,cacheWrite:0},contextWindow:256e3,maxTokens:32e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStrictMode:!0,supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:kimi-k3":{id:"kimi-k3",name:"Kimi K3",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:0},contextWindow:1048576,maxTokens:131072,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStrictMode:!0,supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,supportsMidConvoSystemMessages:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"}},"openai-responses":{"chat:gpt-5-mini":{id:"gpt-5-mini",name:"GPT-5 Mini",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.25,output:2,cacheRead:.025,cacheWrite:0},contextWindow:264e3,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:null,max:null},compat:{supportsOpenAIGrammarTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.3-codex":{id:"gpt-5.3-codex",name:"GPT-5.3 Codex",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.4":{id:"gpt-5.4",name:"GPT-5.4",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2.5,output:15,cacheRead:.25,cacheWrite:0,tiers:[{inputTokensAbove:272e3,input:5,output:22.5,cacheRead:.5,cacheWrite:0}]},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.4-mini":{id:"gpt-5.4-mini",name:"GPT-5.4 mini",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.75,output:4.5,cacheRead:.075,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.4-nano":{id:"gpt-5.4-nano",name:"GPT-5.4 nano",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.2,output:1.25,cacheRead:.02,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",xhigh:"xhigh"},compat:{supportsOpenAIGrammarTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.5":{id:"gpt-5.5",name:"GPT-5.5",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:30,cacheRead:.5,cacheWrite:0,tiers:[{inputTokensAbove:272e3,input:10,output:45,cacheRead:1,cacheWrite:0}]},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.6-luna":{id:"gpt-5.6-luna",name:"GPT-5.6 Luna",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.2,output:1.2,cacheRead:.02,cacheWrite:.25,tiers:[{inputTokensAbove:2e5,input:.4,output:1.8,cacheRead:.04,cacheWrite:.5}]},contextWindow:105e4,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.6-sol":{id:"gpt-5.6-sol",name:"GPT-5.6 Sol",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:4,output:20,cacheRead:.4,cacheWrite:5,tiers:[{inputTokensAbove:272e3,input:8,output:30,cacheRead:.8,cacheWrite:10}]},contextWindow:105e4,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.6-terra":{id:"gpt-5.6-terra",name:"GPT-5.6 Terra",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:12,cacheRead:.2,cacheWrite:2.5,tiers:[{inputTokensAbove:272e3,input:4,output:18,cacheRead:.4,cacheWrite:5}]},contextWindow:105e4,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-6-astra":{id:"gpt-6-astra",name:"GPT-6 Astra",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:10,output:50,cacheRead:1,cacheWrite:12.5,tiers:[{inputTokensAbove:272e3,input:20,output:75,cacheRead:2,cacheWrite:25}]},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-6-luna":{id:"gpt-6-luna",name:"GPT-6 Luna",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.1,output:.5,cacheRead:.01,cacheWrite:.125,tiers:[{inputTokensAbove:272e3,input:.2,output:.75,cacheRead:.02,cacheWrite:.25}]},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-6-sol":{id:"gpt-6-sol",name:"GPT-6 Sol",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.2,cacheWrite:2.5,tiers:[{inputTokensAbove:272e3,input:4,output:15,cacheRead:.4,cacheWrite:5}]},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-6.1-sol":{id:"gpt-6.1-sol",name:"GPT-6.1 Sol",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.1,cacheWrite:2.5,tiers:[{inputTokensAbove:272e3,input:4,output:15,cacheRead:.2,cacheWrite:5}]},contextWindow:105e4,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:grok-4.5":{id:"grok-4.5",name:"Grok 4.5",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:6,cacheRead:.5,cacheWrite:0,tiers:[{inputTokensAbove:2e5,input:4,output:12,cacheRead:1,cacheWrite:0}]},contextWindow:5e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:null},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:grok-4.6":{id:"grok-4.6",name:"Grok 4.6",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:6,cacheRead:.5,cacheWrite:0,tiers:[{inputTokensAbove:2e5,input:4,output:12,cacheRead:1,cacheWrite:0}]},contextWindow:5e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:grok-4.7":{id:"grok-4.7",name:"Grok 4.7",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:6,cacheRead:.5,cacheWrite:0,tiers:[{inputTokensAbove:2e5,input:4,output:12,cacheRead:1,cacheWrite:0}]},contextWindow:5e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:mai-code-1-flash-picker":{id:"mai-code-1-flash-picker",name:"MAI-Code-1-Flash",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text"],cost:{input:.75,output:4.5,cacheRead:.075,cacheWrite:0},contextWindow:256e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:null},type:"chat"},"chat:mai-code-1.1-flash":{id:"mai-code-1.1-flash",name:"MAI-Code-1.1-Flash",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.2,output:1.2,cacheRead:.02,cacheWrite:0},contextWindow:256e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:null},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"}}};function g(e,t){return Object.fromEntries(Object.values(e).flatMap(o=>Object.values(o)).filter(o=>o.type===t).map(o=>[o.id,o]))}r(g,"flattenModelCatalog");function U(e,t){return g(t,"chat")}r(U,"flattenChatModelCatalog");function L(e,t){return g(t,"image")}r(L,"flattenImageModelCatalog");function G(e,t){return g(t,"classifier")}r(G,"flattenClassifierModelCatalog");var H=U("github-copilot",m),X=L("github-copilot",m),Z=G("github-copilot",m);function S(e,t){return new Promise((o,a)=>{t.throwIfAborted();let i=r(()=>{clearTimeout(n),a(t.reason)},"onAbort"),n=setTimeout(()=>{t.removeEventListener("abort",i),o()},e);t.addEventListener("abort",i,{once:!0})})}r(S,"sleep");var x="Login cancelled",R="Device flow timed out",V="Device flow timed out after one or more slow_down responses. This is often caused by clock drift in WSL or VM environments. Please sync or restart the VM clock and try again.";function w(e,t,o){return new Promise((a,i)=>{if(t.aborted){i(new Error(o));return}let n=r(()=>{clearTimeout(p),i(new Error(o))},"onAbort"),p=setTimeout(()=>{t.removeEventListener("abort",n),a()},e);t.addEventListener("abort",n,{once:!0})})}r(w,"abortableSleep");async function P(e){let t=typeof e.expiresInSeconds=="number"?Date.now()+e.expiresInSeconds*1e3:Number.POSITIVE_INFINITY,o=Math.max(1e3,Math.floor((e.intervalSeconds??5)*1e3)),a=0;if(e.waitBeforeFirstPoll){let i=t-Date.now();i>0&&await w(Math.min(o,i),e.signal,x)}for(;Date.now()<t;){if(e.signal.aborted)throw new Error(x);let i=await e.poll();if(i.status==="complete")return i.value;if(i.status==="failed")throw new Error(i.message);i.status==="slow_down"&&(a+=1,o=typeof i.intervalSeconds=="number"&&Number.isFinite(i.intervalSeconds)&&i.intervalSeconds>0?Math.max(1e3,Math.floor(i.intervalSeconds*1e3)):Math.max(1e3,o+5e3));let n=t-Date.now();if(n<=0)break;await w(Math.min(o,n),e.signal,x)}throw new Error(a>0?V:R)}r(P,"pollOAuthDeviceCodeFlow");var _=r(e=>atob(e),"decode"),C=_("SXYxLmI1MDdhMDhjODdlY2ZlOTg="),v={"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},j="2026-06-01";function k(e){let t=e.trim();if(!t)return null;try{return(t.includes("://")?new URL(t):new URL(`https://${t}`)).hostname}catch{return null}}r(k,"normalizeDomain");function b(e){return{deviceCodeUrl:`https://${e}/login/device/code`,accessTokenUrl:`https://${e}/login/oauth/access_token`,copilotTokenUrl:`https://api.${e}/copilot_internal/v2/token`}}r(b,"getUrls");function O(e){let t=e.match(/proxy-ep=([^;]+)/);return t?`https://${t[1].replace(/^proxy\./,"api.")}`:null}r(O,"getBaseUrlFromToken");function f(e,t){if(e){let o=O(e);if(o)return o}return t?`https://copilot-api.${t}`:"https://api.individual.githubcopilot.com"}r(f,"getGitHubCopilotBaseUrl");function h(e){return e&&typeof e=="object"?e:void 0}r(h,"asRecord");function B(e,t){let o=h(e)?.data;if(!Array.isArray(o))throw new Error("Invalid Copilot models response");let a=o.flatMap(s=>{let c=h(s),u=c?.id;if(!c||typeof u!="string")return[];let d=h(c.capabilities);return h(d?.supports)?.tool_calls===!1?[]:[{id:u,pickerEnabled:c.model_picker_enabled===!0,policyState:h(c.policy)?.state}]}),i=a.filter(s=>s.pickerEnabled&&s.policyState!=="disabled").map(s=>s.id),n=t&&i.length===0,p=i.length>0||!t?i:a.filter(s=>s.policyState==="enabled").map(s=>s.id),l=a.filter(s=>s.policyState==="unconfigured"&&Object.hasOwn(H,s.id)&&(s.pickerEnabled||n)).map(s=>s.id);return{availableModelIds:p,policyModelIds:l}}r(B,"parseGitHubCopilotModelCatalog");async function T(e,t,o,a){let i=a.maxRetries>0&&a.maxElapsedMs>0?AbortSignal.timeout(a.maxElapsedMs):void 0,n=i?AbortSignal.any([o,i]):o,p=i?Date.now()+a.maxElapsedMs:void 0;for(let l=0;;l++){let s=await fetch(e,{...t,signal:AbortSignal.any([n,AbortSignal.timeout(5e3)])});if(s.status!==429||l===a.maxRetries)return s;let c=s.headers.get("retry-after"),u=500*2**l;if(c){let d=Number.parseFloat(c);if(u=Number.isNaN(d)?Date.parse(c)-Date.now():d*1e3,!Number.isFinite(u))return s}if(u=Math.max(0,u),p!==void 0&&u>=p-Date.now())return s;await s.body?.cancel(),await S(u,n)}}r(T,"fetchWithRateLimitRetry");async function I(e,t,o,a){let i=f(e,t),n=i==="https://api.individual.githubcopilot.com",p=await T(`${i}/models`,{headers:{Accept:"application/json",Authorization:`Bearer ${e}`,...v,"X-GitHub-Api-Version":j}},o,a);if(!p.ok)throw new Error(`${p.status} ${p.statusText}: ${await p.text()}`);return B(await p.json(),n)}r(I,"fetchGitHubCopilotModels");async function y(e,t){let o=await fetch(e,t);if(!o.ok){let a=await o.text();throw new Error(`${o.status} ${o.statusText}: ${a}`)}return o.json()}r(y,"fetchJson");async function z(e,t){let o=b(e),a=await y(o.deviceCodeUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"GitHubCopilotChat/0.35.0"},body:new URLSearchParams({client_id:C,scope:"read:user"}),signal:t});if(!a||typeof a!="object")throw new Error("Invalid device code response");let i=a.device_code,n=a.user_code,p=a.verification_uri,l=a.interval,s=a.expires_in;if(typeof i!="string"||typeof n!="string"||typeof p!="string"||l!==void 0&&typeof l!="number"||typeof s!="number")throw new Error("Invalid device code response fields");let c;try{c=new URL(p)}catch{throw new Error("Untrusted verification_uri in device code response")}if(c.protocol!=="https:"&&c.protocol!=="http:")throw new Error("Untrusted verification_uri in device code response");return{device_code:i,user_code:n,verification_uri:c.href,interval:l,expires_in:s}}r(z,"startDeviceFlow");async function Q(e,t,o){let a=b(e);return P({intervalSeconds:t.interval,expiresInSeconds:t.expires_in,waitBeforeFirstPoll:!0,signal:o,poll:r(async()=>{let i=await y(a.accessTokenUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"GitHubCopilotChat/0.35.0"},body:new URLSearchParams({client_id:C,device_code:t.device_code,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal:o});if(i&&typeof i=="object"&&typeof i.access_token=="string")return{status:"complete",value:i.access_token};if(i&&typeof i=="object"&&typeof i.error=="string"){let{error:n,error_description:p,interval:l}=i;if(n==="authorization_pending")return{status:"pending"};if(n==="slow_down")return{status:"slow_down",intervalSeconds:typeof l=="number"?l:void 0};let s=p?`: ${p}`:"";return{status:"failed",message:`Device flow failed: ${n}${s}`}}return{status:"failed",message:"Invalid device token response"}},"poll")})}r(Q,"pollForGitHubAccessToken");async function E(e,t,o){let a=b(t||"github.com"),i=await y(a.copilotTokenUrl,{headers:{Accept:"application/json",Authorization:`Bearer ${e}`,...v},signal:o});if(!i||typeof i!="object")throw new Error("Invalid Copilot token response");let n=i.token,p=i.expires_at;if(typeof n!="string"||typeof p!="number")throw new Error("Invalid Copilot token response fields");return{type:"oauth",refresh:e,access:n,expires:p*1e3-300*1e3,enterpriseUrl:t}}r(E,"refreshGitHubCopilotAccessToken");async function D(e,t,o){let a=await E(e,t,o),{availableModelIds:i}=await I(a.access,t,o,{maxRetries:0,maxElapsedMs:0});return{...a,availableModelIds:i}}r(D,"refreshGitHubCopilotToken");async function $(e,t,o,a){let i=`${f(e,o)}/models/${t}/policy`,n;try{n=await T(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...v,"openai-intent":"chat-policy","x-interaction-type":"chat-policy"},body:JSON.stringify({state:"enabled"})},a,{maxRetries:2,maxElapsedMs:5e3})}catch(p){if(a.aborted)throw p;return!1}if(n.status===429)throw new Error(`${n.status} ${n.statusText}: ${await n.text()}`);return n.ok}r($,"enableGitHubCopilotModel");async function F(e,t,o,a){let i=[];for(let n of t)try{await $(e,n,o,a)&&i.push(n)}catch(p){if(a.aborted)throw p;break}return i}r(F,"enableGitHubCopilotModels");async function N(e){let t=await e.prompt({type:"text",message:"GitHub Enterprise URL/domain (blank for github.com)",placeholder:"company.ghe.com"});if(e.signal.aborted)throw new Error("Login cancelled");let o=t.trim(),a=k(t);if(o&&!a)throw new Error("Invalid GitHub Enterprise URL/domain");let i=a||"github.com",n=await z(i,e.signal);e.notify({type:"device_code",userCode:n.user_code,verificationUri:n.verification_uri,intervalSeconds:n.interval,expiresInSeconds:n.expires_in});let p=await Q(i,n,e.signal),l=await E(p,a??void 0,e.signal),s=await I(l.access,a??void 0,e.signal,{maxRetries:2,maxElapsedMs:5e3}),c=[];return s.policyModelIds.length>0&&(e.notify({type:"progress",message:"Enabling models..."}),c=await F(l.access,s.policyModelIds,a??void 0,e.signal)),{...l,availableModelIds:[...new Set([...s.availableModelIds,...c])]}}r(N,"loginGitHubCopilot");function M(e){let t=e.enterpriseUrl;if(!(typeof t!="string"||!t))return k(t)??void 0}r(M,"copilotEnterpriseDomain");var K={name:"GitHub Copilot",isSubscription:!0,login:N,refresh:r((e,t)=>D(e.refresh,M(e),t),"refresh"),async toAuth(e){return{apiKey:e.access,baseUrl:f(e.access,M(e))}}};export{K as githubCopilotOAuth};
@@ -0,0 +1 @@
1
+ var T=Object.defineProperty;var d=(n,o)=>T(n,"name",{value:o,configurable:!0});import{createRequire as S}from"node:module";const ie=S(import.meta.url);import{GoogleGenAI as b,convertMessages as R,convertTools as I,getDisabledGoogleThinkingConfig as M,isThinkingPart as _,mapStopReason as G,resolveGoogleFunctionCallingMode as E,resolveGoogleThinkingLevel as P,retainThoughtSignature as w,retryGoogleRequest as A,supportsGoogleStrictToolSampling as L,toGoogleSdkThinkingLevel as O,toGoogleThinkingLevel as q,usesGoogleThinkingLevel as U}from"./chunk-5ULSWE2O.js";import{formatProviderError as $,normalizeProviderError as B}from"./chunk-TEPMHNKQ.js";import"./chunk-PMRZO46Y.js";import{buildBaseOptions as K,getPiUserAgent as W}from"./chunk-4XT6IQQ6.js";import{sanitizeSurrogates as z}from"./chunk-L2ZPNLYD.js";import{providerHeadersToRecord as D}from"./chunk-UTB4DTYQ.js";import{calculateCost as N,clampThinkingLevel as j,collapseSystemMessages as F,getCurrentTools as H,getInitialSystemMessage as J,getSystemMessageText as V}from"./chunk-GYI2XXNW.js";import{AssistantMessageEventStream as Q}from"./chunk-LPXNMA2W.js";import"./chunk-4L3WN2XY.js";var X=0,y=d((n,o,t)=>{let i=new Q,l=F(o);return(async()=>{let e={role:"assistant",content:[],api:"google-generative-ai",provider:n.provider,model:n.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{if(t?.fetch&&t.fetch!==globalThis.fetch)throw new Error("Custom fetch is not supported by the Google Generative AI adapter");let g=t?.apiKey;if(!g)throw new Error(`No API key for provider: ${n.provider}`);let h=Z(n,g,t?.headers),c=ee(n,l,t),f=await t?.onPayload?.(c,n);f!==void 0&&(c=f);let k=await A(()=>h.models.generateContentStream(c),t);i.push({type:"start",partial:e});let a=null,v=e.content,u=d(()=>v.length-1,"blockIndex");for await(let s of k){await t?.onProviderStreamEvent?.(s,n),e.responseId||=s.responseId;let m=s.candidates?.[0];if(m?.content?.parts)for(let r of m.content.parts){if(r.text!==void 0){let p=_(r);(!a||p&&a.type!=="thinking"||!p&&a.type!=="text")&&(a&&(a.type==="text"?i.push({type:"text_end",contentIndex:v.length-1,content:a.text,partial:e}):i.push({type:"thinking_end",contentIndex:u(),content:a.thinking,partial:e})),p?(a={type:"thinking",thinking:"",thinkingSignature:void 0},e.content.push(a),i.push({type:"thinking_start",contentIndex:u(),partial:e})):(a={type:"text",text:""},e.content.push(a),i.push({type:"text_start",contentIndex:u(),partial:e}))),a.type==="thinking"?(a.thinking+=r.text,a.thinkingSignature=w(a.thinkingSignature,r.thoughtSignature),i.push({type:"thinking_delta",contentIndex:u(),delta:r.text,partial:e})):(a.text+=r.text,a.textSignature=w(a.textSignature,r.thoughtSignature),i.push({type:"text_delta",contentIndex:u(),delta:r.text,partial:e}))}if(r.functionCall){a&&(a.type==="text"?i.push({type:"text_end",contentIndex:u(),content:a.text,partial:e}):i.push({type:"thinking_end",contentIndex:u(),content:a.thinking,partial:e}),a=null);let p=r.functionCall.id,C={type:"toolCall",id:!p||e.content.some(x=>x.type==="toolCall"&&x.id===p)?`${r.functionCall.name}_${Date.now()}_${++X}`:p,name:r.functionCall.name||"",arguments:r.functionCall.args??{},...r.thoughtSignature&&{thoughtSignature:r.thoughtSignature}};e.content.push(C),i.push({type:"toolcall_start",contentIndex:u(),partial:e}),i.push({type:"toolcall_delta",contentIndex:u(),delta:JSON.stringify(C.arguments),partial:e}),i.push({type:"toolcall_end",contentIndex:u(),toolCall:C,partial:e})}}m?.finishReason&&(e.rawStopReason=m.finishReason,e.stopReason=G(m.finishReason),e.content.some(r=>r.type==="toolCall")&&e.stopReason==="stop"&&(e.stopReason="toolUse")),s.usageMetadata&&(e.usage={input:(s.usageMetadata.promptTokenCount||0)-(s.usageMetadata.cachedContentTokenCount||0),output:(s.usageMetadata.candidatesTokenCount||0)+(s.usageMetadata.thoughtsTokenCount||0),cacheRead:s.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,reasoning:s.usageMetadata.thoughtsTokenCount||0,totalTokens:s.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},N(n,e.usage))}if(a&&(a.type==="text"?i.push({type:"text_end",contentIndex:u(),content:a.text,partial:e}):i.push({type:"thinking_end",contentIndex:u(),content:a.thinking,partial:e})),t?.signal?.aborted)throw new Error("Request was aborted");if(e.stopReason==="pending")throw new Error("Google stream ended without a finish reason");if(e.stopReason==="aborted"||e.stopReason==="error"){let s=e.rawStopReason?`Provider stopped with: ${e.rawStopReason}`:"An unknown error occurred";throw new Error(s)}i.push({type:"done",reason:e.stopReason,message:e}),i.end()}catch(g){for(let h of e.content)"index"in h&&delete h.index;e.stopReason=t?.signal?.aborted?"aborted":"error",e.errorMessage=$(B(g)),i.push({type:"error",reason:e.stopReason,error:e}),i.end()}})(),i},"stream"),Y=d((n,o,t)=>{let i=t?.apiKey;if(!i)throw new Error(`No API key for provider: ${n.provider}`);let l={...K(n,o,t,i),toolChoice:t?.toolChoice};if(!t?.reasoning)return y(n,o,{...l,thinking:{enabled:!1}});let e=j(n,t.reasoning);if(e==="off")return y(n,o,{...l,thinking:{enabled:!1}});let g=P(n,e);return U(n)?y(n,o,{...l,thinking:{enabled:!0,level:q(g)}}):y(n,o,{...l,thinking:{enabled:!0,budgetTokens:te(n,g,t.thinkingBudgets)}})},"streamSimple");function Z(n,o,t){let i={};n.baseUrl&&(i.baseUrl=n.baseUrl,i.apiVersion="");let l=D({"User-Agent":W(),...n.headers,...t});return l&&(i.headers=l),new b({apiKey:o,httpOptions:Object.keys(i).length>0?i:void 0})}d(Z,"createClient");function ee(n,o,t={}){let i=R(n,o),l=J(o.messages),e=H(o.messages),g={};t.temperature!==void 0&&(g.temperature=t.temperature),t.maxTokens!==void 0&&(g.maxOutputTokens=t.maxTokens);let h=L(n.id),c=e.length>0?E(e,t.toolChoice,h):void 0,f=l?V(l):"",k={...Object.keys(g).length>0&&g,...f&&{systemInstruction:z(f)},...e.length>0&&{tools:I(e,!1,h)},...c!==void 0&&{toolConfig:{functionCallingConfig:{mode:c}}}};if(t.thinking?.enabled&&n.reasoning){let a={includeThoughts:!0};t.thinking.level!==void 0?a.thinkingLevel=O(t.thinking.level):t.thinking.budgetTokens!==void 0&&(a.thinkingBudget=t.thinking.budgetTokens),k.thinkingConfig=a}else n.reasoning&&t.thinking&&!t.thinking.enabled&&(k.thinkingConfig=M(n));if(t.signal){if(t.signal.aborted)throw new Error("Request aborted");k.abortSignal=t.signal}return{model:n.id,contents:i,config:k}}d(ee,"buildParams");function te(n,o,t){return t?.[o]!==void 0?t[o]:n.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[o]:n.id.includes("2.5-flash-lite")?{minimal:512,low:2048,medium:8192,high:24576}[o]:n.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[o]:-1}d(te,"getGoogleBudget");export{y as stream,Y as streamSimple};