@earendil-works/pi-coding-agent 0.99.2 → 1.0.1
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.
- package/CHANGELOG.md +90 -0
- package/README.md +32 -7
- package/dist/bundle/chunks/{anthropic-messages-UID2PALB.js → anthropic-messages-GXHZP2HL.js} +3 -3
- package/dist/bundle/chunks/anthropic.js +2 -2
- package/dist/bundle/chunks/{azure-openai-responses-TLHNIYZK.js → azure-openai-responses-AFMVM6NP.js} +1 -1
- package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
- package/dist/bundle/chunks/chunk-2KAZSACP.js +2 -0
- package/dist/bundle/chunks/{chunk-R5J3MOBF.js → chunk-2VNGUWBO.js} +1 -1
- package/dist/bundle/chunks/chunk-5OEJBNHG.js +1203 -0
- package/dist/bundle/chunks/{chunk-7QSPBJKW.js → chunk-6FX7UEPL.js} +16 -30
- package/dist/bundle/chunks/chunk-F5ZABL6Z.js +20 -0
- package/dist/bundle/chunks/chunk-FDW3AYMM.js +2 -0
- package/dist/bundle/chunks/chunk-OYBSLV7Y.js +16 -0
- package/dist/bundle/chunks/{chunk-45SXDISG.js → chunk-PDFMCAOZ.js} +5 -5
- package/dist/bundle/chunks/{chunk-G3UZ5FWD.js → chunk-SYF2TF6W.js} +11 -60
- package/dist/bundle/chunks/chunk-WCQZGZ6I.js +82 -0
- package/dist/bundle/chunks/chunk-ZSI3BL5Q.js +4 -0
- package/dist/bundle/chunks/{cli-ALNBTL3U.js → cli-KILDDGW3.js} +4 -4
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-NPQN263E.js → cloudflare-workers-ai-system-one-X5PVWWYJ.js} +1 -1
- package/dist/bundle/chunks/codemode-worker.js +68 -8
- package/dist/bundle/chunks/easter-egg-3d-T5FFWIBR.js +2 -0
- package/dist/bundle/chunks/execute-RYVK27GT.js +388 -0
- package/dist/bundle/chunks/node-N5BSDOA5.js +16 -0
- package/dist/bundle/chunks/openai-chatgpt.js +2 -2
- package/dist/bundle/chunks/{openai-codex-responses-3GKGNXC4.js → openai-codex-responses-GK67DQQJ.js} +1 -1
- package/dist/bundle/chunks/openai-codex.js +1 -1
- package/dist/bundle/chunks/{openai-responses-S7GKCCDG.js → openai-responses-CQDDLDQF.js} +1 -1
- package/dist/bundle/chunks/openrouter.js +1 -1
- package/dist/bundle/chunks/radius.js +1 -1
- package/dist/bundle/chunks/runtime-D5I2NTIF.js +2 -0
- package/dist/bundle/chunks/virtual-modules-OO3V5ZPE.js +2 -0
- package/dist/bundle/cli-runtime.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +6 -3
- package/dist/cli/args.js.map +1 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +3 -0
- package/dist/config.js.map +1 -1
- package/dist/core/agent-session.d.ts +8 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +38 -9
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/export-html/tool-renderer.d.ts +3 -3
- package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
- package/dist/core/export-html/tool-renderer.js +3 -3
- package/dist/core/export-html/tool-renderer.js.map +1 -1
- package/dist/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +5 -0
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/runner.d.ts +3 -1
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +6 -0
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +9 -0
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/mcp-servers.d.ts +12 -0
- package/dist/core/mcp-servers.d.ts.map +1 -1
- package/dist/core/mcp-servers.js +18 -0
- package/dist/core/mcp-servers.js.map +1 -1
- package/dist/core/model-registry.d.ts +3 -1
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +4 -0
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/model-resolver.js +1 -1
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/radius.d.ts +2 -0
- package/dist/core/radius.d.ts.map +1 -1
- package/dist/core/radius.js +2 -0
- package/dist/core/radius.js.map +1 -1
- package/dist/core/settings-manager.d.ts +7 -5
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +3 -2
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/system-prompt.js +1 -1
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +3 -5
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/renderers/index.d.ts +2 -2
- package/dist/core/tools/renderers/index.d.ts.map +1 -1
- package/dist/core/tools/renderers/index.js.map +1 -1
- package/dist/extensions/codemode/execute.d.ts.map +1 -1
- package/dist/extensions/codemode/execute.js +154 -47
- package/dist/extensions/codemode/execute.js.map +1 -1
- package/dist/extensions/codemode/tool.d.ts +7 -7
- package/dist/extensions/codemode/tool.d.ts.map +1 -1
- package/dist/extensions/codemode/tool.js +55 -102
- package/dist/extensions/codemode/tool.js.map +1 -1
- package/dist/extensions/mcp/cli.d.ts.map +1 -1
- package/dist/extensions/mcp/cli.js +5 -2
- package/dist/extensions/mcp/cli.js.map +1 -1
- package/dist/extensions/mcp/config.d.ts +15 -3
- package/dist/extensions/mcp/config.d.ts.map +1 -1
- package/dist/extensions/mcp/config.js +46 -10
- package/dist/extensions/mcp/config.js.map +1 -1
- package/dist/extensions/mcp/index.d.ts +4 -1
- package/dist/extensions/mcp/index.d.ts.map +1 -1
- package/dist/extensions/mcp/index.js +97 -51
- package/dist/extensions/mcp/index.js.map +1 -1
- package/dist/extensions/mcp/oauth.d.ts +12 -8
- package/dist/extensions/mcp/oauth.d.ts.map +1 -1
- package/dist/extensions/mcp/oauth.js +104 -35
- package/dist/extensions/mcp/oauth.js.map +1 -1
- package/dist/extensions/mcp/runtime.d.ts.map +1 -1
- package/dist/extensions/mcp/runtime.js +3 -1
- package/dist/extensions/mcp/runtime.js.map +1 -1
- package/dist/extensions/mcp/tools.d.ts +3 -1
- package/dist/extensions/mcp/tools.d.ts.map +1 -1
- package/dist/extensions/mcp/tools.js +19 -13
- package/dist/extensions/mcp/tools.js.map +1 -1
- package/dist/extensions/mcp/ui.d.ts.map +1 -1
- package/dist/extensions/mcp/ui.js +8 -4
- package/dist/extensions/mcp/ui.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +6 -0
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/armin.d.ts +3 -0
- package/dist/modes/interactive/components/armin.d.ts.map +1 -1
- package/dist/modes/interactive/components/armin.js +7 -5
- package/dist/modes/interactive/components/armin.js.map +1 -1
- package/dist/modes/interactive/components/auth-url.d.ts +14 -0
- package/dist/modes/interactive/components/auth-url.d.ts.map +1 -0
- package/dist/modes/interactive/components/auth-url.js +37 -0
- package/dist/modes/interactive/components/auth-url.js.map +1 -0
- package/dist/modes/interactive/components/easter-egg-3d.d.ts +104 -0
- package/dist/modes/interactive/components/easter-egg-3d.d.ts.map +1 -0
- package/dist/modes/interactive/components/easter-egg-3d.js +1139 -0
- package/dist/modes/interactive/components/easter-egg-3d.js.map +1 -0
- package/dist/modes/interactive/components/easter-egg-3d.lazy.d.ts +6 -0
- package/dist/modes/interactive/components/easter-egg-3d.lazy.d.ts.map +1 -0
- package/dist/modes/interactive/components/easter-egg-3d.lazy.js +23 -0
- package/dist/modes/interactive/components/easter-egg-3d.lazy.js.map +1 -0
- package/dist/modes/interactive/components/index.d.ts +0 -1
- package/dist/modes/interactive/components/index.d.ts.map +1 -1
- package/dist/modes/interactive/components/index.js +0 -1
- package/dist/modes/interactive/components/index.js.map +1 -1
- package/dist/modes/interactive/components/login-dialog.d.ts +2 -0
- package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
- package/dist/modes/interactive/components/login-dialog.js +11 -5
- package/dist/modes/interactive/components/login-dialog.js.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.d.ts +8 -2
- package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.js +24 -21
- package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
- package/dist/modes/interactive/components/pi-logo.d.ts +7 -0
- package/dist/modes/interactive/components/pi-logo.d.ts.map +1 -1
- package/dist/modes/interactive/components/pi-logo.js +13 -1
- package/dist/modes/interactive/components/pi-logo.js.map +1 -1
- package/dist/modes/interactive/components/radius-login-selector.d.ts +15 -0
- package/dist/modes/interactive/components/radius-login-selector.d.ts.map +1 -0
- package/dist/modes/interactive/components/radius-login-selector.js +85 -0
- package/dist/modes/interactive/components/radius-login-selector.js.map +1 -0
- package/dist/modes/interactive/components/settings-selector.d.ts +3 -3
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +5 -5
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts +6 -18
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +22 -45
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/user-message.js +5 -4
- package/dist/modes/interactive/components/user-message.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +12 -2
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +166 -55
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/theme/system-theme.d.ts +2 -1
- package/dist/modes/interactive/theme/system-theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/system-theme.js +16 -5
- package/dist/modes/interactive/theme/system-theme.js.map +1 -1
- package/dist/package-manager-cli.d.ts.map +1 -1
- package/dist/package-manager-cli.js +12 -0
- package/dist/package-manager-cli.js.map +1 -1
- package/dist/utils/image-convert.d.ts +12 -0
- package/dist/utils/image-convert.d.ts.map +1 -1
- package/dist/utils/image-convert.js +45 -6
- package/dist/utils/image-convert.js.map +1 -1
- package/docs/cli.md +8 -16
- package/docs/codemode.md +207 -0
- package/docs/docs.json +5 -1
- package/docs/environment-variables.md +2 -2
- package/docs/extensions.md +4 -0
- package/docs/index.md +1 -1
- package/docs/keybindings.md +1 -1
- package/docs/mcp.md +40 -1
- package/docs/models.md +24 -3
- package/docs/providers.md +16 -6
- package/docs/quickstart.md +16 -2
- package/docs/sdk.md +1 -1
- package/docs/settings.md +3 -3
- package/docs/usage.md +1 -1
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/package.json +13 -14
- package/dist/bundle/chunks/chunk-3KYEVQKX.js +0 -82
- package/dist/bundle/chunks/chunk-3NVH2HQH.js +0 -4
- package/dist/bundle/chunks/chunk-3YAHQSW6.js +0 -1438
- package/dist/bundle/chunks/chunk-DTD7JQ7Y.js +0 -42
- package/dist/bundle/chunks/chunk-ECRK44UV.js +0 -2
- package/dist/bundle/chunks/execute-RC7W4ML3.js +0 -328
- package/dist/bundle/chunks/node-O3RIBJRH.js +0 -16
- package/dist/bundle/chunks/runtime-NJPX4ID2.js +0 -2
- package/dist/bundle/chunks/virtual-modules-5UGH4HRZ.js +0 -2
- package/dist/modes/interactive/components/daxnuts.d.ts +0 -23
- package/dist/modes/interactive/components/daxnuts.d.ts.map +0 -1
- package/dist/modes/interactive/components/daxnuts.js +0 -140
- package/dist/modes/interactive/components/daxnuts.js.map +0 -1
- package/npm-shrinkwrap.json +0 -1957
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
import{Bm25Ranker,CODEMODE_DOCS_PATH,CODEMODE_STORE_ENTRY_TYPE,DEFAULT_TOOL_SEARCH_LIMIT,combineUsage,createToolSearchDocument,getCodemodeCallableTools,parseCodemodeSource,renderToolSample,toCodemodeDeclaration,toCodemodeIdentifier}from"./chunk-SYF2TF6W.js";import"./chunk-OYBSLV7Y.js";import{getCodemodeWorkerSpecifier,getQuickJSWasmPath}from"./chunk-6FX7UEPL.js";import"./chunk-S3GGRYIO.js";import"./chunk-4L3WN2XY.js";import{randomBytes}from"node:crypto";import{writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{join}from"node:path";import{Worker}from"node:worker_threads";import{readFile}from"node:fs/promises";import{createRequire}from"node:module";var modules=new Map;function loadQuickJSWasm(path){let resolved=path??createRequire(import.meta.url).resolve("quickjs-wasi/quickjs.wasm"),module=modules.get(resolved);if(!module){let{WebAssembly}=globalThis;module=readFile(resolved).then(bytes=>WebAssembly.compile(bytes)).catch(error=>{throw modules.delete(resolved),error}),modules.set(resolved,module)}return module}function isWorkerToHostMessage(value){if(typeof value!="object"||value===null)return!1;let type=value.type;return type==="call"||type==="output"||type==="done"||type==="crash"}var DEFAULT_TIMEOUT_MS=3e5,IDENTIFIER=/^[A-Za-z_$][A-Za-z0-9_$]*$/,RESERVED_GLOBALS=new Set(["tools","ALL_TOOLS","console","text","image","exit","globalThis","store","load"]);function errorMessage(error){return error instanceof Error?error.message:String(error)}function serializeStore(store){let serialized={};for(let[key,value]of Object.entries(store??{})){let json=JSON.stringify(value);json!==void 0&&(serialized[key]=json)}return serialized}function parseStoreWrites(json){let writes={set:{},delete:[]};for(let[key,value]of JSON.parse(json))value===void 0?writes.delete.push(key):writes.set[key]=JSON.parse(value);return writes}function defaultWorkerUrl(){return new URL(import.meta.url.endsWith(".ts")?"./worker.ts":"./worker.js",import.meta.url)}var Execution=class{promise;resolveResult;worker;interrupt=new SharedArrayBuffer(4);tools;globals;signal;timer;output=[];calls=[];pending=new Map;finished=!1;constructor(options){this.promise=new Promise(resolve=>{this.resolveResult=resolve}),this.tools=options.tools,this.globals=options.globals,this.signal=options.signal,Number.isFinite(options.timeoutMs)&&(this.timer=setTimeout(()=>{this.finish({kind:"timeout",message:`Execution timed out after ${options.timeoutMs} ms`})},options.timeoutMs)),options.signal&&(options.signal.aborted?this.onAbort():options.signal.addEventListener("abort",this.onAbort,{once:!0})),options.wasm.then(wasm=>this.start(options,wasm),error=>{this.finish({kind:"sandbox",message:`Failed to load QuickJS: ${errorMessage(error)}`})})}abort(message){return this.finish({kind:"aborted",message}),this.promise}start(options,wasm){if(this.finished)return;let workerData={code:options.code,tools:[...options.tools.values()].map(tool=>({name:tool.name,jsName:toCodemodeIdentifier(tool.name),description:tool.description??""})),globals:[...options.globals.values()].map(global=>({name:global.name,spread:global.spread===!0})),wasm,memoryLimitBytes:options.memoryLimitBytes,store:options.store,interrupt:this.interrupt},worker;try{worker=new Worker(options.workerUrl,{workerData})}catch(error){this.finish({kind:"sandbox",message:`Failed to start worker: ${errorMessage(error)}`});return}this.worker=worker,worker.on("message",message=>this.handleMessage(message)),worker.on("error",error=>{this.finish({kind:"sandbox",name:error instanceof Error?error.name:void 0,message:errorMessage(error)})}),worker.on("exit",code=>{this.finish({kind:"sandbox",message:`Worker exited with code ${code} before the script settled`})})}onAbort=()=>{let reason=this.signal?.reason;this.finish({kind:"aborted",message:reason instanceof Error?reason.message:"Execution aborted"})};post(message){this.worker?.postMessage(message)}handleMessage(message){if(!(this.finished||!isWorkerToHostMessage(message)))switch(message.type){case"output":this.output.push(message.item);break;case"call":this.handleCall(message);break;case"done":this.handleDone(message);break;case"crash":this.finish({kind:"sandbox",message:message.message});break}}handleDone(message){if(!message.ok){let parsed=JSON.parse(message.error);this.finish({kind:"script",...parsed});return}this.finish(void 0,message.value===void 0?void 0:JSON.parse(message.value),message.writes)}async handleCall(message){let{id,name}=message,isTool=message.target==="tool",record=isTool?{name,status:"cancelled",durationMs:0}:void 0;record&&this.calls.push(record);let pending={record,startedAt:performance.now(),controller:new AbortController};this.pending.set(id,pending);let status,reply;try{let tool=(isTool?this.tools:this.globals).get(name);if(!tool)throw new Error(`Unknown ${isTool?"tool":"global"} "${name}"`);let args=message.args===void 0?void 0:JSON.parse(message.args),value=await tool.execute(args,{signal:pending.controller.signal});reply={type:"result",id,ok:!0,payload:value===void 0?void 0:JSON.stringify(value)},status="ok"}catch(error){reply={type:"result",id,ok:!1,payload:errorMessage(error)},status="error"}this.pending.delete(id)&&(record&&(record.status=status,record.durationMs=performance.now()-pending.startedAt),this.post(reply))}finish(error,value,writes){if(this.finished)return;this.finished=!0,clearTimeout(this.timer),this.signal?.removeEventListener("abort",this.onAbort);let now=performance.now();for(let pending of this.pending.values())pending.record&&(pending.record.durationMs=now-pending.startedAt),pending.controller.abort();this.pending.clear();let result=error?{ok:!1,error,output:this.output,calls:this.calls}:{ok:!0,value,output:this.output,calls:this.calls,storeWrites:writes===void 0?{set:{},delete:[]}:parseStoreWrites(writes)};if(!this.worker){this.resolveResult(result);return}Atomics.store(new Int32Array(this.interrupt),0,1),this.worker.terminate().catch(()=>{}).then(()=>this.resolveResult(result))}},CodemodeSandbox=class{toolsByName=new Map;globalsByName=new Map;timeoutMs;memoryLimitBytes;wasm;workerUrl;running=new Set;closed=!1;constructor(options={}){this.timeoutMs=options.timeoutMs??DEFAULT_TIMEOUT_MS,this.memoryLimitBytes=options.memoryLimitBytes,this.wasm=options.wasm,this.workerUrl=options.workerUrl??defaultWorkerUrl();for(let tool of options.tools??[])this.registerTool(tool);let namespaces=new Set;for(let global of options.globals??[]){let parts=global.name.split(".");if(parts.length>2||!parts.every(part=>IDENTIFIER.test(part))||RESERVED_GLOBALS.has(parts[0]))throw new Error(`Invalid global name "${global.name}"`);if(this.globalsByName.has(global.name))throw new Error(`Global "${global.name}" is already registered`);parts.length===2&&namespaces.add(parts[0]),this.globalsByName.set(global.name,global)}for(let name of namespaces)if(this.globalsByName.has(name))throw new Error(`Global "${name}" conflicts with the namespace "${name}"`)}registerTool(tool){if(this.toolsByName.has(tool.name))throw new Error(`Tool "${tool.name}" is already registered`);this.toolsByName.set(tool.name,tool)}unregisterTool(name){return this.toolsByName.delete(name)}get tools(){return[...this.toolsByName.values()]}get globals(){return[...this.globalsByName.values()]}execute(code,options={}){if(this.closed)return Promise.reject(new Error("Sandbox is closed"));let execution=new Execution({code,tools:new Map(this.toolsByName),globals:this.globalsByName,timeoutMs:options.timeoutMs??this.timeoutMs,signal:options.signal,memoryLimitBytes:this.memoryLimitBytes,store:serializeStore(options.store),wasm:this.wasm===void 0?loadQuickJSWasm():Promise.resolve(this.wasm),workerUrl:this.workerUrl});return this.running.add(execution),execution.promise.finally(()=>this.running.delete(execution))}async close(){this.closed=!0,await Promise.all([...this.running].map(execution=>execution.abort("Sandbox closed")))}};var IMAGE_HELPER_EXPECTS="image expects a non-empty image URL string, an object with image_url, or a raw MCP image block",PRELUDE_SOURCE=`(function (bridge, toolsJson, globalsJson, storeJson) {
|
|
3
|
+
"use strict";
|
|
4
|
+
const stringify = JSON.stringify;
|
|
5
|
+
const parse = JSON.parse;
|
|
6
|
+
const promiseThen = Promise.prototype.then;
|
|
7
|
+
const ErrorCtor = Error;
|
|
8
|
+
const TypeErrorCtor = TypeError;
|
|
9
|
+
const RangeErrorCtor = RangeError;
|
|
10
|
+
const pending = new Map();
|
|
11
|
+
let nextId = 1;
|
|
12
|
+
let finished = false;
|
|
13
|
+
// Thrown by exit() to unwind the script after it already reported success.
|
|
14
|
+
const EXIT = Object.freeze({});
|
|
15
|
+
|
|
16
|
+
function done(ok, payload, writes) {
|
|
17
|
+
if (finished) return;
|
|
18
|
+
finished = true;
|
|
19
|
+
bridge("done", ok, payload, writes);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function serialize(value) {
|
|
23
|
+
return value === undefined ? undefined : stringify(value);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// QuickJS stacks list frames only. Prefix "Name: message" like V8 so the
|
|
27
|
+
// text reads the same as a Node error, and drop this prelude's frames.
|
|
28
|
+
function errorText(error) {
|
|
29
|
+
const head = error.message ? error.name + ": " + error.message : String(error.name);
|
|
30
|
+
const frames =
|
|
31
|
+
typeof error.stack === "string"
|
|
32
|
+
? error.stack.split("\\n").filter((line) => line.trim() && !line.includes("codemode-prelude.js"))
|
|
33
|
+
: [];
|
|
34
|
+
return [head, ...frames].join("\\n");
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function format(value) {
|
|
38
|
+
if (typeof value === "string") return value;
|
|
39
|
+
if (value instanceof ErrorCtor) return errorText(value);
|
|
40
|
+
try {
|
|
41
|
+
const json = stringify(value);
|
|
42
|
+
return json === undefined ? String(value) : json;
|
|
43
|
+
} catch {
|
|
44
|
+
return String(value);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function describeError(error) {
|
|
49
|
+
if (error instanceof ErrorCtor) {
|
|
50
|
+
return stringify({ name: error.name, message: error.message, stack: errorText(error) });
|
|
51
|
+
}
|
|
52
|
+
return stringify({ message: format(error) });
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function caller(kind, name, spread) {
|
|
56
|
+
return (...args) =>
|
|
57
|
+
new Promise((resolve, reject) => {
|
|
58
|
+
let json;
|
|
59
|
+
try {
|
|
60
|
+
json = serialize(spread ? args : args[0]);
|
|
61
|
+
} catch (error) {
|
|
62
|
+
reject(error);
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
const id = nextId++;
|
|
66
|
+
pending.set(id, { resolve, reject });
|
|
67
|
+
bridge(kind, id, name, json);
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const tools = Object.create(null);
|
|
72
|
+
const allTools = [];
|
|
73
|
+
for (const { name, jsName, description } of parse(toolsJson)) {
|
|
74
|
+
const fn = caller("call", name);
|
|
75
|
+
// The first tool wins when two names normalize to the same identifier.
|
|
76
|
+
if (!(jsName in tools)) {
|
|
77
|
+
tools[jsName] = fn;
|
|
78
|
+
allTools.push(Object.freeze({ name: jsName, description }));
|
|
79
|
+
}
|
|
80
|
+
if (!(name in tools)) tools[name] = fn;
|
|
81
|
+
}
|
|
82
|
+
Object.freeze(tools);
|
|
83
|
+
Object.freeze(allTools);
|
|
84
|
+
|
|
85
|
+
// Reading a member that does not exist throws an error that names the close matches, instead of
|
|
86
|
+
// a later "not a function". \`in\` checks still work.
|
|
87
|
+
const comparable = (name) => name.toLowerCase().replace(/[^a-z0-9]/g, "");
|
|
88
|
+
function guard(target, label, names, hint) {
|
|
89
|
+
return new Proxy(target, {
|
|
90
|
+
get(object, property, receiver) {
|
|
91
|
+
if (typeof property !== "string" || property in object || property in Object.prototype || property === "then" || property === "toJSON") {
|
|
92
|
+
return Reflect.get(object, property, receiver);
|
|
93
|
+
}
|
|
94
|
+
const wanted = comparable(property);
|
|
95
|
+
const exact = names.filter((name) => comparable(name) === wanted);
|
|
96
|
+
const close = exact.length > 0 ? exact : names.filter((name) => wanted && (comparable(name).includes(wanted) || wanted.includes(comparable(name))));
|
|
97
|
+
let message = label + "." + property + " does not exist.";
|
|
98
|
+
if (close.length > 0) message += " Did you mean " + close.slice(0, 5).map((name) => label + "." + name).join(", ") + "?";
|
|
99
|
+
else if (names.length <= 20) message += " Available: " + names.join(", ") + ".";
|
|
100
|
+
if (hint) message += " " + hint;
|
|
101
|
+
message += ' Check for a member with "' + property + '" in ' + label + ".";
|
|
102
|
+
throw new TypeErrorCtor(message);
|
|
103
|
+
},
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
const toolsProxy = guard(
|
|
107
|
+
tools,
|
|
108
|
+
"tools",
|
|
109
|
+
allTools.map((tool) => tool.name),
|
|
110
|
+
"ALL_TOOLS lists every tool; searchTools(query) finds tools by topic.",
|
|
111
|
+
);
|
|
112
|
+
|
|
113
|
+
const namespaces = new Map();
|
|
114
|
+
for (const { name, spread } of parse(globalsJson)) {
|
|
115
|
+
const fn = caller("global", name, spread);
|
|
116
|
+
const dot = name.indexOf(".");
|
|
117
|
+
if (dot === -1) {
|
|
118
|
+
Object.defineProperty(globalThis, name, { value: fn, enumerable: true });
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
const namespace = name.slice(0, dot);
|
|
122
|
+
if (!namespaces.has(namespace)) namespaces.set(namespace, Object.create(null));
|
|
123
|
+
namespaces.get(namespace)[name.slice(dot + 1)] = fn;
|
|
124
|
+
}
|
|
125
|
+
for (const [namespace, members] of namespaces) {
|
|
126
|
+
Object.freeze(members);
|
|
127
|
+
const value = guard(members, namespace, Object.keys(members));
|
|
128
|
+
Object.defineProperty(globalThis, namespace, { value, enumerable: true });
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// key -> JSON text. Sizes count key and JSON characters.
|
|
132
|
+
const stored = new Map(Object.entries(parse(storeJson)));
|
|
133
|
+
const writes = new Map();
|
|
134
|
+
let storedChars = 0;
|
|
135
|
+
for (const [key, json] of stored) storedChars += key.length + json.length;
|
|
136
|
+
|
|
137
|
+
const STORE_HINT =
|
|
138
|
+
"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.";
|
|
139
|
+
|
|
140
|
+
function checkKey(name, key) {
|
|
141
|
+
if (typeof key !== "string") throw new TypeError(name + "() key must be a string");
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function store(key, value) {
|
|
145
|
+
checkKey("store", key);
|
|
146
|
+
const previous = stored.has(key) ? key.length + stored.get(key).length : 0;
|
|
147
|
+
if (value === undefined) {
|
|
148
|
+
stored.delete(key);
|
|
149
|
+
storedChars -= previous;
|
|
150
|
+
writes.set(key, undefined);
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
let json;
|
|
154
|
+
try {
|
|
155
|
+
json = stringify(value);
|
|
156
|
+
} catch (error) {
|
|
157
|
+
throw new TypeError("store(" + stringify(key) + ") value is not JSON-serializable: " + format(error));
|
|
158
|
+
}
|
|
159
|
+
if (json === undefined) {
|
|
160
|
+
throw new TypeError("store(" + stringify(key) + ") value is not JSON-serializable");
|
|
161
|
+
}
|
|
162
|
+
if (json.length > 262144) {
|
|
163
|
+
throw new RangeError(
|
|
164
|
+
"store(" + stringify(key) + ") value has " + json.length + " characters of JSON, more than the limit of 262144. " +
|
|
165
|
+
STORE_HINT,
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
const next = storedChars - previous + key.length + json.length;
|
|
169
|
+
if (next > 1048576) {
|
|
170
|
+
throw new RangeError(
|
|
171
|
+
"store is full: stored values would exceed 1048576 characters of JSON. Delete keys with store(key, undefined). " +
|
|
172
|
+
STORE_HINT,
|
|
173
|
+
);
|
|
174
|
+
}
|
|
175
|
+
stored.set(key, json);
|
|
176
|
+
storedChars = next;
|
|
177
|
+
writes.set(key, json);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function load(key) {
|
|
181
|
+
checkKey("load", key);
|
|
182
|
+
const json = stored.get(key);
|
|
183
|
+
return json === undefined ? undefined : parse(json);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function serializeWrites() {
|
|
187
|
+
const entries = [];
|
|
188
|
+
for (const [key, json] of writes) entries.push(json === undefined ? [key] : [key, json]);
|
|
189
|
+
return stringify(entries);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
Object.defineProperty(globalThis, "store", { value: store, enumerable: true });
|
|
193
|
+
Object.defineProperty(globalThis, "load", { value: load, enumerable: true });
|
|
194
|
+
|
|
195
|
+
let outputChars = 0;
|
|
196
|
+
let outputItems = 0;
|
|
197
|
+
|
|
198
|
+
// Past the output limits the script fails: done() reports the error, so catching it does not
|
|
199
|
+
// resume output, and the host ends the script.
|
|
200
|
+
function output(kind, data, mimeType) {
|
|
201
|
+
if (finished) return;
|
|
202
|
+
outputChars += data.length;
|
|
203
|
+
outputItems++;
|
|
204
|
+
if (outputChars > 16777216 || outputItems > 100000) {
|
|
205
|
+
const error = new RangeErrorCtor(
|
|
206
|
+
"script output exceeded the limit of 16777216 characters or 100000 text(), image(), and console calls. " +
|
|
207
|
+
"Print a summary instead, or write large data to a file with a tool.",
|
|
208
|
+
);
|
|
209
|
+
done(false, describeError(error));
|
|
210
|
+
throw error;
|
|
211
|
+
}
|
|
212
|
+
bridge("output", kind, data, mimeType);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// Primitives become their string form, everything else JSON.
|
|
216
|
+
function outputText(value) {
|
|
217
|
+
if (value === undefined || value === null || typeof value !== "object" && typeof value !== "function") {
|
|
218
|
+
return String(value);
|
|
219
|
+
}
|
|
220
|
+
const json = stringify(value);
|
|
221
|
+
return json === undefined ? String(value) : json;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function text(value) {
|
|
225
|
+
let rendered;
|
|
226
|
+
try {
|
|
227
|
+
rendered = outputText(value);
|
|
228
|
+
} catch (error) {
|
|
229
|
+
throw new TypeErrorCtor(error instanceof ErrorCtor ? error.message : String(error));
|
|
230
|
+
}
|
|
231
|
+
output("text", rendered);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function imageUrl(value) {
|
|
235
|
+
if (typeof value === "string") return value;
|
|
236
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
237
|
+
throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});
|
|
238
|
+
}
|
|
239
|
+
if (value.image_url !== undefined) {
|
|
240
|
+
if (typeof value.image_url !== "string") throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});
|
|
241
|
+
return value.image_url;
|
|
242
|
+
}
|
|
243
|
+
if (typeof value.type !== "string") throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});
|
|
244
|
+
if (value.type !== "image") {
|
|
245
|
+
throw new TypeErrorCtor('image only accepts MCP image blocks, got "' + value.type + '"');
|
|
246
|
+
}
|
|
247
|
+
if (typeof value.data !== "string" || value.data === "") throw new TypeErrorCtor("image expected MCP image data");
|
|
248
|
+
if (value.data.toLowerCase().startsWith("data:")) return value.data;
|
|
249
|
+
return "data:;base64," + value.data;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// Base64 of the signatures of the formats providers accept inline (PNG, JPEG except
|
|
253
|
+
// JPEG-LS, GIF, "RIFF....WEBP"). Signatures start at byte 0, so their encodings are prefixes.
|
|
254
|
+
const IMAGE_SIGNATURES = [
|
|
255
|
+
["image/png", /^iVBORw0KGg/],
|
|
256
|
+
["image/jpeg", /^[/]9j[/](?!9)/],
|
|
257
|
+
["image/gif", /^R0lGOD[dl]h/],
|
|
258
|
+
["image/webp", /^UklG.{8}RUJQ/],
|
|
259
|
+
];
|
|
260
|
+
|
|
261
|
+
function image(value) {
|
|
262
|
+
const url = imageUrl(value);
|
|
263
|
+
if (url === "") throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});
|
|
264
|
+
const colon = url.indexOf(":");
|
|
265
|
+
const scheme = colon === -1 ? "" : url.slice(0, colon).toLowerCase();
|
|
266
|
+
if (scheme === "http" || scheme === "https") {
|
|
267
|
+
throw new TypeErrorCtor("remote image URLs are not supported in tool outputs. Pass a base64 data URI instead");
|
|
268
|
+
}
|
|
269
|
+
const comma = url.indexOf(",");
|
|
270
|
+
const header = comma === -1 ? [] : url.slice(colon + 1, comma).split(";");
|
|
271
|
+
if (scheme !== "data" || comma === -1 || header.slice(1).every((part) => part.toLowerCase() !== "base64")) {
|
|
272
|
+
throw new TypeErrorCtor("invalid image output. Pass a base64 data URI instead");
|
|
273
|
+
}
|
|
274
|
+
// Providers reject the whole request on a bad image, and a persisted image block would be
|
|
275
|
+
// resent on every later turn. Line breaks from wrapped base64 are dropped. The declared type
|
|
276
|
+
// is ignored in favor of the detected one, as providers also reject mismatches.
|
|
277
|
+
const data = url.slice(comma + 1).replace(/\\s+/g, "");
|
|
278
|
+
if (data.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(data)) {
|
|
279
|
+
throw new TypeErrorCtor("invalid image output. The image data is not valid base64 (truncated or corrupted?)");
|
|
280
|
+
}
|
|
281
|
+
const head = data.slice(0, 16);
|
|
282
|
+
const signature = IMAGE_SIGNATURES.find(([, pattern]) => pattern.test(head));
|
|
283
|
+
if (!signature) {
|
|
284
|
+
throw new TypeErrorCtor("invalid image output. The image data is not a PNG, JPEG, GIF, or WebP image");
|
|
285
|
+
}
|
|
286
|
+
output("image", data, signature[0]);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function exit() {
|
|
290
|
+
let writesJson;
|
|
291
|
+
try {
|
|
292
|
+
writesJson = serializeWrites();
|
|
293
|
+
} catch (error) {
|
|
294
|
+
done(false, describeError(error));
|
|
295
|
+
throw EXIT;
|
|
296
|
+
}
|
|
297
|
+
done(true, undefined, writesJson);
|
|
298
|
+
throw EXIT;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
const console = {};
|
|
302
|
+
for (const level of ["log", "info", "warn", "error", "debug"]) {
|
|
303
|
+
console[level] = (...args) => {
|
|
304
|
+
output("text", args.map(format).join(" "));
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
Object.freeze(console);
|
|
308
|
+
|
|
309
|
+
Object.defineProperty(globalThis, "tools", { value: toolsProxy, enumerable: true });
|
|
310
|
+
Object.defineProperty(globalThis, "ALL_TOOLS", { value: allTools, enumerable: true });
|
|
311
|
+
Object.defineProperty(globalThis, "console", { value: console, enumerable: true });
|
|
312
|
+
Object.defineProperty(globalThis, "text", { value: text, enumerable: true });
|
|
313
|
+
Object.defineProperty(globalThis, "image", { value: image, enumerable: true });
|
|
314
|
+
Object.defineProperty(globalThis, "exit", { value: exit, enumerable: true });
|
|
315
|
+
|
|
316
|
+
return {
|
|
317
|
+
settle(id, ok, payload) {
|
|
318
|
+
const entry = pending.get(id);
|
|
319
|
+
if (!entry) return;
|
|
320
|
+
pending.delete(id);
|
|
321
|
+
if (!ok) {
|
|
322
|
+
entry.reject(new ErrorCtor(payload));
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
let value;
|
|
326
|
+
try {
|
|
327
|
+
value = payload === undefined ? undefined : parse(payload);
|
|
328
|
+
} catch (error) {
|
|
329
|
+
entry.reject(error);
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
entry.resolve(value);
|
|
333
|
+
},
|
|
334
|
+
run(fn) {
|
|
335
|
+
let promise;
|
|
336
|
+
try {
|
|
337
|
+
promise = fn(toolsProxy, console);
|
|
338
|
+
} catch (error) {
|
|
339
|
+
done(false, describeError(error));
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
promiseThen.call(
|
|
343
|
+
promise,
|
|
344
|
+
(value) => {
|
|
345
|
+
let json;
|
|
346
|
+
try {
|
|
347
|
+
json = serialize(value);
|
|
348
|
+
} catch (error) {
|
|
349
|
+
done(false, describeError(error));
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
352
|
+
done(true, json, serializeWrites());
|
|
353
|
+
},
|
|
354
|
+
(error) => {
|
|
355
|
+
done(false, describeError(error));
|
|
356
|
+
},
|
|
357
|
+
);
|
|
358
|
+
},
|
|
359
|
+
stalled() {
|
|
360
|
+
if (finished || pending.size > 0) return false;
|
|
361
|
+
done(
|
|
362
|
+
false,
|
|
363
|
+
stringify({
|
|
364
|
+
name: "Error",
|
|
365
|
+
message:
|
|
366
|
+
"The script is waiting on a promise that can never settle: no tool call is pending, and timers do not exist here.",
|
|
367
|
+
}),
|
|
368
|
+
);
|
|
369
|
+
return true;
|
|
370
|
+
},
|
|
371
|
+
};
|
|
372
|
+
})`;var ARGS_PREVIEW_CHARS=200,ERROR_PREVIEW_CHARS=500,MAX_CONCURRENT_MODEL_CALLS=4,CODEMODE_MEMORY_LIMIT_BYTES=256*1024*1024,MODEL_TYPES=new Set(["chat","image","classifier"]);function truncateText(text,maxChars){return text.length>maxChars?`${text.slice(0,maxChars-3)}...`:text}function previewArgs(args){if(args===void 0)return"";try{return truncateText(JSON.stringify(args)??"",ARGS_PREVIEW_CHARS)}catch{return""}}function textOf(result){return(result.content??[]).filter(block=>block.type==="text").map(block=>block.text).join(`
|
|
373
|
+
`)}function toModelType(value){if(typeof value=="string"&&MODEL_TYPES.has(value))return value;throw new Error(`Unknown model type ${JSON.stringify(value)}. Use "chat", "image", or "classifier".`)}function toProvider(value){if(value!=null){if(typeof value!="string")throw new Error("provider must be a string");return value}}function toModelInfo(model){let info={...model};return delete info.headers,info}function withArticle(word){return`${/^[aeiou]/.test(word)?"an":"a"} ${word}`}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function describeValue(value){if(value==null)return String(value);if(Array.isArray(value))return value.length===0?"an empty array":"an array";if(typeof value=="object"){let keys=Object.keys(value);return keys.length===0?"{}":`{ ${keys.slice(0,6).join(", ")}${keys.length>6?", ...":""} }`}return typeof value=="string"?"a string":`a ${typeof value}`}var CLASSIFIER_CONTEXT_SHAPE='{ state: { ... }, 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 checkClassifierContext(context){let fail=problem=>new Error(`models.classify() ${problem}. Expected context: ${CLASSIFIER_CONTEXT_SHAPE}. See "Classify" in ${CODEMODE_DOCS_PATH}.`);if(!isRecord(context))throw fail(`expects a context object as its second argument, got ${describeValue(context)}`);if(!isRecord(context.state))throw fail(`context.state must be an object, got ${describeValue(context.state)}`);let{questions}=context;if(!isRecord(questions)||Object.keys(questions).length===0)throw fail(`context.questions must map question IDs to questions, got ${describeValue(questions)}`);let isStrings=values=>values.length>0&&values.every(value=>typeof value=="string");for(let[id,question]of Object.entries(questions)){let at=`context.questions.${id}`;if(!isRecord(question))throw fail(`${at} must be a question object, got ${describeValue(question)}`);if(typeof question.instructions!="string")throw fail(`${at}.instructions must be a string`);let{criteria}=question;if(question.type==="choice"){if(!isRecord(criteria)||!isStrings(Object.values(criteria)))throw fail(`${at} is a "choice" question, so criteria must map each label to its meaning`)}else if(question.type==="score"){if(!Array.isArray(criteria)||!isStrings(criteria))throw fail(`${at} is a "score" question, so criteria must list the levels as strings, lowest first`)}else if(question.type==="bool"){if(!isRecord(criteria)||typeof criteria.true!="string"||typeof criteria.false!="string")throw fail(`${at} is a "bool" question, so criteria must be { true: string, false: string }`)}else throw fail(`${at}.type must be "choice", "score", or "bool", got ${JSON.stringify(question.type)}`)}return context}function checkImagesContext(context){let fail=problem=>new Error(`models.generateImages() ${problem}. Expected context: { input: [{ type: "text", text: <prompt> }, ...optional { type: "image", data: <base64>, mimeType } references] }. See "Generate images" in ${CODEMODE_DOCS_PATH}.`);if(!isRecord(context))throw fail(`expects a context object as its second argument, got ${describeValue(context)}`);let{input}=context;if(!Array.isArray(input)||input.length===0)throw fail(`context.input must be a non-empty array of blocks, got ${describeValue(input)}`);return input.forEach((block,index)=>{if(!(isRecord(block)&&block.type==="text"&&typeof block.text=="string")&&!(isRecord(block)&&block.type==="image"&&typeof block.data=="string"&&typeof block.mimeType=="string"))throw fail(`context.input[${index}] must be a text or image block, got ${describeValue(block)}`)}),context}function createLimiter(limit){let active=0,waiting=[];return async run=>{active>=limit&&await new Promise(resolve=>waiting.push(resolve)),active++;try{return await run()}finally{active--,waiting.shift()?.()}}}function isStoreEntryData(data){if(typeof data!="object"||data===null)return!1;let{set,delete:deleted}=data;return typeof set=="object"&&set!==null&&Array.isArray(deleted)&&deleted.every(key=>typeof key=="string")}function readCodemodeStore(branch){let store=new Map;for(let entry of branch)if(!(entry.type!=="custom"||entry.customType!==CODEMODE_STORE_ENTRY_TYPE||!isStoreEntryData(entry.data))){for(let key of entry.data.delete)store.delete(key);for(let[key,value]of Object.entries(entry.data.set))store.set(key,value)}return Object.fromEntries(store)}var DEFAULT_MAX_OUTPUT_TOKENS=1e4,CHARS_PER_TOKEN=4;function valueText(value){return typeof value=="string"?value:JSON.stringify(value)??String(value)}function formatCallSummary(calls){return calls.length===0?"No tool calls were made.":`Tool calls made before the failure (they are not undone): ${calls.map(call=>`${call.name} (${call.status})`).join(", ")}`}function formatError(result,calls){let{error}=result;return`${error.kind==="script"?error.stack??`${error.name??"Error"}: ${error.message}`:error.kind==="timeout"?`Script timed out: ${error.message}`:error.kind==="aborted"?`Script aborted: ${error.message}`:`Script sandbox failed: ${error.message}`}
|
|
374
|
+
|
|
375
|
+
${formatCallSummary(calls)}`}async function spillOutput(text){let path=join(tmpdir(),`pi-codemode-${randomBytes(8).toString("hex")}.txt`);try{return await writeFile(path,text),{path}}catch(error){return{error:error instanceof Error?error.message:String(error)}}}async function truncateOutput(items,maxTokens){let texts=items.filter(item=>item.type==="text").map(item=>item.text),combined=texts.join(`
|
|
376
|
+
`),budget=maxTokens*CHARS_PER_TOKEN;if(texts.length===0||combined.length<=budget)return{items};let headChars=Math.floor(budget/2),tailChars=budget-headChars,removed=combined.length-headChars-tailChars,head=combined.slice(0,headChars),tail=tailChars>0?combined.slice(-tailChars):"",text=`Warning: truncated output (original token count: ${Math.ceil(combined.length/CHARS_PER_TOKEN)})
|
|
377
|
+
Total output lines: ${combined.split(`
|
|
378
|
+
`).length}
|
|
379
|
+
|
|
380
|
+
${head}\u2026${Math.ceil(removed/CHARS_PER_TOKEN)} tokens truncated\u2026${tail}`,spilled=await spillOutput(combined);return text+="path"in spilled?`
|
|
381
|
+
|
|
382
|
+
[Full output: ${spilled.path} (read with offset/limit)]`:`
|
|
383
|
+
|
|
384
|
+
[Could not save the full output: ${spilled.error}]`,{items:[{type:"text",text},...items.filter(item=>item.type==="image")],..."path"in spilled?{fullOutputPath:spilled.path}:{}}}function toScriptValue(tool,outcome){let{result}=outcome;if(tool.outputSchema&&result.structuredContent!==void 0)return result.structuredContent;let text=textOf(result);if(outcome.isError)throw new Error(text||`Tool "${tool.name}" failed`);return text}async function executeCodemode(toolCallId,input,signal,onUpdate,ctx,options={}){let startedAt=performance.now(),{code,options:sourceOptions}=parseCodemodeSource(input.code),calls=[],modelUsage,generatedImages=0,addGeneratedImages=count=>{generatedImages+=count},addModelUsage=usage=>{modelUsage=modelUsage?combineUsage(modelUsage,usage):usage},snapshot=()=>({calls:calls.map(call=>({...call}))}),publish=()=>onUpdate?.({content:[],details:snapshot()}),callable=ctx?getCodemodeCallableTools(ctx.tools):[],samples=new Map(callable.map(tool=>[tool.name,renderToolSample(toCodemodeDeclaration(tool))])),sandboxTools=callable.map(tool=>({name:tool.name,description:samples.get(tool.name),execute:async(args,{signal:callSignal})=>{let record={id:`${toolCallId}/?`,name:tool.name,args:previewArgs(args),status:"running"};calls.push(record),publish();let callStartedAt=performance.now();if(!ctx)throw new Error("Tool calls need a session");let outcome=await ctx.executeTool(tool.name,args,{signal:callSignal});return record.id=outcome.toolCall.id,record.durationMs=performance.now()-callStartedAt,outcome.isError?(record.status=callSignal.aborted?"cancelled":"error",record.error=truncateText(textOf(outcome.result)||`Tool "${tool.name}" failed`,ERROR_PREVIEW_CHARS)):record.status="ok",publish(),toScriptValue(tool,outcome)}})),sandbox=new CodemodeSandbox({tools:sandboxTools,globals:[...createDiscoveryGlobals(callable,samples,options),...options.models&&ctx?createModelGlobals(ctx.modelRegistry,toolCallId,calls,publish,addModelUsage,addGeneratedImages):[]],timeoutMs:sourceOptions.timeoutMs??Number.POSITIVE_INFINITY,memoryLimitBytes:CODEMODE_MEMORY_LIMIT_BYTES,wasm:loadQuickJSWasm(getQuickJSWasmPath()),workerUrl:getCodemodeWorkerSpecifier()}),result;try{let store=ctx?readCodemodeStore(ctx.sessionManager.getBranch()):{};result=await sandbox.execute(code,{signal,store})}finally{await sandbox.close()}for(let call of calls)call.status==="running"&&(call.status="cancelled");let items=result.output.map(item=>item.type==="text"?{type:"text",text:item.text}:item);if(result.ok){let{set,delete:deleted}=result.storeWrites;(Object.keys(set).length>0||deleted.length>0)&&options.appendEntry?.(CODEMODE_STORE_ENTRY_TYPE,{set,delete:deleted}),result.value!==void 0&&items.push({type:"text",text:valueText(result.value)})}else items.push({type:"text",text:`Script error:
|
|
385
|
+
${formatError(result,calls)}`});generatedImages>0&&!items.some(item=>item.type==="image")&&items.push({type:"text",text:`Note: models.generateImages() returned ${generatedImages} image${generatedImages===1?"":"s"} that the script did not show. Show each image block of result.output with image(block).`});let truncated=await truncateOutput(items,sourceOptions.maxOutputTokens??DEFAULT_MAX_OUTPUT_TOKENS),wallTime=((performance.now()-startedAt)/1e3).toFixed(1),header=`${result.ok?"Script completed":"Script failed"}
|
|
386
|
+
Wall time ${wallTime} seconds
|
|
387
|
+
Output:
|
|
388
|
+
`,details=snapshot();return truncated.fullOutputPath&&(details.fullOutputPath=truncated.fullOutputPath),{content:[{type:"text",text:header},...truncated.items],details,...modelUsage?{usage:modelUsage}:{},...result.ok?{}:{isError:!0}}}function isNamespaceName(namespace,query){let id=toCodemodeIdentifier(namespace),queryId=toCodemodeIdentifier(query),suffix=name=>name.includes("__")?name.slice(name.lastIndexOf("__")+2):void 0;return namespace===query||id===queryId||suffix(namespace)===query||suffix(id)===queryId}function createDiscoveryGlobals(tools,samples,options){let ranker=new Bm25Ranker,entry=name=>({name:toCodemodeIdentifier(name),description:samples.get(name)??""});return[{name:"searchTools",spread:!0,execute:args=>{let[query,searchOptions]=args;if(typeof query!="string")throw new Error("searchTools() expects a query string");let limit=searchOptions?.limit??DEFAULT_TOOL_SEARCH_LIMIT;if(typeof limit!="number"||!Number.isInteger(limit)||limit<=0)throw new Error("searchTools() limit must be a positive integer");let namespace=searchOptions?.namespace;if(namespace!=null&&typeof namespace!="string")throw new Error("searchTools() namespace must be a string");let documents=tools.flatMap(tool=>{let toolNamespace=options.getToolNamespace?.(tool.name);return namespace&&(!toolNamespace||!isNamespaceName(toolNamespace.name,namespace))?[]:[createToolSearchDocument(tool,toolNamespace)]});return ranker.rank(query,documents,limit).map(match=>entry(match.name))}},{name:"describeTool",spread:!0,execute:args=>{let[name]=args;if(typeof name!="string")throw new Error("describeTool() expects a tool name");let tool=tools.find(candidate=>candidate.name===name||toCodemodeIdentifier(candidate.name)===name);return tool?samples.get(tool.name):void 0}},{name:"describeNamespace",spread:!0,execute:args=>{let[name]=args;if(typeof name!="string")throw new Error("describeNamespace() expects a namespace name");let namespace,names=[];for(let tool of tools){let toolNamespace=options.getToolNamespace?.(tool.name);!toolNamespace||!isNamespaceName(toolNamespace.name,name)||(namespace??=toolNamespace,names.push(toCodemodeIdentifier(tool.name)))}if(namespace)return{name:namespace.name,...namespace.description?{description:namespace.description}:{},...namespace.instructions?{instructions:namespace.instructions}:{},tools:names}}}]}function createModelGlobals(models,toolCallId,calls,publish,addUsage,addGeneratedImages){let limit=createLimiter(MAX_CONCURRENT_MODEL_CALLS),callCount=0,runModelCall=async(name,type,[model,context],checkContext,run)=>{let listHint=`List the ${type} models you can use with models.getAvailableOfType("${type}").`;if(!isRecord(model)||typeof model.provider!="string"||typeof model.id!="string"){let undefinedHint=model==null?" models.getModelOfType() returns undefined for an unknown provider or id.":"";throw new Error(`${name}() expects ${withArticle(type)} model as its first argument, got ${describeValue(model)}.${undefinedHint} ${listHint}`)}let{provider,id}=model,ref=`${provider}/${id}`,resolved=models.getModelOfType(type,provider,id);if(!resolved){let actualType=[...MODEL_TYPES].find(other=>other!==type&&models.getModelOfType(other,provider,id)!==void 0);throw new Error(actualType?`"${ref}" is ${withArticle(actualType)} model, not ${withArticle(type)} model. ${listHint}`:`Unknown ${type} model "${ref}". ${listHint}`)}let checked=checkContext(context),record={id:`${toolCallId}/${name}/${++callCount}`,name,args:`${resolved.provider}/${resolved.id}`,status:"running"};calls.push(record),publish();let startedAt=performance.now(),result=await limit(()=>run(resolved,checked));return record.durationMs=performance.now()-startedAt,record.status=result.stopReason==="stop"?"ok":result.stopReason==="aborted"?"cancelled":"error",result.errorMessage&&(record.error=truncateText(result.errorMessage,ERROR_PREVIEW_CHARS)),result.usage&&(record.cost=result.usage.cost.total,addUsage(result.usage)),publish(),result};return Object.entries({"models.getModelsOfType":args=>{let[type,provider]=args;return models.getModelsOfType(toModelType(type),toProvider(provider)).map(toModelInfo)},"models.getAvailableOfType":async(args,{signal})=>{let[type,provider]=args;return(await models.getAvailableOfType(toModelType(type),toProvider(provider),{signal})).map(toModelInfo)},"models.getModelOfType":args=>{let[type,provider,id]=args;if(typeof provider!="string"||typeof id!="string")throw new Error(`models.getModelOfType(type, provider, id) expects three strings, got (${args.map(describeValue).join(", ")}). The provider and the id are separate arguments, for example models.getModelOfType("classifier", "typesafe", "jev-latest").`);let model=models.getModelOfType(toModelType(type),provider,id);return model===void 0?void 0:toModelInfo(model)},"models.classify":(args,{signal})=>runModelCall("models.classify","classifier",args,checkClassifierContext,(resolved,context)=>models.classify(resolved,context,{signal})),"models.generateImages":(args,{signal})=>runModelCall("models.generateImages","image",args,checkImagesContext,async(resolved,context)=>{let result=await models.generateImages(resolved,context,{signal});return addGeneratedImages(result.output.filter(block=>block.type==="image").length),result})}).map(([name,execute])=>({name,spread:!0,execute}))}export{executeCodemode,readCodemodeStore};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
import{child_process,crypto,fs,path,stream,util}from"./chunk-7ZC4UXSL.js";import{AnthropicError,DEFAULT_MEMORY_SYNC_INTERVAL_MS,MIN_MEMORY_SYNC_INTERVAL_MS,ToolError,__classPrivateFieldGet,__classPrivateFieldSet,checkMemorySyncInterval,decodeUTF8,encodeUTF8,isStatus,loggerFor,promiseWithResolvers}from"./chunk-F5ZABL6Z.js";import"./chunk-4L3WN2XY.js";import*as fs4 from"node:fs/promises";import*as fssync from"node:fs";import*as path2 from"node:path";import*as cp from"node:child_process";import*as crypto2 from"node:crypto";import*as readline from"node:readline";function betaTool(options){if(options.inputSchema.type!=="object")throw new Error(`JSON schema for tool "${options.name}" must be an object, but got ${options.inputSchema.type}`);return{type:"custom",name:options.name,input_schema:options.inputSchema,description:options.description,run:options.run,parse:content=>content,...options.close?{close:options.close}:{}}}var fs2=fs.promises,DIR_CREATE_MODE=448,FILE_CREATE_MODE=384;function isWithin(root,p){let rel=path.relative(root,p);return rel===""||!rel.startsWith(".."+path.sep)&&rel!==".."&&!path.isAbsolute(rel)}async function containingRoot(roots,target){for(let root of roots)if(isWithin(await canonicalize(path.resolve(root)),target))return root}var MAX_SYMLINK_HOPS=40;function errnoCode(err){let code=err?.code;return typeof code=="string"?code:void 0}async function canonicalize(abs){let tail=[],prefix=abs,hops=0;for(;;){let real;try{real=await fs2.realpath(prefix)}catch(realpathErr){let isLink;try{isLink=(await fs2.lstat(prefix)).isSymbolicLink()}catch(lstatErr){let code=errnoCode(lstatErr);if(code!=="ENOENT"&&code!=="ENOTDIR")throw lstatErr;let parent=path.dirname(prefix);if(parent===prefix)throw lstatErr;tail.push(path.basename(prefix)),prefix=parent;continue}if(!isLink)throw realpathErr;if(++hops>MAX_SYMLINK_HOPS)throw Object.assign(new Error("too many levels of symbolic links"),{code:"ELOOP"});prefix=path.resolve(path.dirname(prefix),await fs2.readlink(prefix));continue}return tail.length?path.join(real,...tail.reverse()):real}}async function confineToRoot(root,p,opts){let allowedRoots=opts?.allowedRoots??[],realRoot=await canonicalize(path.resolve(root)),real;try{real=await canonicalize(path.resolve(realRoot,p))}catch(err){throw new ToolError(fsErrorMessage(err,`path ${JSON.stringify(p)}`))}if(isWithin(realRoot,real)||await containingRoot(allowedRoots,real)!==void 0)return real;let permitted=allowedRoots.length?"the session's working directory and its other permitted directories":"the session's working directory";throw new ToolError(`path ${JSON.stringify(p)} is outside ${permitted}`)}async function atomicWriteFile(targetPath,content){let dir=path.dirname(targetPath),tempPath=path.join(dir,`.tmp-${process.pid}-${crypto.randomUUID()}`),existingMode=await fs2.stat(targetPath).then(st=>st.mode&511,()=>{}),handle;try{handle=await fs2.open(tempPath,"wx",FILE_CREATE_MODE),existingMode!==void 0&&await handle.chmod(existingMode),await handle.writeFile(content,"utf-8"),await handle.sync(),await handle.close(),handle=void 0,await fs2.rename(tempPath,targetPath)}catch(err){throw handle&&await handle.close().catch(()=>{}),await fs2.unlink(tempPath).catch(()=>{}),err}}function fsErrorMessage(err,file){let code=errnoCode(err);switch(code){case"ENOENT":return`${file}: no such file or directory`;case"EACCES":case"EPERM":return`${file}: permission denied`;case"ENOTDIR":return`${file}: not a directory`;case"EISDIR":return`${file}: is a directory`;case"ELOOP":return`${file}: too many levels of symbolic links`;case"ENAMETOOLONG":return`${file}: file name too long`;case"ENOSPC":return`${file}: no space left on device`;case"EMFILE":case"ENFILE":return`${file}: too many open files`;default:return`${file}: ${code!==void 0?`i/o error (${code})`:"i/o error"}`}}var fs3=fs.promises,execFileAsync=util.promisify(child_process.execFile);async function setupSkills(ctx){let{client,sessionId}=ctx;if(!client)return async()=>{};let log=loggerFor(client),session=ctx.session;if(!session){if(sessionId===void 0)return async()=>{};log.warn("AgentToolContext.sessionId is deprecated and costs an extra session fetch; fetch the session once and set `session` instead",{component:"agent-tool-context"}),session=await client.beta.sessions.retrieve(sessionId)}let skillsRoot=path.resolve(ctx.workdir,"skills"),created=[];for(let skill of session.agent.skills)try{let version=await client.beta.skills.versions.retrieve(skill.version,{skill_id:skill.skill_id}),dirname2=path.basename(version.name.trim());(dirname2===""||dirname2==="."||dirname2==="..")&&(dirname2=skill.skill_id);let dest=path.resolve(skillsRoot,dirname2);if(dest!==skillsRoot&&!dest.startsWith(skillsRoot+path.sep)){log.warn("skill name escapes the skills dir; skipping",{component:"agent-tool-context",name:version.name});continue}let resp=await client.beta.skills.versions.download(version.id,{skill_id:skill.skill_id});await fs3.rm(dest,{recursive:!0,force:!0}),await fs3.mkdir(dest,{recursive:!0,mode:DIR_CREATE_MODE}),created.push(dest),await extractSkillArchive(resp,dest),log.info("downloaded skill",{component:"agent-tool-context",skill_id:skill.skill_id,version:version.id,dest})}catch(e){log.warn("failed to download skill",{component:"agent-tool-context",skill_id:skill.skill_id,error:String(e)})}return async()=>{for(let dest of created)await fs3.rm(dest,{recursive:!0,force:!0}).catch(e=>{log.warn("failed to clean up skill",{component:"agent-tool-context",dest,error:String(e)})})}}function assertSafeMemberNames(names){for(let raw of names){let entry=raw.trim();if(entry&&(path.isAbsolute(entry)||entry.split(/[\\/]/).includes("..")))throw new AnthropicError(`refusing to extract unsafe archive member: ${entry}`)}}var INCONSISTENT_LISTING="skill archive listing is inconsistent; refusing to extract",PLAIN_TYPE_CHARS={unzip:new Set(["-","d","?"]),tar:new Set(["-","d","C"])};function listingLines(listing){let lines=listing.split(`
|
|
3
|
+
`);return lines[lines.length-1]===""&&lines.pop(),lines}function canExcludeVerbatim(cmd,name){return/^[\x20-\x7E]+$/.test(name)&&!/[\\^#]/.test(name)&&!(cmd==="unzip"&&name.startsWith("-"))}function classifyArchiveListing(cmd,names,typed){let nameLines=listingLines(names),typedLines=listingLines(typed);if(nameLines.length!==typedLines.length)throw new AnthropicError(INCONSISTENT_LISTING);let plain=[],special=[];return nameLines.forEach((name,i)=>{if(PLAIN_TYPE_CHARS[cmd].has(typedLines[i].charAt(0))){plain.push(name);return}if(!canExcludeVerbatim(cmd,name))throw new AnthropicError(`refusing to extract archive: cannot safely exclude member ${JSON.stringify(name)}`);special.push(name)}),{plain,special}}async function assertOnlyPlainEntries(dir){for(let entry of await fs3.readdir(dir,{withFileTypes:!0}))if(entry.isDirectory())await assertOnlyPlainEntries(path.join(dir,entry.name));else if(!entry.isFile())throw new AnthropicError(INCONSISTENT_LISTING)}async function runArchiveTool(cmd,args){try{let{stdout}=await execFileAsync(cmd,args);return stdout}catch(e){throw errnoCode(e)==="ENOENT"?new AnthropicError(`skill extraction requires the \`${cmd}\` command, but it was not found on PATH`):e}}function archiveTopDir(names){let top,nested=!1;for(let raw of names){let parts=raw.trim().split("/").filter(p=>p!==""&&p!==".");if(parts.length===0)continue;let first=parts[0];if(top===void 0)top=first;else if(first!==top)return"";parts.length>1&&(nested=!0)}return top!==void 0&&nested?top:""}async function extractSkillArchive(resp,dest){let tmp=path.join(dest,`.skill-archive-${process.pid}-${Date.now()}`);if(!resp.body)throw new AnthropicError("skill download response had no body");await stream.promises.pipeline(stream.Readable.fromWeb(resp.body),fs.createWriteStream(tmp));let stage=path.join(path.dirname(dest),`.skill-stage-${process.pid}-${Date.now()}`),excludeFile=path.join(path.dirname(dest),`.skill-exclude-${process.pid}-${Date.now()}`);try{let head=await readHead(tmp,4),isZip=head.length>=4&&head[0]===80&&head[1]===75&&head[2]===3&&head[3]===4,archiveCmd=isZip?"unzip":"tar",names=await runArchiveTool(archiveCmd,isZip?["-Z1",tmp]:["-tf",tmp]),typed=await runArchiveTool(archiveCmd,isZip?["-Z","--h","--t",tmp]:["-tvf",tmp]),{plain,special}=classifyArchiveListing(archiveCmd,names,typed);assertSafeMemberNames([...plain,...special]);let top=archiveTopDir(plain);await fs3.mkdir(stage,{recursive:!0,mode:DIR_CREATE_MODE}),plain.length>0&&await runArchiveTool(archiveCmd,await extractArgs(archiveCmd,tmp,stage,special,excludeFile)),await assertOnlyPlainEntries(stage);let srcRoot=top?path.join(stage,top):stage,entries=await fs3.readdir(srcRoot).catch(e=>{throw errnoCode(e)==="ENOENT"?new AnthropicError(INCONSISTENT_LISTING):e});for(let entry of entries)await fs3.rename(path.join(srcRoot,entry),path.join(dest,entry))}finally{await fs3.rm(tmp,{force:!0}),await fs3.rm(excludeFile,{force:!0}),await fs3.rm(stage,{recursive:!0,force:!0})}}async function extractArgs(cmd,archive,stage,special,excludeFile){let patterns=special.map(name=>name.replace(/[*?[\\]/g,"\\$&"));return cmd==="unzip"?["-oq",archive,"-d",stage,...patterns.length>0?["-x",...patterns]:[]]:patterns.length===0?["-xf",archive,"-C",stage]:(await fs3.writeFile(excludeFile,patterns.join(`
|
|
4
|
+
`)+`
|
|
5
|
+
`,{flag:"wx",mode:384}),["-xf",archive,"-C",stage,"-X",excludeFile])}async function readHead(file,n){let handle=await fs3.open(file,"r");try{let buf=Buffer.alloc(n),{bytesRead}=await handle.read(buf,0,n,0);return buf.subarray(0,bytesRead)}finally{await handle.close()}}var fsp=fs.promises,C=fs.constants,OWNER_ONLY_DIR_MODE=448,OWNER_ONLY_FILE_MODE=384,OWNER_ONLY_EXEC_MODE=448,O_NOFOLLOW=C.O_NOFOLLOW??0,O_NONBLOCK=C.O_NONBLOCK??0,FileStoreError=(()=>{class FileStoreError2 extends Error{constructor(reason,relPath){super(`path ${JSON.stringify(relPath)} ${reason}`),this.name="FileStoreError",this.reason=reason,this.relPath=relPath}}return FileStoreError2.ESCAPES_ROOT="escapes the store root",FileStoreError2.IS_A_SYMLINK="is a symlink",FileStoreError2.NOT_A_FILE="is not a regular file",FileStoreError2.NOT_A_DIRECTORY="is not a directory",FileStoreError2.NOT_UTF8="is not valid utf-8",FileStoreError2.MOVE_DESTINATION_EXISTS="already exists",FileStoreError2})();function isPathLegal(p){return p.startsWith("/")&&!p.split("/").includes("..")}var FileStore=(()=>{class FileStore2{constructor(root,removedOnDispose,utf8Only=!1){this.hashes=new Map,this.rootPath=root,this.removedOnDispose=removedOnDispose,this.decoder=utf8Only?new TextDecoder("utf-8",{fatal:!0}):void 0}static async open(root,opts){if(!platformSupported())throw new Error("FileStore requires O_NOFOLLOW support on this platform");let removedOnDispose=!1;try{await fsp.lstat(root)}catch(e){if(e.code!=="ENOENT")throw e;removedOnDispose=!0}return new FileStore2(path.resolve(root),removedOnDispose,opts?.utf8??!1)}async createRoot(){await makeDirAndAncestors(this.rootPath)}root(){return{path:this.rootPath,removedOnDispose:this.removedOnDispose}}async dispose(){this.removedOnDispose&&await fsp.rm(this.rootPath,{recursive:!0,force:!0})}async put(relPath,data,opts){let tail=relPath.replace(/\\/g,"/");if(tail.endsWith("/")||tail.endsWith("/.")||tail===""||tail===".")throw new FileStoreError(FileStoreError.NOT_A_FILE,relPath);let dest=this.resolveUnderRoot(relPath),payload=typeof data=="string"?encodeUTF8(data):data;this.requireUtf8(relPath,payload),await makeDirsBelowRoot(this.rootPath,path.dirname(dest)),await replaceViaTemp(dest,payload,opts?.executable??!1)}async get(relPath){let dest=this.resolveUnderRoot(relPath),handle;try{handle=await openRegularFile(relPath,dest)}catch(e){if(e.code==="ENOENT")return null;throw e}let data;try{let buf=await handle.readFile();data=new Uint8Array(buf.buffer,buf.byteOffset,buf.byteLength)}finally{await handle.close()}return this.requireUtf8(relPath,data),data}async ls(under="/"){let base=this.resolveUnderRoot(under);return new Set((await filenamesInDir(this.rootPath,under,base)).map(([rel])=>rel))}async findSymlinks(under="/"){let base=this.resolveUnderRoot(under);return symlinksInDir(this.rootPath,under,base)}async hashtree(under="/"){let base=this.resolveUnderRoot(under),walkStartNs=_internals.nowNs(),out=Object.create(null);for(let[rel,full]of await filenamesInDir(this.rootPath,under,base)){let sha=await this.hashViaCache(rel,full,walkStartNs);sha!==null&&(out[rel]=sha)}return out}async hashFile(relPath){let dest=this.resolveUnderRoot(relPath),st;try{st=await fsp.lstat(dest,{bigint:!0})}catch(e){if(e.code==="ENOENT")return null;throw e}if(st.isSymbolicLink())throw new FileStoreError(FileStoreError.IS_A_SYMLINK,relPath);if(!st.isFile())throw new FileStoreError(FileStoreError.NOT_A_FILE,relPath);let rel=path.relative(this.rootPath,dest).split(path.sep).join("/");return this.hashViaCache(rel,dest,_internals.nowNs())}async move(src,dst){let s=this.resolveUnderRoot(src),d=this.resolveUnderRoot(dst);if(s===this.rootPath||d===this.rootPath)return;if(await fsp.stat(d).then(()=>!0,()=>!1))throw new FileStoreError(FileStoreError.MOVE_DESTINATION_EXISTS,dst);await makeDirsBelowRoot(this.rootPath,path.dirname(d)),await fsp.rename(s,d)}async remove(relPath){let dest=this.resolveUnderRoot(relPath);if(dest===this.rootPath)return;let st;try{st=await fsp.lstat(dest,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}if(st.isDirectory())await fsp.rm(dest,{recursive:!0,force:!0});else try{await fsp.unlink(dest)}catch(e){if(e.code!=="ENOENT")throw e}}resolveUnderRoot(relPath){let norm=relPath.replace(/\\/g,"/").replace(/^\/+/,""),parts=norm.split("/").filter(p=>p!==""&&p!==".");if(path.posix.isAbsolute(norm)||parts.includes(".."))throw new FileStoreError(FileStoreError.ESCAPES_ROOT,relPath);return parts.length===0?this.rootPath:path.join(this.rootPath,...parts)}requireUtf8(relPath,data){if(this.decoder)try{this.decoder.decode(data)}catch{throw new FileStoreError(FileStoreError.NOT_UTF8,relPath)}}async hashViaCache(rel,full,walkStartNs){let st;try{st=await fsp.lstat(full,{bigint:!0})}catch(e){if(e.code==="ENOENT")return null;throw e}if(!st.isFile())return null;let cached=this.hashes.get(rel),sha;if(cached!==void 0&&unchangedSinceHashed(cached,st))sha=cached.sha;else try{sha=await _internals.hashFile(full)}catch(e){let code=e.code;if(code==="ENOENT"||e instanceof FileStoreError||code==="ELOOP"||code==="EMLINK")return null;throw e}return oldEnoughToCache(st,walkStartNs)&&this.hashes.set(rel,{mtimeNs:st.mtimeNs,ctimeNs:st.ctimeNs,size:st.size,sha}),sha}}return FileStore2.isPathLegal=isPathLegal,FileStore2})();function platformSupported(){return O_NOFOLLOW!==0}async function makeDirAndAncestors(dir){let missing=[],current=dir;for(;;){try{await fsp.stat(current);break}catch(e){let code=e.code;if(code!=="ENOENT"&&code!=="ENOTDIR"&&code!=="ELOOP")throw e}missing.push(current);let parent=path.dirname(current);if(parent===current)break;current=parent}for(let directory of missing.reverse())try{await fsp.mkdir(directory,{mode:OWNER_ONLY_DIR_MODE})}catch(e){if(e.code!=="EEXIST")throw e}}async function makeDirsBelowRoot(root,dir){let below=path.relative(root,dir);if(below==="")return;let current=root;for(let part of below.split(path.sep)){current=path.join(current,part);try{await fsp.mkdir(current,{mode:OWNER_ONLY_DIR_MODE})}catch(e){if(e.code!=="EEXIST")throw e}}}async function replaceViaTemp(dest,data,isExecutable){let mode=isExecutable?OWNER_ONLY_EXEC_MODE:OWNER_ONLY_FILE_MODE,tmp=path.join(path.dirname(dest),`.fs-${crypto.randomBytes(8).toString("hex")}.tmp`),handle;try{handle=await fsp.open(tmp,C.O_WRONLY|C.O_CREAT|C.O_EXCL|O_NOFOLLOW,mode),await handle.writeFile(data),await handle.close(),handle=void 0,await fsp.rename(tmp,dest)}catch(err){throw handle&&await handle.close().catch(()=>{}),await fsp.unlink(tmp).catch(()=>{}),err}}async function openRegularFile(relPath,dest){let handle;try{handle=await fsp.open(dest,C.O_RDONLY|O_NOFOLLOW|O_NONBLOCK)}catch(e){let code=e.code;throw code==="ELOOP"||code==="EMLINK"?new FileStoreError(FileStoreError.IS_A_SYMLINK,relPath):e}try{if(!(await handle.stat()).isFile())throw new FileStoreError(FileStoreError.NOT_A_FILE,relPath)}catch(e){throw await handle.close().catch(()=>{}),e}return handle}async function hashFile(full){let digest=crypto.createHash("sha256"),handle=await openRegularFile(path.basename(full),full),buf=new Uint8Array(1024*1024);try{for(;;){let{bytesRead}=await handle.read(buf,0,buf.length);if(bytesRead===0)break;digest.update(buf.subarray(0,bytesRead))}}finally{await handle.close()}return digest.digest("hex")}async function filenamesInDir(root,under,base){if(!await requireDir(under,base))return[];let out=[];return await walk(base,(full,entry)=>{entry.isFile()&&out.push([path.relative(root,full).split(path.sep).join("/"),full])}),out.sort(),out}async function symlinksInDir(root,under,base){let relOf=full=>path.relative(root,full).split(path.sep).join("/"),st;try{st=await fsp.lstat(base,{bigint:!0})}catch(e){let code=e.code;if(code==="ENOENT"||code==="ENOTDIR")return new Set;throw e}if(st.isSymbolicLink())return new Set([relOf(base)]);if(!st.isDirectory())throw new FileStoreError(FileStoreError.NOT_A_DIRECTORY,under);let out=new Set;return await walk(base,(full,entry)=>{entry.isSymbolicLink()&&out.add(relOf(full))}),out}async function requireDir(under,base){let st;try{st=await fsp.lstat(base,{bigint:!0})}catch(e){let code=e.code;if(code==="ENOENT"||code==="ENOTDIR")return!1;throw e}if(!st.isDirectory())throw new FileStoreError(FileStoreError.NOT_A_DIRECTORY,under);return!0}async function walk(base,visit){let stack=[base];for(;stack.length;){let dir=stack.pop(),entries;try{entries=await fsp.readdir(dir,{withFileTypes:!0})}catch(e){if(e.code==="ENOENT")continue;throw e}for(let entry of entries){let full=path.join(dir,entry.name);visit(full,entry),entry.isDirectory()&&!entry.isSymbolicLink()&&stack.push(full)}}}function unchangedSinceHashed(cached,st){return st.mtimeNs===cached.mtimeNs&&st.ctimeNs===cached.ctimeNs&&st.size===cached.size}function oldEnoughToCache(st,walkStartNs){return(st.mtimeNs>st.ctimeNs?st.mtimeNs:st.ctimeNs)<walkStartNs-_internals.timestampTrustMarginNs}var TIMESTAMP_TRUST_MARGIN_NS=2000000000n,_internals={hashFile,timestampTrustMarginNs:TIMESTAMP_TRUST_MARGIN_NS,nowNs:()=>BigInt(Date.now())*1000000n},LocalFileStore=FileStore,asyncDispose=Symbol.asyncDispose;asyncDispose&&Object.defineProperty(FileStore.prototype,asyncDispose,{value:FileStore.prototype.dispose,configurable:!0,writable:!0});var _SessionMemoryStores_instances,_SessionMemoryStores_client,_SessionMemoryStores_workdir,_SessionMemoryStores_syncIntervalMs,_SessionMemoryStores_syncDeletions,_SessionMemoryStores_log,_SessionMemoryStores_lastSyncAt,_SessionMemoryStores_finished,_SessionMemoryStores_stores,_SessionMemoryStores_storeRoot,_SessionMemoryStores_scanMarker,_SessionMemoryStores_syncStore,_SessionMemoryStores_flushStore,_SessionMemoryStores_recover,_SessionMemoryStores_stampAndPull,_SessionMemoryStores_syncPath,_SessionMemoryStores_removeLocal,_SessionMemoryStores_write,_SessionMemoryStores_pullAll,_SessionMemoryStores_uploadAll,_SessionMemoryStores_listMemories,_SessionMemoryStores_upload,_SessionMemoryStores_corroboratedDelete,_SessionMemoryStores_deleteRemote,MEMORY_FLUSH_TIMEOUT_MS=3e4,MARKER_PATH=".anthropic-memory-store",MARKER_VERSION=1;function markerSha(memoryStoreId){return crypto.createHash("sha256").update(`version ${MARKER_VERSION}
|
|
6
|
+
${memoryStoreId}`,"utf-8").digest("hex")}var DELETE_CORROBORATION_MS=3e4,LIST_PAGE_SIZE=100,FULL_LIST_PAGE_SIZE=20,FETCH_CONCURRENCY=16,UPLOAD_CONCURRENCY=32,DELETE_CAP_FLOOR=8,DELETE_CAP_CEILING=50,SessionMemoryError=class extends AnthropicError{constructor(message,cause){super(message),this.name="SessionMemoryError",cause!==void 0&&(this.cause=cause)}},DeletePass=class{constructor(mode,cap,waiveWindow){this.mode=mode,this.cap=cap,this.waiveWindow=waiveWindow,this.attempted=0,this.capped=0,this.suppressed=0}takeSlot(){return this.attempted>=this.cap?(this.capped++,!1):(this.attempted++,!0)}},SessionMemoryStores=(()=>{class SessionMemoryStores2{constructor(client,opts){_SessionMemoryStores_instances.add(this),_SessionMemoryStores_client.set(this,void 0),_SessionMemoryStores_workdir.set(this,void 0),_SessionMemoryStores_syncIntervalMs.set(this,void 0),_SessionMemoryStores_syncDeletions.set(this,void 0),_SessionMemoryStores_log.set(this,void 0),_SessionMemoryStores_lastSyncAt.set(this,void 0),_SessionMemoryStores_finished.set(this,!1),_SessionMemoryStores_stores.set(this,[]),__classPrivateFieldSet(this,_SessionMemoryStores_client,client,"f"),__classPrivateFieldSet(this,_SessionMemoryStores_workdir,opts.workdir,"f"),__classPrivateFieldSet(this,_SessionMemoryStores_syncIntervalMs,opts.syncIntervalMs??DEFAULT_MEMORY_SYNC_INTERVAL_MS,"f"),checkMemorySyncInterval(__classPrivateFieldGet(this,_SessionMemoryStores_syncIntervalMs,"f"),"syncIntervalMs"),__classPrivateFieldSet(this,_SessionMemoryStores_syncDeletions,opts.syncDeletions??"enabled","f"),__classPrivateFieldSet(this,_SessionMemoryStores_log,loggerFor(client),"f"),__classPrivateFieldSet(this,_SessionMemoryStores_lastSyncAt,Date.now(),"f")}get roots(){return __classPrivateFieldGet(this,_SessionMemoryStores_stores,"f").map(s=>s.files.root().path)}get readOnlyRoots(){return __classPrivateFieldGet(this,_SessionMemoryStores_stores,"f").filter(s=>s.readOnly).map(s=>s.files.root().path)}async download(session){for(let resource of session.resources){if(resource.type!=="memory_store")continue;let root=__classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_storeRoot).call(this,resource),store;try{if(store={memoryStoreId:resource.memory_store_id,files:await LocalFileStore.open(root,{utf8:!0}),readOnly:resource.access==="read_only",baseline:new Map,refusedShas:new Map,pendingDeletes:new Map},!store.files.root().removedOnDispose)throw new SessionMemoryError(`something already exists at the memory store's path: ${root} (memory_store_id=${resource.memory_store_id}); it must not exist when the session starts`);try{await store.files.createRoot()}catch(e){throw isErrno(e)?new SessionMemoryError(`cannot create the memory store's folder: ${root} (memory_store_id=${resource.memory_store_id}): ${e}; the worker host must make this mount path writable`,e):e}await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_stampAndPull).call(this,store),__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").info("downloaded memories",{count:store.baseline.size,memory_store_id:store.memoryStoreId,dest:store.files.root().path}),__classPrivateFieldGet(this,_SessionMemoryStores_stores,"f").push(store)}catch(e){throw store&&await store.files.dispose().catch(()=>{}),e instanceof SessionMemoryError?e:new SessionMemoryError(`failed to download memory store memory_store_id=${resource.memory_store_id}: ${e}`,e)}}__classPrivateFieldSet(this,_SessionMemoryStores_lastSyncAt,Date.now(),"f")}async finish(){if(__classPrivateFieldGet(this,_SessionMemoryStores_finished,"f"))throw new AnthropicError("finish() was already called: it is the session's last sync and runs once");__classPrivateFieldSet(this,_SessionMemoryStores_finished,!0,"f"),await this.syncAll(!0)}async syncAll(final){await Promise.all(__classPrivateFieldGet(this,_SessionMemoryStores_stores,"f").map(store=>__classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_syncStore).call(this,store,final))),__classPrivateFieldSet(this,_SessionMemoryStores_lastSyncAt,Date.now(),"f")}async syncIfDue(){Date.now()-__classPrivateFieldGet(this,_SessionMemoryStores_lastSyncAt,"f")<__classPrivateFieldGet(this,_SessionMemoryStores_syncIntervalMs,"f")||await this.syncAll(!1)}async flushWrites(signal){await Promise.all(__classPrivateFieldGet(this,_SessionMemoryStores_stores,"f").map(store=>__classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_flushStore).call(this,store,signal)))}async dispose(){for(let store of __classPrivateFieldGet(this,_SessionMemoryStores_stores,"f")){let root=store.files.root();try{let scan=await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_scanMarker).call(this,store);if(!scan.markerOk&&Object.keys(scan.files).length>0){__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn(`${scan.distrustReason}; leaving the memory store folder on disk`,{root:root.path,memory_store_id:store.memoryStoreId});continue}await store.files.dispose()}catch(e){if(!(e instanceof FileStoreError)&&!isErrno(e))throw e;__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("failed to remove the memory store folder",{root:store.files.root().path,memory_store_id:store.memoryStoreId,error:String(e)});continue}root.removedOnDispose&&__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").info("removed memory store dir",{dest:root.path,memory_store_id:store.memoryStoreId})}}}return _SessionMemoryStores_client=new WeakMap,_SessionMemoryStores_workdir=new WeakMap,_SessionMemoryStores_syncIntervalMs=new WeakMap,_SessionMemoryStores_syncDeletions=new WeakMap,_SessionMemoryStores_log=new WeakMap,_SessionMemoryStores_lastSyncAt=new WeakMap,_SessionMemoryStores_finished=new WeakMap,_SessionMemoryStores_stores=new WeakMap,_SessionMemoryStores_instances=new WeakSet,_SessionMemoryStores_storeRoot=function(resource){if(resource.mount_path){if(!isPathLegal(resource.mount_path))throw new SessionMemoryError(`memory store mount_path is not a clean absolute path: ${JSON.stringify(resource.mount_path)} (memory_store_id=${resource.memory_store_id})`);return resource.mount_path}return path.join(__classPrivateFieldGet(this,_SessionMemoryStores_workdir,"f"),"memory",resource.name||resource.memory_store_id)},_SessionMemoryStores_scanMarker=async function(store){let local=await store.files.hashtree(),marker=local[MARKER_PATH];return delete local[MARKER_PATH],marker===markerSha(store.memoryStoreId)?{files:local,markerOk:!0,distrustReason:null}:{files:local,markerOk:!1,distrustReason:marker!==void 0?"the marker file does not match this store":"the marker file is gone"}},_SessionMemoryStores_syncStore=async function(store,final){try{let scan=await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_scanMarker).call(this,store),local=scan.files;if(!scan.markerOk){if(Object.keys(local).length>0){__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn(`${scan.distrustReason}; leaving the memory store folder as found and not syncing`,{root:store.files.root().path,memory_store_id:store.memoryStoreId});return}await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_recover).call(this,store,"the folder or its marker is gone");return}if(Object.keys(local).length===0&&store.baseline.size>1){await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_recover).call(this,store,"every memory file is gone at once");return}let remote=new Map;for await(let[rel,item]of __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_listMemories).call(this,store.memoryStoreId))remote.set(rel,item);let deletes=new DeletePass(__classPrivateFieldGet(this,_SessionMemoryStores_syncDeletions,"f"),Math.max(DELETE_CAP_FLOOR,Math.min(DELETE_CAP_CEILING,Math.floor(store.baseline.size/4))),final),pulls=[],baseline=new Map,paths=[...new Set([...remote.keys(),...Object.keys(local),...store.baseline.keys()])].sort();for(let rel of paths){let remoteItem=remote.get(rel),localSha=local[rel],baseSha=store.baseline.get(rel),sha;localSha===void 0&&baseSha!==void 0&&remoteItem!==void 0&&remoteItem.content_sha256===baseSha&&!store.readOnly?sha=await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_corroboratedDelete).call(this,store,rel,remoteItem,baseSha,deletes):sha=await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_syncPath).call(this,store,rel,remoteItem,localSha,pulls),sha!==void 0&&baseline.set(rel,sha)}store.baseline=baseline,await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_pullAll).call(this,store,pulls),deletes.suppressed>0&&__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").debug("remote deletes are disabled; locally deleted memories stay on the server",{count:deletes.suppressed,memory_store_id:store.memoryStoreId}),deletes.capped>0&&__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn(`delete cap reached: ${deletes.mode==="log_only"?"would send":"sent"} ${deletes.attempted} deletes, held ${deletes.capped} for later syncs`,{memory_store_id:store.memoryStoreId})}catch(e){__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("memory sync failed",{memory_store_id:store.memoryStoreId,error:String(e)})}},_SessionMemoryStores_flushStore=async function(store,signal){let dirty=new Map,unsent=new Set,push=async()=>{if(store.readOnly)return;let scan=await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_scanMarker).call(this,store);if(!scan.markerOk){__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn(`${scan.distrustReason}; not uploading anything from the memory store folder`,{root:store.files.root().path,memory_store_id:store.memoryStoreId});return}for(let[rel,sha]of Object.entries(scan.files))sha!==store.baseline.get(rel)&&store.refusedShas.get(rel)!==sha&&(dirty.set(rel,sha),unsent.add(rel));if(dirty.size===0||signal?.aborted)return;let remote=new Map;for await(let[rel,item]of __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_listMemories).call(this,store.memoryStoreId)){if(signal?.aborted)return;remote.set(rel,item)}let uploads=[];for(let rel of[...dirty.keys()].sort()){let localSha=dirty.get(rel),baseSha=store.baseline.get(rel),existing=remote.get(rel);if(existing!==void 0&&existing.content_sha256===localSha){store.baseline.set(rel,existing.content_sha256),unsent.delete(rel);continue}if(existing!==void 0&&existing.content_sha256!==baseSha){__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("memory changed both locally and remotely; the flush leaves the remote version",{path:rel,memory_store_id:store.memoryStoreId}),unsent.delete(rel);continue}uploads.push([rel,localSha,existing])}await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_uploadAll).call(this,store,uploads,unsent,signal)};try{await settledOrAborted(push(),signal),signal?.aborted&&unsent.size>0&&__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn(`memory flush cut off part-way; ${unsent.size} of ${dirty.size} changed files had not finished uploading`,{memory_store_id:store.memoryStoreId})}catch(e){__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("memory flush failed",{memory_store_id:store.memoryStoreId,error:String(e)})}},_SessionMemoryStores_recover=async function(store,reason){__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn(`${reason}; re-downloading the memory store folder instead of syncing`,{root:store.files.root().path,memory_store_id:store.memoryStoreId}),await store.files.createRoot(),await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_stampAndPull).call(this,store)},_SessionMemoryStores_stampAndPull=async function(store){store.baseline=new Map,store.pendingDeletes.clear(),await store.files.put(MARKER_PATH,`version ${MARKER_VERSION}
|
|
7
|
+
${store.memoryStoreId}`);for await(let[rel,item]of __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_listMemories).call(this,store.memoryStoreId,"full"))await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_write).call(this,store,rel,item.content??"")&&store.baseline.set(rel,item.content_sha256)},_SessionMemoryStores_syncPath=async function(store,rel,remote,localSha,pulls){let baseSha=store.baseline.get(rel);if(localSha!==void 0&&store.pendingDeletes.delete(rel),!remote){if(localSha===void 0){store.pendingDeletes.delete(rel);return}if(baseSha!==void 0){if(localSha===baseSha){let fresh=await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_removeLocal).call(this,store,rel,baseSha);if(fresh===void 0)return;if(fresh===baseSha)return baseSha;localSha=fresh}store.readOnly?__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("memory deleted remotely but edited locally; keeping the file, which a read-only store cannot push",{path:rel,memory_store_id:store.memoryStoreId}):store.refusedShas.get(rel)!==localSha&&__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").info("memory deleted remotely but edited locally; re-creating it from the file",{path:rel,memory_store_id:store.memoryStoreId})}return store.readOnly||store.refusedShas.get(rel)===localSha?void 0:await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_upload).call(this,store,rel,localSha,void 0)}let remoteSha=remote.content_sha256,remoteChanged=remoteSha!==baseSha,locallyEdited=localSha!==void 0&&localSha!==baseSha&&localSha!==remoteSha,localChanged=!store.readOnly&&locallyEdited;return localSha===void 0&&baseSha!==void 0?(remoteChanged&&(__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("memory deleted locally but changed remotely; restoring the remote version",{path:rel,memory_store_id:store.memoryStoreId}),store.pendingDeletes.delete(rel),pulls.push([rel,remote])),baseSha):remoteChanged?localSha===remoteSha?remoteSha:(locallyEdited&&__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("memory changed both locally and remotely; keeping the remote version",{path:rel,memory_store_id:store.memoryStoreId}),pulls.push([rel,remote]),baseSha):localChanged?store.refusedShas.get(rel)===localSha?remoteSha:await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_upload).call(this,store,rel,localSha,remote)??remoteSha:remoteSha},_SessionMemoryStores_removeLocal=async function(store,rel,expectSha){let freshSha;try{freshSha=await store.files.hashFile(rel)}catch(e){if(!(e instanceof FileStoreError)&&!isErrno(e))throw e;return expectSha}if(freshSha!==null){if(freshSha!==expectSha)return freshSha;try{await store.files.remove(rel)}catch(e){if(!(e instanceof FileStoreError)&&!isErrno(e))throw e;return __classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("failed to remove memory deleted remotely",{path:rel,memory_store_id:store.memoryStoreId,error:String(e)}),expectSha}}},_SessionMemoryStores_write=async function(store,rel,content){try{await store.files.put(rel,content)}catch(e){if(!(e instanceof FileStoreError)&&!isErrno(e))throw e;return __classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("failed to write memory",{path:rel,memory_store_id:store.memoryStoreId,error:String(e)}),!1}return!0},_SessionMemoryStores_pullAll=async function(store,pulls){if(pulls.length===0)return;let pullOne=async(rel,listed)=>{let item;try{item=await __classPrivateFieldGet(this,_SessionMemoryStores_client,"f").beta.memoryStores.memories.retrieve(listed.id,{memory_store_id:store.memoryStoreId,view:"full"})}catch(e){if(isStatus(e,404))return;__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("failed to fetch memory content",{path:rel,memory_store_id:store.memoryStoreId,error:String(e)});return}await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_write).call(this,store,rel,item.content??"")&&store.baseline.set(rel,item.content_sha256)},queue=pulls[Symbol.iterator](),worker=async()=>{for(let[rel,listed]of queue)await pullOne(rel,listed)};await Promise.all(Array.from({length:Math.min(FETCH_CONCURRENCY,pulls.length)},worker))},_SessionMemoryStores_uploadAll=async function(store,uploads,unsent,signal){let queue=uploads[Symbol.iterator](),worker=async()=>{for(let[rel,localSha,existing]of queue){if(signal?.aborted)return;let sha=await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_upload).call(this,store,rel,localSha,existing);unsent.delete(rel),sha!==void 0&&store.baseline.set(rel,sha)}};await Promise.all(Array.from({length:Math.min(UPLOAD_CONCURRENCY,uploads.length)},worker))},_SessionMemoryStores_listMemories=async function*(memoryStoreId,view="basic"){let limit=view==="basic"?LIST_PAGE_SIZE:FULL_LIST_PAGE_SIZE;for await(let item of __classPrivateFieldGet(this,_SessionMemoryStores_client,"f").beta.memoryStores.memories.list(memoryStoreId,{view,limit})){if(item.type!=="memory")continue;let rel=item.path.replace(/^\/+/,"");if(rel===MARKER_PATH){__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("the server listed the reserved marker path; skipping",{path:item.path,memory_store_id:memoryStoreId});continue}yield[rel,item]}},_SessionMemoryStores_upload=async function _SessionMemoryStores_upload2(store,rel,localSha,existing){try{let data=await store.files.get(rel);if(data===null)return;let content=decodeUTF8(data),item=existing?await __classPrivateFieldGet(this,_SessionMemoryStores_client,"f").beta.memoryStores.memories.update(existing.id,{memory_store_id:store.memoryStoreId,content,precondition:{type:"content_sha256",content_sha256:existing.content_sha256}}):await __classPrivateFieldGet(this,_SessionMemoryStores_client,"f").beta.memoryStores.memories.create(store.memoryStoreId,{path:"/"+rel,content});return store.refusedShas.delete(rel),item.content_sha256}catch(e){if(existing&&isStatus(e,404))return await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_upload2).call(this,store,rel,localSha,void 0);let permanent=e instanceof FileStoreError||isStatus(e,400)||isStatus(e,413);existing&&isStatus(e,409)?__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("memory changed both locally and remotely; the upload was refused and the local edit loses",{path:rel,memory_store_id:store.memoryStoreId}):permanent&&localSha!==void 0?(store.refusedShas.set(rel,localSha),__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("the server rejected this memory file, so it stays un-synced until its content changes",{path:rel,memory_store_id:store.memoryStoreId,rejection:String(e)})):__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("failed to upload memory",{path:rel,memory_store_id:store.memoryStoreId,error:String(e)});return}},_SessionMemoryStores_corroboratedDelete=async function(store,rel,remote,baseSha,deletes){if(deletes.mode==="disabled")return deletes.suppressed++,baseSha;let firstAbsent=store.pendingDeletes.get(rel);if(firstAbsent===void 0&&(firstAbsent=Date.now(),store.pendingDeletes.set(rel,firstAbsent)),!deletes.waiveWindow&&Date.now()-firstAbsent<DELETE_CORROBORATION_MS)return baseSha;let markerOk,stillAbsent;try{markerOk=await store.files.hashFile(MARKER_PATH)===markerSha(store.memoryStoreId),stillAbsent=await store.files.hashFile(rel)===null}catch(e){if(!(e instanceof FileStoreError)&&!isErrno(e))throw e;markerOk=stillAbsent=!1}if(!markerOk)return baseSha;if(!stillAbsent)return store.pendingDeletes.delete(rel),baseSha;if(!deletes.takeSlot())return baseSha;if(deletes.mode==="log_only")return __classPrivateFieldGet(this,_SessionMemoryStores_log,"f").info("log-only: sync would delete this memory on the server",{path:rel,memory_store_id:store.memoryStoreId}),baseSha;let sha=await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_deleteRemote).call(this,store,rel,remote,baseSha);return sha===void 0&&store.pendingDeletes.delete(rel),sha},_SessionMemoryStores_deleteRemote=async function(store,rel,remote,baseSha){try{await __classPrivateFieldGet(this,_SessionMemoryStores_client,"f").beta.memoryStores.memories.delete(remote.id,{memory_store_id:store.memoryStoreId,expected_content_sha256:baseSha})}catch(e){return isStatus(e,404)?void 0:(isStatus(e,409)||isStatus(e,412)?__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("memory deleted locally but changed remotely; keeping the remote version",{path:rel,memory_store_id:store.memoryStoreId}):__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("failed to delete memory",{path:rel,memory_store_id:store.memoryStoreId,error:String(e)}),baseSha)}__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").info("propagated local deletion",{path:rel,memory_store_id:store.memoryStoreId})},SessionMemoryStores2})();function isErrno(e){return typeof e=="object"&&e!==null&&typeof e.code=="string"}async function settledOrAborted(p,signal){if(!signal){await p;return}let onAbort,aborted=new Promise(resolve2=>{onAbort=resolve2,signal.aborted&&resolve2()});signal.addEventListener("abort",onAbort,{once:!0});try{await Promise.race([p,aborted])}finally{signal.removeEventListener("abort",onAbort)}}var _BashSession_instances,_BashSession_proc,_BashSession_buf,_BashSession_truncated,_BashSession_closed,_BashSession_waiting,_BashSession_append,_LineRangeCollector_instances,_LineRangeCollector_filePath,_LineRangeCollector_startLine,_LineRangeCollector_endLine,_LineRangeCollector_start,_LineRangeCollector_end,_LineRangeCollector_limit,_LineRangeCollector_line,_LineRangeCollector_collected,_LineRangeCollector_collectedBytes,_LineRangeCollector_collect,_LineRangeCollector_overLimitError,BASH_OUTPUT_LIMIT=100*1024,BASH_DEFAULT_TIMEOUT_MS=12e4,DEFAULT_MAX_FILE_BYTES=256*1024,READ_STREAM_CHUNK_BYTES=64*1024,NEWLINE=Buffer.from(`
|
|
8
|
+
`),GREP_OUTPUT_LIMIT=100*1024,GREP_MAX_LINE_LENGTH=2e3,GLOB_RESULT_LIMIT=200,BashTimeoutError=class extends AnthropicError{constructor(timeoutMs){super(`bash command timed out after ${timeoutMs}ms`),this.name="BashTimeoutError",this.timeoutMs=timeoutMs}},ANSI_RE=/\x1b\[[0-9;?]*[ -/]*[@-~]/g,fsGlob=fs4.glob;function resolveMaxBytes(configured){return configured===void 0?DEFAULT_MAX_FILE_BYTES:configured}function rejectUnrestrictedPaths(value){if(value!==void 0)throw new AnthropicError("The `unrestrictedPaths` option you passed to the agent toolset (AgentToolContext) is no longer supported. The toolset's file tools (read, write, edit, glob, grep) are now always confined to the working directory plus the directories listed in `allowedRoots`. Remove `unrestrictedPaths` from your context; to let the file tools reach any other directory, add it to `allowedRoots`.")}function betaAgentToolset20260401(ctx){return[betaBashTool(ctx),betaReadTool(ctx),betaWriteTool(ctx),betaEditTool(ctx),betaGlobTool(ctx),betaGrepTool(ctx)]}async function resolvePath(ctx,p){return rejectUnrestrictedPaths(ctx.unrestrictedPaths),confineToRoot(ctx.workdir,p,{allowedRoots:ctx.allowedRoots??[]})}function readOnlyRootFor(ctx,target){return containingRoot(ctx.readOnlyRoots??[],target)}function scrubbedShellEnv(){let env={};for(let[key,value]of Object.entries(process.env))key.startsWith("ANTHROPIC_")||(env[key]=value);return env}var BashSession=(()=>{class BashSession2{constructor(dir,env=scrubbedShellEnv()){_BashSession_instances.add(this),_BashSession_proc.set(this,void 0),_BashSession_buf.set(this,""),_BashSession_truncated.set(this,!1),_BashSession_closed.set(this,!1),_BashSession_waiting.set(this,null),__classPrivateFieldSet(this,_BashSession_proc,cp.spawn("/bin/bash",["--noprofile","--norc"],{cwd:dir,env:{...env,PS1:"",PS2:"",TERM:"dumb"},stdio:["pipe","pipe","pipe"],detached:!0}),"f"),__classPrivateFieldGet(this,_BashSession_proc,"f").stdout.setEncoding("utf8"),__classPrivateFieldGet(this,_BashSession_proc,"f").stderr.setEncoding("utf8"),__classPrivateFieldGet(this,_BashSession_proc,"f").stdout.on("data",d=>__classPrivateFieldGet(this,_BashSession_instances,"m",_BashSession_append).call(this,d)),__classPrivateFieldGet(this,_BashSession_proc,"f").stderr.on("data",d=>__classPrivateFieldGet(this,_BashSession_instances,"m",_BashSession_append).call(this,d)),__classPrivateFieldGet(this,_BashSession_proc,"f").once("close",()=>{__classPrivateFieldSet(this,_BashSession_closed,!0,"f");let w=__classPrivateFieldGet(this,_BashSession_waiting,"f");__classPrivateFieldSet(this,_BashSession_waiting,null,"f"),w?.resolve()})}get closed(){return __classPrivateFieldGet(this,_BashSession_closed,"f")}async exec(command,opts={}){if(__classPrivateFieldGet(this,_BashSession_closed,"f"))throw new AnthropicError("bash session terminated");let timeoutMs=opts.timeoutMs??BASH_DEFAULT_TIMEOUT_MS,signal=opts.signal;signal?.throwIfAborted(),__classPrivateFieldSet(this,_BashSession_buf,"","f"),__classPrivateFieldSet(this,_BashSession_truncated,!1,"f");let sentinel=`__ANT_CMD_${crypto2.randomUUID()}_DONE__`,sentinelSplit=`${sentinel.slice(0,8)}''${sentinel.slice(8)}`,wrapped=`{ ${command}
|
|
9
|
+
} </dev/null 2>&1; printf '\\n${sentinelSplit}%d\\n' $?
|
|
10
|
+
`;if(__classPrivateFieldGet(this,_BashSession_proc,"f").stdin.write(wrapped),__classPrivateFieldGet(this,_BashSession_buf,"f").indexOf(sentinel)<0){let{promise:sentinelSeen,resolve:resolve2}=promiseWithResolvers();__classPrivateFieldSet(this,_BashSession_waiting,{sentinel,resolve:resolve2},"f");let timer,onAbort;try{await Promise.race([sentinelSeen,new Promise((_,reject)=>{timer=setTimeout(()=>reject(new BashTimeoutError(timeoutMs)),timeoutMs)}),new Promise((_,reject)=>{signal&&(onAbort=()=>reject(signal.reason),signal.addEventListener("abort",onAbort,{once:!0}))})])}finally{timer&&clearTimeout(timer),onAbort&&signal&&signal.removeEventListener("abort",onAbort),__classPrivateFieldSet(this,_BashSession_waiting,null,"f")}}let idx=__classPrivateFieldGet(this,_BashSession_buf,"f").indexOf(sentinel);if(idx<0)throw new AnthropicError("bash session terminated");let m=__classPrivateFieldGet(this,_BashSession_buf,"f").slice(idx+sentinel.length).match(/^(-?\d+)/),exitCode=m?parseInt(m[1],10):-1,out=__classPrivateFieldGet(this,_BashSession_buf,"f").slice(0,idx).replace(ANSI_RE,"").replace(/\n+$/,"");return __classPrivateFieldGet(this,_BashSession_truncated,"f")&&(out=`[output truncated]
|
|
11
|
+
${out}`),{output:out,exitCode}}close(){if(__classPrivateFieldGet(this,_BashSession_closed,"f"))return;__classPrivateFieldSet(this,_BashSession_closed,!0,"f");let w=__classPrivateFieldGet(this,_BashSession_waiting,"f");__classPrivateFieldSet(this,_BashSession_waiting,null,"f"),w?.resolve(),__classPrivateFieldGet(this,_BashSession_proc,"f").stdout.destroy(),__classPrivateFieldGet(this,_BashSession_proc,"f").stderr.destroy(),__classPrivateFieldGet(this,_BashSession_proc,"f").stdin.destroy();try{process.kill(-__classPrivateFieldGet(this,_BashSession_proc,"f").pid,"SIGKILL")}catch{__classPrivateFieldGet(this,_BashSession_proc,"f").kill("SIGKILL")}__classPrivateFieldGet(this,_BashSession_proc,"f").unref()}}return _BashSession_proc=new WeakMap,_BashSession_buf=new WeakMap,_BashSession_truncated=new WeakMap,_BashSession_closed=new WeakMap,_BashSession_waiting=new WeakMap,_BashSession_instances=new WeakSet,_BashSession_append=function(d){if(__classPrivateFieldSet(this,_BashSession_buf,__classPrivateFieldGet(this,_BashSession_buf,"f")+d,"f"),__classPrivateFieldGet(this,_BashSession_buf,"f").length>BASH_OUTPUT_LIMIT&&(__classPrivateFieldSet(this,_BashSession_buf,__classPrivateFieldGet(this,_BashSession_buf,"f").slice(__classPrivateFieldGet(this,_BashSession_buf,"f").length-BASH_OUTPUT_LIMIT),"f"),__classPrivateFieldSet(this,_BashSession_truncated,!0,"f")),__classPrivateFieldGet(this,_BashSession_waiting,"f")&&__classPrivateFieldGet(this,_BashSession_buf,"f").indexOf(__classPrivateFieldGet(this,_BashSession_waiting,"f").sentinel)>=0){let w=__classPrivateFieldGet(this,_BashSession_waiting,"f");__classPrivateFieldSet(this,_BashSession_waiting,null,"f"),w.resolve()}},BashSession2})();function betaBashTool(ctx){rejectUnrestrictedPaths(ctx.unrestrictedPaths);let session,tail=Promise.resolve();return betaTool({name:"bash",description:"Run a bash command in a persistent shell. State (cwd, env vars) persists across calls.",inputSchema:{type:"object",properties:{command:{type:"string",description:"The command to run"},restart:{type:"boolean",description:"Restart the persistent shell before running"},timeout_ms:{type:"integer",description:"Per-call timeout in milliseconds"}}},run:async({command,restart,timeout_ms},context)=>{let prev=tail,gate=promiseWithResolvers();tail=gate.promise;try{await prev}catch{}try{if(restart&&(session?.close(),session=void 0),!command){if(restart)return"bash session restarted";throw new ToolError("bash: command is required")}session??(session=new BashSession(ctx.workdir,ctx.env));try{let{output,exitCode}=await session.exec(command,{timeoutMs:timeout_ms??BASH_DEFAULT_TIMEOUT_MS,signal:context?.signal});if(exitCode!==0)throw new ToolError(output||`exit ${exitCode}`);return output}catch(e){throw e instanceof ToolError?e:(session.close(),session=void 0,new ToolError(`bash: ${e instanceof Error?e.message:String(e)}`))}}finally{gate.resolve()}},close:()=>{session?.close(),session=void 0}})}function betaReadTool(ctx){return rejectUnrestrictedPaths(ctx.unrestrictedPaths),betaTool({name:"read",description:"Read a UTF-8 text file relative to the workdir.",inputSchema:{type:"object",properties:{file_path:{type:"string"},view_range:{type:"array",items:{type:"integer"},description:"[start_line, end_line] 1-indexed inclusive"}},required:["file_path"]},run:async({file_path,view_range})=>{if(!file_path)throw new ToolError("read: file_path is required");let abs=await resolvePath(ctx,file_path);if(view_range?.length&&view_range.length!==2)throw new ToolError("read: view_range must be [start_line, end_line]");let data;try{let st=await fs4.stat(abs);if(!st.isFile())throw new ToolError(`read: ${file_path} is not a regular file`);let limit=resolveMaxBytes(ctx.maxFileBytes);if(limit!==null&&st.size>limit){if(!view_range?.length)throw new ToolError(`read: ${file_path} is ${st.size} bytes, exceeds ${limit}-byte limit. Use the view_range parameter to read specific line ranges, e.g. view_range: [1, 500].`);let[startLine2,endLine2]=view_range;return await readRangeStreaming(abs,file_path,startLine2,endLine2,limit)}data=await fs4.readFile(abs,"utf8")}catch(e){throw e instanceof ToolError?e:new ToolError(`read: ${fsErrorMessage(e,file_path)}`)}if(!view_range?.length)return data;let[startLine,endLine]=view_range,lines=data.split(`
|
|
12
|
+
`),start=Math.max(0,startLine-1),end=endLine>0?endLine:lines.length;return lines.slice(start,end).join(`
|
|
13
|
+
`)}})}async function readRangeStreaming(abs,filePath,startLine,endLine,limit){let lines=new LineRangeCollector(filePath,startLine,endLine,limit);if(lines.rangeIsEmpty())return"";let stream2=fssync.createReadStream(abs,{highWaterMark:READ_STREAM_CHUNK_BYTES});try{for await(let chunk of stream2)if(lines.collectFrom(chunk),lines.rangeIsCollected())break}finally{stream2.destroy()}return lines.text()}var LineRangeCollector=(()=>{class LineRangeCollector2{constructor(filePath,startLine,endLine,limit){_LineRangeCollector_instances.add(this),_LineRangeCollector_filePath.set(this,void 0),_LineRangeCollector_startLine.set(this,void 0),_LineRangeCollector_endLine.set(this,void 0),_LineRangeCollector_start.set(this,void 0),_LineRangeCollector_end.set(this,void 0),_LineRangeCollector_limit.set(this,void 0),_LineRangeCollector_line.set(this,0),_LineRangeCollector_collected.set(this,[]),_LineRangeCollector_collectedBytes.set(this,0),__classPrivateFieldSet(this,_LineRangeCollector_filePath,filePath,"f"),__classPrivateFieldSet(this,_LineRangeCollector_startLine,startLine,"f"),__classPrivateFieldSet(this,_LineRangeCollector_endLine,endLine,"f"),__classPrivateFieldSet(this,_LineRangeCollector_start,Math.max(0,startLine-1),"f"),__classPrivateFieldSet(this,_LineRangeCollector_end,endLine>0?endLine:1/0,"f"),__classPrivateFieldSet(this,_LineRangeCollector_limit,limit,"f")}rangeIsEmpty(){return __classPrivateFieldGet(this,_LineRangeCollector_end,"f")<=__classPrivateFieldGet(this,_LineRangeCollector_start,"f")}rangeIsCollected(){return __classPrivateFieldGet(this,_LineRangeCollector_line,"f")>=__classPrivateFieldGet(this,_LineRangeCollector_end,"f")}collectFrom(chunk){var _a;let lineStart=0;for(;lineStart<chunk.length&&!this.rangeIsCollected();){let newline=chunk.indexOf(10,lineStart),lineEnd=newline<0?chunk.length:newline;if(__classPrivateFieldGet(this,_LineRangeCollector_line,"f")>=__classPrivateFieldGet(this,_LineRangeCollector_start,"f")&&__classPrivateFieldGet(this,_LineRangeCollector_instances,"m",_LineRangeCollector_collect).call(this,chunk.subarray(lineStart,lineEnd),newline>=0),newline<0)break;__classPrivateFieldSet(this,_LineRangeCollector_line,(_a=__classPrivateFieldGet(this,_LineRangeCollector_line,"f"),_a++,_a),"f"),lineStart=newline+1}}text(){return Buffer.concat(__classPrivateFieldGet(this,_LineRangeCollector_collected,"f"),__classPrivateFieldGet(this,_LineRangeCollector_collectedBytes,"f")).toString("utf8")}}return _LineRangeCollector_filePath=new WeakMap,_LineRangeCollector_startLine=new WeakMap,_LineRangeCollector_endLine=new WeakMap,_LineRangeCollector_start=new WeakMap,_LineRangeCollector_end=new WeakMap,_LineRangeCollector_limit=new WeakMap,_LineRangeCollector_line=new WeakMap,_LineRangeCollector_collected=new WeakMap,_LineRangeCollector_collectedBytes=new WeakMap,_LineRangeCollector_instances=new WeakSet,_LineRangeCollector_collect=function(lineBytes,newlineTerminated){if(__classPrivateFieldGet(this,_LineRangeCollector_collected,"f").push(lineBytes),__classPrivateFieldSet(this,_LineRangeCollector_collectedBytes,__classPrivateFieldGet(this,_LineRangeCollector_collectedBytes,"f")+lineBytes.length,"f"),newlineTerminated&&__classPrivateFieldGet(this,_LineRangeCollector_line,"f")+1<__classPrivateFieldGet(this,_LineRangeCollector_end,"f")&&(__classPrivateFieldGet(this,_LineRangeCollector_collected,"f").push(NEWLINE),__classPrivateFieldSet(this,_LineRangeCollector_collectedBytes,__classPrivateFieldGet(this,_LineRangeCollector_collectedBytes,"f")+NEWLINE.length,"f")),__classPrivateFieldGet(this,_LineRangeCollector_collectedBytes,"f")>__classPrivateFieldGet(this,_LineRangeCollector_limit,"f"))throw __classPrivateFieldGet(this,_LineRangeCollector_instances,"m",_LineRangeCollector_overLimitError).call(this)},_LineRangeCollector_overLimitError=function(){return __classPrivateFieldGet(this,_LineRangeCollector_end,"f")-__classPrivateFieldGet(this,_LineRangeCollector_start,"f")===1?new ToolError(`read: line ${__classPrivateFieldGet(this,_LineRangeCollector_start,"f")+1} of ${__classPrivateFieldGet(this,_LineRangeCollector_filePath,"f")} alone exceeds ${__classPrivateFieldGet(this,_LineRangeCollector_limit,"f")}-byte limit. The read tool cannot return part of a line, so view_range cannot narrow this further.`):new ToolError(`read: view_range [${__classPrivateFieldGet(this,_LineRangeCollector_startLine,"f")}, ${__classPrivateFieldGet(this,_LineRangeCollector_endLine,"f")}] of ${__classPrivateFieldGet(this,_LineRangeCollector_filePath,"f")} exceeds ${__classPrivateFieldGet(this,_LineRangeCollector_limit,"f")}-byte limit. Narrow the view_range to read a smaller portion.`)},LineRangeCollector2})();function betaWriteTool(ctx){return rejectUnrestrictedPaths(ctx.unrestrictedPaths),betaTool({name:"write",description:"Write a UTF-8 text file relative to the workdir, creating parent directories as needed.",inputSchema:{type:"object",properties:{file_path:{type:"string"},content:{type:"string"}},required:["file_path","content"]},run:async({file_path,content})=>{if(!file_path)throw new ToolError("write: file_path is required");let abs=await resolvePath(ctx,file_path),ro=await readOnlyRootFor(ctx,abs);if(ro!==void 0)throw new ToolError(`write: ${file_path} is inside read-only directory ${ro}`);try{await fs4.mkdir(path2.dirname(abs),{recursive:!0,mode:DIR_CREATE_MODE}),await atomicWriteFile(abs,content??"")}catch(e){throw new ToolError(`write: ${fsErrorMessage(e,file_path)}`)}return`wrote ${Buffer.byteLength(content??"")} bytes to ${file_path}`}})}function betaEditTool(ctx){return rejectUnrestrictedPaths(ctx.unrestrictedPaths),betaTool({name:"edit",description:"Replace old_string with new_string in a file. old_string must be unique unless replace_all.",inputSchema:{type:"object",properties:{file_path:{type:"string"},old_string:{type:"string"},new_string:{type:"string"},replace_all:{type:"boolean"}},required:["file_path","old_string","new_string"]},run:async({file_path,old_string,new_string,replace_all})=>{if(!file_path)throw new ToolError("edit: file_path is required");if(!old_string)throw new ToolError("edit: old_string is required");let abs=await resolvePath(ctx,file_path),ro=await readOnlyRootFor(ctx,abs);if(ro!==void 0)throw new ToolError(`edit: ${file_path} is inside read-only directory ${ro}`);let data;try{let st=await fs4.stat(abs);if(!st.isFile())throw new ToolError(`edit: ${file_path} is not a regular file`);let limit=resolveMaxBytes(ctx.maxFileBytes);if(limit!==null&&st.size>limit)throw new ToolError(`edit: ${file_path} is ${st.size} bytes, exceeds ${limit}-byte limit. The edit tool loads the whole file and cannot modify a file this large.`);data=await fs4.readFile(abs,"utf8")}catch(e){throw e instanceof ToolError?e:new ToolError(`edit: ${fsErrorMessage(e,file_path)}`)}let count=data.split(old_string).length-1;if(count===0)throw new ToolError(`edit: old_string not found in ${file_path}`);let updated;if(replace_all)updated=data.split(old_string).join(new_string);else{if(count>1)throw new ToolError(`edit: old_string appears ${count} times in ${file_path} (must be unique)`);updated=data.replace(old_string,()=>new_string)}try{await atomicWriteFile(abs,updated)}catch(e){throw new ToolError(`edit: write: ${fsErrorMessage(e,file_path)}`)}return`edited ${file_path} (${replace_all?count:1} replacement(s))`}})}function patternCanAscend(pattern){return pattern.split(/[\\/{},]/).includes("..")}function betaGlobTool(ctx){return rejectUnrestrictedPaths(ctx.unrestrictedPaths),betaTool({name:"glob",description:"Match files under the workdir against a glob pattern. Results are mtime-sorted, newest first.",inputSchema:{type:"object",properties:{pattern:{type:"string"},path:{type:"string",description:"Directory to search in. Defaults to the workdir."}},required:["pattern"]},run:async({pattern,path:searchPath})=>{if(!pattern)throw new ToolError("glob: pattern is required");if(path2.isAbsolute(pattern))throw new ToolError("glob: absolute pattern not permitted; pass a relative pattern (and optionally path)");if(patternCanAscend(pattern))throw new ToolError('glob: ".." is not permitted in the pattern');let root=searchPath?await resolvePath(ctx,searchPath):path2.resolve(ctx.workdir),realRoot=searchPath?root:await canonicalize(root),matches=[],remaining=WALK_MAX_ENTRIES;try{for await(let entry of fsGlob(pattern,{cwd:root,withFileTypes:!0,exclude:d=>d.name===".git"||d.name==="node_modules"})){if(remaining--<=0)break;if(!entry.isFile())continue;let full=path2.join(entry.parentPath,entry.name),real;try{real=await fs4.realpath(full)}catch{continue}if(!isWithin(realRoot,real))continue;let mtime=0;try{mtime=(await fs4.stat(full)).mtimeMs}catch{}matches.push({path:full,mtime})}}catch(e){throw new ToolError(`glob: ${e instanceof Error?e.message:String(e)}`)}return matches.length===0?"no matches":(matches.sort((a,b)=>b.mtime-a.mtime),matches.slice(0,GLOB_RESULT_LIMIT).map(m=>m.path).join(`
|
|
14
|
+
`))}})}function betaGrepTool(ctx){return rejectUnrestrictedPaths(ctx.unrestrictedPaths),betaTool({name:"grep",description:"Search file contents for a regex. Uses ripgrep if available, otherwise a built-in walker.",inputSchema:{type:"object",properties:{pattern:{type:"string"},path:{type:"string"}},required:["pattern"]},run:async({pattern,path:p},context)=>{if(!pattern)throw new ToolError("grep: pattern is required");let searchPath=path2.resolve(ctx.workdir);p&&(searchPath=await resolvePath(ctx,p));let rg=await findRg();return rg?runRipgrep(rg,pattern,searchPath,context?.signal):runWalkGrep(pattern,searchPath,context?.signal)}})}function runRipgrep(rg,pattern,searchPath,signal){return new Promise((resolve2,reject)=>{let proc=cp.spawn(rg,["-n","--no-heading","-e",pattern,"--",searchPath],{...signal?{signal}:{}}),out="",errOut="",truncated=!1;proc.stdout.on("data",d=>{truncated||(out+=d,out.length>GREP_OUTPUT_LIMIT&&(truncated=!0,out=out.slice(0,GREP_OUTPUT_LIMIT),proc.kill("SIGKILL")))}),proc.stderr.on("data",d=>errOut+=d),proc.on("close",code=>{if(signal?.aborted)return reject(new ToolError("grep: aborted"));if(truncated)return resolve2(out+`
|
|
15
|
+
[output truncated at ${GREP_OUTPUT_LIMIT} bytes]`);if(code===0)return resolve2(out);if(code===1)return resolve2("no matches");reject(new ToolError(`grep: rg failed: ${errOut||`exit ${code}`}`))}),proc.on("error",e=>{if(signal?.aborted)return reject(new ToolError("grep: aborted"));reject(new ToolError(`grep: rg failed: ${e.message}`))})})}async function runWalkGrep(pattern,root,signal){let re;try{re=new RegExp(pattern)}catch(e){throw new ToolError(`grep: invalid regex: ${e instanceof Error?e.message:String(e)}`)}let hits=[],budget=GREP_OUTPUT_LIMIT,push=line=>(budget-=line.length+1,budget<0?(hits.push(`[output truncated at ${GREP_OUTPUT_LIMIT} bytes]`),!1):(hits.push(line),!0));if((await fs4.stat(root).catch(()=>null))?.isFile()?await grepFile(root,re,push):await walk2(root,"",rel=>grepFile(path2.join(root,rel),re,push),signal),signal?.aborted)throw new ToolError("grep: aborted");return hits.length===0?"no matches":hits.join(`
|
|
16
|
+
`)}async function grepFile(file,re,push){let stream2=fssync.createReadStream(file,{encoding:"utf8"}),rl=readline.createInterface({input:stream2,crlfDelay:1/0}),i=0;try{for await(let line of rl)if(i++,!(line.length>GREP_MAX_LINE_LENGTH)&&re.test(line)&&!push(`${file}:${i}:${line}`))return!1}catch{}finally{stream2.destroy()}return!0}var WALK_MAX_DEPTH=40,WALK_MAX_ENTRIES=5e4;async function walk2(root,rel,fn,signal){let remaining=WALK_MAX_ENTRIES;async function inner(rel2,depth){if(depth>WALK_MAX_DEPTH)return!0;if(signal?.aborted)return!1;let entries;try{entries=await fs4.readdir(path2.join(root,rel2),{withFileTypes:!0})}catch{return!0}for(let e of entries){if(e.name===".git"||e.name==="node_modules")continue;if(remaining--<=0||signal?.aborted)return!1;let childRel=rel2?path2.join(rel2,e.name):e.name;if(e.isDirectory()){if(!await inner(childRel,depth+1))return!1}else if(e.isFile()&&await fn(childRel)===!1)return!1}return!0}await inner(rel,0)}async function findRg(){let dirs=(process.env.PATH??"").split(path2.delimiter);for(let d of dirs){let candidate=path2.join(d,"rg");try{return await fs4.access(candidate,fssync.constants.X_OK),candidate}catch{}}return null}export{BashSession,BashTimeoutError,DEFAULT_MEMORY_SYNC_INTERVAL_MS,MARKER_PATH,MEMORY_FLUSH_TIMEOUT_MS,MIN_MEMORY_SYNC_INTERVAL_MS,SessionMemoryError,SessionMemoryStores,betaAgentToolset20260401,betaBashTool,betaEditTool,betaGlobTool,betaGrepTool,betaReadTool,betaWriteTool,extractSkillArchive,resolvePath,setupSkills};
|