@fugood/buttress-server 2.26.0-beta.2 → 2.26.0-beta.20
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/README.md +415 -10
- package/config/function-samples/README.md +1 -0
- package/config/function-samples/classify-ticket.ts +73 -0
- package/config/function-samples/run-agent.ts +39 -0
- package/config/sample.toml +67 -0
- package/lib/agent/cli.d.ts +19 -0
- package/lib/agent/client.d.ts +66 -0
- package/lib/agent/codemode-worker.d.ts +1 -0
- package/lib/agent/codemode.d.ts +7 -0
- package/lib/agent/config.d.ts +15 -0
- package/lib/agent/context.d.ts +11 -0
- package/lib/agent/decisions.check.d.ts +1 -0
- package/lib/agent/decisions.d.ts +113 -0
- package/lib/agent/device-auth.d.ts +3 -0
- package/lib/agent/device-tools.d.ts +5 -0
- package/lib/agent/loopback.d.ts +21 -0
- package/lib/agent/mcp.d.ts +22 -0
- package/lib/agent/models.d.ts +22 -0
- package/lib/agent/service.d.ts +16 -0
- package/lib/agent/sessions.d.ts +30 -0
- package/lib/agent/tools.d.ts +35 -0
- package/lib/agent/tui.d.ts +17 -0
- package/lib/agent/types.d.ts +155 -0
- package/lib/cli-KbjOekMI.mjs +22 -0
- package/lib/client-qqI-HCOj.mjs +8 -0
- package/lib/codemode-Cva7OeQX.mjs +112 -0
- package/lib/codemode-worker.mjs +3 -0
- package/lib/command-B92OGHj0.mjs +38 -0
- package/lib/config-DiYweJ2m.mjs +2 -0
- package/lib/functions/executor.d.ts +7 -1
- package/lib/functions/index.d.ts +3 -1
- package/lib/functions/status.d.ts +1 -1
- package/lib/functions/templates.d.ts +1 -1
- package/lib/functions/types.d.ts +15 -2
- package/lib/index.d.ts +12 -5
- package/lib/index.mjs +146 -93
- package/lib/mcp-DzknURyz.mjs +5 -0
- package/lib/mlx-bridge.py +681 -0
- package/lib/net-DPM9odNy.mjs +46 -0
- package/lib/protocol-WkPByalT.mjs +468 -0
- package/lib/quickjs.wasm +0 -0
- package/lib/rolldown-runtime-dTnj95Mm.mjs +2 -0
- package/lib/routes/agents.d.ts +66 -0
- package/lib/routes/decision-shared.d.ts +28 -0
- package/lib/routes/generator-cache.d.ts +3 -1
- package/lib/routes/index.d.ts +2 -0
- package/lib/routes/llm-shared.d.ts +1 -0
- package/lib/routes/openai-compat.d.ts +13 -2
- package/lib/routes/openai-decisions.check.d.ts +1 -0
- package/lib/routes/openai-decisions.d.ts +97 -0
- package/lib/routes/status.d.ts +2 -1
- package/lib/routes/typesafe-compat.check.d.ts +1 -0
- package/lib/routes/typesafe-compat.d.ts +30 -0
- package/lib/services/ggml-decision.d.ts +80 -0
- package/lib/services/ggml-llm.d.ts +29 -1
- package/lib/services/index.d.ts +3 -0
- package/lib/tui-ClNupsCH.mjs +2 -0
- package/lib/types.d.ts +48 -2
- package/lib/ui/command.d.ts +2 -0
- package/lib/ui/host.d.ts +1 -0
- package/lib/ui/window-module.d.ts +6 -0
- package/lib/utils/config.d.ts +3 -3
- package/lib/utils/cors.d.ts +1 -0
- package/lib/utils/decision-sharing.d.ts +37 -0
- package/lib/utils/downloadStatus.d.ts +57 -0
- package/lib/utils/hostFacts.d.ts +13 -0
- package/lib/utils/workspaceState.d.ts +8 -0
- package/lib/wrapper-3PX6qE3t.mjs +7 -0
- package/package.json +17 -9
- package/public/status.html +219 -1489
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent feature types: config-defined agents that run pi-agent-core loops
|
|
3
|
+
* inside the buttress-server process, with local functions, MCP servers and
|
|
4
|
+
* opt-in device tools, plus config-scoped JSONL sessions.
|
|
5
|
+
*/
|
|
6
|
+
export type AgentMcpServerConfig = {
|
|
7
|
+
/** StreamableHTTP endpoint; mutually exclusive with `command`. */
|
|
8
|
+
url?: string;
|
|
9
|
+
headers?: Record<string, string>;
|
|
10
|
+
/** Stdio server command; mutually exclusive with `url`. */
|
|
11
|
+
command?: string;
|
|
12
|
+
args?: string[];
|
|
13
|
+
env?: Record<string, string>;
|
|
14
|
+
/** Degrade-and-continue when this server fails to connect (default: fail the run). */
|
|
15
|
+
optional?: boolean;
|
|
16
|
+
/** Per-request timeout in seconds (default 60; progress notifications renew it). */
|
|
17
|
+
timeout?: number;
|
|
18
|
+
/**
|
|
19
|
+
* `direct` (default) declares every tool; `codemode` / `deferred` leave tools
|
|
20
|
+
* to codemode scripts (agents with `codemode = true` only); `hidden` makes
|
|
21
|
+
* them unreachable.
|
|
22
|
+
*/
|
|
23
|
+
exposure?: AgentMcpExposure;
|
|
24
|
+
/** Per-tool exposure by exact tool name or `*` pattern. */
|
|
25
|
+
toolExposure?: Record<string, AgentMcpExposure>;
|
|
26
|
+
};
|
|
27
|
+
export type AgentMcpExposure = 'direct' | 'codemode' | 'deferred' | 'hidden';
|
|
28
|
+
export type AgentDefinition = {
|
|
29
|
+
/** Unique agent name — the session scope key. */
|
|
30
|
+
name: string;
|
|
31
|
+
/** Model reference split on the FIRST slash: `provider/model-id`. */
|
|
32
|
+
provider: string;
|
|
33
|
+
modelId: string;
|
|
34
|
+
/** Raw `model` string from config, for error messages. */
|
|
35
|
+
modelRef: string;
|
|
36
|
+
systemPrompt: string | null;
|
|
37
|
+
/** Resolved absolute path; loaded lazily so edits apply per run. */
|
|
38
|
+
systemPromptFile: string | null;
|
|
39
|
+
/** Local function names exposed as tools (explicit list, no wildcard). */
|
|
40
|
+
tools: string[];
|
|
41
|
+
/** Opt-in LAN discovery and device DevTools access (default false). */
|
|
42
|
+
localDevices: boolean;
|
|
43
|
+
/**
|
|
44
|
+
* Opt-in `codemode` tool (default false): scripts that call the agent's
|
|
45
|
+
* tools, including MCP tools with `codemode` / `deferred` exposure.
|
|
46
|
+
*/
|
|
47
|
+
codemode: boolean;
|
|
48
|
+
mcpServers: Record<string, AgentMcpServerConfig>;
|
|
49
|
+
/** Assistant↔tool round-trips per run. */
|
|
50
|
+
maxTurns: number;
|
|
51
|
+
/** Cumulative token budget per run; null = unlimited (default). */
|
|
52
|
+
maxTokensPerRun: number | null;
|
|
53
|
+
thinking?: 'off' | 'minimal' | 'low' | 'medium' | 'high';
|
|
54
|
+
/**
|
|
55
|
+
* Classifier model (`provider/model-id`, e.g. `buttress/<decision generator>`
|
|
56
|
+
* or `typesafe/jev-latest`) for the `decision_evaluate` tool and decision
|
|
57
|
+
* assistance; null = no decisions (never falls back to the chat model).
|
|
58
|
+
*/
|
|
59
|
+
decisionModel: {
|
|
60
|
+
provider: string;
|
|
61
|
+
modelId: string;
|
|
62
|
+
modelRef: string;
|
|
63
|
+
} | null;
|
|
64
|
+
/** Opt-in tool prefilter before each run (needs `decisionModel`; default false). */
|
|
65
|
+
decisionAssistance: boolean;
|
|
66
|
+
/** Prefilter deadline; past it the run keeps every tool. */
|
|
67
|
+
decisionTimeoutMs: number;
|
|
68
|
+
/** Generation passthrough (temperature, top_p, …). */
|
|
69
|
+
generation: Record<string, unknown>;
|
|
70
|
+
};
|
|
71
|
+
export type AgentsConfig = {
|
|
72
|
+
agents: AgentDefinition[];
|
|
73
|
+
/** Directory the TOML config lives in (stdio MCP servers run with this cwd). */
|
|
74
|
+
configDir: string;
|
|
75
|
+
/** Absolute sessions root (default `./.buttress-agent/sessions` next to the config). */
|
|
76
|
+
sessionsDir: string;
|
|
77
|
+
/** Absolute path of the 0600 file holding the internal token for same-host CLIs. */
|
|
78
|
+
runtimeTokenFile: string;
|
|
79
|
+
sessionMaxAgeMs: number | null;
|
|
80
|
+
sessionMaxCount: number | null;
|
|
81
|
+
/** Agent-invocation chain depth cap (function → agent → function → agent…). */
|
|
82
|
+
maxDepth: number;
|
|
83
|
+
/** Serve /agents endpoints on an unbound server (default false — fail closed). */
|
|
84
|
+
allowUnauthenticated: boolean;
|
|
85
|
+
};
|
|
86
|
+
export type AgentUsage = {
|
|
87
|
+
input: number;
|
|
88
|
+
output: number;
|
|
89
|
+
cacheRead: number;
|
|
90
|
+
totalTurns: number;
|
|
91
|
+
};
|
|
92
|
+
export type AgentStopReason = 'end_turn' | 'max_turns' | 'token_budget' | 'aborted' | 'error';
|
|
93
|
+
export type AgentRunOptions = {
|
|
94
|
+
prompt: string;
|
|
95
|
+
/** Continue this session; omitted → new session. */
|
|
96
|
+
sessionId?: string;
|
|
97
|
+
/** With `sessionId`: fork it into a fresh session instead of continuing. */
|
|
98
|
+
fork?: boolean;
|
|
99
|
+
/** pi agent event passthrough (shape follows the pinned pi version). */
|
|
100
|
+
onEvent?: (event: unknown) => void;
|
|
101
|
+
/**
|
|
102
|
+
* Fires once the run's session exists (created, opened, or forked), before
|
|
103
|
+
* the model starts — the id to abort or continue with. A streaming client
|
|
104
|
+
* otherwise only learns it from the terminal event.
|
|
105
|
+
*/
|
|
106
|
+
onSession?: (sessionId: string) => void;
|
|
107
|
+
/** Aborts the run (chains into tool calls and spawned processes). */
|
|
108
|
+
signal?: AbortSignal;
|
|
109
|
+
/** Internal: agent-invocation chain depth of the caller. */
|
|
110
|
+
depth?: number;
|
|
111
|
+
};
|
|
112
|
+
export type AgentRunResult = {
|
|
113
|
+
sessionId: string;
|
|
114
|
+
content: string;
|
|
115
|
+
reasoningContent?: string;
|
|
116
|
+
usage: AgentUsage;
|
|
117
|
+
stopReason: AgentStopReason;
|
|
118
|
+
};
|
|
119
|
+
export type AgentSessionSummary = {
|
|
120
|
+
sessionId: string;
|
|
121
|
+
createdAt: string;
|
|
122
|
+
updatedAt: string;
|
|
123
|
+
parentSession: string | null;
|
|
124
|
+
/** First user prompt (truncated) when available. */
|
|
125
|
+
preview: string | null;
|
|
126
|
+
};
|
|
127
|
+
export type AgentSessionListOptions = {
|
|
128
|
+
limit?: number;
|
|
129
|
+
};
|
|
130
|
+
/** Error whose `sessionId` survives a failed/aborted run (transcript is continuable). */
|
|
131
|
+
export declare class AgentRunError extends Error {
|
|
132
|
+
sessionId: string | null;
|
|
133
|
+
stopReason: AgentStopReason;
|
|
134
|
+
constructor(message: string, sessionId: string | null, stopReason?: AgentStopReason);
|
|
135
|
+
}
|
|
136
|
+
export type AgentsService = {
|
|
137
|
+
config: AgentsConfig;
|
|
138
|
+
/** Configured agent names. */
|
|
139
|
+
list: () => string[];
|
|
140
|
+
run: (name: string, options: AgentRunOptions) => Promise<AgentRunResult>;
|
|
141
|
+
sessions: (name: string, options?: AgentSessionListOptions) => Promise<AgentSessionSummary[]>;
|
|
142
|
+
/** Full transcript of one session (pi AgentMessage array). */
|
|
143
|
+
transcript: (name: string, sessionId: string) => Promise<unknown[]>;
|
|
144
|
+
/** Abort the active run on a session; true when one was running. */
|
|
145
|
+
abort: (name: string, sessionId: string) => boolean;
|
|
146
|
+
/** Constant-time check of the internal loopback/CLI token. */
|
|
147
|
+
verifyInternalToken: (token: string | null | undefined) => boolean;
|
|
148
|
+
dispose: () => Promise<void>;
|
|
149
|
+
};
|
|
150
|
+
/** The `context.agents` surface local functions receive. */
|
|
151
|
+
export type AgentsFunctionApi = {
|
|
152
|
+
run: (name: string, options: Omit<AgentRunOptions, 'signal' | 'depth'>) => Promise<AgentRunResult>;
|
|
153
|
+
list: () => string[];
|
|
154
|
+
sessions: (name: string, options?: AgentSessionListOptions) => Promise<AgentSessionSummary[]>;
|
|
155
|
+
};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{a as e,i as t,n,r,t as i}from"./client-qqI-HCOj.mjs";import a from"node:readline";const o=`\x1B[2m`,s=`\x1B[33m`,c=`\x1B[31m`,l=`\x1B[0m`,u=e=>{let t={name:null,configArg:null,url:null,token:null,sessionId:null,fork:!1,listSessions:!1,plain:!1};for(let n=0;n<e.length;n+=1){let r=e[n];r===`-h`||r===`--help`?(console.log(`
|
|
3
|
+
bricks-buttress agent — chat with a configured agent on a running server
|
|
4
|
+
|
|
5
|
+
Usage:
|
|
6
|
+
bricks-buttress agent [name] [options]
|
|
7
|
+
|
|
8
|
+
Options:
|
|
9
|
+
-c, --config <path|toml> Config file (finds server port + local token)
|
|
10
|
+
--url <url> Server base URL (default from config, else http://127.0.0.1:2080)
|
|
11
|
+
--token <token> Access token (default: the config's runtime token file)
|
|
12
|
+
--session <id> Continue an existing session
|
|
13
|
+
--fork <id> Fork a session, then continue the fork
|
|
14
|
+
--sessions List the agent's sessions and exit
|
|
15
|
+
--plain Line-based output (default when not a TTY)
|
|
16
|
+
-h, --help Show this help
|
|
17
|
+
|
|
18
|
+
In the chat: /exit quits, /new starts a fresh session, Ctrl+C aborts the
|
|
19
|
+
current run (a second Ctrl+C quits).
|
|
20
|
+
`),process.exit(0)):r===`-c`||r===`--config`?t.configArg=e[++n]??null:r===`--url`?t.url=e[++n]??null:r===`--token`?t.token=e[++n]??null:r===`--session`?t.sessionId=e[++n]??null:r===`--fork`?(t.sessionId=e[++n]??null,t.fork=!0):r===`--sessions`?t.listSessions=!0:r===`--plain`?t.plain=!0:!r.startsWith(`-`)&&!t.name?t.name=r:(console.error(`Unknown argument: ${r}`),process.exit(1))}return t},d=e=>{console.error(`${c}${e}${l}`),process.exit(1)},f=async(t,n,r,i,a,u)=>{let d=i,f=!1,p=!1,m=()=>{f&&=(process.stdout.write(`${l}\n`),!1)},h=await e(t,n,{prompt:r,sessionId:i??void 0,fork:a},{signal:u,onFrame:({event:e,payload:t})=>{if(e===`session`){t.sessionId&&t.sessionId!==d&&(d=t.sessionId,i||console.log(`${o}session ${d}${l}`));return}if(e!==`agent`)return;let n=t?.event;if(t?.type===`message_update`&&n)n.type===`thinking_delta`?(f||=(process.stdout.write(`${o}`),!0),process.stdout.write(n.delta??``),p=!0):n.type===`text_delta`&&(m(),process.stdout.write(n.delta??``),p=!0);else if(t?.type===`tool_execution_start`){m(),p&&process.stdout.write(`
|
|
21
|
+
`);let e=JSON.stringify(t.args??{});console.log(`${s}⚙ ${t.toolName}${l}${o}(${e.length>160?`${e.slice(0,160)}…`:e})${l}`),p=!1}else t?.type===`tool_execution_end`?console.log(t.isError?`${c}✗ ${t.toolName} failed${l}`:`${o}✓ ${t.toolName}${l}`):t?.type===`tool_emit`&&console.log(`${o} ${t.toolName} → ${t.event}${l}`)}});if(m(),h.kind===`result`){let e=h.result;d=e.sessionId??d;let t=e.usage||{};return process.stdout.write(`
|
|
22
|
+
`),console.log(`${o}— ${e.stopReason} · ${t.totalTurns??`?`} turn(s) · ${t.input??0} in / ${t.output??0} out · session ${d}${l}`),{sessionId:d,ok:!0}}return h.kind===`aborted`?(console.log(`\n${s}(aborted)${l}`),{sessionId:h.sessionId??d,ok:!1}):h.kind===`error`?(console.error(`\n${c}Run failed: ${h.message}${l}`),{sessionId:h.sessionId??d,ok:!1}):(console.error(`\n${c}Connection lost mid-run.${l}`),{sessionId:h.sessionId??d,ok:!1})},p=async(e,t,n,r)=>{let s=n,u=r;console.log(`[1m${t}${l} @ ${e.baseUrl}`+(s?` ${o}(${u?`forking`:`continuing`} ${s})${l}`:``)),console.log(`${o}/exit to quit, /new for a fresh session, Ctrl+C aborts a running turn${l}`);let d=a.createInterface({input:process.stdin,output:process.stdout}),p=!1;d.on(`close`,()=>{p=!0});let m=e=>new Promise(t=>{if(p){t(null);return}d.question(e,t),d.once(`close`,()=>t(null))}),h=null;for(d.on(`SIGINT`,()=>{h?(h.abort(),h=null):(d.close(),process.exit(0))});;){let n=await m(`[36m> ${l}`);if(n==null)break;let r=n.trim();if(!r)continue;if(r===`/exit`||r===`/quit`)break;if(r===`/new`){s=null,u=!1,console.log(`${o}Started a fresh session.${l}`);continue}h=new AbortController;let a=s;try{let n=await f(e,t,r,s,u,h.signal);n.sessionId&&(s=n.sessionId),i(a,s)&&(u=!1)}catch(e){console.error(`${c}${e?.message||e}${l}`)}finally{h=null}}d.close()},m=async e=>{let i=u(e),{config:a,agentsConfig:s}=n(i.configArg),c=a.server.port||2080,f=(i.url||`http://127.0.0.1:${c}`).replace(/\/$/,``),m={baseUrl:f,token:i.token||(s?r(s.runtimeTokenFile):null)||process.env.BUTTRESS_AGENT_TOKEN||null},h=await t(m,`/agents`).catch(e=>d(`Cannot reach ${f}: ${e?.message||e} (is the server running?)`));if(!h.ok){let e=await h.text().catch(()=>``);d(`Server rejected the request (${h.status}): ${e.slice(0,300)}`)}let{agents:g}=await h.json();if(!i.name){console.log(`Configured agents on ${f}:`);for(let e of g)console.log(`- ${e}`);g.length===0&&console.log(`(none — add [[agents]] to the server config)`);return}if(g.includes(i.name)||d(`Unknown agent "${i.name}" (configured: ${g.join(`, `)||`none`})`),i.listSessions){let{sessions:e}=await(await t(m,`/agents/${encodeURIComponent(i.name)}/sessions`)).json();if(!e?.length){console.log(`No sessions yet.`);return}for(let t of e)console.log(`${t.sessionId} ${o}${t.updatedAt}${l}${t.parentSession?` ${o}(fork of ${t.parentSession})${l}`:``}`),t.preview&&console.log(` ${o}${t.preview}${l}`);return}if(process.stdin.isTTY&&process.stdout.isTTY&&!i.plain){let{runAgentTui:e}=await import(`./tui-ClNupsCH.mjs`);await e({connection:m,agentName:i.name,sessionId:i.sessionId,fork:i.fork});return}await p(m,i.name,i.sessionId,i.fork)};export{m as runAgentCommand};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{a as e,n as t}from"./config-DiYweJ2m.mjs";import n from"node:path";import r from"node:fs";import i from"@iarna/toml";const a=a=>{let o={},s=process.cwd();a&&(r.existsSync(a)?(o=i.parse(r.readFileSync(a,`utf8`)),s=n.dirname(n.resolve(a))):o=i.parse(a));let c=e(o);return{config:c,configDir:s,agentsConfig:t(c,{configDir:s})}},o=e=>{try{return r.readFileSync(e,`utf8`).trim()||null}catch{return null}},s=async(e,t,n)=>fetch(`${e.baseUrl}${t}`,{...n,headers:{"content-type":`application/json`,...e.token?{authorization:`Bearer ${e.token}`}:{},...n?.headers}});async function*c(e){let t=e.getReader(),n=new TextDecoder,r=``;try{for(;;){let{done:e,value:i}=await t.read();if(e)break;r+=n.decode(i,{stream:!0});let a=r.indexOf(`
|
|
3
|
+
|
|
4
|
+
`);for(;a!==-1;){let e=r.slice(0,a);r=r.slice(a+2),a=r.indexOf(`
|
|
5
|
+
|
|
6
|
+
`);let t=`message`,n=[];for(let r of e.split(`
|
|
7
|
+
`))r.startsWith(`event:`)?t=r.slice(6).trim():r.startsWith(`data:`)&&n.push(r.slice(5).trimStart());n.length>0&&(yield{event:t,data:n.join(`
|
|
8
|
+
`)})}}}finally{t.releaseLock()}}const l=(e,t)=>t!=null&&t!==e,u=async(e,t,n,{signal:r,onFrame:i})=>{let a=n.sessionId??null,o;try{o=await s(e,`/agents/${encodeURIComponent(t)}/run?stream=1`,{method:`POST`,body:JSON.stringify({prompt:n.prompt,...n.sessionId?{sessionId:n.sessionId}:{},...n.fork?{fork:!0}:{}}),signal:r})}catch(e){if(r?.aborted)return{kind:`aborted`,sessionId:a};throw e}if(!o.ok||!o.body){let e=await o.text().catch(()=>``);return{kind:`error`,message:`Run request failed (${o.status}): ${e.slice(0,400)}`,sessionId:a}}try{for await(let e of c(o.body)){let t;try{t=JSON.parse(e.data)}catch{continue}if(e.event===`session`&&t?.sessionId&&(a=t.sessionId),e.event===`result`)return i({event:e.event,payload:t}),{kind:`result`,result:t};if(e.event===`error`)return i({event:e.event,payload:t}),{kind:`error`,message:t?.message||`run failed`,sessionId:t?.sessionId??a};i({event:e.event,payload:t})}}catch(e){if(r?.aborted)return{kind:`aborted`,sessionId:a};throw e}return r?.aborted?{kind:`aborted`,sessionId:a}:{kind:`disconnected`,sessionId:a}};export{u as a,s as i,a as n,o as r,l as t};
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{n as e}from"./protocol-WkPByalT.mjs";import{createRequire as t}from"node:module";import{readFile as n}from"node:fs/promises";import{runToolCall as r}from"@earendil-works/pi-agent-core";import{Worker as i}from"node:worker_threads";function a(e){let t=``;for(let n of e){let e=t===``?/^[A-Za-z_$]$/.test(n):/^[A-Za-z0-9_$]$/.test(n);t+=e?n:`_`}return t===``?`_`:t}const o=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function s(e,t={}){let n=e.inputSchema===void 0?`unknown`:m(e.inputSchema,{maxChars:t.inputMaxChars??16e3});return`${a(e.name)}(args: ${n}): Promise<${u(e.outputSchema)}>;`}function c(e,t={}){let n=`declare const tools: { ${s(e,t)} };`;return`${e.description?.trim()??``}\n\ncodemode tool declaration:\n\`\`\`ts\n${n}\n\`\`\``}function l(e){if(!f(e)||!f(e.properties))return;let{content:t,isError:n,_meta:r,structuredContent:i}=e.properties;if(!(!f(t)||t.type!==`array`||!f(t.items)||t.items.type!==`object`)&&!(!f(n)||n.type!==`boolean`||!f(r)||r.type!==`object`))return f(i)||typeof i==`boolean`?i:!0}function u(e){let t=l(e);if(t!==void 0){let e=m(t);return e===`unknown`?`CallToolResult`:`CallToolResult<${e}>`}return e===void 0?`unknown`:m(e)}function d(e){return o.test(e)?e:JSON.stringify(e)}function f(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function p(e){let t=[...new Set(e)];return t.includes(`unknown`)?`unknown`:t.length===0?`never`:t.join(` | `)}function m(e,t={}){let n=g(e,{root:e,resolving:new Set,expansions:0});return t.maxChars!==void 0&&n.length>t.maxChars?`unknown`:n}function h(e,t){if(e!==`#`&&!e.startsWith(`#/`))return;let n=t;for(let t of e.slice(2).split(`/`).filter(Boolean)){let e=decodeURIComponent(t).replaceAll(`~1`,`/`).replaceAll(`~0`,`~`);if(!f(n)||!(e in n))return;n=n[e]}return typeof n==`boolean`||f(n)?n:void 0}function g(e,t){if(e===!0)return`unknown`;if(e===!1)return`never`;if(!f(e))return`unknown`;if(typeof e.$ref==`string`){let n=e.$ref;if(t.resolving.has(n)||t.expansions>=32)return`unknown`;let r=h(n,t.root);if(r===void 0)return`unknown`;t.expansions++,t.resolving.add(n);try{return g(r,t)}finally{t.resolving.delete(n)}}if(`const`in e)return JSON.stringify(e.const)??`unknown`;if(Array.isArray(e.enum))return p(e.enum.map(e=>JSON.stringify(e)??`unknown`));let n=Array.isArray(e.anyOf)?e.anyOf:Array.isArray(e.oneOf)?e.oneOf:void 0;if(n)return p(n.map(e=>g(e,t)));if(Array.isArray(e.allOf)){let n=e.allOf.map(e=>g(e,t)).filter(e=>e!==`unknown`);return n.length===0?`unknown`:n.map(e=>e.includes(` | `)?`(${e})`:e).join(` & `)}let r=e.type;if(Array.isArray(r))return p(r.map(n=>g({...e,type:n},t)));switch(r){case`string`:return`string`;case`number`:case`integer`:return`number`;case`boolean`:return`boolean`;case`null`:return`null`;case`array`:return _(e,t);case`object`:return y(e,t);case void 0:return`properties`in e||`additionalProperties`in e||`required`in e?y(e,t):`items`in e||`prefixItems`in e?_(e,t):`unknown`;default:return`unknown`}}function _(e,t){if(e.items!==void 0&&!Array.isArray(e.items))return`Array<${g(e.items,t)}>`;let n=Array.isArray(e.prefixItems)?e.prefixItems:Array.isArray(e.items)?e.items:[];return n.length>0?`[${n.map(e=>g(e,t)).join(`, `)}]`:`unknown[]`}function v(e){return f(e)&&typeof e.description==`string`?e.description.trim():``}function y(e,t){let n=f(e.properties)?e.properties:{},r=new Set(Array.isArray(e.required)?e.required:[]),i=Object.keys(n).sort(),a=i.map(e=>{let i=r.has(e)?``:`?`;return`${d(e)}${i}: ${g(n[e],t)};`}),o=e.additionalProperties;if(o!==void 0&&o!==!1){let e=o===!0?`unknown`:g(o,t);a.push(`[key: string]: ${e};`)}else o===void 0&&i.length===0&&a.push(`[key: string]: unknown;`);if(a.length===0)return`{}`;if(!i.some(e=>v(n[e])))return`{ ${a.join(` `)} }`;let s=[`{`];i.forEach((e,t)=>{for(let t of v(n[e]).split(/\r?\n/))t.trim()&&s.push(` // ${t.trim()}`);s.push(` ${a[t].replaceAll(`
|
|
3
|
+
`,`
|
|
4
|
+
`)}`)});for(let e of a.slice(i.length))s.push(` ${e}`);return s.push(`}`),s.join(`
|
|
5
|
+
`)}const b=3e3,x={type:`string`};function S(e){return[`Globals:`,"- `text(value)`, `image(dataUrlOrImageBlock)`, `console.log(...)`, and top-level `return` add output; `exit()` ends the script.","- `store(key, value)` and `load(key)` keep small JSON values across codemode calls.","- `ALL_TOOLS`, `searchTools(query, { limit?, namespace? })`, `describeTool(name)`, `describeNamespace(name)`: find tools you were not given directly, such as MCP tools, and read their declarations.",...e?['- `models`: non-chat models with your credentials. `await models.getAvailableOfType("image" | "classifier")` lists them; `models.generateImages(model, { input: [{ type: "text", text }, ...{ type: "image", data, mimeType }] })` resolves to `{ output, stopReason, errorMessage? }` (show its image blocks with `image(block)`; can take minutes, so do not set a short timeout_ms); `models.classify(model, { state: {...}, questions: { id: { type: "choice" | "score" | "bool", instructions, criteria } } })` resolves to `{ answers, stopReason, errorMessage? }`. They do not throw on provider errors: check `stopReason`.']:[]].join(`
|
|
6
|
+
`)}function ee(e){return{name:e.name,description:e.description,inputSchema:e.parameters,outputSchema:e.outputSchema??x}}function C(e){let t=a(e.name);return`${t===e.name?`### \`${t}\``:`### \`${t}\` (\`${e.name}\`)`}\n${c(e).trim()}`}function w(e,t){let n=e.map(e=>[...e.entries].sort((e,t)=>e.cost-t.cost)),r=new Set,i=t,a=n.filter(e=>e.length>0);for(;a.length>0;)a=a.filter(e=>{let t=e[0];return t.cost>i?!1:(i-=t.cost,r.add(t.name),e.shift(),e.length>0)});return r}function T({tools:e,declaredNames:t=new Set,isDeferred:n=()=>!1,getNamespace:r=()=>void 0,models:i=!1,inlineBudget:a=b}){let o=['Run JavaScript that calls other tools. The input is raw JavaScript (not JSON, no code fence), run as an async function body in a QuickJS sandbox: top-level `await` and `return` work. No Node, file system, network, or timers.\n- `await tools.<name>({ ...args })` calls a tool by its name (characters outside [A-Za-z0-9_] become `_`), including most tools you can call directly (`ALL_TOOLS` is the exact list). It resolves to the tool\'s text output; MCP tools (`mcp__*`) resolve to their `CallToolResult` (`{ content, structuredContent?, isError? }`). A failed or blocked call rejects with an Error. Calls still running when the script ends are cancelled.\n- Use it to batch independent calls (`Promise.allSettled`), chain calls, or filter large output; only what the script outputs reaches you.\n- Optional first line: `// @options: {"max_output_tokens": 10000, "timeout_ms": 60000}`',S(i)],s=new Map;for(let i of e){if(t.has(i.name))continue;let e=r(i);if(!e||!n(i))continue;let a=s.get(e.name)??{...e,count:0};a.count+=1,s.set(e.name,a)}if(s.size>0){let e=[...s.values()].sort((e,t)=>e.name.localeCompare(t.name)).map(e=>{let t=e.description?.trim().split(`
|
|
7
|
+
`)[0];return`- \`${e.name}\` (${e.count} tool${e.count===1?``:`s`})${t?`: ${t}`:``}`});o.push(`Tool namespaces (find their tools with \`searchTools(query, { namespace })\` or \`describeNamespace(name)\`):\n${e.join(`
|
|
8
|
+
`)}`)}let c=e.filter(e=>!t.has(e.name)&&!n(e)).map(ee);if(c.length===0)return o.join(`
|
|
9
|
+
|
|
10
|
+
`);let u=new Map([[``,{namespace:void 0,entries:[]}]]);for(let t of c){let n=r(e.find(e=>e.name===t.name)),i=n?`ns:${n.name}`:``,a=u.get(i)??{namespace:n,entries:[]};u.set(i,a);let o=C(t);a.entries.push({name:t.name,section:o,cost:Math.ceil(o.length/4)})}let d=[...u.values()].sort((e,t)=>e.namespace===void 0?-1:t.namespace===void 0?1:e.namespace.name.localeCompare(t.namespace.name)),f=w(d,a);c.some(e=>f.has(e.name)&&l(e.outputSchema)!==void 0)&&o.push(`Shared MCP Types:
|
|
11
|
+
\`\`\`ts
|
|
12
|
+
type Role = "user" | "assistant";
|
|
13
|
+
type MetaObject = Record<string, unknown>;
|
|
14
|
+
type Annotations = {
|
|
15
|
+
audience?: Role[];
|
|
16
|
+
priority?: number;
|
|
17
|
+
lastModified?: string;
|
|
18
|
+
};
|
|
19
|
+
type Icon = {
|
|
20
|
+
src: string;
|
|
21
|
+
mimeType?: string;
|
|
22
|
+
sizes?: string[];
|
|
23
|
+
theme?: "light" | "dark";
|
|
24
|
+
};
|
|
25
|
+
type TextResourceContents = {
|
|
26
|
+
uri: string;
|
|
27
|
+
mimeType?: string;
|
|
28
|
+
_meta?: MetaObject;
|
|
29
|
+
text: string;
|
|
30
|
+
};
|
|
31
|
+
type BlobResourceContents = {
|
|
32
|
+
uri: string;
|
|
33
|
+
mimeType?: string;
|
|
34
|
+
_meta?: MetaObject;
|
|
35
|
+
blob: string;
|
|
36
|
+
};
|
|
37
|
+
type TextContent = {
|
|
38
|
+
type: "text";
|
|
39
|
+
text: string;
|
|
40
|
+
annotations?: Annotations;
|
|
41
|
+
_meta?: MetaObject;
|
|
42
|
+
};
|
|
43
|
+
type ImageContent = {
|
|
44
|
+
type: "image";
|
|
45
|
+
data: string;
|
|
46
|
+
mimeType: string;
|
|
47
|
+
annotations?: Annotations;
|
|
48
|
+
_meta?: MetaObject;
|
|
49
|
+
};
|
|
50
|
+
type AudioContent = {
|
|
51
|
+
type: "audio";
|
|
52
|
+
data: string;
|
|
53
|
+
mimeType: string;
|
|
54
|
+
annotations?: Annotations;
|
|
55
|
+
_meta?: MetaObject;
|
|
56
|
+
};
|
|
57
|
+
type ResourceLink = {
|
|
58
|
+
icons?: Icon[];
|
|
59
|
+
name: string;
|
|
60
|
+
title?: string;
|
|
61
|
+
uri: string;
|
|
62
|
+
description?: string;
|
|
63
|
+
mimeType?: string;
|
|
64
|
+
annotations?: Annotations;
|
|
65
|
+
size?: number;
|
|
66
|
+
_meta?: MetaObject;
|
|
67
|
+
type: "resource_link";
|
|
68
|
+
};
|
|
69
|
+
type EmbeddedResource = {
|
|
70
|
+
type: "resource";
|
|
71
|
+
resource: TextResourceContents | BlobResourceContents;
|
|
72
|
+
annotations?: Annotations;
|
|
73
|
+
_meta?: MetaObject;
|
|
74
|
+
};
|
|
75
|
+
type ContentBlock =
|
|
76
|
+
| TextContent
|
|
77
|
+
| ImageContent
|
|
78
|
+
| AudioContent
|
|
79
|
+
| ResourceLink
|
|
80
|
+
| EmbeddedResource;
|
|
81
|
+
type CallToolResult<TStructured = { [key: string]: unknown }> = {
|
|
82
|
+
_meta?: MetaObject;
|
|
83
|
+
content: ContentBlock[];
|
|
84
|
+
isError?: boolean;
|
|
85
|
+
structuredContent?: TStructured;
|
|
86
|
+
[key: string]: unknown;
|
|
87
|
+
};
|
|
88
|
+
\`\`\``);let p=[`Script-only tools:`];for(let{namespace:e,entries:t}of d){let n=t.filter(e=>f.has(e.name));if(e){let r=n.length===t.length?``:n.length===0?` (tools not listed)`:` (some tools not listed)`;p.push(`## ${e.name}${r}`)}for(let e of n)p.push(e.section)}return o.push(p.join(`
|
|
89
|
+
|
|
90
|
+
`)),o.join(`
|
|
91
|
+
|
|
92
|
+
`)}const E=new Map;function te(e){let r=e??t(import.meta.url).resolve(`quickjs-wasi/quickjs.wasm`),i=E.get(r);if(!i){let{WebAssembly:e}=globalThis;i=n(r).then(t=>e.compile(t)).catch(e=>{throw E.delete(r),e}),E.set(r,i)}return i}const ne=/^[A-Za-z_$][A-Za-z0-9_$]*$/,D=new Set([`tools`,`ALL_TOOLS`,`console`,`text`,`image`,`exit`,`globalThis`,`store`,`load`]);function O(e){return e instanceof Error?e.message:String(e)}function k(e){let t=Object.create(null);for(let[n,r]of Object.entries(e??{})){let e=JSON.stringify(r);e!==void 0&&(t[n]=e)}return t}var A=class extends Error{};function j(e,t){try{return JSON.parse(e)}catch{throw new A(`${t} is not valid JSON`)}}function M(e){let t=j(e,`store writes`);if(!Array.isArray(t))throw new A(`store writes are not an array`);let n={set:Object.create(null),delete:[]};for(let e of t){if(!Array.isArray(e)||typeof e[0]!=`string`||(e.length===2?typeof e[1]!=`string`:e.length!==1))throw new A(`store writes contain a malformed entry`);let[t,r]=e;r===void 0?n.delete.push(t):n.set[t]=j(r,`store value for ${JSON.stringify(t)}`)}return n}function re(e){let t=j(e,`script error`);if(typeof t!=`object`||!t)throw new A(`script error is not an object`);let{name:n,message:r,stack:i}=t;if(typeof r!=`string`||n!==void 0&&typeof n!=`string`||i!==void 0&&typeof i!=`string`)throw new A(`script error is malformed`);return{kind:`script`,name:n,message:r,stack:i}}function ie(){return new URL(import.meta.url.endsWith(`.ts`)?`./worker.ts`:`./worker.js`,import.meta.url)}var ae=class{promise;resolveResult;worker;interrupt=new SharedArrayBuffer(4);tools;globals;signal;timer;output=[];calls=[];pending=new Map;finished=!1;constructor(e){this.promise=new Promise(e=>{this.resolveResult=e}),this.tools=e.tools,this.globals=e.globals,this.signal=e.signal,Number.isFinite(e.timeoutMs)&&(this.timer=setTimeout(()=>{this.finish({kind:`timeout`,message:`Execution timed out after ${e.timeoutMs} ms`})},e.timeoutMs)),e.signal&&(e.signal.aborted?this.onAbort():e.signal.addEventListener(`abort`,this.onAbort,{once:!0})),e.wasm.then(t=>this.start(e,t),e=>{this.finish({kind:`sandbox`,message:`Failed to load QuickJS: ${O(e)}`})})}abort(e){return this.finish({kind:`aborted`,message:e}),this.promise}start(e,t){if(this.finished)return;let n={code:e.code,tools:[...e.tools.values()].map(e=>({name:e.name,jsName:a(e.name),description:e.description??``})),globals:[...e.globals.values()].map(e=>({name:e.name,spread:e.spread===!0})),wasm:t,memoryLimitBytes:e.memoryLimitBytes,store:e.store,interrupt:this.interrupt},r;try{r=new i(e.workerUrl,{workerData:n})}catch(e){this.finish({kind:`sandbox`,message:`Failed to start worker: ${O(e)}`});return}this.worker=r,r.on(`message`,e=>{try{this.handleMessage(e)}catch(e){this.finish({kind:`sandbox`,message:e instanceof A?`Sandbox bridge broken: ${e.message}. The script may have modified built-ins such as a prototype's toJSON.`:`Sandbox host failed: ${O(e)}`})}}),r.on(`error`,e=>{this.finish({kind:`sandbox`,name:e instanceof Error?e.name:void 0,message:O(e)})}),r.on(`exit`,e=>{this.finish({kind:`sandbox`,message:`Worker exited with code ${e} before the script settled`})})}onAbort=()=>{let e=this.signal?.reason;this.finish({kind:`aborted`,message:e instanceof Error?e.message:`Execution aborted`})};post(e){this.worker?.postMessage(e)}handleMessage(t){if(!this.finished){if(!e(t))throw new A(`unknown message from the worker`);switch(t.type){case`output`:this.output.push(t.item);break;case`call`:if(this.pending.has(t.id))throw new A(`duplicate call id ${t.id}`);this.handleCall(t);break;case`done`:this.handleDone(t);break;case`crash`:this.finish({kind:`sandbox`,message:t.message});break}}}handleDone(e){if(!e.ok){this.finish(re(e.error));return}let t=e.value===void 0?void 0:j(e.value,`return value`);this.finish(void 0,t,M(e.writes))}async handleCall(e){let{id:t,name:n}=e,r=e.target===`tool`,i=r?{name:n,status:`cancelled`,durationMs:0}:void 0;i&&this.calls.push(i);let a={record:i,startedAt:performance.now(),controller:new AbortController};this.pending.set(t,a);let o,s;try{let i=(r?this.tools:this.globals).get(n);if(!i)throw Error(`Unknown ${r?`tool`:`global`} "${n}"`);let c=e.args===void 0?void 0:JSON.parse(e.args),l=await i.execute(c,{signal:a.controller.signal});s={type:`result`,id:t,ok:!0,payload:l===void 0?void 0:JSON.stringify(l)},o=`ok`}catch(e){s={type:`result`,id:t,ok:!1,payload:O(e)},o=`error`}this.pending.delete(t)&&(i&&(i.status=o,i.durationMs=performance.now()-a.startedAt),this.post(s))}finish(e,t,n){if(this.finished)return;this.finished=!0,clearTimeout(this.timer),this.signal?.removeEventListener(`abort`,this.onAbort);let r=performance.now();for(let e of this.pending.values())e.record&&(e.record.durationMs=r-e.startedAt),e.controller.abort();this.pending.clear();let i=e?{ok:!1,error:e,output:this.output,calls:this.calls}:{ok:!0,value:t,output:this.output,calls:this.calls,storeWrites:n??{set:{},delete:[]}};if(!this.worker){this.resolveResult(i);return}Atomics.store(new Int32Array(this.interrupt),0,1),this.worker.terminate().catch(()=>void 0).then(()=>this.resolveResult(i))}},oe=class{toolsByName=new Map;globalsByName=new Map;timeoutMs;memoryLimitBytes;wasm;workerUrl;running=new Set;closed=!1;constructor(e={}){this.timeoutMs=e.timeoutMs??3e5,this.memoryLimitBytes=e.memoryLimitBytes,this.wasm=e.wasm,this.workerUrl=e.workerUrl??ie();for(let t of e.tools??[])this.registerTool(t);let t=new Set;for(let n of e.globals??[]){let e=n.name.split(`.`);if(e.length>2||!e.every(e=>ne.test(e))||D.has(e[0]))throw Error(`Invalid global name "${n.name}"`);if(this.globalsByName.has(n.name))throw Error(`Global "${n.name}" is already registered`);e.length===2&&t.add(e[0]),this.globalsByName.set(n.name,n)}for(let e of t)if(this.globalsByName.has(e))throw Error(`Global "${e}" conflicts with the namespace "${e}"`)}registerTool(e){if(this.toolsByName.has(e.name))throw Error(`Tool "${e.name}" is already registered`);this.toolsByName.set(e.name,e)}unregisterTool(e){return this.toolsByName.delete(e)}get tools(){return[...this.toolsByName.values()]}get globals(){return[...this.globalsByName.values()]}execute(e,t={}){if(this.closed)return Promise.reject(Error(`Sandbox is closed`));let n=new ae({code:e,tools:new Map(this.toolsByName),globals:this.globalsByName,timeoutMs:t.timeoutMs??this.timeoutMs,signal:t.signal,memoryLimitBytes:this.memoryLimitBytes,store:k(t.store),wasm:this.wasm===void 0?te():Promise.resolve(this.wasm),workerUrl:this.workerUrl});return this.running.add(n),n.promise.finally(()=>this.running.delete(n))}async close(){this.closed=!0,await Promise.all([...this.running].map(e=>e.abort(`Sandbox closed`)))}};const se=[`max_output_tokens`,`timeout_ms`],N="`max_output_tokens` and `timeout_ms`",ce=2147483647;String.raw`
|
|
93
|
+
start: options_source | plain_source
|
|
94
|
+
options_source: OPTIONS_LINE NEWLINE SOURCE
|
|
95
|
+
plain_source: SOURCE
|
|
96
|
+
|
|
97
|
+
OPTIONS_LINE: /[ \t]*\/\/ @options:[^\r\n]*/
|
|
98
|
+
NEWLINE: /\r?\n/
|
|
99
|
+
SOURCE: /[\s\S]+/
|
|
100
|
+
`;var P=class extends Error{constructor(e){super(e),this.name=`CodemodeSourceError`}};function le(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function ue(e){if(e===``)throw new P(`@options must be a JSON object with supported fields ${N}`);let t;try{t=JSON.parse(e)}catch(e){throw new P(`@options must be valid JSON with supported fields ${N}: ${e instanceof Error?e.message:String(e)}`)}if(typeof t!=`object`||!t||Array.isArray(t))throw new P(`@options must be a JSON object with supported fields ${N}`);let n=t;for(let e of Object.keys(n))if(!se.includes(e))throw new P(`@options only supports ${N}; got \`${e}\``);let r={},{max_output_tokens:i,timeout_ms:a}=n;if(i!==void 0){if(!le(i))throw new P("@options field `max_output_tokens` must be a non-negative safe integer");r.maxOutputTokens=i}if(a!==void 0){if(!le(a)||a===0||a>ce)throw new P(`@options field \`timeout_ms\` must be a positive integer up to ${ce}`);r.timeoutMs=a}return r}function de(e){if(e.trim()===``)throw new P('Expected JavaScript source text (non-empty). Provide JS only, optionally with a first line `// @options: {"max_output_tokens": 1000}`.');let t=e.indexOf(`
|
|
101
|
+
`),n=(t===-1?e:e.slice(0,t)).replace(/\r$/,``).trimStart();if(!n.startsWith(`// @options:`))return{code:e,options:{}};let r=t===-1?``:e.slice(t);if(r.trim()===``)throw new P(`The @options line must be followed by JavaScript source on subsequent lines`);return{code:r,options:ue(n.slice(12).trim())}}function F(e){return String(e||``).toLowerCase().match(/[\p{L}\p{N}]+/gu)||[]}function fe(e){try{return JSON.stringify(e||{}).toLowerCase()}catch{return``}}function pe(e,t,n){let r=e.name.toLowerCase(),i=String(e.label||``).toLowerCase(),a=n?.(e),o=String(e._mcpServer||a?.name||``).toLowerCase(),s=String([e.description,a?.description].filter(Boolean).join(` `)).toLowerCase(),c=F(`${r} ${i}`);return{tool:e,index:t,name:r,label:i,server:o,namespace:a?.name,description:s,schema:fe(e.parameters),namePhrase:c.join(` `),nameTerms:new Set(c),serverTerms:new Set(F(o))}}function me(e,t,n,r){let i=0;(e.name===t||e.label===t)&&(i+=100),n&&e.namePhrase.includes(n)&&(i+=24);for(let t of r)e.nameTerms.has(t)?i+=14:(e.name.includes(t)||e.label.includes(t))&&(i+=9),e.serverTerms.has(t)?i+=7:e.server.includes(t)&&(i+=4),e.description.includes(t)&&(i+=3),e.schema.includes(t)&&(i+=1);return i}function he(e,{getNamespace:t}={}){return e.map((e,n)=>pe(e,n,t))}function ge(e,{max:t=10}={}){return Number.isInteger(e)?Math.max(1,Math.min(e,t)):5}function _e(e,t,n,{namespace:r,maxLimit:i}={}){let a=String(t||``).trim().toLowerCase(),o=F(a);if(o.length===0)return[];let s=o.join(` `);return e.filter(e=>!r||e.namespace===r).map(e=>({entry:e,score:me(e,a,s,o)})).filter(({score:e})=>e>0).sort((e,t)=>t.score-e.score||e.entry.index-t.entry.index).slice(0,ge(n,{max:i})).map(({entry:e})=>e.tool)}const I=new Set([`chat`,`image`,`classifier`]),L=e=>typeof e==`object`&&!!e&&!Array.isArray(e),ve=(e,t)=>e.length>t?`${e.slice(0,t-3)}...`:e,R=e=>`${/^[aeiou]/.test(e)?`an`:`a`} ${e}`;function ye(e){return{read:async t=>{let n=await e(t);return n?{type:`api_key`,key:n}:void 0},list:async()=>[],modify:async()=>void 0,delete:async()=>{}}}function be({getApiKey:e}){let t;return async()=>{if(!t){let{builtinModels:n}=await import(`@earendil-works/pi-ai/providers/all`);t=n({credentials:ye(e)})}return t}}function xe({classifiers:e,images:t}={}){let n=async(n,r)=>{let i=n===`classifier`?e?(await e()).getModelsOfType(`classifier`):[]:n===`image`?t?.list()??[]:[];return r?i.filter(e=>e.provider===r):i};return{getModelsOfType:n,getAvailableOfType:async(t,r,i)=>t===`classifier`&&e?(await e()).getAvailableOfType(`classifier`,r,i):n(t,r),getModelOfType:async(e,t,r)=>(await n(e,t)).find(e=>e.id===r),classify:async(t,n,r)=>(await e()).classify(t,n,r),generateImages:(e,n,r)=>t.generateImages(e,n,r)}}function z(e){if(typeof e==`string`&&I.has(e))return e;throw Error(`Unknown model type ${JSON.stringify(e)}. Use "chat", "image", or "classifier".`)}function Se(e){if(e!=null){if(typeof e!=`string`)throw Error(`provider must be a string`);return e}}function B(e){let{headers:t,...n}=e;return n}function V(e){if(e==null)return String(e);if(Array.isArray(e))return e.length===0?`an empty array`:`an array`;if(typeof e==`object`){let t=Object.keys(e);return t.length===0?`{}`:`{ ${t.slice(0,6).join(`, `)}${t.length>6?`, ...`:``} }`}return typeof e==`string`?`a string`:`a ${typeof e}`}function Ce(e){let t=e=>Error(`models.classify() ${e}. Expected context: { 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> } } } }.`);if(!L(e))throw t(`expects a context object as its second argument, got ${V(e)}`);if(!L(e.state))throw t(`context.state must be an object, got ${V(e.state)}`);let{questions:n}=e;if(!L(n)||Object.keys(n).length===0)throw t(`context.questions must map question IDs to questions, got ${V(n)}`);let r=e=>e.length>0&&e.every(e=>typeof e==`string`);for(let[e,i]of Object.entries(n)){let n=`context.questions.${e}`;if(!L(i))throw t(`${n} must be a question object, got ${V(i)}`);if(typeof i.instructions!=`string`)throw t(`${n}.instructions must be a string`);let{criteria:a}=i;if(i.type===`choice`){if(!L(a)||!r(Object.values(a)))throw t(`${n} is a "choice" question, so criteria must map each label to its meaning`)}else if(i.type===`score`){if(!Array.isArray(a)||!r(a))throw t(`${n} is a "score" question, so criteria must list the levels as strings, lowest first`)}else if(i.type===`bool`){if(!L(a)||typeof a.true!=`string`||typeof a.false!=`string`)throw t(`${n} is a "bool" question, so criteria must be { true: string, false: string }`)}else throw t(`${n}.type must be "choice", "score", or "bool", got ${JSON.stringify(i.type)}`)}return e}function we(e){let t=e=>Error(`models.generateImages() ${e}. Expected context: { input: [{ type: "text", text: <prompt> }, ...optional { type: "image", data: <base64>, mimeType } references] }.`);if(!L(e))throw t(`expects a context object as its second argument, got ${V(e)}`);let{input:n}=e;if(!Array.isArray(n)||n.length===0)throw t(`context.input must be a non-empty array of blocks, got ${V(n)}`);return n.forEach((e,n)=>{if(!(L(e)&&e.type===`text`&&typeof e.text==`string`)&&!(L(e)&&e.type===`image`&&typeof e.data==`string`&&typeof e.mimeType==`string`))throw t(`context.input[${n}] must be a text or image block, got ${V(e)}`)}),e}function Te(e){let t=0,n=[];return async r=>{t>=e?await new Promise(e=>n.push(e)):t+=1;try{return await r()}finally{let e=n.shift();e?e():--t}}}function Ee(e,{toolCallId:t,track:n,publish:r,addUsage:i,addGeneratedImages:a}){let o=Te(4),s=0,c=async(a,c,[l,u],d,f)=>{let p=`List the ${c} models you can use with models.getAvailableOfType("${c}").`;if(!L(l)||typeof l.provider!=`string`||typeof l.id!=`string`){let e=l==null?` models.getModelOfType() returns undefined for an unknown provider or id.`:``;throw Error(`${a}() expects ${R(c)} model as its first argument, got ${V(l)}.${e} ${p}`)}let{provider:m,id:h}=l,g=await e.getModelOfType(c,m,h);if(!g){let t;for(let n of I)n!==c&&await e.getModelOfType(n,m,h)&&(t=n);throw Error(t?`"${m}/${h}" is ${R(t)} model, not ${R(c)} model. ${p}`:`Unknown ${c} model "${m}/${h}". ${p}`)}let _=d(u),v=n({id:`${t}/${a}/${++s}`,name:a,args:`${g.provider}/${g.id}`,status:`running`});r();let y=performance.now(),b=await o(()=>f(g,_));return v.durationMs=performance.now()-y,v.status=b.stopReason===`stop`?`ok`:b.stopReason===`aborted`?`cancelled`:`error`,b.errorMessage&&(v.error=ve(b.errorMessage,500)),b.usage&&(v.cost=b.usage.cost?.total,i(b.usage)),r(),b};return Object.entries({"models.getModelsOfType":async([t,n])=>(await e.getModelsOfType(z(t),Se(n))).map(B),"models.getAvailableOfType":async([t,n],{signal:r})=>(await e.getAvailableOfType(z(t),Se(n),{signal:r})).map(B),"models.getModelOfType":async t=>{let[n,r,i]=t;if(typeof r!=`string`||typeof i!=`string`)throw Error(`models.getModelOfType(type, provider, id) expects three strings, got (${t.map(V).join(`, `)}). The provider and the id are separate arguments.`);let a=await e.getModelOfType(z(n),r,i);return a===void 0?void 0:B(a)},"models.classify":(t,{signal:n})=>c(`models.classify`,`classifier`,t,Ce,(t,r)=>e.classify(t,r,{signal:n})),"models.generateImages":(t,{signal:n})=>c(`models.generateImages`,`image`,t,we,async(t,r)=>{let i=await e.generateImages(t,r,{signal:n});return a(i.output.filter(e=>e.type===`image`).length),i})}).map(([e,t])=>({name:e,spread:!0,execute:t}))}const De=256*1024*1024,Oe=5*6e4,ke=30*6e4,Ae=(e,t)=>e.length>t?`${e.slice(0,t-3)}...`:e;function je(e){if(e===void 0)return``;try{return Ae(JSON.stringify(e)??``,200)}catch{return``}}const Me=e=>(e?.content??[]).filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
102
|
+
`),Ne=e=>typeof e==`string`?e:JSON.stringify(e)??String(e);function Pe(e,t){if(!e)return structuredClone(t);for(let n of[`input`,`output`,`cacheRead`,`cacheWrite`,`totalTokens`])e[n]=(e[n]??0)+(t[n]??0);if(t.cost){e.cost??={};for(let[n,r]of Object.entries(t.cost))e.cost[n]=(e.cost[n]??0)+(r??0)}return e}function Fe(e){return e.length===0?`No tool calls were made.`:`Tool calls made before the failure (they are not undone): ${e.map(e=>`${e.name} (${e.status})`).join(`, `)}`}function Ie(e,t){return`${e.kind===`script`?e.stack??`${e.name??`Error`}: ${e.message}`:e.kind===`timeout`?`Script timed out: ${e.message}`:e.kind===`aborted`?`Script aborted: ${e.message}`:`Script sandbox failed: ${e.message}`}\n\n${Fe(t)}`}function Le(e,t){let n=Math.floor(t/2),r=t-n,i=e.length-n-r;return`${e.slice(0,n)}…${Math.ceil(i/4)} tokens truncated…${r>0?e.slice(-r):``}`}function Re(e,t){let n=Array.from({length:e.length}),r=e.map((e,t)=>({length:e,index:t})).sort((e,t)=>e.length-t.length),i=t;return r.forEach(({length:e,index:t},a)=>{n[t]=Math.min(e,Math.floor(i/(r.length-a))),i-=n[t]}),n}async function ze(e,t,n){let r=e.filter(e=>e.type===`text`).map(e=>e.text),i=r.join(`
|
|
103
|
+
`),a=t*4;if(r.length===0||i.length<=a)return{items:e};let o=Re(r.map(e=>e.length),a),s=r.every((e,t)=>e.length<=o[t]||o[t]>=400)?r.map((e,t)=>e.length>o[t]?Le(e,o[t]):e).join(`
|
|
104
|
+
`):Le(i,a),c=`Warning: truncated output (original token count: ${Math.ceil(i.length/4)})\nTotal output lines: ${i.split(`
|
|
105
|
+
`).length}\n\n${s}`,l;if(n)try{l=await n(i),l&&(c+=`\n\n[Full output: ${l} (read with offset/limit)]`)}catch(e){c+=`\n\n[Could not save the full output: ${e?.message||e}]`}return{items:[{type:`text`,text:c},...e.filter(e=>e.type===`image`)],...l?{fullOutputPath:l}:{}}}function Be(e,t){let{result:n}=t;if(e.outputSchema&&n.structuredContent!==void 0)return n.structuredContent;let r=Me(n);if(t.isError)throw Error(r||`Tool "${e.name}" failed`);return r}function Ve(e,t){let n=a(e),r=a(t),i=e=>e.includes(`__`)?e.slice(e.lastIndexOf(`__`)+2):void 0;return e===t||n===r||i(e)===t||i(n)===r}function He(e,t,n){let r=he(e,{getNamespace:n}),i=e=>({name:a(e.name),description:t.get(e.name)??``}),o=t=>e.map(n).find(e=>e&&Ve(e.name,t));return[{name:`searchTools`,spread:!0,execute:([e,t])=>{if(typeof e!=`string`)throw Error(`searchTools() expects a query string`);let n=t?.limit??8;if(typeof n!=`number`||!Number.isInteger(n)||n<=0)throw Error(`searchTools() limit must be a positive integer`);let a=t?.namespace;if(a!=null&&typeof a!=`string`)throw Error(`searchTools() namespace must be a string`);let s=a?o(a):void 0;return a&&!s?[]:_e(r,e,n,{namespace:s?.name,maxLimit:Math.max(n,8)}).map(i)}},{name:`describeTool`,spread:!0,execute:([n])=>{if(typeof n!=`string`)throw Error(`describeTool() expects a tool name`);let r=e.find(e=>e.name===n||a(e.name)===n);return r?t.get(r.name):void 0}},{name:`describeNamespace`,spread:!0,execute:([t])=>{if(typeof t!=`string`)throw Error(`describeNamespace() expects a namespace name`);let r=o(t);if(r)return{name:r.name,...r.description?{description:r.description}:{},...r.instructions?{instructions:r.instructions}:{},tools:e.filter(e=>n(e)?.name===r.name).map(e=>a(e.name))}}}]}async function Ue({toolCallId:e,code:t,signal:n,onUpdate:r,tools:i,executeTool:a,store:o={},models:s,getNamespace:l=()=>void 0,sandbox:u={},spillOutput:d}){let f=performance.now(),p;try{p=de(t)}catch(e){if(!(e instanceof P))throw e;return{content:[{type:`text`,text:`Script failed\nScript error:\n${e.message}`}],details:{calls:[]},isError:!0}}let{code:m,options:h}=p,g=[],_=0,v,y=0,b=()=>g.slice(-200).map(e=>({...e})),x=()=>r?.({content:[],details:{calls:b()}}),S=e=>(g.push(e),e),C=new Map(i.map(e=>[e.name,c(ee(e))])),w=i.map(t=>({name:t.name,description:C.get(t.name),execute:async(n,{signal:r})=>{let i=S({id:`${e}/${++_}`,name:t.name,args:je(n),status:`running`});x();let o=performance.now(),s=await a(t,n,{id:i.id,parentToolCallId:e,signal:r});return i.durationMs=performance.now()-o,s.isError?(i.status=r.aborted?`cancelled`:`error`,i.error=Ae(Me(s.result)||`Tool "${t.name}" failed`,500)):i.status=`ok`,x(),Be(t,s)}})),T=Math.min(h.timeoutMs??u.defaultTimeoutMs??1/0,u.maxTimeoutMs??1/0),E=new oe({tools:w,globals:[...He(i,C,l),...s?Ee(s,{toolCallId:e,track:S,publish:x,addUsage:e=>{v=Pe(v,e)},addGeneratedImages:e=>{y+=e}}):[]],timeoutMs:T,memoryLimitBytes:u.memoryLimitBytes??268435456,...u.wasmPath?{wasm:te(u.wasmPath)}:{},...u.workerUrl?{workerUrl:u.workerUrl}:{}}),ne=u.limit??(e=>e()),D;try{D=await ne(()=>E.execute(m,{signal:n,store:o}))}finally{await E.close()}for(let e of g)e.status===`running`&&(e.status=`cancelled`);let O=D.output.map(e=>e.type===`text`?{type:`text`,text:e.text}:e);D.ok?D.value!==void 0&&O.push({type:`text`,text:Ne(D.value)}):O.push({type:`text`,text:`Script error:\n${Ie(D.error,g)}`}),y>0&&!O.some(e=>e.type===`image`)&&O.push({type:`text`,text:`Note: models.generateImages() returned ${y} image${y===1?``:`s`} that the script did not show. Show each image block of result.output with image(block).`});let k=await ze(O,h.maxOutputTokens??1e4,d),A=((performance.now()-f)/1e3).toFixed(1),j=`${D.ok?`Script completed`:`Script failed`}\nWall time ${A} seconds\nOutput:\n`,M=D.ok?D.storeWrites:null,re=M&&(Object.keys(M.set).length>0||M.delete.length>0);return{content:[{type:`text`,text:j},...k.items],details:{calls:b(),...g.length>200?{omittedCalls:g.length-200}:{},...re?{storeWrites:M}:{},...k.fullOutputPath?{fullOutputPath:k.fullOutputPath}:{}},...v?{usage:v}:{},...D.ok?{}:{isError:!0}}}const H=`codemode`,U=`codemodeStore`,W=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function We(e,t){if(!(!W(t)||!W(t.set)||!Array.isArray(t.delete))){for(let n of t.delete)delete e[n];Object.assign(e,t.set)}}function Ge(e){let t=Object.create(null);for(let n of Array.isArray(e)?e:[]){if(W(n?.codemodeStore)){for(let e of Object.keys(t))delete t[e];Object.assign(t,n[U])}n?.role===`toolResult`&&n.toolName===`codemode`&&We(t,n.details?.storeWrites)}return t}function Ke(e,t){let n=Ge(t);Object.keys(n).length>0&&(e[U]=n)}var qe=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function G(e){}function Je(e){if(typeof e==`function`)throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=G,onError:n=G,onRetry:r=G,onComment:i}=e,a=``,o=!0,s,c=``,l=``;function u(e){let t=o?e.replace(/^\xEF\xBB\xBF/,``):e,[n,r]=Ye(`${a}${t}`);for(let e of n)d(e);a=r,o=!1}function d(e){if(e===``){p();return}if(e.startsWith(`:`)){i&&i(e.slice(e.startsWith(`: `)?2:1));return}let t=e.indexOf(`:`);if(t!==-1){let n=e.slice(0,t),r=e[t+1]===` `?2:1;f(n,e.slice(t+r),e);return}f(e,``,e)}function f(e,t,i){switch(e){case`event`:l=t;break;case`data`:c=`${c}${t}
|
|
106
|
+
`;break;case`id`:s=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new qe(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new qe(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}));break}}function p(){c.length>0&&t({id:s,event:l||void 0,data:c.endsWith(`
|
|
107
|
+
`)?c.slice(0,-1):c}),s=void 0,c=``,l=``}function m(e={}){a&&e.consume&&d(a),o=!0,s=void 0,c=``,l=``,a=``}return{feed:u,reset:m}}function Ye(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e.indexOf(`\r`,r),a=e.indexOf(`
|
|
108
|
+
`,r),o=-1;if(i!==-1&&a!==-1?o=Math.min(i,a):i===-1?a!==-1&&(o=a):o=i===e.length-1?-1:i,o===-1){n=e.slice(r);break}else{let n=e.slice(r,o);t.push(n),r=o+1,e[r-1]===`\r`&&e[r]===`
|
|
109
|
+
`&&r++}}return[t,n]}const K=`ctor-images`,q=2e3;async function J(e,t,n){let r=await e(t,n),i=await r.text();if(!r.ok)throw Error(`HTTP ${r.status}: ${i.slice(0,q)}`);try{return JSON.parse(i)}catch{throw Error(`Provider returned invalid JSON: ${i.slice(0,q)}`)}}function Y(e){return{prompt:e.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
110
|
+
`),images:e.filter(e=>e.type===`image`)}}const X=(e,t,n)=>{let r=e[t];if(!r)throw Error(n);return r};function Xe(e){let{prompt:t,images:n}=Y(e);return{contents:[{role:`user`,parts:[{text:t},...n.map(e=>({inlineData:{mimeType:e.mimeType,data:e.data}}))]}],generationConfig:{responseModalities:[`TEXT`,`IMAGE`]}}}function Ze(e){let t=e?.candidates?.[0]?.content?.parts||e?.parts||[],n=[];for(let e of t){e?.text&&n.push({type:`text`,text:e.text});let t=e?.inlineData||e?.inline_data;t?.data&&n.push({type:`image`,data:t.data,mimeType:t.mimeType||t.mime_type||`image/png`})}return n}function Qe(e,t,n){let r=encodeURIComponent(t);if(e===`bricks`){let e=X(n,`BRICKS_AI_GATEWAY_URL`,`BRICKS image generation needs a signed-in BRICKS account.`),t;try{t=JSON.parse(n.BRICKS_AI_GATEWAY_HEADERS||`{}`)}catch{throw Error(`BRICKS_AI_GATEWAY_HEADERS must be a JSON object of request headers.`)}return{url:`${e.replace(/\/+$/,``)}/v1/gemini/models/${r}:generateContent`,headers:t}}if(e===`google`){let e=n.GEMINI_API_KEY||n.GOOGLE_API_KEY;if(!e)throw Error(`Google image generation needs a Gemini API key.`);return{url:`https://generativelanguage.googleapis.com/v1beta/models/${r}:generateContent?key=${encodeURIComponent(e)}`,headers:{}}}let i=X(n,`GOOGLE_CLOUD_PROJECT`,`Vertex AI image generation needs a Google Cloud project.`),a=n.GOOGLE_CLOUD_LOCATION||`global`,o=a===`global`?`aiplatform.googleapis.com`:`${a}-aiplatform.googleapis.com`,s=n.GOOGLE_VERTEX_API_KEY?{"x-goog-api-key":n.GOOGLE_VERTEX_API_KEY}:n.GOOGLE_VERTEX_ACCESS_TOKEN?{Authorization:`Bearer ${n.GOOGLE_VERTEX_ACCESS_TOKEN}`}:null;if(!s)throw Error(`Vertex AI image generation needs an API key or an access token.`);return{url:`https://${o}/v1/projects/${encodeURIComponent(i)}/locations/${encodeURIComponent(a)}/publishers/google/models/${r}:generateContent`,headers:s}}async function Z(e,t,n,r,{fetch:i,signal:a}){let{url:o,headers:s}=Qe(e,t,r);return Ze(await J(i,o,{method:`POST`,headers:{...s,"Content-Type":`application/json`},body:JSON.stringify(Xe(n)),signal:a}))}async function Q(e,t,n){let r=[];for(let i of Array.isArray(t?.data)?t.data:[])if(i?.b64_json)r.push({type:`image`,data:i.b64_json,mimeType:`image/png`});else if(i?.url){let t=await e(i.url,{signal:n});if(!t.ok)throw Error(`Failed to download image URL: HTTP ${t.status}`);let a=t.headers.get(`content-type`)||`image/png`;r.push({type:`image`,data:Buffer.from(await t.arrayBuffer()).toString(`base64`),mimeType:a})}return r}async function $e(e,t,n,{fetch:r,signal:i}){let a=X(n,`OPENAI_API_KEY`,`OpenAI image generation needs an API key.`),o=(n.OPENAI_BASE_URL||`https://api.openai.com/v1`).replace(/\/$/,``),{prompt:s,images:c}=Y(t),l={model:e,prompt:s,n:1,size:`auto`,quality:`medium`,output_format:`png`};if(c.length===0)return Q(r,await J(r,`${o}/images/generations`,{method:`POST`,headers:{Authorization:`Bearer ${a}`,"Content-Type":`application/json`},body:JSON.stringify(l),signal:i}),i);let u=new FormData;for(let[e,t]of Object.entries(l))u.append(e,String(t));return c.forEach((e,t)=>{let n=e.mimeType.split(`/`)[1]||`png`;u.append(c.length>1?`image[]`:`image`,new Blob([Buffer.from(e.data,`base64`)],{type:e.mimeType}),`reference-${t+1}.${n}`)}),Q(r,await J(r,`${o}/images/edits`,{method:`POST`,headers:{Authorization:`Bearer ${a}`},body:u,signal:i}),i)}function et(e){let t=(e.OPENAI_CODEX_BASE_URL||`https://chatgpt.com/backend-api`).replace(/\/+$/,``);return t.endsWith(`/codex/responses`)?t:t.endsWith(`/codex`)?`${t}/responses`:`${t}/codex/responses`}function tt(e){try{let t=JSON.parse(Buffer.from(e.split(`.`)[1]||``,`base64url`).toString(`utf8`))?.[`https://api.openai.com/auth`]?.chatgpt_account_id;if(typeof t==`string`&&t)return t}catch{}throw Error(`The OpenAI Codex token does not include a ChatGPT account ID.`)}async function*nt(e){if(!e.body)return;let t=e.body.getReader(),n=new TextDecoder,r=[],i=Je({onEvent:({data:e})=>r.push(e)}),a=!1;try{for(;;){let{done:e,value:o}=await t.read(),s=n.decode(o,{stream:!e});i.feed(s),s&&(a=s.endsWith(`\r`)),e&&a&&i.feed(`
|
|
111
|
+
`);for(let e of r)if(e&&e!==`[DONE]`)try{yield JSON.parse(e)}catch{}if(r.length=0,e)break}}finally{await t.cancel().catch(()=>{}),t.releaseLock()}}async function rt(e,t,n,{fetch:r,signal:i}){let a=X(n,`OPENAI_CODEX_ACCESS_TOKEN`,`OpenAI Codex image generation needs a ChatGPT sign-in.`),{prompt:o,images:s}=Y(t),c=await r(et(n),{method:`POST`,headers:{Authorization:`Bearer ${a}`,"chatgpt-account-id":tt(a),originator:`pi`,"OpenAI-Beta":`responses=experimental`,Accept:`text/event-stream`,"Content-Type":`application/json`},body:JSON.stringify({model:e,store:!1,stream:!0,instructions:[`You are an image generation agent.`,`Use the image_generation tool for the user request.`,`Do not finish with text only when an image can be generated.`,s.length>0?`Use the attached image(s) as visual input and create one edited image.`:`Create one image.`].join(` `),input:[{role:`user`,content:[{type:`input_text`,text:o},...s.map(e=>({type:`input_image`,detail:`auto`,image_url:`data:${e.mimeType};base64,${e.data}`}))]}],tools:[{type:`image_generation`,output_format:`png`}],tool_choice:`auto`,parallel_tool_calls:!1,text:{verbosity:`low`}}),signal:i});if(!c.ok)throw Error(`HTTP ${c.status}: ${(await c.text()).slice(0,q)}`);let l=[];for await(let e of nt(c)){if(e?.type===`error`)throw Error(e.message||e.code||`Codex error`);if(e?.type===`response.failed`)throw Error(e.response?.error?.message||`OpenAI Codex response failed.`);let t=e?.item;if(t?.type===`message`)for(let e of Array.isArray(t.content)?t.content:[]){let t=e?.text||e?.content?.[0]?.text;typeof t==`string`&&t.trim()&&l.push({type:`text`,text:t})}t?.type===`image_generation_call`&&t.result&&l.push({type:`image`,data:t.result,mimeType:`image/png`})}return l}const it={bricks:(e,t,n,r)=>Z(`bricks`,e,t,n,r),google:(e,t,n,r)=>Z(`google`,e,t,n,r),"google-vertex":(e,t,n,r)=>Z(`google-vertex`,e,t,n,r),openai:$e,"openai-codex":rt};function at({listProviders:e,resolveEnv:t,fetch:n=globalThis.fetch}){return{list:()=>e().filter(({provider:e})=>it[e]).map(({provider:e,defaultModel:t})=>({type:`image`,provider:e,id:t,name:t,api:K,input:[`text`,`image`],output:[`text`,`image`]})),generateImages:async(e,r,{signal:i}={})=>{let a={api:K,provider:e.provider,model:e.id};try{let o=await t(e.provider),s=await it[e.provider](e.id,r.input,o,{fetch:n,signal:i}),c=s.some(e=>e.type===`image`);return{...a,output:s,stopReason:c?`stop`:`error`,...c?{}:{errorMessage:`The model returned no image.`},timestamp:Date.now()}}catch(e){return{...a,output:[],stopReason:i?.aborted?`aborted`:`error`,errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()}}}}}const ot={type:`object`,properties:{code:{type:`string`,description:`Raw JavaScript source.`}},required:[`code`],additionalProperties:!1};function st(e){if(!e?._mcpNamespace)return;let t=e._mcpServerInstructions?.trim();return{name:e._mcpNamespace,description:e._mcpServerDescription??t?.split(`
|
|
112
|
+
`)[0],...t?{instructions:t}:{}}}const $=e=>!!e?._mcpServer&&e._mcpExposure!==`direct`;function ct(e,t,{id:n,parentToolCallId:i,signal:a,hooks:o,state:s}){let c={type:`toolCall`,id:n,name:e.name,arguments:t,parentToolCallId:i},l=s?.messages??[],u=[...l].reverse().find(e=>e.role===`assistant`);return r(c,{tools:[e],assistantMessage:u??{role:`assistant`,content:[c]},context:{systemPrompt:s?.systemPrompt??``,messages:l,tools:s?.tools??[e]},beforeToolCall:o?.beforeToolCall,afterToolCall:o?.afterToolCall,signal:a})}function lt(e){return{...e,execute:(t,n,r,i)=>e.execute(t,n,r,i&&(e=>i(e.details)))}}function ut({getTools:e,declaredNames:t,isDeferred:n=$,getNamespace:r=st,executeTool:i,getStore:a=()=>({}),models:o,sandbox:s,spillOutput:c,inlineBudget:l}){let u=()=>e().filter(e=>e.name!==H);return{name:H,label:`Codemode`,description:T({tools:u(),declaredNames:t,isDeferred:n,getNamespace:r,models:!!o,inlineBudget:l}),parameters:ot,execute:(e,t,n,l)=>Ue({toolCallId:e,code:t?.code??``,signal:n,onUpdate:l,tools:u(),executeTool:i,store:a(),models:o,getNamespace:r,sandbox:s,spillOutput:c})}}export{ot as CODEMODE_PARAMETERS,U as CODEMODE_STORE_SNAPSHOT_KEY,H as CODEMODE_TOOL_NAME,K as CTOR_IMAGE_API,b as DEFAULT_CODEMODE_INLINE_BUDGET,De as DEFAULT_CODEMODE_MEMORY_LIMIT_BYTES,Oe as DEFAULT_CODEMODE_TIMEOUT_MS,ke as MAX_CODEMODE_TIMEOUT_MS,Ke as annotateCodemodeStore,Ge as collectCodemodeStore,be as createClassifierModels,T as createCodemodeDescription,xe as createCodemodeModels,ut as createCodemodeTool,at as createImageModels,Te as createLimiter,Ue as executeCodemode,$ as isSearchOnlyMcpTool,st as mcpToolNamespace,ct as runNestedToolCall,lt as withDetailsUpdates};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{r as e,t}from"./protocol-WkPByalT.mjs";import{parentPort as n,workerData as r}from"node:worker_threads";function i(e){return{clock_time_get(t,n,r){let i=e(),a=new DataView(i.buffer);if(t===0||t===1){let e=BigInt(Date.now())*1000000n;return a.setBigUint64(r,e,!0),0}return 52},fd_write(t,n,r,i){let a=e(),o=new DataView(a.buffer),s=new Uint8Array(a.buffer),c=0;if(t!==1&&t!==2)return 8;for(let e=0;e<r;e++){let r=o.getUint32(n+e*8,!0),i=o.getUint32(n+e*8+4,!0),a=s.slice(r,r+i),l=new TextDecoder().decode(a);t===1?typeof process<`u`&&process.stdout?process.stdout.write(l):console.log(l):typeof process<`u`&&process.stderr?process.stderr.write(l):console.error(l),c+=i}return o.setUint32(i,c,!0),0},fd_close(e){return 52},fd_fdstat_get(t,n){let r=e(),i=new DataView(r.buffer);return t===1||t===2?(i.setUint8(n,2),i.setUint16(n+2,0,!0),i.setBigUint64(n+8,0n,!0),i.setBigUint64(n+16,0n,!0),0):8},fd_seek(e,t,n,r){return 52},random_get(t,n){let r=e(),i=new Uint8Array(r.buffer,t,n);if(typeof crypto<`u`&&crypto.getRandomValues)crypto.getRandomValues(i);else for(let e=0;e<n;e++)i[e]=Math.floor(Math.random()*256);return 0}}}const a=new TextDecoder;function o(e,t){let n=new Uint8Array(e.buffer),r=t;for(;n[r]!==0;)r++;if(r===t)return{};let i=a.decode(n.slice(t,r)),o={};for(let e of i.split(`
|
|
3
|
+
`)){let t=e.indexOf(`=`);t>0&&(o[e.slice(0,t)]=e.slice(t+1))}return o}function s(e,t){let n=`qjs_ext_${e.name.replace(/-/g,`_`)}_versions`,r=e.instance.exports[n];if(typeof r!=`function`)return;let i=r();if(i!==0)return o(t,i)}function c(e,t){let n=0,r=0;for(;t.value<e.length;){let i=e[t.value++];if(n|=(i&127)<<r,!(i&128))break;r+=7}return n}function l(e){let t=WebAssembly.Module.customSections(e,`dylink.0`);if(t.length===0)return null;let n=new Uint8Array(t[0]),r={value:0},i={memorySize:0,memoryAlignment:0,tableSize:0,tableAlignment:0,needed:[]};for(;r.value<n.length;){let e=c(n,r),t=c(n,r),a=r.value+t;if(e===1)i.memorySize=c(n,r),i.memoryAlignment=c(n,r),i.tableSize=c(n,r),i.tableAlignment=c(n,r);else if(e===2){let e=c(n,r);for(let t=0;t<e;t++){let e=c(n,r),t=new TextDecoder().decode(n.slice(r.value,r.value+e));r.value+=e,i.needed.push(t)}}r.value=a}return i}async function u(e,t,n,r,i,a){let o;o=e.wasm instanceof WebAssembly.Module?e.wasm:await WebAssembly.compile(e.wasm);let c=l(o);if(!c)throw Error(`Extension "${e.name}" is not a WASM shared library (missing dylink.0 section)`);let u=t.memory,d=t.__indirect_function_table,f=t.__stack_pointer,p=t.malloc;if(!u)throw Error(`Main module does not export memory`);if(!d)throw Error(`Main module does not export __indirect_function_table`);if(!p)throw Error(`Main module does not export malloc`);let m,h;if(a)m=a.memoryBase,h=a.tableBase;else if(c.memorySize>0){if(m=p(c.memorySize),m===0)throw Error(`Failed to allocate ${c.memorySize} bytes for extension "${e.name}"`);new Uint8Array(u.buffer,m,c.memorySize).fill(0)}else m=0;a?(h=a.tableBase,h+c.tableSize>d.length&&d.grow(h+c.tableSize-d.length)):(h=d.length,c.tableSize>0&&d.grow(c.tableSize));let g=WebAssembly.Module.imports(o),_={env:{},"GOT.mem":{},"GOT.func":{}};if(g.some(e=>e.module===`wasi_snapshot_preview1`)){let t=e.wasi&&i?e.wasi(i):void 0;_.wasi_snapshot_preview1={...n,...t,...r}}let v=new Set(WebAssembly.Module.exports(o).filter(e=>e.kind===`function`).map(e=>e.name)),y=new Set;for(let n of g)if(n.module===`env`){if(n.name===`memory`&&n.kind===`memory`)_.env.memory=u;else if(n.name===`__indirect_function_table`&&n.kind===`table`)_.env.__indirect_function_table=d;else if(n.name===`__memory_base`&&n.kind===`global`)_.env.__memory_base=new WebAssembly.Global({value:`i32`,mutable:!1},m);else if(n.name===`__table_base`&&n.kind===`global`)_.env.__table_base=new WebAssembly.Global({value:`i32`,mutable:!1},h);else if(n.name===`__stack_pointer`&&n.kind===`global`)_.env.__stack_pointer=f;else if(n.kind===`function`){let r=t[n.name];r&&typeof r==`function`?_.env[n.name]=r:(y.add(n.name),_.env[n.name]=()=>{throw Error(`Extension "${e.name}" called unresolved symbol: env.${n.name}`)})}else if(n.kind===`global`){let e=t[n.name];e instanceof WebAssembly.Global?_.env[n.name]=e:_.env[n.name]=new WebAssembly.Global({value:`i32`,mutable:!0},0)}}else if(n.module===`GOT.mem`&&n.kind===`global`)_[`GOT.mem`][n.name]=new WebAssembly.Global({value:`i32`,mutable:!0},0);else if(n.module===`GOT.func`&&n.kind===`global`){let e=t[n.name];if(e&&typeof e==`function`){let t=d.length;d.grow(1),d.set(t,e),_[`GOT.func`][n.name]=new WebAssembly.Global({value:`i32`,mutable:!0},t)}else _[`GOT.func`][n.name]=new WebAssembly.Global({value:`i32`,mutable:!0},0)}let b=[...y].filter(e=>v.has(e)),x={};for(let t of b){let n={target:null};x[t]=n,_.env[t]=(...r)=>{if(!n.target)throw Error(`Extension "${e.name}" called unresolved symbol during init: env.${t}`);return n.target(...r)}}let S=await WebAssembly.instantiate(o,_),C=S.exports;for(let e of b){let t=C[e];typeof t==`function`&&(x[e].target=t)}typeof C.__wasm_apply_data_relocs==`function`&&C.__wasm_apply_data_relocs(),typeof C.__wasm_call_ctors==`function`&&C.__wasm_call_ctors();let w=e.initFn??`qjs_ext_${e.name.replace(/-/g,`_`)}_init`,T={name:e.name,module:o,instance:S,dylink:c,memoryBase:m,tableBase:h,initFn:w};return T.versions=s(T,u),T}function d(e,t){let n=e.instance.exports[e.initFn];if(typeof n!=`function`)throw Error(`Extension "${e.name}" does not export init function "${e.initFn}"`);let r=n(t.qjs_get_context_ptr(),t.qjs_get_runtime_ptr());if(r!==0)throw Error(`Extension "${e.name}" init function returned error code ${r}`)}async function f(e,t,n,r,i,a){let o=[];for(let s of t){let t=e.find(e=>e.name===s.name);if(!t)throw Error(`Extension "${s.name}" required by snapshot but not provided`);let c=await u(t,n,r,i,a,{memoryBase:s.memoryBase,tableBase:s.tableBase});c.initFn=s.initFn,o.push(c)}return o}var p=function(e,t,n){if(t!=null){if(typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Object expected.`);var r,i;if(n){if(!Symbol.asyncDispose)throw TypeError(`Symbol.asyncDispose is not defined.`);r=t[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw TypeError(`Symbol.dispose is not defined.`);r=t[Symbol.dispose],n&&(i=r)}if(typeof r!=`function`)throw TypeError(`Object not disposable.`);i&&(r=function(){try{i.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:n})}else n&&e.stack.push({async:!0});return t},m=(function(e){return function(t){function n(n){t.error=t.hasError?new e(n,t.error,`An error was suppressed during disposal.`):n,t.hasError=!0}var r,i=0;function a(){for(;r=t.stack.pop();)try{if(!r.async&&i===1)return i=0,t.stack.push(r),Promise.resolve().then(a);if(r.dispose){var e=r.dispose.call(r.value);if(r.async)return i|=2,Promise.resolve(e).then(a,function(e){return n(e),a()})}else i|=1}catch(e){n(e)}if(i===1)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}return a()}})(typeof SuppressedError==`function`?SuppressedError:function(e,t,n){var r=Error(n);return r.name=`SuppressedError`,r.error=e,r.suppressed=t,r});const h=512*1024,g=1363825491;var _=class e{exports;module;instance;encoder=new TextEncoder;decoder=new TextDecoder;disposed=!1;hostCallbacks=new Map;nextInternalId=1;interruptHandler=null;unhandledRejectionHandler=null;moduleNormalizeHandler=null;moduleLoadHandler=null;timezoneOffsetHandler=null;_global=null;_versions=null;_undefined=null;_null=null;_true=null;_false=null;_ownedHandles=new Set;_activeScope=null;loadedExtensions=[];constructor(e){this.module=e,this.instance=null,this.exports=null}setInstance(e){this.instance=e,this.exports=e.exports}get versions(){if(this.assertNotDisposed(),!this._versions){let e={"quickjs-wasi":`3.6.2`,quickjs:this.readCString(this.exports.qjs_get_quickjs_version())};for(let t of this.loadedExtensions)t.versions&&Object.assign(e,t.versions);this._versions=e}return this._versions}get global(){return this._global||=new T(this,this.exports.qjs_get_global(),!0),this._global}get undefined(){return this._undefined||=new T(this,this.exports.qjs_get_undefined(),!0),this._undefined}get null(){return this._null||=new T(this,this.exports.qjs_get_null(),!0),this._null}get true(){return this._true||=new T(this,this.exports.qjs_get_true(),!0),this._true}get false(){return this._false||=new T(this,this.exports.qjs_get_false(),!0),this._false}static async create(t){let n=e.normalizeOptions(t),r=await e.resolveModule(n.wasm),i=new e(r),{instance:a,wasiBuiltins:o,wasiUserOverrides:s,memoryProxy:c}=await e.instantiate(r,i,n.wasi);if(i.setInstance(a),i.exports._initialize(),(n.intrinsics===void 0?i.exports.qjs_init():i.exports.qjs_init2(n.intrinsics))!==0)throw Error(`Failed to initialize QuickJS runtime`);if(n.extensions){let e=a.exports;for(let t of n.extensions){let n=await u(t,e,o,s,c);i.loadedExtensions.push(n),d(n,e)}}return e.applyLimits(i,n),i}static async restore(t,n){let r=e.normalizeOptions(n),i=await e.resolveModule(r.wasm),a=new e(i),{instance:o,wasiBuiltins:s,wasiUserOverrides:c,memoryProxy:l}=await e.instantiate(i,a,r.wasi);a.setInstance(o);let u=o.exports,d=a.exports.memory,p=d.buffer.byteLength/65536,m=Math.ceil(t.memory.byteLength/65536);return m>p&&d.grow(m-p),t.extensions.length>0&&(a.loadedExtensions=await f(r.extensions??[],t.extensions,u,s,c,l)),new Uint8Array(d.buffer).set(t.memory),a.exports.qjs_set_runtime_and_context(t.runtimePtr,t.contextPtr),a.exports.__stack_pointer.value=t.stackPointer,e.applyLimits(a,r),a}static serializeSnapshot(e){let t=new TextEncoder,n=4,r=[],i=[];for(let a of e.extensions){let e=t.encode(a.name),o=t.encode(a.initFn);r.push(e),i.push(o),n+=4+e.length+4+4+4+o.length}let a=24+n+e.memory.byteLength,o=new ArrayBuffer(a),s=new DataView(o),c=new Uint8Array(o);s.setUint32(0,g,!1),s.setUint8(4,2),s.setUint32(8,e.memory.byteLength,!0),s.setUint32(12,e.stackPointer,!0),s.setUint32(16,e.runtimePtr,!0),s.setUint32(20,e.contextPtr,!0);let l=24;s.setUint32(l,e.extensions.length,!0),l+=4;for(let t=0;t<e.extensions.length;t++){let n=e.extensions[t],a=r[t],o=i[t];s.setUint32(l,a.length,!0),l+=4,c.set(a,l),l+=a.length,s.setUint32(l,n.memoryBase,!0),l+=4,s.setUint32(l,n.tableBase,!0),l+=4,s.setUint32(l,o.length,!0),l+=4,c.set(o,l),l+=o.length}return c.set(e.memory,l),c}static deserializeSnapshot(e){if(e.length<24)throw Error(`Invalid snapshot: too small`);let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t.getUint32(0,!1);if(n!==g)throw Error(`Invalid snapshot: bad magic (expected 0x${g.toString(16)}, got 0x${n.toString(16)})`);let r=t.getUint8(4);if(r!==2&&r!==1)throw Error(`Unsupported snapshot version: ${r} (expected 2)`);let i=t.getUint32(8,!0),a=t.getUint32(12,!0),o=t.getUint32(16,!0),s=t.getUint32(20,!0),c=[],l=24;if(r>=2){let n=t.getUint32(24,!0),r=28,i=new TextDecoder;for(let a=0;a<n;a++){let n=t.getUint32(r,!0);r+=4;let a=i.decode(e.slice(r,r+n));r+=n;let o=t.getUint32(r,!0);r+=4;let s=t.getUint32(r,!0);r+=4;let l=t.getUint32(r,!0);r+=4;let u=i.decode(e.slice(r,r+l));r+=l,c.push({name:a,memoryBase:o,tableBase:s,initFn:u})}l=r}let u=l+i;if(e.length<u)throw Error(`Invalid snapshot: expected ${u} bytes, got ${e.length}`);return{memory:e.slice(l,l+i),stackPointer:a,runtimePtr:o,contextPtr:s,extensions:c}}static normalizeOptions(e){if(!e)return{wasm:void 0};if(e instanceof WebAssembly.Module)return{wasm:e};if(typeof e==`object`&&(`wasm`in e||`wasi`in e||`memoryLimit`in e||`maxStackSize`in e||`interruptHandler`in e||`onUnhandledRejection`in e||`moduleLoader`in e||`intrinsics`in e||`extensions`in e||`timezoneOffset`in e)){let t=e;if(t.maxStackSize!==void 0&&(!Number.isInteger(t.maxStackSize)||t.maxStackSize<0||t.maxStackSize>524288))throw RangeError(`maxStackSize must be an integer between 0 and ${h}`);return t}return{wasm:e}}static applyLimits(e,t){t.memoryLimit!==void 0&&e.exports.qjs_set_memory_limit(t.memoryLimit),t.maxStackSize!==void 0&&e.exports.qjs_set_max_stack_size(t.maxStackSize),t.interruptHandler&&(e.interruptHandler=t.interruptHandler,e.exports.qjs_set_interrupt_handler(1)),t.onUnhandledRejection&&(e.unhandledRejectionHandler=t.onUnhandledRejection,e.exports.qjs_set_promise_rejection_handler(1)),t.moduleLoader&&(e.moduleLoadHandler=t.moduleLoader.load,e.moduleNormalizeHandler=t.moduleLoader.normalize??null,e.exports.qjs_set_module_loader(1));let n=t.timezoneOffset;if(typeof n==`function`)e.timezoneOffsetHandler=e=>-n(e)*60;else if(typeof n==`number`){let t=-n*60;e.timezoneOffsetHandler=()=>t}else e.timezoneOffsetHandler=e=>-new Date(e*1e3).getTimezoneOffset()*60}static async resolveModule(e){if(e instanceof WebAssembly.Module)return e;if(e)return WebAssembly.compile(e);throw TypeError("QuickJS: `wasm` option is required. Provide WASM bytes or a compiled `WebAssembly.Module`. The binary is shipped at `quickjs-wasi/quickjs.wasm` and can be loaded via your environment's preferred mechanism (e.g. `fetch()`, `node:fs/promises`, or a bundler import like Vite's `?url`).")}static async instantiate(e,t,n){let r=null,a=new Proxy({},{get(e,t){return r[t]}}),o=i(()=>r),s=n?n(a):void 0,c={...o,...s},l=(e,n,r,i,a)=>t.handleHostCall(e,n,r,i,a),u=()=>t.interruptHandler?+!!t.interruptHandler():0,d=(e,n,r)=>{if(!t.unhandledRejectionHandler){t.exports.qjs_free_value(e),t.exports.qjs_free_value(n);return}let i=new T(t,e),a=new T(t,n);try{t.unhandledRejectionHandler(i,a,r!==0)}finally{i.dispose(),a.dispose()}},f=e=>{let n=t.newError(e instanceof Error?e:String(e));t.exports.qjs_throw(n.ptr),n.dispose()},p=(e,t)=>{if(typeof e==`string`)return e;let n=typeof e==`object`&&e&&typeof e.then==`function`?`a Promise`:`type ${typeof e}`;throw TypeError(`moduleLoader.${t} must synchronously return a string (got ${n}). Async module loading is not supported. Pre-fetch module sources instead (see the "ES Modules" section of the quickjs-wasi README).`)},m=await WebAssembly.instantiate(e,{env:{host_call:l,host_interrupt:u,host_promise_rejection:d,host_module_normalize:(e,n)=>{if(!t.moduleNormalizeHandler){let e=t.readCString(n);return t.writeString(e).ptr}let r=t.readCString(e),i=t.readCString(n);try{let e=p(t.moduleNormalizeHandler(r,i),`normalize`);return t.writeString(e).ptr}catch(e){return f(e),0}},host_module_load:(e,n)=>{if(!t.moduleLoadHandler)return 0;let r=t.readCString(e);try{let e=p(t.moduleLoadHandler(r),`load`),{ptr:i,len:a}=t.writeString(e);return new Uint32Array(t.exports.memory.buffer,n,1)[0]=a,i}catch(e){return f(e),0}},host_get_timezone_offset:(e,n)=>{let r=Number(BigInt(e)<<32n|BigInt(n>>>0));return t.timezoneOffsetHandler?t.timezoneOffsetHandler(r):0}},wasi_snapshot_preview1:c});return r=m.exports.memory,{instance:m,wasiBuiltins:o,wasiUserOverrides:s,memoryProxy:a}}handleHostCall(e,t,n,r,i){let a=this.decoder.decode(new Uint8Array(this.exports.memory.buffer,e,t)),o=this.hostCallbacks.get(a);if(!o){let e=this.newError(`Host callback "${a}" is not registered: it was unregistered, its ephemeral function handle was disposed, or it was never re-registered after a snapshot restore.`);return this.exports.qjs_throw(e.ptr),e.dispose(),0}let s=new T(this,n,!1,!0),c=[];if(r>0&&i!==0){let e=new DataView(this.exports.memory.buffer);for(let t=0;t<r;t++){let n=e.getUint32(i+t*4,!0);c.push(new T(this,n,!1,!0))}}try{let e=o.call(s,...c);return this.exports.qjs_dup_value(e.ptr)}catch(e){let t=this.newError(e instanceof Error?e:String(e));return this.exports.qjs_throw(t.ptr),t.dispose(),0}}writeString(e){let t=S(e),n=this.exports.wasm_malloc(t.length+1);if(n===0)throw Error(`wasm_malloc failed`);let r=new Uint8Array(this.exports.memory.buffer);return r.set(t,n),r[n+t.length]=0,{ptr:n,len:t.length}}readCString(e){let t=new Uint8Array(this.exports.memory.buffer),n=e;for(;t[n]!==0;)n++;return this.decoder.decode(t.slice(e,n))}throwIfException(e){if(this.exports.qjs_is_exception(e.ptr)!==0){let t=this.getException();throw e.dispose(),this._ownedHandles.add(t),new w(t)}return e}evalCode(e,t=`<eval>`,n=0){this.assertNotDisposed();let r=this.writeString(e),i=this.writeString(t),a=this.exports.qjs_eval(r.ptr,r.len,i.ptr,n);return this.exports.wasm_free(r.ptr),this.exports.wasm_free(i.ptr),this.throwIfException(new T(this,a))}compile(e,t=`<compile>`,n=0,r=0){this.assertNotDisposed();let i=this.writeString(e),a=this.writeString(t),o=this.exports.wasm_malloc(4),s=this.exports.qjs_compile(i.ptr,i.len,a.ptr,n,r,o);if(this.exports.wasm_free(i.ptr),this.exports.wasm_free(a.ptr),s===0){this.exports.wasm_free(o);let e=this.getException();throw Error(`Compilation error: ${e.toString()}`)}let c=new Uint32Array(this.exports.memory.buffer,o,1)[0];this.exports.wasm_free(o);let l=new Uint8Array(this.exports.memory.buffer,s,c).slice();return this.exports.wasm_free(s),l}evalBytecode(e){this.assertNotDisposed();let t=this.exports.wasm_malloc(e.byteLength);new Uint8Array(this.exports.memory.buffer,t,e.byteLength).set(e);let n=this.exports.qjs_eval_bytecode(t,e.byteLength);return this.exports.wasm_free(t),this.throwIfException(new T(this,n))}executePendingJobs(){this.assertNotDisposed();let e=0;for(;this.exports.qjs_is_job_pending();){if(this.exports.qjs_execute_pending_job()<0){let e=this.getException();throw Error(`Job execution error: ${e.toString()}`)}e++}return e}runGC(){this.assertNotDisposed(),this.exports.qjs_run_gc()}get gcThreshold(){return this.assertNotDisposed(),this.exports.qjs_get_gc_threshold()}set gcThreshold(e){this.assertNotDisposed(),this.exports.qjs_set_gc_threshold(e)}getMemoryUsage(){this.assertNotDisposed();let e=this.exports.wasm_malloc(208);this.exports.qjs_compute_memory_usage(e);let t=new BigInt64Array(this.exports.memory.buffer,e,26),n={mallocSize:Number(t[0]),mallocLimit:Number(t[1]),memoryUsedSize:Number(t[2]),mallocCount:Number(t[3]),memoryUsedCount:Number(t[4]),atomCount:Number(t[5]),atomSize:Number(t[6]),strCount:Number(t[7]),strSize:Number(t[8]),objCount:Number(t[9]),objSize:Number(t[10]),propCount:Number(t[11]),propSize:Number(t[12]),shapeCount:Number(t[13]),shapeSize:Number(t[14]),jsFuncCount:Number(t[15]),jsFuncSize:Number(t[16]),jsFuncCodeSize:Number(t[17]),jsFuncPc2lineCount:Number(t[18]),jsFuncPc2lineSize:Number(t[19]),cFuncCount:Number(t[20]),arrayCount:Number(t[21]),fastArrayCount:Number(t[22]),fastArrayElements:Number(t[23]),binaryObjectCount:Number(t[24]),binaryObjectSize:Number(t[25])};return this.exports.wasm_free(e),n}getGlobal(){return this.assertNotDisposed(),new T(this,this.exports.qjs_get_global())}newString(e){this.assertNotDisposed();let{ptr:t,len:n}=this.writeString(e),r=this.exports.qjs_new_string(t,n);return this.exports.wasm_free(t),new T(this,r)}newNumber(e){return this.assertNotDisposed(),new T(this,this.exports.qjs_new_number(e))}newBigInt(e){this.assertNotDisposed();let t=Number(e&4294967295n),n=Number(e>>32n&4294967295n);return new T(this,this.exports.qjs_new_big_int64(t,n))}newObject(){return this.assertNotDisposed(),new T(this,this.exports.qjs_new_object())}newArray(){return this.assertNotDisposed(),new T(this,this.exports.qjs_new_array())}newSymbolFor(e){this.assertNotDisposed();let{ptr:t,len:n}=this.writeString(e),r=new T(this,this.exports.qjs_new_symbol(t,n,1));return this.exports.wasm_free(t),r}newArrayBuffer(e){this.assertNotDisposed();let t=e instanceof ArrayBuffer?new Uint8Array(e):e,n=this.exports.wasm_malloc(t.length);if(n===0)throw Error(`wasm_malloc failed`);new Uint8Array(this.exports.memory.buffer).set(t,n);let r=new T(this,this.exports.qjs_new_array_buffer(n,t.length));return this.exports.wasm_free(n),r}newUint8Array(e){this.assertNotDisposed();let t=this.exports.wasm_malloc(e.length);if(t===0)throw Error(`wasm_malloc failed`);new Uint8Array(this.exports.memory.buffer).set(e,t);let n=new T(this,this.exports.qjs_new_uint8_array(t,e.length));return this.exports.wasm_free(t),n}getUndefined(){return this.assertNotDisposed(),new T(this,this.exports.qjs_get_undefined())}getNull(){return this.assertNotDisposed(),new T(this,this.exports.qjs_get_null())}getTrue(){return this.assertNotDisposed(),new T(this,this.exports.qjs_get_true())}getFalse(){return this.assertNotDisposed(),new T(this,this.exports.qjs_get_false())}newFunction(e,t){if(this.assertNotDisposed(),this.hostCallbacks.has(e))throw Error(`Host callback with name "${e}" is already registered`);this.hostCallbacks.set(e,t);let{ptr:n,len:r}=this.writeString(e),i=this.exports.qjs_new_host_function(n,r,0);return this.exports.wasm_free(n),new T(this,i)}withScope(e){this.assertNotDisposed();let t=this._activeScope,n=new Set;this._activeScope=n;let r={escape:e=>(n.delete(e),t?.add(e),e)};try{return e(r)}finally{this._activeScope=t;for(let e of n)e.dispose()}}exportHandle(e){if(this.assertNotDisposed(),e.vm!==this)throw Error(`exportHandle: handle belongs to a different VM`);if(e.disposed)throw Error(`exportHandle: handle is disposed`);if(e._isBorrowed)throw Error(`exportHandle: cannot export a borrowed handle (host-callback this/argument); its box is freed when the callback returns. dup() it and export the duplicate.`);return e.ptr}importHandle(e){if(this.assertNotDisposed(),!Number.isInteger(e)||e<=0||e>=this.exports.memory.buffer.byteLength)throw Error(`importHandle: invalid token ${e}`);return new T(this,this.exports.qjs_dup_value(e))}newEphemeralFunction(e){this.assertNotDisposed();let t=`__ephemeral:${this.nextInternalId++}`;this.hostCallbacks.set(t,e);let{ptr:n,len:r}=this.writeString(t),i=this.exports.qjs_new_host_function(n,r,0);this.exports.wasm_free(n);let a=new T(this,i);return a._onDispose=()=>{this.hostCallbacks.delete(t)},a}unregisterHostCallback(e){return this.hostCallbacks.delete(e)}newInternalFunction(e,t){this.hostCallbacks.set(e,t);let{ptr:n,len:r}=this.writeString(e),i=this.exports.qjs_new_host_function(n,r,0);return this.exports.wasm_free(n),new T(this,i)}newPromise(){this.assertNotDisposed();let e=this.exports.wasm_malloc(4),t=this.exports.wasm_malloc(4),n=this.exports.qjs_new_promise(e,t),r=new DataView(this.exports.memory.buffer),i=r.getUint32(e,!0),a=r.getUint32(t,!0);this.exports.wasm_free(e),this.exports.wasm_free(t);let o=new T(this,n),s=new T(this,i),c=new T(this,a),l=this;l._ownedHandles.add(s),l._ownedHandles.add(c);let u=null;return{handle:o,get settled(){if(!u){let e;u=new Promise(t=>{e=t});let t=`__settle:${l.nextInternalId++}`,n=l.newInternalFunction(t,()=>(e(),l.hostCallbacks.delete(t),l.undefined));l.promiseThenRaw(o,n,n).dispose(),n.dispose()}return u},resolve(e){l.callFunctionRaw(s,l.undefined,e).dispose(),l._ownedHandles.delete(s),s.dispose()},reject(e){l.callFunctionRaw(c,l.undefined,e).dispose(),l._ownedHandles.delete(c),c.dispose()}}}resolvePromise(e){if(this.assertNotDisposed(),!this.exports.qjs_is_promise(e.ptr))return Promise.resolve({value:e.dup()});let t=this.exports.qjs_promise_state(e.ptr);return t===1?Promise.resolve({value:new T(this,this.exports.qjs_promise_result(e.ptr))}):t===2?Promise.resolve({error:new T(this,this.exports.qjs_promise_result(e.ptr))}):new Promise(t=>{let n=this.nextInternalId++,r=`__onFulfilled:${n}`,i=`__onRejected:${n}`,a=this.newInternalFunction(r,(...e)=>{let n=e[0]?.dup()??this.undefined;return this.hostCallbacks.delete(r),this.hostCallbacks.delete(i),t({value:n}),this.undefined}),o=this.newInternalFunction(i,(...e)=>{let n=e[0]?.dup()??this.undefined;return this.hostCallbacks.delete(r),this.hostCallbacks.delete(i),t({error:n}),this.undefined});this.promiseThenRaw(e,a,o).dispose(),a.dispose(),o.dispose()})}promiseThenRaw(e,t,n){return new T(this,this.exports.qjs_promise_then(e.ptr,t.ptr,n.ptr))}markPromiseHandled(e){this.assertNotDisposed(),this.exports.qjs_promise_mark_as_handled(e.ptr)}callFunction(e,t,...n){return this.throwIfException(this.callFunctionRaw(e,t,...n))}construct(e,...t){this.assertNotDisposed();let n=t.length,r=0;if(n>0){r=this.exports.wasm_malloc(n*4);let e=new DataView(this.exports.memory.buffer);for(let i=0;i<n;i++)e.setUint32(r+i*4,t[i].ptr,!0)}let i=this.exports.qjs_call_constructor(e.ptr,n,r);return r&&this.exports.wasm_free(r),this.throwIfException(new T(this,i))}callFunctionRaw(e,t,...n){this.assertNotDisposed();let r=n.length,i=0;if(r>0){i=this.exports.wasm_malloc(r*4);let e=new DataView(this.exports.memory.buffer);for(let t=0;t<r;t++)e.setUint32(i+t*4,n[t].ptr,!0)}let a=this.exports.qjs_call(e.ptr,t.ptr,r,i);return i&&this.exports.wasm_free(i),new T(this,a)}setProp(e,t,n){if(this.assertNotDisposed(),typeof t==`string`){let{ptr:r}=this.writeString(t);this.exports.qjs_set_prop_string(e.ptr,r,n.ptr),this.exports.wasm_free(r)}else this.exports.qjs_set_prop_value(e.ptr,t.ptr,n.ptr)}defineProp(e,t,n,r){this.assertNotDisposed();let i=0;if(r?.configurable&&(i|=1),r?.writable&&(i|=2),r?.enumerable&&(i|=4),typeof t==`string`){let{ptr:r}=this.writeString(t);this.exports.qjs_define_prop_string(e.ptr,r,n.ptr,i),this.exports.wasm_free(r)}else this.exports.qjs_define_prop_value(e.ptr,t.ptr,n.ptr,i)}getProp(e,t){return this.assertNotDisposed(),new T(this,this.exports.qjs_get_prop_value(e.ptr,t.ptr))}getException(){return this.assertNotDisposed(),new T(this,this.exports.qjs_get_exception())}newError(e){this.assertNotDisposed();let t=this.exports.qjs_new_error(),n=new T(this,t);if(typeof e==`string`){let t=this.newString(e);n.setProp(`message`,t),t.dispose()}else{let t=this.newString(e.message);if(n.setProp(`message`,t),t.dispose(),e.name){let t=this.newString(e.name);n.setProp(`name`,t),t.dispose()}if(e.stack){let t=this.newString(e.stack);n.setProp(`stack`,t),t.dispose()}}return n}typeof(e){this.assertNotDisposed();let t=this.exports;return t.qjs_is_undefined(e.ptr)?`undefined`:t.qjs_is_null(e.ptr)?`object`:t.qjs_is_bool(e.ptr)?`boolean`:t.qjs_is_number(e.ptr)?`number`:t.qjs_is_big_int(e.ptr)?`bigint`:t.qjs_is_string(e.ptr)?`string`:t.qjs_is_symbol(e.ptr)?`symbol`:t.qjs_is_function(e.ptr)?`function`:t.qjs_is_object(e.ptr)?`object`:`unknown`}dump(e){return this.assertNotDisposed(),this._dump(e,new Map)}_dump(e,t){let n=this.exports;if(!n.qjs_is_undefined(e.ptr)){if(n.qjs_is_null(e.ptr))return null;if(n.qjs_is_bool(e.ptr))return n.qjs_get_bool(e.ptr)!==0;if(n.qjs_is_number(e.ptr))return n.qjs_get_float64(e.ptr);if(n.qjs_is_string(e.ptr))return e.toString();if(n.qjs_is_big_int(e.ptr))return e.toBigInt();if(n.qjs_is_symbol(e.ptr)){let t=n.wasm_malloc(4),r=n.qjs_get_symbol_description(e.ptr,t),i=new DataView(n.memory.buffer).getUint32(t,!0);if(n.wasm_free(t),r===1){let e=new T(this,i),t=e.toString();return e.dispose(),Symbol.for(t)}else if(r===2){new T(this,i).dispose();return}return}if(n.qjs_is_array_buffer(e.ptr))return e.toArrayBuffer();if(n.qjs_is_exception(e.ptr)){let e=this.getException(),t=e.toString();return e.dispose(),Error(t)}if(!n.qjs_is_function(e.ptr)){if(n.qjs_is_object(e.ptr)){let r=n.qjs_get_value_ptr(e.ptr);if(r){let e=t.get(r);if(e!==void 0)return e}}if(n.qjs_is_object(e.ptr)){let t=n.wasm_malloc(4),r=n.wasm_malloc(4),i=n.wasm_malloc(4),a=n.qjs_get_typed_array_buffer(e.ptr,t,r,i),o=new T(this,a);if(n.qjs_is_exception(o.ptr)===0){let e=new DataView(n.memory.buffer),a=e.getUint32(t,!0),s=e.getUint32(r,!0),c=e.getUint32(i,!0);n.wasm_free(t),n.wasm_free(r),n.wasm_free(i);let l=n.wasm_malloc(4),u=n.qjs_get_array_buffer(o.ptr,l);if(n.wasm_free(l),o.dispose(),u!==0){let e=new Uint8Array(n.memory.buffer,u+a,s).slice();switch(c){case 1:return e;case 2:return new Uint16Array(e.buffer);case 4:return new Uint32Array(e.buffer);case 8:return new Float64Array(e.buffer);default:return e}}}else o.dispose(),n.wasm_free(t),n.wasm_free(r),n.wasm_free(i)}if(n.qjs_is_array(e.ptr)){let r=e.getProp(`length`),i=n.qjs_get_float64(r.ptr);r.dispose();let a=[],o=n.qjs_get_value_ptr(e.ptr);o&&t.set(o,a);for(let r=0;r<i;r++){let i=n.qjs_get_prop_uint32(e.ptr,r),o=new T(this,i);a.push(this._dump(o,t)),o.dispose()}return a}if(n.qjs_is_error(e.ptr)){let t=e.getProp(`name`),n=e.getProp(`message`),r=e.getProp(`stack`),i=t.isUndefined?`Error`:t.toString(),a=n.isUndefined?``:n.toString(),o=r.isUndefined?void 0:r.toString();t.dispose(),n.dispose(),r.dispose();let s=Error(a);return s.name=i,o!==void 0&&(s.stack=o),s}if(n.qjs_is_object(e.ptr)){let r=n.qjs_get_own_property_names(e.ptr),i=new T(this,r);if(n.qjs_is_exception(i.ptr)!==0)return i.dispose(),{};let a=i.getProp(`length`),o=n.qjs_get_float64(a.ptr);a.dispose();let s={},c=n.qjs_get_value_ptr(e.ptr);c&&t.set(c,s);for(let r=0;r<o;r++){let a=n.qjs_get_prop_uint32(i.ptr,r),o=new T(this,a),c=o.toString();o.dispose();let l=e.getProp(c);s[c]=this._dump(l,t),l.dispose()}return i.dispose(),s}}}}hostToHandle(e){if(this.assertNotDisposed(),e===void 0)return this.undefined;if(e===null)return this.null;if(e===!0)return this.true;if(e===!1)return this.false;if(typeof e==`number`)return this.newNumber(e);if(typeof e==`string`)return this.newString(e);if(typeof e==`bigint`)return this.newBigInt(e);if(typeof e==`symbol`){let t=Symbol.keyFor(e);if(t!==void 0)return this.newSymbolFor(t);throw Error(`Cannot convert local symbol to QuickJS handle. Use Symbol.for() for cross-boundary symbols.`)}if(e instanceof Promise){let t=this.newPromise();return e.then(e=>{t.resolve(this.hostToHandle(e)),this.executePendingJobs()},e=>{t.reject(this.hostToHandle(e)),this.executePendingJobs()}),t.handle}if(e instanceof Error)return this.newError(e);if(e instanceof ArrayBuffer)return this.newArrayBuffer(e);if(e instanceof Uint8Array)return this.newUint8Array(e);if(ArrayBuffer.isView(e))return this.newArrayBuffer(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));if(Array.isArray(e)){let t=this.newArray();for(let n=0;n<e.length;n++){let r=this.hostToHandle(e[n]);this.exports.qjs_set_prop_uint32(t.ptr,n,r.ptr),r.dispose()}return t}if(typeof e==`object`&&e){let t=this.newObject();for(let[n,r]of Object.entries(e)){let e=this.hostToHandle(r);t.setProp(n,e),e.dispose()}return t}return this.undefined}snapshot(){return this.assertNotDisposed(),{memory:new Uint8Array(this.exports.memory.buffer).slice(),stackPointer:this.exports.__stack_pointer.value,runtimePtr:this.exports.qjs_get_runtime_ptr(),contextPtr:this.exports.qjs_get_context_ptr(),extensions:this.loadedExtensions.map(e=>({name:e.name,memoryBase:e.memoryBase,tableBase:e.tableBase,initFn:e.initFn}))}}registerHostCallback(e,t){this.hostCallbacks.set(e,t)}dispose(){this.disposed||(this.disposed=!0,this._global=null,this._undefined=null,this._null=null,this._true=null,this._false=null,this._ownedHandles.clear(),this.hostCallbacks.clear(),this._activeScope=null,this.exports=null,this.instance=null,this.module=null)}[Symbol.dispose](){this.dispose()}assertNotDisposed(){if(this.disposed)throw Error(`QuickJS instance has been disposed`)}_getExports(){return this.exports}_getMemory(){return this.exports.memory}_writeString(e){return this.writeString(e)}_readCString(e){return this.readCString(e)}};function v(e){return e.includes(`\0`)||x.test(e)}const y=new TextDecoder,b=new TextEncoder,x=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF]))|(?:(?<![\uD800-\uDBFF])[\uDC00-\uDFFF])/;function S(e){if(!x.test(e))return b.encode(e);let t=[];for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r<128)t.push(r);else if(r<2048)t.push(192|r>>6,128|r&63);else if(r>=55296&&r<=56319&&n+1<e.length){let i=e.charCodeAt(n+1);if(i>=56320&&i<=57343){let e=65536+(r-55296<<10)+(i-56320);t.push(240|e>>18,128|e>>12&63,128|e>>6&63,128|e&63),n++;continue}t.push(224|r>>12,128|r>>6&63,128|r&63)}else t.push(224|r>>12,128|r>>6&63,128|r&63)}return new Uint8Array(t)}function C(e){let t=!1;for(let n=0;n<e.length-1;n++)if(e[n]===237&&e[n+1]>=160&&e[n+1]<=191){t=!0;break}if(!t)return y.decode(e);let n=``,r=0;for(;r<e.length;){let t=e[r];if(t<128)n+=String.fromCharCode(t),r+=1;else if(t<224)n+=String.fromCharCode((t&31)<<6|e[r+1]&63),r+=2;else if(t<240)n+=String.fromCharCode((t&15)<<12|(e[r+1]&63)<<6|e[r+2]&63),r+=3;else{let i=(t&7)<<18|(e[r+1]&63)<<12|(e[r+2]&63)<<6|e[r+3]&63;n+=String.fromCodePoint(i),r+=4}}return n}var w=class extends Error{handle;#e;#t;#n;constructor(e){let t={stack:[],error:void 0,hasError:!1};try{super(),this.handle=e,delete this.stack;let n=p(t,e.getProp(`message`),!1);this.#e=e.getProp(`name`).consume(e=>e.isUndefined?`Error`:e.toString()),this.#t=n.isUndefined?e.toString():n.toString(),this.#n=e.getProp(`stack`).consume(e=>e.isUndefined?void 0:e.toString())}catch(e){t.error=e,t.hasError=!0}finally{m(t)}}get name(){return this.#e}set name(e){this.#e=e}get message(){return this.#t}set message(e){this.#t=e}get stack(){return this.#n}set stack(e){this.#n=e}dispose(){this.handle.dispose()}[Symbol.dispose](){this.handle.dispose()}},T=class e{vm;ptr;disposed_=!1;singleton;borrowed;_onDispose;constructor(e,t,n=!1,r=!1){this.vm=e,this.ptr=t,this.singleton=n,this.borrowed=r,!n&&!r&&e._activeScope?.add(this)}get _isBorrowed(){return this.borrowed}get disposed(){return this.disposed_}get isUndefined(){return this.vm._getExports().qjs_is_undefined(this.ptr)!==0}get isNull(){return this.vm._getExports().qjs_is_null(this.ptr)!==0}get isBool(){return this.vm._getExports().qjs_is_bool(this.ptr)!==0}get isNumber(){return this.vm._getExports().qjs_is_number(this.ptr)!==0}get isString(){return this.vm._getExports().qjs_is_string(this.ptr)!==0}get isSymbol(){return this.vm._getExports().qjs_is_symbol(this.ptr)!==0}get isBigInt(){return this.vm._getExports().qjs_is_big_int(this.ptr)!==0}get isObject(){return this.vm._getExports().qjs_is_object(this.ptr)!==0}get isArray(){return this.vm._getExports().qjs_is_array(this.ptr)!==0}get isFunction(){return this.vm._getExports().qjs_is_function(this.ptr)!==0}get isError(){return this.vm._getExports().qjs_is_error(this.ptr)!==0}get isPromise(){return this.vm._getExports().qjs_is_promise(this.ptr)!==0}get isArrayBuffer(){return this.vm._getExports().qjs_is_array_buffer(this.ptr)!==0}get isProxy(){return this.vm._getExports().qjs_is_proxy(this.ptr)!==0}get isMap(){return this.vm._getExports().qjs_is_map(this.ptr)!==0}get isSet(){return this.vm._getExports().qjs_is_set(this.ptr)!==0}get isDate(){return this.vm._getExports().qjs_is_date(this.ptr)!==0}get isRegExp(){return this.vm._getExports().qjs_is_regexp(this.ptr)!==0}get isWeakRef(){return this.vm._getExports().qjs_is_weak_ref(this.ptr)!==0}get isWeakMap(){return this.vm._getExports().qjs_is_weak_map(this.ptr)!==0}get isWeakSet(){return this.vm._getExports().qjs_is_weak_set(this.ptr)!==0}get isDataView(){return this.vm._getExports().qjs_is_data_view(this.ptr)!==0}get identity(){return this.vm._getExports().qjs_get_value_ptr(this.ptr)}toBoolean(){return this.vm._getExports().qjs_get_bool(this.ptr)!==0}get classId(){return this.vm._getExports().qjs_get_class_id(this.ptr)}get className(){let t=new e(this.vm,this.vm._getExports().qjs_get_class_name(this.ptr));if(this.vm._getExports().qjs_is_exception(t.ptr)!==0)throw t.dispose(),new w(this.vm.getException());try{return t.isUndefined?void 0:t.toString()}finally{t.dispose()}}get promiseState(){return this.vm._getExports().qjs_promise_state(this.ptr)}get typeof(){return this.vm.typeof(this)}get length(){let e=this.getProp(`length`),t=e.toNumber();return e.dispose(),t}get constructorName(){let e=this.getProp(`constructor`);if(e.isUndefined||e.isNull){e.dispose();return}let t=e.getProp(`name`);if(e.dispose(),t.isUndefined||t.isNull){t.dispose();return}let n=t.toString();return t.dispose(),n}keys(){let t=this.vm._getExports(),n=t.qjs_get_own_property_names(this.ptr),r=new e(this.vm,n);if(t.qjs_is_exception(r.ptr)!==0)return r.dispose(),[];let i=r.getProp(`length`),a=t.qjs_get_float64(i.ptr);i.dispose();let o=[];for(let n=0;n<a;n++){let i=t.qjs_get_prop_uint32(r.ptr,n),a=new e(this.vm,i);o.push(a.toString()),a.dispose()}return r.dispose(),o}getOwnPropertyNames(){let t=this.vm._getExports(),n=t.qjs_get_own_property_names_all(this.ptr),r=new e(this.vm,n);if(t.qjs_is_exception(r.ptr)!==0)return r.dispose(),[];let i=r.getProp(`length`),a=t.qjs_get_float64(i.ptr);i.dispose();let o=[];for(let n=0;n<a;n++){let i=t.qjs_get_prop_uint32(r.ptr,n),a=new e(this.vm,i);o.push(a.toString()),a.dispose()}return r.dispose(),o}getOwnPropertyKeys(){let t=this.vm._getExports(),n=t.qjs_get_own_property_keys(this.ptr),r=new e(this.vm,n);if(t.qjs_is_exception(r.ptr)!==0)return r.dispose(),[];let i=r.getProp(`length`),a=t.qjs_get_float64(i.ptr);i.dispose();let o=[];for(let n=0;n<a;n++){let i=t.qjs_get_prop_uint32(r.ptr,n),a=new e(this.vm,i);a.isSymbol?o.push(a):(o.push(a.toString()),a.dispose())}return r.dispose(),o}getOwnPropertyDescriptor(t){let n={stack:[],error:void 0,hasError:!1};try{let r=this.vm._getExports(),i,a;typeof t==`string`?(i=this.vm.newString(t),a=i.ptr):a=t.ptr;let o=r.qjs_get_own_property_descriptor(this.ptr,a);if(i?.dispose(),o===0)return;let s=p(n,new e(this.vm,o),!1);if(r.qjs_is_exception(s.ptr)!==0)throw new w(this.vm.getException());let c=s.getProp(`enumerable`).consume(e=>r.qjs_get_bool(e.ptr)!==0),l=s.getProp(`configurable`).consume(e=>r.qjs_get_bool(e.ptr)!==0);return s.hasOwnProperty(`value`)?{value:s.getProp(`value`),writable:s.getProp(`writable`).consume(e=>r.qjs_get_bool(e.ptr)!==0),enumerable:c,configurable:l}:{get:s.getProp(`get`),set:s.getProp(`set`),enumerable:c,configurable:l}}catch(e){n.error=e,n.hasError=!0}finally{m(n)}}hasOwnProperty(e){if(v(e)){let t={stack:[],error:void 0,hasError:!1};try{let n=p(t,this.vm.newString(e),!1);return this.vm._getExports().qjs_has_own_property_value(this.ptr,n.ptr)===1}catch(e){t.error=e,t.hasError=!0}finally{m(t)}}let{ptr:t}=this.vm._writeString(e),n=this.vm._getExports().qjs_has_own_property(this.ptr,t);return this.vm._getExports().wasm_free(t),n===1}propertyIsEnumerable(e){if(v(e)){let t={stack:[],error:void 0,hasError:!1};try{let n=p(t,this.vm.newString(e),!1);return this.vm._getExports().qjs_property_is_enumerable_value(this.ptr,n.ptr)===1}catch(e){t.error=e,t.hasError=!0}finally{m(t)}}let{ptr:t}=this.vm._writeString(e),n=this.vm._getExports().qjs_property_is_enumerable(this.ptr,t);return this.vm._getExports().wasm_free(t),n===1}getPrototypeOf(){let t=this.vm._getExports().qjs_get_prototype_of(this.ptr);return new e(this.vm,t)}getProxyTarget(){let t=this.vm._getExports().qjs_get_proxy_target(this.ptr),n=new e(this.vm,t);if(this.vm._getExports().qjs_is_exception(n.ptr)!==0)throw n.dispose(),new w(this.vm.getException());return n}getProxyHandler(){let t=this.vm._getExports().qjs_get_proxy_handler(this.ptr),n=new e(this.vm,t);if(this.vm._getExports().qjs_is_exception(n.ptr)!==0)throw n.dispose(),new w(this.vm.getException());return n}getProp(t){if(v(t)){let e={stack:[],error:void 0,hasError:!1};try{let n=p(e,this.vm.newString(t),!1);return this.vm.getProp(this,n)}catch(t){e.error=t,e.hasError=!0}finally{m(e)}}let{ptr:n}=this.vm._writeString(t),r=this.vm._getExports().qjs_get_prop_string(this.ptr,n);return this.vm._getExports().wasm_free(n),new e(this.vm,r)}setProp(e,t){if(v(e)){let n={stack:[],error:void 0,hasError:!1};try{let r=p(n,this.vm.newString(e),!1);this.vm.setProp(this,r,t);return}catch(e){n.error=e,n.hasError=!0}finally{m(n)}}let{ptr:n}=this.vm._writeString(e);this.vm._getExports().qjs_set_prop_string(this.ptr,n,t.ptr),this.vm._getExports().wasm_free(n)}defineProp(e,t,n){let r=0;if(n?.configurable&&(r|=1),n?.writable&&(r|=2),n?.enumerable&&(r|=4),typeof e==`string`){if(v(e)){let n={stack:[],error:void 0,hasError:!1};try{let i=p(n,this.vm.newString(e),!1);this.vm._getExports().qjs_define_prop_value(this.ptr,i.ptr,t.ptr,r);return}catch(e){n.error=e,n.hasError=!0}finally{m(n)}}let{ptr:n}=this.vm._writeString(e);this.vm._getExports().qjs_define_prop_string(this.ptr,n,t.ptr,r),this.vm._getExports().wasm_free(n)}else this.vm._getExports().qjs_define_prop_value(this.ptr,e.ptr,t.ptr,r)}toNumber(){return this.vm._getExports().qjs_get_float64(this.ptr)}toBigInt(){let e=this.vm._getExports(),t=e.wasm_malloc(4),n=e.wasm_malloc(4);if(e.qjs_get_big_int64(this.ptr,t,n)!==0)throw e.wasm_free(t),e.wasm_free(n),Error(`Failed to convert value to BigInt`);let r=new DataView(e.memory.buffer),i=r.getUint32(t,!0),a=r.getInt32(n,!0);return e.wasm_free(t),e.wasm_free(n),BigInt(a)<<32n|BigInt(i)}toArrayBuffer(){let t=this.vm._getExports(),n=t.wasm_malloc(4);if(t.qjs_is_array_buffer(this.ptr)){let e=t.qjs_get_array_buffer(this.ptr,n);if(e===0)throw t.wasm_free(n),Error(`Failed to get ArrayBuffer data`);let r=new DataView(t.memory.buffer).getUint32(n,!0);return t.wasm_free(n),new Uint8Array(t.memory.buffer,e,r).slice().buffer}t.wasm_free(n);let r=t.wasm_malloc(4),i=t.wasm_malloc(4),a=t.wasm_malloc(4),o=t.qjs_get_typed_array_buffer(this.ptr,r,i,a),s=new e(this.vm,o);if(this.vm._getExports().qjs_is_exception(s.ptr)!==0)throw s.dispose(),t.wasm_free(r),t.wasm_free(i),t.wasm_free(a),Error(`Value is not an ArrayBuffer or typed array`);let c=new DataView(t.memory.buffer),l=c.getUint32(r,!0),u=c.getUint32(i,!0);t.wasm_free(r),t.wasm_free(i),t.wasm_free(a);let d=t.wasm_malloc(4),f=t.qjs_get_array_buffer(s.ptr,d);if(t.wasm_free(d),s.dispose(),f===0)throw Error(`Failed to get ArrayBuffer data from typed array`);return new Uint8Array(t.memory.buffer,f+l,u).slice().buffer}toUint8Array(){return new Uint8Array(this.toArrayBuffer())}toString(){let e=this.vm._getExports(),t=e.wasm_malloc(4);if(t===0)throw Error(`wasm_malloc failed`);try{let n=e.qjs_get_string_len(this.ptr,t);if(n===0)return`<null>`;let r=new DataView(e.memory.buffer).getUint32(t,!0),i=C(new Uint8Array(e.memory.buffer,n,r));return e.qjs_free_cstring(n),i}finally{e.wasm_free(t)}}consume(e){try{return e(this)}finally{this.dispose()}}dup(){return new e(this.vm,this.vm._getExports().qjs_dup_value(this.ptr))}dispose(){if(!(this.singleton||this.borrowed)&&!this.disposed_){this.disposed_=!0,this._onDispose?.(),this._onDispose=void 0;let e=this.vm._getExports();e&&e.qjs_free_value(this.ptr)}}[Symbol.dispose](){this.dispose()}};function E(e){n?.postMessage(e)}function D(e){E({type:`crash`,message:e instanceof Error?`${e.name}: ${e.message}`:String(e)})}function O(e){return{fd_write(t,n,r,i){let a=new DataView(e.buffer),o=0;for(let e=0;e<r;e++)o+=a.getUint32(n+e*8+4,!0);return a.setUint32(i,o,!0),0}}}function k(e){let t=e.message?`${e.name}: ${e.message}`:e.name,n=e.stack?.trimEnd();return JSON.stringify({name:e.name,message:e.message,stack:n?`${t}\n${n}`:t})}async function A(r){let i=new Int32Array(r.interrupt),a=await _.create({wasm:r.wasm,memoryLimit:r.memoryLimitBytes,maxStackSize:h,interruptHandler:()=>Atomics.load(i,0)!==0,wasi:O}),o=a.newFunction(`bridge`,(e,t,n,r)=>{switch(e.toString()){case`call`:case`global`:E({type:`call`,id:t.toNumber(),target:e.toString()===`call`?`tool`:`global`,name:n.toString(),args:r===void 0||r.isUndefined?void 0:r.toString()});break;case`output`:E({type:`output`,item:t.toString()===`image`?{type:`image`,data:n.toString(),mimeType:r.toString()}:t.toString()===`console`?{type:`text`,text:n.toString(),console:!0}:{type:`text`,text:n.toString()}});break;case`done`:t.toBoolean()?E({type:`done`,ok:!0,value:n===void 0||n.isUndefined?void 0:n.toString(),writes:r.toString()}):E({type:`done`,ok:!1,error:n.toString()});break}return a.undefined}),s=a.withScope(t=>t.escape(a.callFunction(a.evalCode(e,`codemode-prelude.js`),a.undefined,o,a.newString(JSON.stringify(r.tools)),a.newString(JSON.stringify(r.globals)),a.newString(JSON.stringify(r.store))))),c=s.getProp(`settle`),l=s.getProp(`run`),u=s.getProp(`stalled`),d=()=>{a.executePendingJobs(),a.callFunction(u,s).dispose()};n?.on(`message`,e=>{if(t(e))try{a.withScope(()=>{a.callFunction(c,s,a.newNumber(e.id),e.ok?a.true:a.false,e.payload===void 0?a.undefined:a.newString(e.payload))}),d()}catch(e){D(e)}});let f;try{f=a.evalCode(`(async (tools, console) => {${r.code}\n})`,`codemode.js`)}catch(e){if(!(e instanceof w))throw e;E({type:`done`,ok:!1,error:k(e)});return}a.callFunction(l,s,f).dispose(),f.dispose(),d()}n&&A(r).catch(D);export{};
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{a as e,i as t,n,o as r,r as i}from"./net-DPM9odNy.mjs";import{a,c as o,n as s}from"./config-DiYweJ2m.mjs";import{n as c,r as l}from"./client-qqI-HCOj.mjs";import u from"node:fs/promises";import d from"node:path";import f from"node:fs";import{execFile as p,spawn as m}from"node:child_process";import h from"node-machine-id";import g from"@iarna/toml";import{promisify as _}from"node:util";const v=_(p),y=e=>e?.code===`ENOENT`,b=async e=>{try{return await u.stat(e)}catch(e){if(y(e))return null;throw e}},x=e=>{if(!e)return{};try{let{env:t}=g.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:{}}catch{return{}}},S=e=>(process.platform===`win32`?/^[\w@%+=:,./\\-]+$/:/^[\w@%+=:,./-]+$/).test(e)?e:process.platform===`win32`?`"${e}"`:`'${e.replaceAll(`'`,`'\\''`)}'`,C=e=>process.platform===`darwin`?[`open`,e]:process.platform===`win32`?[`rundll32`,`url.dll,FileProtocolHandler`,e]:[`xdg-open`,e],w=()=>{if(process.platform===`darwin`)return[{argv:[`pbcopy`]}];if(process.platform===`win32`)return[{argv:[`clip`],encode:e=>Buffer.from(`\ufeff${e}`,`utf16le`)}];let e={argv:[`wl-copy`]},t={argv:[`xclip`,`-selection`,`clipboard`]};return process.env.WAYLAND_DISPLAY?[e,t]:[t,e]},T=(e,t)=>new Promise((n,r)=>{let i=m(e,t,{detached:!0,stdio:`ignore`});i.once(`error`,r),i.once(`spawn`,()=>{i.unref(),n()})}),E=(e,t,n)=>new Promise((r,i)=>{let a=m(e,t,{stdio:[`pipe`,`ignore`,`ignore`]});a.once(`error`,i),a.stdin.once(`error`,i),a.once(`exit`,t=>{t===0?r():i(Error(`${e} exited with code ${t}`))}),a.stdin.end(n)}),D=n=>{let o=new Set,p=()=>{for(let e of[...o])e()};return{configPath:n,serverVersion:e().version,machineId:h.machineIdSync(),async readConfigText(){try{return await u.readFile(n,`utf8`)}catch(e){if(y(e))return null;throw e}},async writeConfigText(e,{backup:t}){let r=await u.realpath(n).catch(()=>n),i=await b(r);await u.mkdir(d.dirname(r),{recursive:!0}),p();let a=d.join(d.dirname(r),`.${d.basename(r)}.${process.pid}-${Date.now()}.tmp`);try{await u.writeFile(a,e,{encoding:`utf8`,flag:`wx`,...i?{mode:i.mode&511}:{}}),i&&await u.chmod(a,i.mode&4095);let o=null;return t&&i&&(o=`${n}.bak`,await u.copyFile(r,o)),await u.rename(a,r),{backupPath:o}}catch(e){throw await u.rm(a,{force:!0}),e}},async statConfig(){let e=await b(n);return e?{mtimeMs:e.mtimeMs}:null},watchConfig(e){let t=d.basename(n),r=null,i=null,a=!1,s=()=>{if(o.delete(s),!a)try{i=f.watch(d.dirname(n),(n,i)=>{i&&i!==t||(r&&clearTimeout(r),r=setTimeout(()=>{r=null,e()},100))}),i.on(`error`,e=>{console.warn(`[ui] Stopped watching ${n}: ${e.message}`),i?.close()})}catch(e){y(e)?o.add(s):console.warn(`[ui] Cannot watch ${n}: ${e.message}`)}};return s(),()=>{a=!0,o.delete(s),r&&clearTimeout(r),i?.close()}},async probeCaps(e){return(await t(e.map(e=>({type:e})))).map(({type:e,score:t,hasGpu:n,usableBytes:r})=>({type:e,score:t??0,hasGpu:n??!1,usableBytes:r??0}))},async getBackendDefaults(e){return r(e)},resolveHfToken(e){let t={...x(e.raw.env),...process.env};return[e.runtime.huggingface_token,t.HUGGINGFACE_TOKEN,t.HF_TOKEN].find(e=>typeof e==`string`&&e.trim()!==``)?.trim()??null},async hostInfo(){return i()},async preferredAppearance(){if(process.platform!==`darwin`)return`light`;try{let{stdout:e}=await v(`defaults`,[`read`,`-g`,`AppleInterfaceStyle`]);return e.trim()===`Dark`?`dark`:`light`}catch{return`light`}},async openExternal(e){let{protocol:t}=new URL(e);if(t!==`http:`&&t!==`https:`)throw Error(`Only http(s) links can be opened: ${e}`);let[n,...r]=C(e);await T(n,r)},async copyToClipboard(e){let t=null;for(let{argv:n,encode:r}of w()){let[i,...a]=n;try{await E(i,a,r?r(e):e);return}catch(e){t=e}}throw t},startCommand:()=>`bricks-buttress --config ${S(n)}`,agentConnection(e){if(!f.existsSync(n))return null;let t;try{t=c(n)}catch{return null}let{config:r,agentsConfig:i}=t;return i?{baseUrl:`http://127.0.0.1:${e?.port??(r.server.port||2080)}`,token:l(i.runtimeTokenFile)}:null},agentsConfigError(e){let t=e;if(t===void 0)try{t=f.readFileSync(n,`utf8`)}catch{return{agents:0,error:null}}let r;try{r=g.parse(t)}catch(e){return{agents:0,error:`invalid TOML: ${O(e)}`}}let i=Array.isArray(r.agents)?r.agents.length:0;if(i===0)return{agents:0,error:null};try{return s(a(r),{configDir:d.dirname(n)}),{agents:i,error:null}}catch(e){return{agents:i,error:O(e)}}}}},O=e=>e instanceof Error?e.message:String(e),k=()=>import(`@fugood/buttress-ui`),A=[`darwin-arm64`,`linux-x64`,`win32-x64`],j=[`chat`,`status`,`settings`],M=e=>j.includes(e),N=e=>{let t=[],n;for(let r=0;r<e.length;r+=1){let i=e[r];if(i===`-h`||i===`--help`)return{kind:`help`};if(i===`-c`||i===`--config`){let n=e[r+1];if(n===void 0)return{kind:`error`,message:`${i} needs a config file path`};t.push(n),r+=1}else if(i===`--tab`){let t=e[r+1];if(t===void 0||!M(t)){let e=t===void 0?``:` (got "${t}")`;return{kind:`error`,message:`--tab needs one of ${j.join(`, `)}${e}`}}n=t,r+=1}else if(i.startsWith(`-`))return{kind:`error`,message:`Unknown option: ${i}`};else t.push(i)}return t.length===0?{kind:`error`,message:`bricks-buttress ui needs a config file path`}:t.length>1?{kind:`error`,message:`Give one config file path (got ${t.join(`, `)})`}:t[0].includes(`
|
|
3
|
+
`)?{kind:`error`,message:`bricks-buttress ui edits a config file; inline TOML is not supported`}:{kind:`run`,configPath:d.resolve(t[0]),initialTab:n}},P=()=>({isBun:`Bun`in globalThis,platform:process.platform,arch:process.arch}),F=(e,t)=>e.isBun?A.includes(`${e.platform}-${e.arch}`)?null:`bricks-buttress ui runs on darwin-arm64, linux-x64 and win32-x64; on this machine open ${t()} in a browser instead`:`bricks-buttress ui needs Bun; run it with bun or the standalone bricks-buttress binary`,I=e=>{try{let t=g.parse(f.readFileSync(e,`utf8`)).server?.port;return Number.isInteger(t)&&t>0?t:o}catch{return o}},L=e=>`http://${n()??`localhost`}:${I(e)}/status`,R=e=>e instanceof Error?e.message:String(e),z=e=>{let{code:t,specifier:n}=e??{};return t===`ERR_MODULE_NOT_FOUND`&&n===`@fugood/buttress-ui`},B=e=>process.env.BUTTRESS_SERVER_DISTRIBUTION===`1`&&R(e).includes(`@gpuix/native-`),V=async e=>{try{let{launchButtressUi:e}=await k();return e}catch(t){z(t)?console.error(`This bricks-buttress install does not include the settings window (the npm package leaves it out); use the standalone bricks-buttress binary or a source checkout, or open ${L(e)} in a browser instead`):B(t)?console.error(`The window's native module (gpuix) is missing next to bricks-buttress; run \`bricks-buttress update\` to reinstall it, or open ${L(e)} in a browser instead (${R(t)})`):console.error(`bricks-buttress ui failed to load the window: ${R(t)}`),process.exit(1)}},H=async e=>{let t=N(e);t.kind===`help`&&(console.log(`
|
|
4
|
+
Usage:
|
|
5
|
+
bricks-buttress ui [-c|--config] <config.toml> [--tab <chat|status|settings>]
|
|
6
|
+
|
|
7
|
+
Opens a native window to edit a buttress-server config file, to watch the
|
|
8
|
+
server that runs it and to chat with its agents.
|
|
9
|
+
|
|
10
|
+
Settings A form over the TOML file. Save shows the diff first, writes the
|
|
11
|
+
file atomically and keeps the previous content as <config>.bak.
|
|
12
|
+
A missing file starts a new config that is written only after
|
|
13
|
+
you confirm Create file.
|
|
14
|
+
Status Live dashboard of the server started with this config, found by
|
|
15
|
+
its id on http://127.0.0.1:<port> (/buttress/info, else
|
|
16
|
+
/buttress/status). The window never starts, stops or restarts
|
|
17
|
+
the server: restart it to apply saved changes.
|
|
18
|
+
Chat Chat with the [[agents]] of the running server: sessions grouped
|
|
19
|
+
by agent, streamed answers and tool calls, Stop, Fork and new
|
|
20
|
+
sessions. Uses the server's local runtime token, so it works on
|
|
21
|
+
an unbound server too.
|
|
22
|
+
|
|
23
|
+
The window opens on Chat when the server runs and has agents, on Status
|
|
24
|
+
when it runs without agents, and on Settings otherwise; --tab overrides it.
|
|
25
|
+
|
|
26
|
+
Runs under Bun on darwin-arm64, linux-x64 and win32-x64. On other machines,
|
|
27
|
+
open http://<host>:<port>/status in a browser.
|
|
28
|
+
|
|
29
|
+
Options:
|
|
30
|
+
-c, --config <path> Config file to edit (a positional path works too)
|
|
31
|
+
--tab <chat|status|settings> Tab to open first
|
|
32
|
+
-h, --help Show this help message
|
|
33
|
+
|
|
34
|
+
Examples:
|
|
35
|
+
bricks-buttress ui -c ./config.toml
|
|
36
|
+
bricks-buttress ui ./config.toml
|
|
37
|
+
bricks-buttress ui -c ./config.toml --tab chat
|
|
38
|
+
`),process.exit(0)),t.kind===`error`&&(console.error(`${t.message}\nRun \`bricks-buttress ui --help\` for usage.`),process.exit(1));let{configPath:n,initialTab:r}=t,i=F(P(),()=>L(n));i&&(console.error(i),process.exit(1));let a=await V(n);try{await a(D(n),{initialTab:r})}catch(e){console.error(`bricks-buttress ui failed: ${R(e)}`),process.exit(1)}process.exit(0)};export{H as runUiCommand};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import e from"node:path";import t from"node:os";import n from"bytes";import{z as r}from"zod";import i from"ms";import a from"node-machine-id";import"@iarna/toml";const o=e=>{let t=e?.model?.repo_id||e?.type||``,n=e?.model?.filename;return n?`${t}:${n}`:t},s=({family:e,types:t})=>(n,r)=>{let i=(n.generators||[]).filter(e=>t.includes(e.type));if(i.length===0){let n=t.map(e=>`"${e}"`).join(` or `);throw Error(`No ${e} generator configured. Add a [[generators]] with type = ${n} to your config.`)}let a=i[0];if(r){let t=i.find(e=>o(e)===r)||i.find(e=>{let{repo_id:t,filename:n}=e?.model||{};return t===r||n===r});if(!t){let t=i.map(o).join(`, `);throw Error(`Unknown ${e} model "${r}". Configured models: ${t||`(none)`}`)}a=t}let{generators:s,server:c,...l}=n.global||{};return{type:a.type||t[0],repoId:o(a),mergedConfig:{...l,...a,model:{...a.model}}}},c=({max:e,resolve:t,prepare:n,dispose:r})=>{let i=new Map,a=new Map,o=(e,t)=>{i.delete(e),i.set(e,t)},s=(e,t)=>(t.activeRequests+=1,o(e,t),t),c=async(t,n)=>{for(;i.size>e;){let e=Array.from(i.entries()).find(([,e])=>e.activeRequests===0);if(!e)return;let[a,o]=e;i.delete(a);try{await r?.(t,o),await t.finalizeGenerator?.(o.id),console.log(`${n} Evicted idle generator: ${a}`)}catch(e){console.warn(`${n} Failed to evict idle generator ${a}:`,e?.message)}}};return{getOrCreate:async(e,r,o,l)=>{let{type:u,repoId:d,mergedConfig:f}=t(r,o),p=d,m=i.get(p);if(m?.initialized)return s(p,m);let h=a.get(p);if(h)return s(p,await h);console.log(`${l} Creating ${u} generator for ${p}`);let g=(async()=>{let{id:t}=await e.startGenerator(u,f),r={id:t,type:u,config:f,repoId:d,initialized:!1,activeRequests:0};return await n(e,r),r.initialized=!0,i.set(p,r),console.log(`${l} Generator ready: ${p}`),r})().finally(()=>{a.delete(p)});a.set(p,g);let _=s(p,await g);return await c(e,l),_},release:async(e,t,n)=>{t&&(t.activeRequests=Math.max(0,t.activeRequests-1),await c(e,n))}}};function l(e){e.cancel().catch(()=>{})}const u=[`ggml-llm`,`ggml-stt`,`ggml-tts`,`ggml-decision`,`mlx-llm`,`onnx-stt`,`onnx-tts`],d=2080;function f(e){return`buttress-${e}`}function p(e){return`Buttress Server (${e.slice(-8)})`}function m(e){return e.enabled!==!1}function h(e){return e.filter(m)}const g=[`ggml-llm`,`ggml-stt`,`ggml-tts`,`ggml-decision`],_=[`onnx-stt`,`onnx-tts`],v=[`ggml-llm`],y=[`ggml-stt`],b=[`ggml-tts`],x=[`ggml-decision`],S=[`mlx-llm`],C=[...g,..._],w=[`debug`,`info`,`warn`,`error`],T=[`auto`,`on`,`off`],E=[`none`,`layer`,`row`,`tensor`],D=[`f16`,`f32`,`bf16`,`q8_0`,`q4_0`,`q4_1`,`iq4_nl`,`q5_0`,`q5_1`],O=[`cuda`,`vulkan`,`snapdragon`,`default`],k=[`cuda`,`vulkan`,`default`],A=[`cuda`,`coreml`,`dml`,`webgpu`,`cpu`],j=(e,t,n,r,i,a={})=>({section:e,key:t,kind:n,label:r,help:i,tier:2,...a}),M=(e,t,n,r,i)=>j(`server`,e,t,n,r,{tier:1,...i}),ee=[M(`id`,`string`,`Server id`,`Stable id used for autodiscover and workspace binding.`,{defaultHint:`buttress-<machine id>`}),M(`name`,`string`,`Display name`,`Name shown to clients that discover this server.`,{defaultHint:`Buttress Server (<short id>)`}),M(`port`,`integer`,`Port`,`HTTP/RPC listener port; the --port flag overrides it.`,{defaultHint:`2080`,min:1,max:65535}),M(`log_level`,`enum`,`Log level`,`Server log verbosity.`,{enumValues:w}),M(`max_body_size`,`size`,`Max body size`,`Request body limit: "100MB", "1GB" or bytes.`,{defaultHint:`50MB`}),M(`session_timeout`,`duration`,`Session timeout`,`Idle time before a session is dropped: milliseconds or "30s", "5m".`,{defaultHint:`60000`}),M(`temp_file_dir`,`path`,`Temp file directory`,`Where uploaded session files go.`,{defaultHint:`$TMPDIR/.buttress`})],N=[j(`runtime`,`cache_dir`,`path`,`Cache directory`,`Model and metadata cache root.`,{tier:1,defaultHint:`~/.buttress/models`}),j(`runtime`,`huggingface_token`,`secret`,`HuggingFace token`,`Used for HuggingFace downloads; falls back to $HUGGINGFACE_TOKEN.`,{tier:1}),j(`runtime`,`n_threads`,`integer`,`Threads`,`CPU thread count.`,{tier:1,min:1}),j(`runtime`,`n_gpu_layers`,`integer`,`GPU layers`,`Layers offloaded to the GPU.`,{tier:1,enumValues:[`auto`],defaultHint:`auto`}),j(`runtime`,`n_parallel`,`integer`,`Parallel sequences`,`Parallel sequences.`,{tier:1,min:1,defaultHint:`4`}),j(`runtime`,`n_batch`,`integer`,`Batch size`,`Prompt batch size. ggml-llm has a model-level default of 512 that shadows this value; set n_batch on the generator model instead.`,{tier:1,min:1}),j(`runtime`,`n_ctx`,`integer`,`Context window`,`Context window. A per-model value wins; ggml-llm caps it at the training context.`,{tier:1,min:1}),j(`runtime`,`context_release_delay_ms`,`integer`,`Context release delay (ms)`,`Idle time before a context is unloaded; 0 releases it right away.`,{tier:1,min:0,defaultHint:`10000`}),j(`runtime`,`flash_attn_type`,`enum`,`Flash attention`,`Defaults to "auto" when a GPU backend is selected and "off" on CPU.`,{tier:1,enumValues:T,defaultHint:`auto on GPU, off on CPU`}),j(`runtime`,`cache_type_k`,`enum`,`KV cache type (K)`,`KV-cache dtype for keys.`,{tier:1,enumValues:D,defaultHint:`f16`}),j(`runtime`,`cache_type_v`,`enum`,`KV cache type (V)`,`KV-cache dtype for values.`,{tier:1,enumValues:D,defaultHint:`f16`}),j(`runtime`,`kv_unified`,`boolean`,`Unified KV cache`,`One KV cache across sequences.`,{tier:1}),j(`runtime`,`http_headers`,`table`,`HTTP headers`,`Extra headers for HF / HTTP downloads.`),j(`runtime`,`prefer_variants`,`string-list`,`Preferred variants`,`Overrides the variant probe order of the ggml backends.`),j(`runtime`,`n_ubatch`,`integer`,`Micro-batch size`,`Prompt micro-batch size.`,{min:1}),j(`runtime`,`n_cpu_moe`,`integer`,`CPU MoE layers`,`MoE expert layers kept on the CPU.`,{min:0}),j(`runtime`,`swa_full`,`boolean`,`Full SWA cache`,`Full attention for sliding-window layers.`),j(`runtime`,`ctx_shift`,`boolean`,`Context shift`,`Allow llama.cpp's rolling context shift.`),j(`runtime`,`state_cache_budget_mb`,`integer`,`State cache budget (MB)`,`Memory budget of the cross-turn KV prefix cache for recurrent / hybrid models; 0 disables it.`,{min:0,defaultHint:`160`}),j(`runtime`,`state_cache_max_checkpoints`,`integer`,`State cache checkpoints`,`Snapshot count cap for that cache; 0 = unlimited. The memory budget takes precedence.`,{min:0,defaultHint:`8`}),j(`runtime`,`use_mmap`,`boolean`,`Memory-map weights`,`Memory-map the model file.`),j(`runtime`,`use_mlock`,`boolean`,`Lock weights in RAM`,`Lock the model in memory.`),j(`runtime`,`no_extra_bufts`,`boolean`,`No extra buffer types`,`Disable extra compute buffer types.`),j(`runtime`,`cpu_mask`,`string`,`CPU mask`,`CPU affinity mask.`),j(`runtime`,`cpu_strict`,`boolean`,`Strict CPU placement`,`Strict CPU affinity.`),j(`runtime`,`devices`,`string-list`,`Devices`,`Restrict to these GGML devices.`),j(`runtime`,`split_mode`,`enum`,`GPU split mode`,`ggml-llm GPU splitting: one GPU, layers + KV, weight rows, or weights + KV (experimental).`,{enumValues:E,defaultHint:`layer`}),j(`runtime`,`tensor_split`,`number-list`,`Tensor split`,`ggml-llm per-GPU proportions, e.g. [3, 1] or "3,1"; unset uses the automatic split.`),j(`runtime`,`model_draft`,`table`,`Draft model`,`Default draft model for speculative decoding: a URL/path string or a model table.`),...P(`runtime`),j(`runtime`,`max_threads`,`integer`,`Max threads`,`Caps the native thread count.`,{generatorTypes:[`ggml-stt`,`ggml-tts`,`ggml-decision`],min:1}),j(`runtime`,`vocoder_batch_size`,`integer`,`Vocoder batch size`,`Passed to initVocoder.`,{generatorTypes:b,min:1,defaultHint:`4096`}),j(`runtime`,`output_cache`,`table`,`Output cache`,`Synthesized audio cache: enabled, max_size_bytes, max_entries.`,{generatorTypes:[...b,`onnx-tts`],defaultHint:`enabled, 2GB, 5000 entries`}),j(`runtime`,`mlx_env_dir`,`path`,`MLX venv directory`,`Auto-managed Python venv.`,{generatorTypes:S,defaultHint:`{cache_dir}/mlx-env`}),j(`runtime`,`mlx_lm_package`,`string`,`mlx-lm package`,`pip spec for the venv.`,{generatorTypes:S,defaultHint:`mlx-lm==0.31.1`}),j(`runtime`,`mlx_vlm_package`,`string`,`mlx-vlm package`,`pip spec for the venv.`,{generatorTypes:S,defaultHint:`mlx-vlm==0.4.0`}),j(`runtime`,`prefer_providers`,`string-list`,`Preferred providers`,`Overrides the ONNX execution provider order.`,{generatorTypes:_})];function P(e,t){let n=(n,r,i,a,o)=>j(e,n,r,i,a,{generatorTypes:t,...o});return[n(`speculative`,`table`,`Speculative decoding`,`Enable speculative decoding: true, a strategy name, or a table.`),n(`spec_type`,`string`,`Speculative strategy`,`Strategy, such as "draft-mtp".`),n(`spec_draft_n_max`,`integer`,`Draft tokens (max)`,`Max drafted tokens per step.`,{min:0}),n(`spec_draft_n_min`,`integer`,`Draft tokens (min)`,`Min drafted tokens.`,{min:0}),n(`spec_draft_p_min`,`number`,`Draft min probability`,`Min acceptance probability.`),n(`spec_draft_p_split`,`number`,`Draft split threshold`,`Split threshold.`),n(`spec_draft_n_gpu_layers`,`integer`,`Draft GPU layers`,`Draft-model layers offloaded to the GPU (-1 auto, -2 all).`),n(`spec_draft_cache_type_k`,`enum`,`Draft KV cache type (K)`,`Draft-model K-cache dtype.`,{enumValues:D}),n(`spec_draft_cache_type_v`,`enum`,`Draft KV cache type (V)`,`Draft-model V-cache dtype.`,{enumValues:D})]}const F=[j(`runtime.session_cache`,`enabled`,`boolean`,`Session cache`,`Save the KV cache to disk after completions for prompt reuse (ggml-llm).`,{tier:1,defaultHint:`true`}),j(`runtime.session_cache`,`max_size_bytes`,`size`,`Max cache size`,`Disk budget: "10GB", "500MB" or bytes.`,{tier:1,defaultHint:`10GB`}),j(`runtime.session_cache`,`max_entries`,`integer`,`Max entries`,`Cached entry cap.`,{tier:1,min:1,defaultHint:`1000`})],I=[j(`autodiscover`,`enabled`,`boolean`,`LAN discovery`,"The server runs discovery whenever an [autodiscover] table exists; `autodiscover = false` turns it off.",{tier:1,defaultHint:`on while the [autodiscover] table exists`}),j(`autodiscover`,`udp.port`,`integer`,`UDP port`,`Discovery UDP port.`,{tier:1,min:1,max:65535,defaultHint:`8089`}),j(`autodiscover`,`udp.announcements.enabled`,`boolean`,`UDP announcements`,`Announce on the LAN.`,{defaultHint:`true`}),j(`autodiscover`,`udp.announcements.interval`,`integer`,`Announcement interval (ms)`,`Time between announcements.`,{min:1,defaultHint:`5000`}),j(`autodiscover`,`udp.requests.enabled`,`boolean`,`Answer UDP requests`,`Reply to scans.`,{defaultHint:`true`}),j(`autodiscover`,`udp.requests.responseDelay`,`integer`,`Response delay (ms)`,`Delay before replying to a scan.`,{min:0,defaultHint:`100`}),j(`autodiscover`,`http.enabled`,`boolean`,`HTTP info endpoint`,`Serve the info endpoint.`,{defaultHint:`true`}),j(`autodiscover`,`http.path`,`string`,`HTTP info path`,`Path of the info endpoint.`,{defaultHint:`/buttress/info`}),j(`autodiscover`,`http.cors`,`boolean`,`HTTP CORS`,`Allow cross-origin info requests.`,{defaultHint:`true`}),j(`autodiscover`,`mdns.enabled`,`boolean`,`mDNS`,`Bonjour / Avahi advertisement.`,{defaultHint:`false`})],L=(e,t,n)=>[j(e,`enabled`,`boolean`,t,`Serve ${n}.`,{tier:1,defaultHint:`false`}),j(e,`cors_allowed_origins`,`string-list`,`CORS allowed origins`,`"*" or a list of origins; unset keeps browsers blocked.`,{tier:1})],R=[...L(`openai_compat`,`OpenAI-compatible API`,`/oai-compat/v1/*`),...L(`anthropic_messages`,`Anthropic Messages API`,`/anthropic-messages`),...L(`typesafe_compat`,`TypeSafe-compatible API`,`/typesafe-compat/v1/*`)],z=(e,t,n,r,i)=>j(`generator.backend`,e,t,n,r,{tier:1,...i}),B=[z(`variant`,`enum`,`Variant`,`Force a native library variant.`,{generatorTypes:[`ggml-llm`,`ggml-stt`],enumValues:O,defaultHint:`auto`}),z(`variant`,`enum`,`Variant`,`Force a native library variant.`,{generatorTypes:[`ggml-tts`,`ggml-decision`],enumValues:k,defaultHint:`auto`}),z(`variant_preference`,`string-list`,`Variant order`,`Probe order when variant is unset.`,{generatorTypes:[`ggml-llm`,`ggml-stt`],defaultHint:`cuda, vulkan, snapdragon, default`}),z(`variant_preference`,`string-list`,`Variant order`,`Probe order when variant is unset.`,{generatorTypes:[`ggml-tts`,`ggml-decision`],defaultHint:`cuda, vulkan, default`}),z(`gpu_memory_fraction`,`fraction`,`GPU memory fraction`,`Max GPU memory share the hardware guardrails may plan against.`,{generatorTypes:C,defaultHint:`0.85`}),z(`cpu_memory_fraction`,`fraction`,`CPU memory fraction`,`Max RAM share for CPU-side buffers.`,{generatorTypes:C,defaultHint:`0.5`}),z(`share_llm_context`,`boolean`,`Share the LLM context`,`Run decisions on a ggml-llm entry with the same weights instead of loading them again.`,{generatorTypes:x,defaultHint:`false`}),z(`provider`,`enum`,`Execution provider`,`Force an ONNX execution provider.`,{tier:2,generatorTypes:_,enumValues:A,defaultHint:`auto`}),z(`provider_preference`,`string-list`,`Provider order`,`Probe order when provider is unset.`,{tier:2,generatorTypes:_,defaultHint:A.join(`, `)})],V=(e,t,n,r,i)=>j(`generator.model`,e,t,n,r,i),H=[`n_ubatch`,`n_threads`,`n_parallel`,`n_cpu_moe`,`flash_attn_type`,`cache_type_k`,`cache_type_v`,`kv_unified`,`swa_full`,`ctx_shift`,`state_cache_budget_mb`,`state_cache_max_checkpoints`,`use_mmap`,`use_mlock`,`no_extra_bufts`,`cpu_mask`,`cpu_strict`,`devices`,`split_mode`,`tensor_split`],te=[V(`repo_id`,`string`,`Repository`,`HuggingFace repo (org/repo). Required.`,{tier:1,generatorTypes:u.filter(e=>e!==`ggml-stt`)}),V(`repo_id`,`string`,`Repository`,`HuggingFace repo (org/repo).`,{tier:1,generatorTypes:y,defaultHint:`BricksDisplay/whisper-ggml`}),V(`revision`,`string`,`Revision`,`Branch, tag or commit.`,{tier:1,defaultHint:`main`}),V(`download`,`boolean`,`Download at startup`,`Pre-download the model when the server starts.`,{tier:1,defaultHint:`false`}),V(`filename`,`string`,`File`,`Pin a specific artifact in the repo.`,{tier:1,generatorTypes:g}),V(`quantization`,`string`,`Quantization`,`Preferred quant tag, e.g. q4_0, q8_0, mxfp4.`,{tier:1,generatorTypes:g}),V(`url`,`string`,`Download URL`,`Direct download URL; skips the manifest lookup.`,{generatorTypes:g}),V(`preferred_quantizations`,`string-list`,`Quantization fallbacks`,`Ordered fallback list when quantization does not match.`,{generatorTypes:v}),V(`preferred_quantizations`,`string-list`,`Quantization fallbacks`,`Ordered fallback list when quantization does not match.`,{generatorTypes:y,defaultHint:`q8_0, <no-quant>, q5_1`}),V(`preferred_quantizations`,`string-list`,`Quantization fallbacks`,`Ordered fallback list when quantization does not match.`,{generatorTypes:b,defaultHint:`q4_k_m, q8_0, <no-quant>`}),V(`preferred_quantizations`,`string-list`,`Quantization fallbacks`,`Ordered fallback list when quantization does not match.`,{generatorTypes:x,defaultHint:`q8_0, q4_k_m, <no-quant>`}),V(`quantizations`,`string-list`,`Quantization fallbacks (alias)`,`Alias of preferred_quantizations.`,{generatorTypes:g}),V(`allow_local_file`,`boolean`,`Allow local files`,`Required to use local_path and the other *_local_path keys.`,{generatorTypes:g,defaultHint:`false`}),V(`local_path`,`path`,`Local file`,`Load this local file; repo metadata still comes from repo_id.`,{generatorTypes:g}),V(`api_base`,`string`,`HF API base`,`Override the HuggingFace API host (mirror / proxy).`,{generatorTypes:g}),V(`base_url`,`string`,`HF base URL`,`Override the HuggingFace blob host (mirror / proxy).`,{generatorTypes:[...g,..._]}),V(`n_ctx`,`integer`,`Context window`,`Auto-capped at the model training context.`,{tier:1,generatorTypes:v,min:1,defaultHint:`auto · capped at the model training context`}),V(`n_gpu_layers`,`integer`,`GPU layers`,`Layers offloaded to the GPU.`,{generatorTypes:v,enumValues:[`auto`],defaultHint:`auto`}),V(`n_batch`,`integer`,`Batch size`,`Prompt batch size.`,{generatorTypes:v,min:1,defaultHint:`512`}),V(`embedding`,`boolean`,`Embedding mode`,`For a dedicated embedding model.`,{generatorTypes:v,defaultHint:`false`}),V(`pooling_type`,`string`,`Pooling type`,`Embedding pooling override, e.g. mean.`,{generatorTypes:v}),...N.filter(e=>H.includes(e.key)).map(e=>({...e,section:`generator.model`,tier:2,generatorTypes:v})),V(`enable_mtmd`,`boolean`,`Vision (mtmd)`,`Load the matching mmproj projector.`,{tier:1,generatorTypes:v,defaultHint:`false`}),V(`mmproj_filename`,`string`,`Projector file`,`Pin a specific projector file.`,{generatorTypes:[...v,...x]}),V(`mmproj_url`,`string`,`Projector URL`,`Direct projector URL.`,{generatorTypes:[...v,...x]}),V(`mmproj_local_path`,`path`,`Local projector`,`Requires allow_local_file.`,{generatorTypes:[...v,...x]}),V(`mmproj_use_gpu`,`boolean`,`Projector on GPU`,`Unset = on when n_gpu_layers > 0.`,{generatorTypes:v,defaultHint:`auto`}),V(`mmproj_image_min_tokens`,`integer`,`Min visual tokens`,`Dynamic-resolution models; -1 = unset.`,{generatorTypes:v,defaultHint:`-1`}),V(`mmproj_image_max_tokens`,`integer`,`Max visual tokens`,`-1 = unset.`,{generatorTypes:v,defaultHint:`-1`}),V(`model_draft`,`table`,`Draft model`,`Separate GGUF draft model: a URL/path string or a table with repo_id, filename, url, local_path.`,{generatorTypes:v}),...P(`generator.model`,v),V(`use_gpu`,`boolean`,`Use GPU`,`Turn off to keep the model on the CPU.`,{tier:1,generatorTypes:[...y,...b,...x],defaultHint:`true`}),V(`use_flash_attn`,`enum`,`Flash attention`,`"auto" enables it when the GPU is in use; true / false are accepted for "on" / "off".`,{tier:1,generatorTypes:y,enumValues:T,defaultHint:`auto`}),V(`engine`,`enum`,`Engine`,`Speech engine; detected from the repo and file names.`,{generatorTypes:y,enumValues:[`whisper`,`parakeet`],defaultHint:`auto`}),V(`n_gpu_layers`,`integer`,`GPU layers`,`Forced to 0 when the GPU is unused.`,{generatorTypes:[...b,...x],defaultHint:`99`}),V(`vocoder_repo_id`,`string`,`Codec repository`,`Repo holding the codec GGUF.`,{tier:1,generatorTypes:[...b,`onnx-tts`],defaultHint:`same as repo_id`}),V(`vocoder_filename`,`string`,`Codec file`,`Pin a specific codec artifact.`,{tier:1,generatorTypes:b,defaultHint:`auto`}),V(`vocoder_url`,`string`,`Codec URL`,`Direct codec URL.`,{generatorTypes:b}),V(`vocoder_revision`,`string`,`Codec revision`,`Falls back to revision.`,{generatorTypes:b}),V(`vocoder_local_path`,`path`,`Local codec`,`Requires allow_local_file.`,{generatorTypes:b}),V(`sample_rate`,`integer`,`Sample rate`,`Fallback only; the codec reports the real rate.`,{generatorTypes:b,min:1,defaultHint:`24000`}),V(`mmproj_repo_id`,`string`,`Projector repository`,`For models whose prompt takes images.`,{generatorTypes:x,defaultHint:`same as repo_id`}),V(`mmproj_revision`,`string`,`Projector revision`,`Falls back to revision.`,{generatorTypes:x}),V(`rank_pooling`,`boolean`,`Rank pooling`,`system_one models with a classification head (rank_head readout).`,{generatorTypes:x,defaultHint:`false`}),V(`vlm`,`boolean`,`Vision model`,`"auto" infers it from the repo.`,{tier:1,generatorTypes:S,enumValues:[`auto`],defaultHint:`auto`}),V(`adapter_path`,`path`,`LoRA adapter`,`Local LoRA adapter directory.`,{generatorTypes:S}),V(`tokenizer_config`,`table`,`Tokenizer config`,`Forwarded to mlx_lm.load.`,{generatorTypes:S}),V(`model_config`,`table`,`Model config`,`Forwarded to mlx_lm.load.`,{generatorTypes:S}),V(`task`,`string`,`Task`,`transformers.js pipeline task.`,{generatorTypes:_}),V(`device`,`string`,`Device`,`transformers.js device.`,{generatorTypes:_}),V(`dtype`,`string`,`Data type`,`Weight dtype.`,{generatorTypes:_,defaultHint:`auto`})],ne=[...N.map(e=>({...e,section:`generator.runtime`,tier:2})),j(`generator.runtime`,`session_cache`,`table`,`Session cache`,`Overrides [runtime.session_cache].`)],re=[...ee,...N,...F,...I,...R,...B,...te,...ne];r.enum(u),new Set(re.filter(e=>e.section===`generator.backend`).map(e=>e.key));const U=(e={},t={})=>{let n=Array.isArray(e)?[...e]:{...e};return Object.entries(t||{}).forEach(([e,t])=>{t&&typeof t==`object`&&!Array.isArray(t)?n[e]=U(n[e]||{},t):n[e]=t}),n},W=e=>e&&typeof e==`object`?structuredClone(e):null,ie=(e,t)=>{let n=W(e)||{},r=W(t)||{};return U(n,r)},G=(e,t)=>U(structuredClone(e.global),t||{}),ae=(e,t,n,r)=>{if(e.generators.length>0){let i=e.generators.filter(e=>e?.type===n);if(i.length>0&&r){let a=i.find(e=>t.getModelIdentifier(n,e)===r);if(a)return G(e,a)}}return Object.keys(e.global).length>0?G(e,{}):null},K={udp:{port:8089,announcements:{enabled:!0,interval:5e3},requests:{enabled:!0,responseDelay:100}},http:{enabled:!0,path:`/buttress/info`,cors:!0}},oe=e=>e?e===!0?{...K}:U(K,e):null,se=(e,t)=>{if(!e.generators||e.generators.length===0)return t.map(e=>({type:e}));let n=new Set;return e.generators.forEach(e=>{e.type&&n.add(e.type)}),n.size===0?t.map(e=>({type:e})):Array.from(n).map(e=>({type:e}))},q=(e,t,n)=>e===void 0?n:typeof e==`number`?e:t(e)??n,J=6e4,Y=1024*1024*50,ce=r=>{let o=a.machineIdSync(),s={server:{id:f(o),name:p(o),port:d,temp_file_dir:e.join(t.tmpdir(),`.buttress`),session_timeout:J,max_body_size:Y},autodiscover:!1},c=U(s,W(r)||{}),l=Array.isArray(c.generators)?h(c.generators):[],{server:u,generators:m,autodiscover:g,..._}=c;return{autodiscover:oe(g),server:{id:u.id,name:u.name,port:u.port,log_level:u.log_level,temp_file_dir:u.temp_file_dir,max_body_size:q(u.max_body_size,n.parse,Y),session_timeout:q(u.session_timeout,e=>i(e),J)},global:_,generators:l}},X=/^[A-Za-z0-9_-]{1,64}$/,Z=n=>n===`~`||n.startsWith(`~/`)?e.join(t.homedir(),n.slice(1)):n;var Q=class extends Error{constructor(e){super(`[Agents] ${e}`),this.name=`AgentsConfigError`}};const le=(e,t,n)=>{if(t==null)return n;if(t===0||t===!1)return null;if(typeof t==`number`){if(Number.isFinite(t)&&t>0)return t}else if(typeof t==`string`){let e;try{e=i(t)}catch{e=void 0}if(typeof e==`number`&&e>0)return e}throw new Q(`agents_options.${e} must be a duration string (e.g. "30d") or a positive number of milliseconds; use 0 to disable it`)},$=[`direct`,`codemode`,`deferred`,`hidden`],ue=new Set([`codemode`,`deferred`]),de=(e,t,n)=>{if(t==null)return{};if(typeof t!=`object`||Array.isArray(t))throw new Q(`agent "${e}": mcp_servers must be a table`);let r={};for(let[i,a]of Object.entries(t)){if(!X.test(i))throw new Q(`agent "${e}": MCP server name "${i}" must match ${X}`);let t=!!(typeof a?.url==`string`&&a.url),o=!!(typeof a?.command==`string`&&a.command);if(t===o)throw new Q(`agent "${e}": MCP server "${i}" needs exactly one of url / command`);let s=`agent "${e}": MCP server "${i}"`;if(a?.timeout!=null&&!(typeof a.timeout==`number`&&a.timeout>0))throw new Q(`${s}: timeout must be a positive number of seconds`);let c=a?.tool_exposure;if(c!=null&&(typeof c!=`object`||Array.isArray(c)))throw new Q(`${s}: tool_exposure must map tool names to exposures`);for(let e of[a?.exposure,...Object.values(c??{})]){if(e!=null&&!$.includes(e))throw new Q(`${s}: exposure must be one of ${$.map(e=>`"${e}"`).join(`, `)}`);if(!n&&ue.has(e))throw new Q(`${s}: exposure "${e}" needs codemode = true on the agent`)}r[i]={url:t?a.url:void 0,headers:a?.headers&&typeof a.headers==`object`?a.headers:void 0,command:o?a.command:void 0,args:Array.isArray(a?.args)?a.args.map(String):void 0,env:a?.env&&typeof a.env==`object`?a.env:void 0,optional:a?.optional===!0,timeout:a?.timeout??void 0,exposure:a?.exposure??void 0,toolExposure:c??void 0}}return r},fe=(e,t,n)=>{let r=e?.name;if(typeof r!=`string`||!X.test(r))throw new Q(`[[agents]] #${t+1}: name is required and must match ${X}`);let i=e?.model;if(typeof i!=`string`||!i.includes(`/`))throw new Q(`agent "${r}": model must be "provider/model-id" (e.g. "buttress/ggml-org/gpt-oss-20b-GGUF")`);let a=i.indexOf(`/`),s=i.slice(0,a),c=i.slice(a+1);if(!s||!c)throw new Q(`agent "${r}": invalid model reference "${i}"`);if(s===`buttress`&&!n.generators.filter(e=>e.type===`ggml-llm`||e.type===`mlx-llm`).some(e=>(e.model?.repo_id||e.model?.repository)===c))throw new Q(`agent "${r}": model "${c}" does not match any configured [[generators]] ggml-llm/mlx-llm repo_id`);if(e?.system_prompt!=null&&e?.system_prompt_file!=null)throw new Q(`agent "${r}": set system_prompt or system_prompt_file, not both`);let l=[];if(e?.tools!=null){if(!Array.isArray(e.tools))throw new Q(`agent "${r}": tools must be an array of function names`);for(let t of e.tools){if(typeof t!=`string`||!X.test(t))throw new Q(`agent "${r}": tool name "${t}" must match ${X} (local function names only)`);if(l.includes(t))throw new Q(`agent "${r}": duplicate tool "${t}"`);l.push(t)}}if(e?.local_devices!==void 0&&typeof e.local_devices!=`boolean`)throw new Q(`agent "${r}": local_devices must be a boolean`);if(e?.codemode!==void 0&&typeof e.codemode!=`boolean`)throw new Q(`agent "${r}": codemode must be a boolean`);let u=Number(e?.max_turns??30);if(!Number.isInteger(u)||u<1)throw new Q(`agent "${r}": max_turns must be a positive integer`);let d=null;if(e?.max_tokens_per_run!=null&&(d=Number(e.max_tokens_per_run),!Number.isInteger(d)||d<1))throw new Q(`agent "${r}": max_tokens_per_run must be a positive integer`);let f=null;if(e?.decision_model!=null&&e.decision_model!==``){let t=e.decision_model,i=typeof t==`string`?t.indexOf(`/`):-1;if(i<=0||i===t.length-1)throw new Q(`agent "${r}": decision_model must be "provider/model-id" (e.g. "buttress/<ggml-decision id>" or "typesafe/jev-latest")`);if(f={provider:t.slice(0,i),modelId:t.slice(i+1),modelRef:t},f.provider===`buttress`){let e=n.generators.filter(e=>e.type===`ggml-decision`).map(o);if(!e.includes(f.modelId))throw new Q(`agent "${r}": decision_model "${f.modelId}" does not match any configured ggml-decision generator (${e.join(`, `)||`none`})`)}}if(e?.decision_assistance!==void 0&&typeof e.decision_assistance!=`boolean`)throw new Q(`agent "${r}": decision_assistance must be a boolean`);if(e?.decision_assistance===!0&&!f)throw new Q(`agent "${r}": decision_assistance needs a decision_model`);let p=e?.decision_timeout_ms??500;if(!Number.isInteger(p)||p<1)throw new Q(`agent "${r}": decision_timeout_ms must be a positive integer`);let{name:m,model:h,system_prompt:g,system_prompt_file:_,tools:v,local_devices:y=!1,codemode:b=!1,mcp_servers:x,max_turns:S,max_tokens_per_run:C,thinking:w,decision_model:T,decision_assistance:E=!1,decision_timeout_ms:D,...O}=e;return{name:r,provider:s,modelId:c,modelRef:i,systemPrompt:typeof g==`string`?g:null,systemPromptFile:typeof _==`string`?_:null,tools:l,localDevices:y,codemode:b,mcpServers:de(r,x,b),maxTurns:u,maxTokensPerRun:d,thinking:typeof w==`string`?w:void 0,decisionModel:f,decisionAssistance:E,decisionTimeoutMs:p,generation:O}},pe=(t,{configDir:n=process.cwd()}={})=>{let r=t.global||{},i=r.agents;if(i==null)return null;if(!Array.isArray(i))throw new Q(`agents must be an array of tables ([[agents]])`);if(i.length===0)return null;let a=i.map((e,n)=>fe(e,n,t)),o=new Set;for(let e of a){if(o.has(e.name))throw new Q(`duplicate agent name "${e.name}"`);o.add(e.name)}let s=r.agents_options||{},c=typeof s.sessions_dir==`string`&&s.sessions_dir?s.sessions_dir:`./.buttress-agent/sessions`,l=Z(c),u=e.isAbsolute(l)?l:e.resolve(n,l);for(let t of a)if(t.systemPromptFile){let r=Z(t.systemPromptFile);t.systemPromptFile=e.isAbsolute(r)?r:e.resolve(n,r)}let d=Number(s.max_depth??2);if(!Number.isInteger(d)||d<1)throw new Q(`agents_options.max_depth must be a positive integer`);let f=s.session_max_count,p=500;if(f===0||f===!1)p=null;else if(f!=null&&(p=Number(f),!Number.isInteger(p)||p<1))throw new Q(`agents_options.session_max_count must be a positive integer`);return{agents:a,configDir:n,sessionsDir:u,runtimeTokenFile:e.join(e.dirname(u),`runtime-token`),sessionMaxAgeMs:le(`session_max_age`,s.session_max_age,2592e6),sessionMaxCount:p,maxDepth:d,allowUnauthenticated:s.allow_unauthenticated===!0}};export{ce as a,d as c,o as d,s as f,W as i,m as l,pe as n,ae as o,c as p,ie as r,se as s,Q as t,l as u};
|