coding-agents-sdk 0.15.0 → 0.16.0
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 +46 -0
- package/dist/Agent-BjaeRtLk.mjs +4 -0
- package/dist/adapters/claude-code-cli/index.d.mts +2 -2
- package/dist/adapters/claude-code-cli/index.mjs +1 -1
- package/dist/adapters/claude-code-cli-pty/index.d.mts +2 -2
- package/dist/adapters/claude-code-cli-pty/index.mjs +2 -2
- package/dist/adapters/claude-code-sdk/index.d.mts +1 -1
- package/dist/adapters/codex-cli/index.d.mts +2 -2
- package/dist/adapters/codex-cli/index.mjs +2 -2
- package/dist/adapters/codex-sdk/index.d.mts +1 -1
- package/dist/adapters/cursor-cli/index.d.mts +1 -1
- package/dist/adapters/cursor-cli/index.mjs +1 -1
- package/dist/adapters/cursor-sdk/index.d.mts +1 -1
- package/dist/adapters/gemini-cli/index.d.mts +1 -1
- package/dist/adapters/gemini-cli/index.mjs +1 -1
- package/dist/adapters/opencode-cli/index.d.mts +1 -1
- package/dist/adapters/opencode-cli/index.mjs +1 -1
- package/dist/adapters/pi-cli/index.d.mts +1 -1
- package/dist/adapters/pi-cli/index.mjs +1 -1
- package/dist/container/index.d.mts +1 -1
- package/dist/container/index.mjs +1 -1
- package/dist/{container-B2i85Vkf.mjs → container-Bdb90GJb.mjs} +1 -1
- package/dist/{container-Dk4QgU9G.mjs → container-DMFxf-kn.mjs} +1 -1
- package/dist/{container-CbvaYn8K.mjs → container-Dvr-p53c.mjs} +1 -1
- package/dist/{container-BwDinlQ1.mjs → container-dCRMBvQw.mjs} +1 -1
- package/dist/container-w0rl1QMH.mjs +1 -0
- package/dist/core/process/index.d.mts +3 -0
- package/dist/core/process/index.mjs +1 -0
- package/dist/diff-Dqyk2cdt.mjs +1 -0
- package/dist/errors-aYGbvsaq.mjs +1 -0
- package/dist/index-65Dv7ed0.d.mts +415 -0
- package/dist/{index-gtpzhLCF.d.mts → index-BbZPkmE-.d.mts} +4 -3
- package/dist/{index-C09YdI2A.d.mts → index-Bi9Dh34t.d.mts} +4 -4
- package/dist/{index-D3yvIIre.d.mts → index-BiUoRRsR.d.mts} +4 -3
- package/dist/{index-CT-rhJzK.d.mts → index-CN0WGc9T.d.mts} +3 -2
- package/dist/{index-BXgvYZSv.d.mts → index-CQzF8Cli.d.mts} +1 -1
- package/dist/{index-CGGPY1qE.d.mts → index-CZbgTv8P.d.mts} +1 -1
- package/dist/{index-Dm9HCmWK.d.mts → index-CjjUmMwQ.d.mts} +1 -1
- package/dist/{index-DGY0wFGC.d.mts → index-CyIiBK-O.d.mts} +130 -4
- package/dist/{index-D_qqPXPO.d.mts → index-DmpVdnKm.d.mts} +4 -3
- package/dist/index-DvwVRB7K.d.mts +10 -0
- package/dist/{index-WaVqMCYN.d.mts → index-kXfBtyJn.d.mts} +2 -1
- package/dist/{index-BkIhoEPd.d.mts → index-m5Pqs8Jz.d.mts} +4 -3
- package/dist/index.d.mts +16 -14
- package/dist/index.mjs +1 -1
- package/dist/oci-DTNwW-WH.mjs +1 -0
- package/dist/{parser-15-5gbtk.mjs → parser-C1kvDtRD.mjs} +1 -1
- package/dist/sandbox/index.d.mts +1 -1
- package/dist/sandbox/index.mjs +1 -1
- package/dist/{sandbox-CoV-gBuM.mjs → sandbox-CYA69miM.mjs} +1 -1
- package/dist/spawner-CgfyvnR4.mjs +1 -0
- package/dist/{types-CeIQCAFV.d.mts → types-Ba2NYJOB.d.mts} +10 -57
- package/dist/types-COmjfh8B.d.mts +57 -0
- package/package.json +5 -1
- package/dist/Agent-mSH_-Sf8.mjs +0 -4
- package/dist/container-DfDs2Bmh.mjs +0 -1
- package/dist/diff-C60ujrU_.mjs +0 -1
- package/dist/index-fZiuDQFa.d.mts +0 -154
- package/dist/oci-BvdPJQRS.mjs +0 -1
- package/dist/spawner-BE2hAC0w.mjs +0 -1
package/README.md
CHANGED
|
@@ -120,6 +120,8 @@ TypeScript infers the completed-result shape from your request:
|
|
|
120
120
|
|
|
121
121
|
Most calls just use a string. If you need richer input, pass parts instead.
|
|
122
122
|
|
|
123
|
+
`claude-code-cli` and `codex-cli` send prompt text through stdin rather than command-line arguments, including when resuming a session.
|
|
124
|
+
|
|
123
125
|
Image input is currently supported by `codex-sdk` and `pi-cli`.
|
|
124
126
|
|
|
125
127
|
```ts
|
|
@@ -206,6 +208,50 @@ unsubscribe();
|
|
|
206
208
|
|
|
207
209
|
All adapters emit `session-start` and `session-end`. Depending on the backend, you may also see `message`, `reasoning`, `tool-call`, `tool-result`, and `stderr`.
|
|
208
210
|
|
|
211
|
+
### Provider events
|
|
212
|
+
|
|
213
|
+
Use `onProviderEvent()` on `claude-code-cli` or `codex-cli` for provider-specific details not included in normalized events.
|
|
214
|
+
|
|
215
|
+
```ts
|
|
216
|
+
import { createClaudeCodeCliAgent } from "coding-agents-sdk/adapters/claude-code-cli";
|
|
217
|
+
|
|
218
|
+
await using claude = createClaudeCodeCliAgent();
|
|
219
|
+
const unsubscribe = claude.onProviderEvent(({ runId, sessionId, event }) => {
|
|
220
|
+
if (event.type === "system" && event.subtype === "init") {
|
|
221
|
+
console.log(runId, sessionId, event.tools, event.mcp_servers);
|
|
222
|
+
}
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
await claude.run({ input: "Explain the package layout." });
|
|
226
|
+
unsubscribe();
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
For Codex, import `createCodexCliAgent` from `coding-agents-sdk/adapters/codex-cli`.
|
|
230
|
+
|
|
231
|
+
Provider events are not stored in `RunResult.events`; collect them in your callback if needed. Subscriptions persist across runs and `reset()`. Subscribe separately on forked agents.
|
|
232
|
+
|
|
233
|
+
## Custom process launchers
|
|
234
|
+
|
|
235
|
+
Wrap `spawnProcess` with a `ProcessSpawner` to customize how a CLI agent launches:
|
|
236
|
+
|
|
237
|
+
```ts
|
|
238
|
+
import { spawnProcess, type ProcessSpawner } from "coding-agents-sdk/process";
|
|
239
|
+
|
|
240
|
+
const spawner: ProcessSpawner = {
|
|
241
|
+
spawn(command, args, options) {
|
|
242
|
+
const child = spawnProcess(command, args, options);
|
|
243
|
+
console.log("Agent process launched");
|
|
244
|
+
return child;
|
|
245
|
+
},
|
|
246
|
+
};
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
Pass `spawner` when creating a CLI agent. For `claude-code-cli` and `codex-cli`, the returned process must provide `stdin.write` and `stdin.end`.
|
|
250
|
+
|
|
251
|
+
Stdin methods may complete synchronously or return `Promise<void>`; agents await their completion. Built-in spawners observe rejected write/EOF promises and retain the failure for `wait()`, so ignoring an operation's return value does not create a separate unhandled rejection.
|
|
252
|
+
|
|
253
|
+
Stdin failures reported by `wait()` use `ProcessStdinError`, exported from the root and `coding-agents-sdk/process`, with the original error in `cause`. Custom spawners should use this error for that case so agents distinguish delivery failures from launch failures. Awaiting a built-in stdin operation still rejects with its original error.
|
|
254
|
+
|
|
209
255
|
## MCP
|
|
210
256
|
|
|
211
257
|
MCP tool calls can show up in the event stream when the underlying runtime supports them.
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{t as e}from"./util-B4HTdOSc.mjs";import{t}from"./env-Cb8MIvH7.mjs";import{t as n}from"./errors-aYGbvsaq.mjs";import{t as r}from"./spawner-CgfyvnR4.mjs";import{a as i,i as a,n as o,s,t as c}from"./classify-error-DOqkMCcy.mjs";import{dirname as l}from"node:path";import{createWriteStream as u,mkdirSync as d}from"node:fs";async function*f(e){let t=new TextDecoder,n=``;for await(let r of e){let e=t.decode(r,{stream:!0});n+=e;let i=n.split(`
|
|
2
|
+
`);n=i.pop()??``;for(let e of i){let t=e.trim();t&&(yield t)}}let r=t.decode();r&&(n+=r);let i=n.trim();i&&(yield i)}const p=t=>t.status===`rejected`?e(t.reason):void 0,m=(t,r)=>{if(t.stopReason)return;if(r.processResult.status===`rejected`){let t=r.processResult.reason;return{kind:t instanceof n?`process`:`spawn`,message:e(t)}}let a=p(r.stdinResult);if(a)return{kind:`process`,message:a};let o=p(r.stdoutResult);if(o)return{kind:`process`,message:o};let s=p(r.stderrResult);if(s)return{kind:`process`,message:s};if(!t.status&&!t.error){let e=t.processResult,n=t.stderrLines.join(`
|
|
3
|
+
`);if(e&&e.exitCode!==null&&e.exitCode!==0)return{kind:`process`,message:n||`Process exited with code ${e.exitCode}.`};if(!i(t)&&t.stderrLines.length>0)return{kind:`process`,message:n}}},h=e=>{let t=c(e);return t.kind===`provider`?{kind:`process`,message:t.message}:t};var g=class extends o{spawner;defaults;executionTargetRef;providerHandlers=/* @__PURE__ */ new Set;logStream;sigkillTimer;constructor(e){super({type:e.type,capabilities:e.capabilities,sessionId:e.defaults?.sessionId,onEvent:e.onEvent}),this.spawner=e.spawner??r,this.defaults=e.defaults??{},this.executionTargetRef=e.executionTarget,e.onProviderEvent&&this.onProviderEvent(e.onProviderEvent),e.logPath&&this.initLogStream(e.logPath)}onProviderEvent(e){return this.providerHandlers.add(e),()=>{this.providerHandlers.delete(e)}}get hasProviderEventListeners(){return this.providerHandlers.size>0}emitProviderEvent(e,t,n=t.sessionId){if(!this.hasProviderEventListeners)return;let r={agentType:this.type,runId:t.runId,sessionId:n,timestamp:/* @__PURE__ */ new Date,event:e};for(let e of this.providerHandlers)try{e(r)}catch(e){this.onHandlerError(e)}}getStdinInput(e){}onParseError(t,n){this.appendRawLog(`[parse-error] ${e(n)} ${t.slice(0,200)}`)}buildDefaultEnv(e){let n=t({propagateEnv:e});return n.CI=n.CI??`true`,this.defaults.env&&Object.assign(n,this.defaults.env),n}async executeRunCore(t,n){let r=this.setupRunLifecycle(t);try{if(r.abortedBeforeStart)return this.buildResult(t,/* @__PURE__ */ new Date);try{await this.onBeforeRun(t);let e={...n,...t.normalizedRequest},r=this.buildArgs(e,t),i=this.buildEnv(e,t),a=this.defaults.command?.[0]??`claude`,o=[...this.defaults.command?.slice(1)??[],...r];if(t.stopReason)return this.buildResult(t,/* @__PURE__ */ new Date);t.sessionId&&this.emitSessionStart(t),t.process=this.spawner.spawn(a,o,{cwd:t.normalizedRequest.cwd,env:i,stdio:[`pipe`,`pipe`,`pipe`]});let[s,c,l,u]=await Promise.allSettled([this.watchStdout(t),this.watchStderr(t),t.process.wait(),this.deliverInput(t.process,this.getStdinInput(e))]);l.status===`fulfilled`&&(t.processResult=l.value);let d=m(t,{stdoutResult:s,stderrResult:c,processResult:l,stdinResult:u});d&&(t.error=d)}catch(e){!t.stopReason&&!t.error&&(t.error=h(e))}return this.buildResult(t,/* @__PURE__ */ new Date)}finally{r.cleanup(),this.sigkillTimer&&=(clearTimeout(this.sigkillTimer),void 0);try{await this.onRunFinished(t)}catch(t){this.appendRawLog(`[cleanup-error] ${e(t)}`)}}}async watchStdout(e){let t=e.process?.stdout;if(t)for await(let n of f(t))this.appendLog(`stdout`,n),this.processLine(e,n)}async deliverInput(e,t){try{if(t!==void 0){if(!e.stdin?.write)throw Error(`The process spawner must provide a stdin writer for this adapter.`);await e.stdin.write(t)}await e.stdin?.end()}catch(t){throw e.kill(`SIGKILL`),t}}async watchStderr(e){let t=e.process?.stderr;if(t)for await(let n of f(t))this.appendLog(`stderr`,n),e.stderrLines.push(n),this.emit(e,s(e.runId,`stderr`,{sessionId:e.sessionId,text:n}))}processLine(e,t){let n;try{n=JSON.parse(t)}catch(e){this.onParseError(t,e);return}let r;try{r=this.mapRawEvent(n,a(e))}catch(e){this.onParseError(t,e);return}this.applyBatch(e,r)}get runRequestDefaults(){return this.defaults}onHandlerError(t){this.appendRawLog(`[handler-error] ${e(t)}`)}async onDispose(){this.providerHandlers.clear();let e=this.logStream;this.logStream=void 0,e&&await new Promise(t=>{e.end(t)})}onStopRequested(e){e.process?.kill(),this.sigkillTimer=setTimeout(()=>{e.process?.kill(`SIGKILL`)},5e3),this.sigkillTimer.unref?.()}onBeforeRun(e){return this.ensureExecutionTarget()}async onRunFinished(e){}appendRawLog(e){if(!this.logStream)return;let t=typeof e==`string`?e:JSON.stringify(e);this.logStream.write(`${t}\n`)}initLogStream(e){try{d(l(e),{recursive:!0}),this.logStream=u(e,{flags:`a`}),this.logStream.write(`\n--- ${(/* @__PURE__ */ new Date()).toISOString()} ---\n`)}catch{this.logStream=void 0}}appendLog(e,t){if(!this.logStream||!t)return;let n=e===`stderr`?`STDERR`:`STDOUT`,r=(/* @__PURE__ */ new Date()).toISOString();for(let e of t.split(`
|
|
4
|
+
`))e&&this.logStream.write(`[${r}] ${n} ${e}\n`)}async ensureExecutionTarget(){this.executionTargetRef&&this.executionTargetRef.status!==`running`&&await this.executionTargetRef.start()}};export{g as t};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as ClaudeCodeCliRunOptions, c as
|
|
2
|
-
export { type ClaudeAssistantEvent, type ClaudeCodeCliAgent, type ClaudeCodeCliAgentOptions, type ClaudeCodeCliPermissionMode, type ClaudeCodeCliRunOptions, type ClaudeEvent, type ClaudeRateLimitEvent, type ClaudeResultEvent, type ClaudeSystemEvent, type ClaudeUserEvent, createClaudeCodeCliAgent };
|
|
1
|
+
import { a as ClaudeCodeCliRunOptions, c as ClaudeProviderEvent, d as ClaudeSystemEvent, f as ClaudeUserEvent, i as ClaudeCodeCliPermissionMode, l as ClaudeRateLimitEvent, n as ClaudeCodeCliAgent, o as ClaudeAssistantEvent, r as ClaudeCodeCliAgentOptions, s as ClaudeEvent, t as createClaudeCodeCliAgent, u as ClaudeResultEvent } from "../../index-CyIiBK-O.mjs";
|
|
2
|
+
export { type ClaudeAssistantEvent, type ClaudeCodeCliAgent, type ClaudeCodeCliAgentOptions, type ClaudeCodeCliPermissionMode, type ClaudeCodeCliRunOptions, type ClaudeEvent, type ClaudeProviderEvent, type ClaudeRateLimitEvent, type ClaudeResultEvent, type ClaudeSystemEvent, type ClaudeUserEvent, createClaudeCodeCliAgent };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e}from"../../types-B72tDMEZ.mjs";import{a as t}from"../../util-B4HTdOSc.mjs";import{t as n}from"../../env-Cb8MIvH7.mjs";import{l as r}from"../../classify-error-DOqkMCcy.mjs";import{t as i}from"../../execution-target-CdlYXh6Z.mjs";import{i as a,n as o,t as s}from"../../session-markers-Dt7TWdKY.mjs";import{
|
|
1
|
+
import{n as e}from"../../types-B72tDMEZ.mjs";import{a as t}from"../../util-B4HTdOSc.mjs";import{t as n}from"../../env-Cb8MIvH7.mjs";import{l as r}from"../../classify-error-DOqkMCcy.mjs";import{t as i}from"../../execution-target-CdlYXh6Z.mjs";import{i as a,n as o,t as s}from"../../session-markers-Dt7TWdKY.mjs";import{i as c,n as l,r as u,t as d}from"../../parser-C1kvDtRD.mjs";import{t as f}from"../../Agent-BjaeRtLk.mjs";import{join as p}from"node:path";import{mkdtempSync as m,rmSync as h,writeFileSync as g}from"node:fs";import{tmpdir as _}from"node:os";import{rm as v}from"node:fs/promises";import{createServer as y}from"node:http";const b=`coding_agents_permission_bridge`,x=`permission_prompt`,S=e=>typeof e==`object`&&!!e&&!Array.isArray(e),C=e=>typeof e==`number`||typeof e==`string`||e===null,w=e=>{if(S(e)&&typeof e.method==`string`&&e.method.length!==0)return{id:C(e.id)?e.id:null,method:e.method,params:e.params}},T=async e=>{let t=[];for await(let n of e)t.push(Buffer.isBuffer(n)?n:Buffer.from(n));if(t.length!==0)try{return w(JSON.parse(Buffer.concat(t).toString(`utf8`)))}catch{return}},E=(e,t)=>{e.writeHead(200,{"content-type":`application/json`}),e.end(JSON.stringify(t))},D=(e,t,n,r)=>{E(e,{jsonrpc:`2.0`,id:t,error:{code:n,message:r}})},O=(e,t)=>e.decision===`allow`?{behavior:`allow`,updatedInput:e.updatedInput??t}:{behavior:`deny`,message:e.message??`Tool call denied.`},k=async({handler:e,signal:t})=>{let n=y(async(n,r)=>{if(n.method!==`POST`){r.writeHead(405).end();return}let i=await T(n);if(!i){r.writeHead(400).end();return}let a=i.id;if(i.method===`initialize`){E(r,{jsonrpc:`2.0`,id:a,result:{protocolVersion:`2025-03-26`,capabilities:{tools:{}},serverInfo:{name:b,version:`1.0.0`}}});return}if(i.method.startsWith(`notifications/`)){r.writeHead(202).end();return}if(i.method===`tools/list`){E(r,{jsonrpc:`2.0`,id:a,result:{tools:[{name:x,description:`Forward Claude Code permission prompts to the host agent's handler.`,inputSchema:{type:`object`,properties:{tool_name:{type:`string`},input:{type:`object`},tool_use_id:{type:`string`}},required:[`tool_name`,`input`,`tool_use_id`]}}]}});return}if(i.method===`tools/call`){if(!S(i.params)){D(r,a,-32600,`tools/call params must be an object.`);return}let n=i.params;if(n.name!==x){D(r,a,-32602,`Unknown tool: ${String(n.name)}`);return}if(!S(n.arguments)){D(r,a,-32600,`permission_prompt arguments must be an object.`);return}let o=n.arguments;if(typeof o.tool_name!=`string`||o.tool_name.length===0){D(r,a,-32600,`permission_prompt.tool_name must be a non-empty string.`);return}if(!S(o.input)){D(r,a,-32600,`permission_prompt.input must be an object.`);return}if(typeof o.tool_use_id!=`string`||o.tool_use_id.length===0){D(r,a,-32600,`permission_prompt.tool_use_id must be a non-empty string.`);return}try{let n=await e({toolName:o.tool_name,input:o.input,toolUseId:o.tool_use_id,signal:t}),i=O(n,o.input);E(r,{jsonrpc:`2.0`,id:a,result:{content:[{type:`text`,text:JSON.stringify(i)}]}})}catch(e){let t=e instanceof Error?e.message:String(e);E(r,{jsonrpc:`2.0`,id:a,result:{content:[{type:`text`,text:JSON.stringify({behavior:`deny`,message:t})}],isError:!0}})}return}D(r,a,-32601,`Method not found: ${i.method}`)});return await new Promise((e,t)=>{n.once(`error`,t),n.listen(0,`127.0.0.1`,()=>{n.removeListener(`error`,t),e()})}),{url:`http://127.0.0.1:${n.address().port}/mcp`,serverName:b,toolName:`mcp__${b}__${x}`,dispose:()=>new Promise(e=>{n.close(()=>e())})}},A={structuredOutput:!0,sessionResume:!0,imageInput:!1,mcp:!0,eventStreaming:!0,sessionFork:!0,permissionRequests:!0};var j=class i extends f{type=`claude-code-cli`;creationOptions;runDefaults;forkOnNextRun;mcpTempDir;activeBridge;constructor(e={}){super({type:`claude-code-cli`,capabilities:A,defaults:{cwd:e.cwd,env:e.env,command:e.command?t(e.command):void 0,sessionId:e.sessionId,model:e.model,systemPrompt:e.systemPrompt},spawner:e.spawner,executionTarget:e.container??e.sandbox,logPath:e.logPath,onEvent:e.onEvent,onProviderEvent:e.onProviderEvent}),this.creationOptions={...e,command:e.command?[...t(e.command)]:void 0,env:e.env?{...e.env}:void 0,allowedTools:e.allowedTools?[...e.allowedTools]:void 0,disallowedTools:e.disallowedTools?[...e.disallowedTools]:void 0,mcpConfig:Array.isArray(e.mcpConfig)?[...e.mcpConfig]:e.mcpConfig,mcpServers:e.mcpServers?{...e.mcpServers}:void 0,extraArgs:e.extraArgs?[...e.extraArgs]:void 0},this.runDefaults={allowedTools:e.allowedTools?[...e.allowedTools]:void 0,disallowedTools:e.disallowedTools?[...e.disallowedTools]:void 0,appendSystemPrompt:e.appendSystemPrompt,permissionMode:e.permissionMode,mcpConfig:Array.isArray(e.mcpConfig)?[...e.mcpConfig]:e.mcpConfig,mcpServers:e.mcpServers?{...e.mcpServers}:void 0,forkSession:e.forkSession,extraArgs:e.extraArgs?[...e.extraArgs]:void 0},this.forkOnNextRun=e.forkOnNextRun??!1}fork(){if(!this.sessionId)throw new e(`Cannot fork a Claude Code CLI agent before it has a sessionId.`);return new i({...this.creationOptions,sessionId:this.sessionId,forkSession:void 0,forkOnNextRun:!0,onProviderEvent:void 0})}onValidateRun(t,n){if((t.forkSession??this.runDefaults.forkSession??this.forkOnNextRun)&&!this.sessionId)throw new e(`forkSession requires an existing sessionId on the agent.`)}async onBeforeRun(t){await super.onBeforeRun(t);let n=this.getPermissionHandler();if(!n)return;if(this.creationOptions.container)throw new e(`onPermissionRequest is not supported when running claude-code-cli inside a container: the in-process MCP bridge listens on host loopback and is unreachable from the container's network namespace.`);let r=t.normalizedRequest.signal??new AbortController().signal;this.activeBridge=await k({handler:n,signal:r})}async onRunFinished(e){await super.onRunFinished(e),await this.cleanupMcpTempDir(),await this.disposeBridge()}async onDispose(){await super.onDispose(),await this.cleanupMcpTempDir(),await this.disposeBridge()}async disposeBridge(){if(!this.activeBridge)return;let e=this.activeBridge;this.activeBridge=void 0,await e.dispose().catch(()=>{})}async cleanupMcpTempDir(){if(this.mcpTempDir){let e=this.mcpTempDir;this.mcpTempDir=void 0,await v(e,{recursive:!0,force:!0}).catch(()=>{})}}ensureMcpTempFile(e){this.mcpTempDir&&=(h(this.mcpTempDir,{recursive:!0,force:!0}),void 0),this.mcpTempDir=m(p(_(),`cw-mcp-`));let t=p(this.mcpTempDir,`mcp.json`);return g(t,JSON.stringify({mcpServers:e}),{encoding:`utf8`,mode:384}),t}buildArgs(e,n){let r=[`--verbose`,`--output-format`,`stream-json`],i=e.permissionMode??this.runDefaults.permissionMode,s=e.appendSystemPrompt??this.runDefaults.appendSystemPrompt,c=e.allowedTools??this.runDefaults.allowedTools,l=a(e.disallowedTools??this.runDefaults.disallowedTools),u=e.mcpConfig??this.runDefaults.mcpConfig,d=e.mcpServers??this.runDefaults.mcpServers,f=e.extraArgs??this.runDefaults.extraArgs,p=e.forkSession??this.runDefaults.forkSession??this.forkOnNextRun;if(e.model&&r.push(`--model`,e.model),e.systemPrompt&&r.push(`--system-prompt`,e.systemPrompt),s&&r.push(`--append-system-prompt`,s),i&&r.push(`--permission-mode`,i),c&&c.length>0&&r.push(`--allowed-tools`,c.join(`,`)),r.push(`--disallowed-tools`,l.join(`,`)),u)for(let e of t(u))r.push(`--mcp-config`,e);let m=this.activeBridge,h=m?{...d,[m.serverName]:{type:`http`,url:m.url}}:d;return h&&r.push(`--mcp-config`,this.ensureMcpTempFile(h)),m&&r.push(`--permission-prompt-tool`,m.toolName),e.schema.kind!==`none`&&r.push(`--json-schema`,JSON.stringify(o(e.schema.jsonSchema))),n.requestedSessionId&&(r.push(`--resume`,n.requestedSessionId),p&&r.push(`--fork-session`)),f&&f.length>0&&r.push(...f),r.push(`--input-format`,`text`,`--print`),r}buildEnv(e,t){let r=n({propagateEnv:this.creationOptions.propagateEnv});return this.creationOptions.ci!==!1&&(r.CI=r.CI??`true`),this.defaults.env&&Object.assign(r,this.defaults.env),s(r),r}mapRawEvent(e,t){if(this.appendRawLog(e),this.hasProviderEventListeners){let n=l.safeParse(e);n.success&&this.emitProviderEvent(n.data,t,n.data.session_id??t.sessionId)}let n=d(e);if(!n)return this.onParseError(JSON.stringify(e).slice(0,200),/* @__PURE__ */ Error(`schema validation failed`)),{events:[]};let r=u(n)??t.sessionId;this.forkOnNextRun&&t.requestedSessionId&&r&&r!==t.requestedSessionId&&(this.forkOnNextRun=!1);let i=c(n,{...t,sessionId:r});return r&&i.sessionId===void 0&&(i.sessionId=r),i}getStdinInput(e){return r(e.input)}};const M=e=>new j(i(e));export{M as createClaudeCodeCliAgent};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { a as ClaudeCodeCliPtyPermissionMode, i as ClaudeCodeCliPtyModule, n as ClaudeCodeCliPtyAgent, o as ClaudeCodeCliPtyProcess, r as ClaudeCodeCliPtyAgentOptions, s as ClaudeCodeCliPtyRunOptions, t as createClaudeCodeCliPtyAgent } from "../../index-
|
|
1
|
+
import { d as ClaudeSystemEvent, f as ClaudeUserEvent, l as ClaudeRateLimitEvent, o as ClaudeAssistantEvent, s as ClaudeEvent, u as ClaudeResultEvent } from "../../index-CyIiBK-O.mjs";
|
|
2
|
+
import { a as ClaudeCodeCliPtyPermissionMode, i as ClaudeCodeCliPtyModule, n as ClaudeCodeCliPtyAgent, o as ClaudeCodeCliPtyProcess, r as ClaudeCodeCliPtyAgentOptions, s as ClaudeCodeCliPtyRunOptions, t as createClaudeCodeCliPtyAgent } from "../../index-Bi9Dh34t.mjs";
|
|
3
3
|
export { type ClaudeAssistantEvent, type ClaudeCodeCliPtyAgent, type ClaudeCodeCliPtyAgentOptions, type ClaudeCodeCliPtyModule, type ClaudeCodeCliPtyPermissionMode, type ClaudeCodeCliPtyProcess, type ClaudeCodeCliPtyRunOptions, type ClaudeEvent, type ClaudeRateLimitEvent, type ClaudeResultEvent, type ClaudeSystemEvent, type ClaudeUserEvent, createClaudeCodeCliPtyAgent };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{n as e}from"../../types-B72tDMEZ.mjs";import{a as t,n,r,t as i}from"../../util-B4HTdOSc.mjs";import{t as a}from"../../env-Cb8MIvH7.mjs";import{t as o}from"../../spawner-
|
|
1
|
+
import{n as e}from"../../types-B72tDMEZ.mjs";import{a as t,n,r,t as i}from"../../util-B4HTdOSc.mjs";import{t as a}from"../../env-Cb8MIvH7.mjs";import{t as o}from"../../spawner-CgfyvnR4.mjs";import{i as s,l as c,n as l,s as u,t as d,u as f}from"../../classify-error-DOqkMCcy.mjs";import{t as p}from"../../execution-target-CdlYXh6Z.mjs";import{i as m,n as h,t as ee}from"../../session-markers-Dt7TWdKY.mjs";import{i as te,r as g,t as _}from"../../parser-C1kvDtRD.mjs";import{join as v,posix as y}from"node:path";import{appendFileSync as ne,existsSync as b,mkdtempSync as x,readFileSync as S,writeFileSync as C}from"node:fs";import{tmpdir as w}from"node:os";import{rm as T}from"node:fs/promises";import{randomUUID as re}from"node:crypto";import{createServer as E}from"node:http";const D=e=>typeof e==`object`&&!!e&&!Array.isArray(e),ie=async e=>{let t=[];for await(let n of e)t.push(Buffer.isBuffer(n)?n:Buffer.from(n));if(t.length===0)return;let n;try{n=JSON.parse(Buffer.concat(t).toString(`utf8`))}catch{return}if(D(n)&&n.hook_event_name===`PermissionRequest`&&typeof n.tool_name==`string`&&n.tool_name.length!==0&&D(n.tool_input))return{toolName:n.tool_name,input:n.tool_input,toolUseId:typeof n.tool_use_id==`string`&&n.tool_use_id.length>0?n.tool_use_id:re()}},O=(e,t)=>{e.writeHead(200,{"content-type":`application/json`}),e.end(JSON.stringify(t))},k=e=>e.decision===`allow`?{hookSpecificOutput:{hookEventName:`PermissionRequest`,decision:{behavior:`allow`,...e.updatedInput?{updatedInput:e.updatedInput}:{}}}}:{hookSpecificOutput:{hookEventName:`PermissionRequest`,decision:{behavior:`deny`,message:e.message??`Tool call denied.`}}},ae=()=>`import { Buffer } from "node:buffer";
|
|
2
2
|
|
|
3
3
|
const url = process.argv[2];
|
|
4
4
|
if (!url) {
|
|
@@ -32,4 +32,4 @@ try {
|
|
|
32
32
|
`):void 0},se=e=>{if(e.type!==`attachment`||!n(e.attachment))return;let t=e.attachment;return`[${[W(t,`type`)??`attachment`,W(t,`hookEvent`)??W(t,`hook_event`),W(t,`hookName`)??W(t,`hook_name`)].filter(e=>e!==void 0).join(` `)}]`},ce=(e,t)=>`${e} Return only valid JSON matching this JSON Schema. Do not wrap the JSON in Markdown. ${JSON.stringify(h(t))}`,J=e=>{let t=c(e.input);return e.schema.kind===`none`?t:ce(t,e.schema.jsonSchema)},Y=e=>e.replace(/[/:\\]/g,`-`),le=e=>Promise.resolve(b(e)),X=e=>{if(!e)return;let t=e.split(`:`)[0];if(t&&!/^\d+$/.test(t))return t===`root`?`/root`:`/home/${t}`},ue=e=>{if(e.type===`assistant`&&n(e.message)&&W(e.message,`stop_reason`)!==`tool_use`)return U(e.message)},Z=e=>e.replace(/\r?\n$/,``),Q=e=>{try{let t=JSON.parse(e);return n(t)?t:void 0}catch{return}},$=(e,t)=>{let n=e.split(/\r?\n/).filter(e=>e.trim().length>0),r=!1,i=!1,a=Z(t);for(let e of n){let t=Q(e);if(!t)continue;let n=q(t);if(n!==void 0){Z(n)===a&&(r=!0,i=!1);continue}r&&ue(t)!==void 0&&(i=!0)}return i},de=(e,t)=>{let n=e.split(/\r?\n/).filter(e=>e.trim().length>0),r=Z(t),i=-1;for(let[e,t]of n.entries()){let n=Q(t);if(!n)continue;let a=q(n);a!==void 0&&Z(a)===r&&(i=e)}if(i<0)return n;let a=n.slice(i),o=a.findIndex((e,t)=>t!==0&&Q(e)?.type===`result`);return o<0?a:a.slice(0,o+1)},fe=e=>{if(!n(e)||`session_id`in e)return e;let t=G(e);if(!t)return e;if(e.type===`user`&&n(e.message)&&typeof e.message.content==`string`){let n=K(e.message.content);if(n)return{...e,session_id:t,message:{...e.message,content:n}}}return{...e,session_id:t}},pe=async(e,t,n)=>{let r=e.sessionId??e.requestedSessionId;if(r)for(let e of t.transcriptPathsForSession(r)){let r=await t.readText(e);if(r!==void 0&&$(r,n))return e}};var me=class o extends l{type=`claude-code-cli-pty`;creationOptions;runDefaults;forkOnNextRun;activePty;executionTargetRef;tempDirs=/* @__PURE__ */ new Set;logPath;constructor(e={}){super({type:`claude-code-cli-pty`,capabilities:A,sessionId:e.sessionId,onEvent:e.onEvent}),this.creationOptions={...e,command:e.command?[...t(e.command)]:void 0,env:e.env?{...e.env}:void 0,allowedTools:e.allowedTools?[...e.allowedTools]:void 0,disallowedTools:e.disallowedTools?[...e.disallowedTools]:void 0,mcpConfig:Array.isArray(e.mcpConfig)?[...e.mcpConfig]:e.mcpConfig,mcpServers:e.mcpServers?{...e.mcpServers}:void 0,extraArgs:e.extraArgs?[...e.extraArgs]:void 0},this.runDefaults={allowedTools:e.allowedTools?[...e.allowedTools]:void 0,disallowedTools:e.disallowedTools?[...e.disallowedTools]:void 0,appendSystemPrompt:e.appendSystemPrompt,permissionMode:e.permissionMode,mcpConfig:Array.isArray(e.mcpConfig)?[...e.mcpConfig]:e.mcpConfig,mcpServers:e.mcpServers?{...e.mcpServers}:void 0,forkSession:e.forkSession,extraArgs:e.extraArgs?[...e.extraArgs]:void 0,readinessTimeoutMs:e.readinessTimeoutMs,stopHookTimeoutMs:e.stopHookTimeoutMs},this.forkOnNextRun=e.forkOnNextRun??!1,this.executionTargetRef=e.container??e.sandbox,this.logPath=e.logPath}get runRequestDefaults(){return{cwd:this.creationOptions.cwd,model:this.creationOptions.model,systemPrompt:this.creationOptions.systemPrompt}}fork(){if(!this.sessionId)throw new e(`Cannot fork a Claude Code CLI PTY agent before it has a sessionId.`);return new o({...this.creationOptions,sessionId:this.sessionId,forkOnNextRun:!0})}onValidateRun(t,n){if((t.forkSession??this.runDefaults.forkSession??this.forkOnNextRun)&&!this.sessionId)throw new e(`forkSession requires an existing sessionId on the agent.`)}async executeRunCore(e,t){let n=this.setupRunLifecycle(e),r,i;try{if(n.abortedBeforeStart)return this.buildResult(e,/* @__PURE__ */ new Date);this.validatePermissionHandlerSupported(),await this.ensureExecutionTarget();let a={...t,...e.normalizedRequest},o=this.getPermissionHandler();if(o){let t=e.normalizedRequest.signal??new AbortController().signal;i=await oe({handler:o,signal:t})}r=await this.createRunFiles(e);let s=i?I(r.permissionHookPath,i.url):void 0;i&&await r.writeText(r.permissionHookPath,ae());let c=a.permissionMode??this.runDefaults.permissionMode;await r.writeText(r.settingsPath,B({sentinelPath:r.sentinelPath,permissionHookCommand:s,skipDangerousModePermissionPrompt:c===`bypassPermissions`}));let l=this.creationOptions.pty??z(this.creationOptions.spawner),u=J(a);await r.writeText(r.bootstrapPath,`prompt_path=$1
|
|
33
33
|
shift
|
|
34
34
|
cat "$prompt_path" | exec "$@"
|
|
35
|
-
`),await r.writeText(r.promptPath,`${u}\n`);let{command:d,args:f}=await this.buildCommand(a,e,r),p=this.buildEnv();if(e.stopReason)return this.buildResult(e,/* @__PURE__ */ new Date);let m=this.spawnPty({run:e,ptyModule:l,command:d,args:f,env:p,initialInputBootstrapPath:r.bootstrapPath,initialInputPath:r.promptPath});e.sessionId&&this.emitSessionStart(e),await this.waitForReadiness(a,e);let h=await this.waitForStopSentinel(a,e,r,m,u);return h&&await this.applyStopSentinel(e,h,r),e.stopReason||this.activePty?.write(`/exit\r`),N(e,{processResult:await this.waitForExit(m)}),!e.stopReason&&!e.error&&!e.status&&N(e,{status:`completed`}),this.buildResult(e,/* @__PURE__ */ new Date)}catch(t){return this.activePty?.kill(),!e.stopReason&&!e.error&&N(e,{error:d(t)}),this.buildResult(e,/* @__PURE__ */ new Date)}finally{n.cleanup(),this.activePty=void 0,await i?.dispose(),await r?.cleanup()}}onStopRequested(e){this.activePty?.kill()}async onDispose(){for(let e of this.tempDirs)await T(e,{recursive:!0,force:!0}).catch(()=>{});this.tempDirs.clear()}onHandlerError(e){this.appendRawLog(`[handler-error] ${i(e)}`)}validatePermissionHandlerSupported(){if(this.getPermissionHandler()&&this.creationOptions.container)throw new e(`onPermissionRequest is not supported when running claude-code-cli-pty inside a container: the generated PermissionRequest hook calls a host loopback bridge and is unreachable from the container's network namespace.`)}async ensureExecutionTarget(){this.executionTargetRef&&this.executionTargetRef.status!==`running`&&await this.executionTargetRef.start()}async createRunFiles(e){let t=this.creationOptions.container,n=this.creationOptions.container?.workdir??this.creationOptions.sandbox?.workdir,r=e.normalizedRequest.cwd??this.creationOptions.cwd??n??process.cwd();if(t){let e=y.join(`/tmp`,`coding-agents-claude-pty-${crypto.randomUUID()}`),n=y.join(e,`prompt-bootstrap.sh`),i=y.join(e,`permission-hook.mjs`),a=y.join(e,`prompt.txt`),o=y.join(e,`settings.json`),s=y.join(e,`stop-sentinel.json`),c=Y(r),l=`user`in t.config?t.config.user:void 0,u=[this.creationOptions.env?.HOME,t.config.env?.HOME,X(l),`/root`,`/home/node`,`/home/bun`,`/home/agent`,`/home/user`].filter(e=>typeof e==`string`&&e.length>0);return await t.mkdir(e),{runDir:e,bootstrapPath:n,permissionHookPath:i,promptPath:a,settingsPath:o,sentinelPath:s,exists:t.fileExists,readText:async e=>await t.fileExists(e)?t.readFile(e):void 0,writeText:(e,n)=>t.writeFile(e,n),transcriptPathsForSession:e=>Array.from(new Set(u)).map(t=>y.join(t,`.claude`,`projects`,c,`${e}.jsonl`)),cleanup:async()=>{await t.exec(`rm`,[`-rf`,e]).catch(()=>void 0)}}}let i=this.creationOptions.sandbox?r:w(),a=x(v(i,`.coding-agents-claude-pty-`)),o=v(a,`prompt-bootstrap.sh`),s=v(a,`permission-hook.mjs`),c=v(a,`prompt.txt`),l=v(a,`settings.json`),u=v(a,`stop-sentinel.json`),d=[this.creationOptions.env?.HOME,this.creationOptions.sandbox?.config.setEnv?.HOME,process.env.HOME].filter(e=>typeof e==`string`&&e.length>0),f=Array.from(new Set(d)).map(e=>v(e,`.claude`,`projects`,Y(r)));return this.tempDirs.add(a),{runDir:a,bootstrapPath:o,permissionHookPath:s,promptPath:c,settingsPath:l,sentinelPath:u,exists:le,readText:async e=>b(e)?S(e,`utf8`):void 0,writeText:async(e,t)=>{C(e,t,{encoding:`utf8`,mode:384})},transcriptPathsForSession:e=>f.map(t=>v(t,`${e}.jsonl`)),cleanup:async()=>{this.tempDirs.delete(a),await T(a,{recursive:!0,force:!0}).catch(()=>{})}}}async buildCommand(e,n,r){let i=this.creationOptions.command?.[0]??`claude`,a=[...this.creationOptions.command?.slice(1)??[]],o=e.permissionMode??this.runDefaults.permissionMode,s=e.appendSystemPrompt??this.runDefaults.appendSystemPrompt,c=e.allowedTools??this.runDefaults.allowedTools,l=m(e.disallowedTools??this.runDefaults.disallowedTools),u=e.mcpConfig??this.runDefaults.mcpConfig,d=e.mcpServers??this.runDefaults.mcpServers,f=e.extraArgs??this.runDefaults.extraArgs,p=e.forkSession??this.runDefaults.forkSession??this.forkOnNextRun;if(e.model&&a.push(`--model`,e.model),e.systemPrompt&&a.push(`--system-prompt`,e.systemPrompt),s&&a.push(`--append-system-prompt`,s),o&&a.push(`--permission-mode`,o),c&&c.length>0&&a.push(`--allowed-tools`,c.join(`,`)),a.push(`--disallowed-tools`,l.join(`,`)),u)for(let e of t(u))a.push(`--mcp-config`,e);if(d){let e=this.creationOptions.container?y.join(r.runDir,`mcp.json`):v(r.runDir,`mcp.json`);await r.writeText(e,JSON.stringify({mcpServers:d})),a.push(`--mcp-config`,e)}if(a.push(`--settings`,r.settingsPath),n.requestedSessionId)a.push(`--resume`,n.requestedSessionId),p&&a.push(`--fork-session`);else{let e=crypto.randomUUID();N(n,{sessionId:e}),this.setSessionId(e),a.push(`--session-id`,e)}return f&&f.length>0&&a.push(...f),this.forkOnNextRun=!1,{command:i,args:a}}buildEnv(){let e=a({propagateEnv:this.creationOptions.propagateEnv});return this.creationOptions.ci!==!1&&(e.CI=e.CI??`true`),this.creationOptions.env&&Object.assign(e,this.creationOptions.env),ee(e),e}spawnPty({run:e,ptyModule:t,command:n,args:r,env:i,initialInputBootstrapPath:a,initialInputPath:o}){this.appendRawLog(`[spawn] ${n} ${r.join(` `)}`);let s=t.spawn(n,r,{cols:120,rows:40,cwd:e.normalizedRequest.cwd,env:i,initialInputBootstrapPath:a,initialInputPath:o});this.activePty=s;let c=new Promise(e=>{s.onExit(t=>{e({exitCode:t.exitCode,signal:typeof t.signal==`string`?R(t.signal)??null:null})})});return N(e,{process:{stdout:null,stderr:null,stdin:{write:e=>s.write(typeof e==`string`?e:new TextDecoder().decode(e)),end:()=>{}},kill:e=>{s.kill(typeof e==`string`?e:void 0)},wait:()=>c}}),s.onData(e=>{this.appendRawLog(`[pty] ${e}`)}),c}async waitForReadiness(e,t){let n=e.readinessTimeoutMs??this.runDefaults.readinessTimeoutMs??5e3,r=this.activePty;!r||n<=0||await new Promise(e=>{let i=!1,a={},o=()=>{i||(i=!0,a.idle&&clearTimeout(a.idle),a.timeout&&clearTimeout(a.timeout),a.subscription?.dispose(),e())};a.timeout=setTimeout(o,n),a.subscription=r.onData(()=>{a.idle&&clearTimeout(a.idle),a.idle=setTimeout(o,Math.min(250,n)),a.idle.unref?.()}),a.timeout.unref?.(),t.stopReason&&o()})}async waitForStopSentinel(e,t,n,r,i){let a=e.stopHookTimeoutMs??this.runDefaults.stopHookTimeoutMs??12e4,o=Date.now()+a,s;for(r.then(e=>{s=e}).catch(()=>{});;){let e=await this.findRunCompletion(t,n,i);if(e)return e;if(t.stopReason)return;if(s){let e=await this.findRunCompletion(t,n,i);if(e)return e;throw N(t,{processResult:s}),Error(`Claude exited before the Stop hook created a sentinel.`)}if(Date.now()>=o)throw Error(`Claude Stop hook did not create a sentinel within ${a}ms.`);await M(50)}}async findRunCompletion(e,t,n){let r=await t.exists(t.sentinelPath)?await t.readText(t.sentinelPath):void 0,i=r===void 0?void 0:H(r);if(i?.transcriptPath){let e=await t.readText(i.transcriptPath);if(e!==void 0&&$(e,n))return i}let a=await pe(e,t,n);if(a)return this.appendRawLog(`[transcript] completed turn from ${a}`),{...i,transcriptPath:a}}async applyStopSentinel(e,t,n){if(t.sessionId&&(N(e,{sessionId:t.sessionId}),this.setSessionId(t.sessionId),this.emitSessionStart(e)),t.transcriptPath){let r=await n.readText(t.transcriptPath);r!==void 0&&this.applyTranscript(e,r,J(e.normalizedRequest))}if(e.assistantTexts.length===0){let n=U(t.lastAssistantMessage);n&&this.emitAssistantText(e,n)}let i=e.output.text??e.assistantTexts.at(-1);if(e.normalizedRequest.schema.kind!==`none`&&i&&e.output.value===void 0)try{let t=e.error?.kind===`parse`&&e.error.message.includes(`structured_output`);this.applyBatch(e,{events:[],state:{output:{value:r(i)}}}),t&&e.output.value!==void 0&&N(e,{error:void 0,status:void 0})}catch(t){N(e,{error:d(t),status:`failed`})}e.assistantTexts.length===0&&!e.output.text&&!e.error&&N(e,{error:{kind:`parse`,message:`Claude Stop hook completed without assistant output.`},status:`failed`})}applyTranscript(e,t,n){let r=de(t,n);for(let t of r){let n;try{n=JSON.parse(t)}catch(t){N(e,{error:d(t),status:`failed`});return}if(this.applyTranscriptNativeEvent(e,n))continue;let r=_(fe(n));if(!r)continue;let i=
|
|
35
|
+
`),await r.writeText(r.promptPath,`${u}\n`);let{command:d,args:f}=await this.buildCommand(a,e,r),p=this.buildEnv();if(e.stopReason)return this.buildResult(e,/* @__PURE__ */ new Date);let m=this.spawnPty({run:e,ptyModule:l,command:d,args:f,env:p,initialInputBootstrapPath:r.bootstrapPath,initialInputPath:r.promptPath});e.sessionId&&this.emitSessionStart(e),await this.waitForReadiness(a,e);let h=await this.waitForStopSentinel(a,e,r,m,u);return h&&await this.applyStopSentinel(e,h,r),e.stopReason||this.activePty?.write(`/exit\r`),N(e,{processResult:await this.waitForExit(m)}),!e.stopReason&&!e.error&&!e.status&&N(e,{status:`completed`}),this.buildResult(e,/* @__PURE__ */ new Date)}catch(t){return this.activePty?.kill(),!e.stopReason&&!e.error&&N(e,{error:d(t)}),this.buildResult(e,/* @__PURE__ */ new Date)}finally{n.cleanup(),this.activePty=void 0,await i?.dispose(),await r?.cleanup()}}onStopRequested(e){this.activePty?.kill()}async onDispose(){for(let e of this.tempDirs)await T(e,{recursive:!0,force:!0}).catch(()=>{});this.tempDirs.clear()}onHandlerError(e){this.appendRawLog(`[handler-error] ${i(e)}`)}validatePermissionHandlerSupported(){if(this.getPermissionHandler()&&this.creationOptions.container)throw new e(`onPermissionRequest is not supported when running claude-code-cli-pty inside a container: the generated PermissionRequest hook calls a host loopback bridge and is unreachable from the container's network namespace.`)}async ensureExecutionTarget(){this.executionTargetRef&&this.executionTargetRef.status!==`running`&&await this.executionTargetRef.start()}async createRunFiles(e){let t=this.creationOptions.container,n=this.creationOptions.container?.workdir??this.creationOptions.sandbox?.workdir,r=e.normalizedRequest.cwd??this.creationOptions.cwd??n??process.cwd();if(t){let e=y.join(`/tmp`,`coding-agents-claude-pty-${crypto.randomUUID()}`),n=y.join(e,`prompt-bootstrap.sh`),i=y.join(e,`permission-hook.mjs`),a=y.join(e,`prompt.txt`),o=y.join(e,`settings.json`),s=y.join(e,`stop-sentinel.json`),c=Y(r),l=`user`in t.config?t.config.user:void 0,u=[this.creationOptions.env?.HOME,t.config.env?.HOME,X(l),`/root`,`/home/node`,`/home/bun`,`/home/agent`,`/home/user`].filter(e=>typeof e==`string`&&e.length>0);return await t.mkdir(e),{runDir:e,bootstrapPath:n,permissionHookPath:i,promptPath:a,settingsPath:o,sentinelPath:s,exists:t.fileExists,readText:async e=>await t.fileExists(e)?t.readFile(e):void 0,writeText:(e,n)=>t.writeFile(e,n),transcriptPathsForSession:e=>Array.from(new Set(u)).map(t=>y.join(t,`.claude`,`projects`,c,`${e}.jsonl`)),cleanup:async()=>{await t.exec(`rm`,[`-rf`,e]).catch(()=>void 0)}}}let i=this.creationOptions.sandbox?r:w(),a=x(v(i,`.coding-agents-claude-pty-`)),o=v(a,`prompt-bootstrap.sh`),s=v(a,`permission-hook.mjs`),c=v(a,`prompt.txt`),l=v(a,`settings.json`),u=v(a,`stop-sentinel.json`),d=[this.creationOptions.env?.HOME,this.creationOptions.sandbox?.config.setEnv?.HOME,process.env.HOME].filter(e=>typeof e==`string`&&e.length>0),f=Array.from(new Set(d)).map(e=>v(e,`.claude`,`projects`,Y(r)));return this.tempDirs.add(a),{runDir:a,bootstrapPath:o,permissionHookPath:s,promptPath:c,settingsPath:l,sentinelPath:u,exists:le,readText:async e=>b(e)?S(e,`utf8`):void 0,writeText:async(e,t)=>{C(e,t,{encoding:`utf8`,mode:384})},transcriptPathsForSession:e=>f.map(t=>v(t,`${e}.jsonl`)),cleanup:async()=>{this.tempDirs.delete(a),await T(a,{recursive:!0,force:!0}).catch(()=>{})}}}async buildCommand(e,n,r){let i=this.creationOptions.command?.[0]??`claude`,a=[...this.creationOptions.command?.slice(1)??[]],o=e.permissionMode??this.runDefaults.permissionMode,s=e.appendSystemPrompt??this.runDefaults.appendSystemPrompt,c=e.allowedTools??this.runDefaults.allowedTools,l=m(e.disallowedTools??this.runDefaults.disallowedTools),u=e.mcpConfig??this.runDefaults.mcpConfig,d=e.mcpServers??this.runDefaults.mcpServers,f=e.extraArgs??this.runDefaults.extraArgs,p=e.forkSession??this.runDefaults.forkSession??this.forkOnNextRun;if(e.model&&a.push(`--model`,e.model),e.systemPrompt&&a.push(`--system-prompt`,e.systemPrompt),s&&a.push(`--append-system-prompt`,s),o&&a.push(`--permission-mode`,o),c&&c.length>0&&a.push(`--allowed-tools`,c.join(`,`)),a.push(`--disallowed-tools`,l.join(`,`)),u)for(let e of t(u))a.push(`--mcp-config`,e);if(d){let e=this.creationOptions.container?y.join(r.runDir,`mcp.json`):v(r.runDir,`mcp.json`);await r.writeText(e,JSON.stringify({mcpServers:d})),a.push(`--mcp-config`,e)}if(a.push(`--settings`,r.settingsPath),n.requestedSessionId)a.push(`--resume`,n.requestedSessionId),p&&a.push(`--fork-session`);else{let e=crypto.randomUUID();N(n,{sessionId:e}),this.setSessionId(e),a.push(`--session-id`,e)}return f&&f.length>0&&a.push(...f),this.forkOnNextRun=!1,{command:i,args:a}}buildEnv(){let e=a({propagateEnv:this.creationOptions.propagateEnv});return this.creationOptions.ci!==!1&&(e.CI=e.CI??`true`),this.creationOptions.env&&Object.assign(e,this.creationOptions.env),ee(e),e}spawnPty({run:e,ptyModule:t,command:n,args:r,env:i,initialInputBootstrapPath:a,initialInputPath:o}){this.appendRawLog(`[spawn] ${n} ${r.join(` `)}`);let s=t.spawn(n,r,{cols:120,rows:40,cwd:e.normalizedRequest.cwd,env:i,initialInputBootstrapPath:a,initialInputPath:o});this.activePty=s;let c=new Promise(e=>{s.onExit(t=>{e({exitCode:t.exitCode,signal:typeof t.signal==`string`?R(t.signal)??null:null})})});return N(e,{process:{stdout:null,stderr:null,stdin:{write:e=>s.write(typeof e==`string`?e:new TextDecoder().decode(e)),end:()=>{}},kill:e=>{s.kill(typeof e==`string`?e:void 0)},wait:()=>c}}),s.onData(e=>{this.appendRawLog(`[pty] ${e}`)}),c}async waitForReadiness(e,t){let n=e.readinessTimeoutMs??this.runDefaults.readinessTimeoutMs??5e3,r=this.activePty;!r||n<=0||await new Promise(e=>{let i=!1,a={},o=()=>{i||(i=!0,a.idle&&clearTimeout(a.idle),a.timeout&&clearTimeout(a.timeout),a.subscription?.dispose(),e())};a.timeout=setTimeout(o,n),a.subscription=r.onData(()=>{a.idle&&clearTimeout(a.idle),a.idle=setTimeout(o,Math.min(250,n)),a.idle.unref?.()}),a.timeout.unref?.(),t.stopReason&&o()})}async waitForStopSentinel(e,t,n,r,i){let a=e.stopHookTimeoutMs??this.runDefaults.stopHookTimeoutMs??12e4,o=Date.now()+a,s;for(r.then(e=>{s=e}).catch(()=>{});;){let e=await this.findRunCompletion(t,n,i);if(e)return e;if(t.stopReason)return;if(s){let e=await this.findRunCompletion(t,n,i);if(e)return e;throw N(t,{processResult:s}),Error(`Claude exited before the Stop hook created a sentinel.`)}if(Date.now()>=o)throw Error(`Claude Stop hook did not create a sentinel within ${a}ms.`);await M(50)}}async findRunCompletion(e,t,n){let r=await t.exists(t.sentinelPath)?await t.readText(t.sentinelPath):void 0,i=r===void 0?void 0:H(r);if(i?.transcriptPath){let e=await t.readText(i.transcriptPath);if(e!==void 0&&$(e,n))return i}let a=await pe(e,t,n);if(a)return this.appendRawLog(`[transcript] completed turn from ${a}`),{...i,transcriptPath:a}}async applyStopSentinel(e,t,n){if(t.sessionId&&(N(e,{sessionId:t.sessionId}),this.setSessionId(t.sessionId),this.emitSessionStart(e)),t.transcriptPath){let r=await n.readText(t.transcriptPath);r!==void 0&&this.applyTranscript(e,r,J(e.normalizedRequest))}if(e.assistantTexts.length===0){let n=U(t.lastAssistantMessage);n&&this.emitAssistantText(e,n)}let i=e.output.text??e.assistantTexts.at(-1);if(e.normalizedRequest.schema.kind!==`none`&&i&&e.output.value===void 0)try{let t=e.error?.kind===`parse`&&e.error.message.includes(`structured_output`);this.applyBatch(e,{events:[],state:{output:{value:r(i)}}}),t&&e.output.value!==void 0&&N(e,{error:void 0,status:void 0})}catch(t){N(e,{error:d(t),status:`failed`})}e.assistantTexts.length===0&&!e.output.text&&!e.error&&N(e,{error:{kind:`parse`,message:`Claude Stop hook completed without assistant output.`},status:`failed`})}applyTranscript(e,t,n){let r=de(t,n);for(let t of r){let n;try{n=JSON.parse(t)}catch(t){N(e,{error:d(t),status:`failed`});return}if(this.applyTranscriptNativeEvent(e,n))continue;let r=_(fe(n));if(!r)continue;let i=g(r)??e.sessionId,a=te(r,s(e,{sessionId:i}));i&&!a.sessionId&&(a.sessionId=i),this.applyBatch(e,a)}}applyTranscriptNativeEvent(e,t){if(!n(t))return!1;let r=G(t)??e.sessionId,i=q(t);if(i!==void 0)return this.emitTextMessage(e,`user`,i,r),!0;let a=se(t);return a!==void 0&&(this.emitTextMessage(e,`system`,a,r),!0)}emitTextMessage(e,t,n,r=e.sessionId){r&&!e.sessionId&&(N(e,{sessionId:r}),this.setSessionId(r)),e.sessionId&&this.emitSessionStart(e),this.emit(e,u(e.runId,`message`,{sessionId:e.sessionId,model:null,role:t,content:[f(n)],text:n}))}emitAssistantText(e,t){this.emitTextMessage(e,`assistant`,t),this.applyBatch(e,{events:[],state:{output:{text:t}}})}async waitForExit(e){let t=this.activePty,n,r=new Promise(e=>{n=setTimeout(()=>{t?.kill(),e({exitCode:null,signal:`SIGKILL`})},2e3),n.unref?.()});try{return await Promise.race([e,r])}finally{n&&clearTimeout(n)}}appendRawLog(e){if(this.logPath)try{ne(this.logPath,`${e}\n`,`utf8`)}catch{}}};const he=e=>new me(p(e));export{he as createClaudeCodeCliPtyAgent};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as ClaudeCodeSdkExecutable, c as ClaudeCodeSdkSettingSource, i as ClaudeCodeSdkEvent, l as ClaudeCodeSdkSettings, n as ClaudeCodeSdkAgent, o as ClaudeCodeSdkPermissionMode, r as ClaudeCodeSdkAgentOptions, s as ClaudeCodeSdkRunOptions, t as createClaudeCodeSdkAgent } from "../../index-
|
|
1
|
+
import { a as ClaudeCodeSdkExecutable, c as ClaudeCodeSdkSettingSource, i as ClaudeCodeSdkEvent, l as ClaudeCodeSdkSettings, n as ClaudeCodeSdkAgent, o as ClaudeCodeSdkPermissionMode, r as ClaudeCodeSdkAgentOptions, s as ClaudeCodeSdkRunOptions, t as createClaudeCodeSdkAgent } from "../../index-CjjUmMwQ.mjs";
|
|
2
2
|
export { type ClaudeCodeSdkAgent, type ClaudeCodeSdkAgentOptions, type ClaudeCodeSdkEvent, type ClaudeCodeSdkExecutable, type ClaudeCodeSdkPermissionMode, type ClaudeCodeSdkRunOptions, type ClaudeCodeSdkSettingSource, type ClaudeCodeSdkSettings, createClaudeCodeSdkAgent };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as CodexCliRunOptions, c as CodexEvent, d as CodexItemUpdatedEvent, f as
|
|
2
|
-
export { type CodexCliAgent, type CodexCliAgentOptions, type CodexCliPermissionMode, type CodexCliRunOptions, type CodexCliSandboxMode, type CodexErrorEvent, type CodexEvent, type CodexItemCompletedEvent, type CodexItemStartedEvent, type CodexItemUpdatedEvent, type CodexThreadStartedEvent, type CodexTurnCompletedEvent, type CodexTurnFailedEvent, createCodexCliAgent };
|
|
1
|
+
import { a as CodexCliRunOptions, c as CodexEvent, d as CodexItemUpdatedEvent, f as CodexProviderEvent, g as CodexTurnFailedEvent, h as CodexTurnCompletedEvent, i as CodexCliPermissionMode, l as CodexItemCompletedEvent, m as CodexThreadStartedEvent, n as CodexCliAgent, o as CodexCliSandboxMode, p as CodexProviderItem, r as CodexCliAgentOptions, s as CodexErrorEvent, t as createCodexCliAgent, u as CodexItemStartedEvent } from "../../index-65Dv7ed0.mjs";
|
|
2
|
+
export { type CodexCliAgent, type CodexCliAgentOptions, type CodexCliPermissionMode, type CodexCliRunOptions, type CodexCliSandboxMode, type CodexErrorEvent, type CodexEvent, type CodexItemCompletedEvent, type CodexItemStartedEvent, type CodexItemUpdatedEvent, type CodexProviderEvent, type CodexProviderItem, type CodexThreadStartedEvent, type CodexTurnCompletedEvent, type CodexTurnFailedEvent, createCodexCliAgent };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"../../types-B72tDMEZ.mjs";import{a as t,i as n,n as r,r as i}from"../../util-B4HTdOSc.mjs";import{c as a,l as o,s,u as c}from"../../classify-error-DOqkMCcy.mjs";import{t as l}from"../../execution-target-CdlYXh6Z.mjs";import{t as u}from"../../Agent-
|
|
2
|
-
`);if(e)return e}},
|
|
1
|
+
import{n as e}from"../../types-B72tDMEZ.mjs";import{a as t,i as n,n as r,r as i}from"../../util-B4HTdOSc.mjs";import{c as a,l as o,s,u as c}from"../../classify-error-DOqkMCcy.mjs";import{t as l}from"../../execution-target-CdlYXh6Z.mjs";import{t as u}from"../../Agent-BjaeRtLk.mjs";import{join as d}from"node:path";import{mkdtempSync as f,readFileSync as ee,rmSync as te,writeFileSync as ne}from"node:fs";import{tmpdir as p}from"node:os";import{z as m}from"zod/v4";const re=m.object({type:m.string()}).passthrough(),h=m.object({input_tokens:m.number().optional(),cached_input_tokens:m.number().optional(),cache_write_input_tokens:m.number().optional(),output_tokens:m.number().optional(),reasoning_output_tokens:m.number().optional(),total_tokens:m.number().optional()}).passthrough(),g=m.object({type:m.literal(`thread.started`),thread_id:m.string()}).passthrough(),_=m.object({type:m.literal(`turn.completed`),usage:h.optional(),last_agent_message:m.string().optional(),duration_ms:m.number().optional(),num_turns:m.number().optional()}).passthrough(),v=m.object({type:m.literal(`turn.failed`),usage:h.optional(),last_agent_message:m.string().optional(),duration_ms:m.number().optional(),num_turns:m.number().optional(),message:m.string().optional(),error:m.unknown().optional()}).passthrough(),y=m.object({id:m.string(),type:m.string()}).passthrough(),b=m.object({type:m.literal(`item.started`),item:y}).passthrough(),x=m.object({type:m.literal(`item.updated`),item:y}).passthrough(),S=m.object({type:m.literal(`item.completed`),item:y}).passthrough(),C=m.object({type:m.literal(`error`),message:m.string().optional(),error:m.unknown().optional()}).passthrough(),w=m.union([m.string(),m.object({message:m.string().optional()}).passthrough()]),T=y.extend({type:m.enum([`agent_message`,`reasoning`,`command_execution`,`file_change`,`mcp_tool_call`,`collab_tool_call`,`web_search`,`plan_update`,`todo_list`,`error`]),text:m.string().optional(),reasoning:m.string().optional(),command:m.string().optional(),status:m.string().optional(),output:m.string().optional(),aggregated_output:m.string().optional(),exit_code:m.number().nullable().optional(),path:m.string().optional(),diff:m.string().optional(),changes:m.array(m.object({path:m.string().optional(),kind:m.string().optional()}).passthrough()).optional(),query:m.string().optional(),results:m.array(m.unknown()).optional(),action:m.unknown().optional(),sender_thread_id:m.string().optional(),receiver_thread_ids:m.array(m.string()).optional(),prompt:m.string().nullable().optional(),agents_states:m.record(m.string(),m.unknown()).optional(),todos:m.array(m.unknown()).optional(),plan:m.string().optional(),items:m.array(m.object({text:m.string().optional(),completed:m.boolean().optional()}).passthrough()).optional(),message:m.string().optional(),error:w.optional(),server:m.string().optional(),tool:m.string().optional(),arguments:m.unknown().optional(),result:m.unknown().optional(),tool_name:m.string().optional(),tool_input:m.record(m.string(),m.unknown()).nullable().optional(),tool_output:m.string().optional()}),E=m.discriminatedUnion(`type`,[g,m.object({type:m.literal(`turn.started`)}),_,v.extend({error:w.optional()}),b.extend({item:T}),x.extend({item:T}),S.extend({item:T}),C.extend({error:w.optional()})]),D=e=>r(e)?e:void 0,O=(e,t)=>{if(e){for(let n of t)if(n in e)return e[n]}},k=(e,t)=>{let n=O(e,t);return typeof n==`string`?n:void 0},A=(e,t)=>{let n=O(e,t);return typeof n==`number`?n:void 0},j=e=>{let t=Object.entries(e).filter(([,e])=>e!==void 0);if(t.length!==0)return Object.fromEntries(t)},M=e=>e.replace(/([\da-z])([A-Z])/g,`$1_$2`).toLowerCase(),N=(e,t)=>{if(typeof e==`string`&&e.trim()!==``)return e;let n=D(e);return n?k(n,[`message`,`error`,`status_message`])??k(D(n.additional_details),[`message`])??t:t},P=e=>{let t=D(e.usage),r=A(t,[`input_tokens`]),i=A(t,[`cached_input_tokens`]),a=A(t,[`cache_write_input_tokens`]),o=A(t,[`output_tokens`]),s=A(t,[`reasoning_output_tokens`]),c=r===void 0?void 0:Math.max(r-(i??0)-(a??0),0),l=A(t,[`total_tokens`])??n(r,o);return{durationMs:A(e,[`duration_ms`,`durationMs`])??0,apiDurationMs:A(e,[`duration_ms`,`durationMs`])??0,turns:A(e,[`num_turns`,`numTurns`])??1,costUsd:0,inputTokens:c,cacheReadInputTokens:i,cacheCreationInputTokens:a,outputTokens:o,reasoningOutputTokens:s,totalTokens:l}},F=e=>({toolName:`Bash`,input:j({command:k(e,[`command`]),cwd:k(e,[`cwd`,`working_directory`]),parsedCommand:O(e,[`parsed_cmd`,`parsedCommand`])})}),I=e=>{let t=k(e,[`tool`,`tool_name`])??`mcp_tool_call`,n=k(e,[`server`]),r=O(e,[`arguments`,`invocation`,`input`]);return{toolName:t,input:n===void 0?r:j({server:n,arguments:r})}},L=e=>({toolName:`WebSearch`,input:j({query:k(e,[`query`]),action:O(e,[`action`])})}),ie=e=>{let t=k(e,[`status`]),n=A(e,[`exit_code`,`exitCode`]),r=k(e,[`error`])??k(D(e.result),[`error`]);return{isError:t===`error`||t===`failed`||t===`errored`||t===`interrupted`||n!==void 0&&n!==0||r!==void 0,error:r}},R=e=>({events:[],sessionId:e.thread_id}),z=(e,t)=>{let n={stats:P(e),status:`completed`};if(e.last_agent_message!==void 0&&(n.output={text:e.last_agent_message}),t.schemaRequested&&e.last_agent_message)try{n.output={...n.output,value:i(e.last_agent_message)}}catch{}return{events:[],state:n}},B=e=>({events:[],state:{stats:P(e),status:`failed`,output:e.last_agent_message===void 0?void 0:{text:e.last_agent_message},error:{kind:`provider`,message:N(e.error??e.message,`Codex turn failed.`)}}}),V=e=>({events:[],state:{status:`failed`,error:{kind:`provider`,message:N(e.error??e.message,`Codex emitted an error event.`)}}}),H=(e,t,n,r)=>{let i=k(e,[`id`]);return i?{events:[s(t.runId,`tool-call`,{sessionId:t.sessionId,model:r.model??null,toolCallId:i,toolName:n.toolName,input:n.input})],toolCalls:[{toolCallId:i,toolName:n.toolName,input:n.input}]}:{events:[]}},U=e=>O(e,[`aggregated_output`,`aggregatedOutput`,`output`,`result`,`text`])??``,W=e=>O(e,[`result`,`output`])??k(e,[`error`])??``,G=e=>O(e,[`results`,`result`,`action`])??``,K=(e,t,n,r,i)=>{let a=k(e,[`id`]);if(!a)return{events:[]};let o=t.toolCalls.get(a),c=o??n,l=ie(e),u=[],d=[];return o||(u.push(s(t.runId,`tool-call`,{sessionId:t.sessionId,model:i.model??null,toolCallId:a,toolName:n.toolName,input:n.input})),d.push({toolCallId:a,toolName:n.toolName,input:n.input})),u.push(s(t.runId,`tool-result`,{sessionId:t.sessionId,toolCallId:a,toolName:c.toolName,input:c.input,output:r,isError:l.isError||void 0,error:l.error})),{events:u,toolCalls:d}},q=e=>{let t=k(e,[`summary_text`,`reasoning_text`,`text`,`summary`,`raw_content`]);if(t)return t;let n=O(e,[`summary`]);if(Array.isArray(n)){let e=n.flatMap(e=>{if(typeof e==`string`)return[e];let t=D(e),n=k(t,[`text`,`summary_text`]);return n?[n]:[]}).join(`
|
|
2
|
+
`);if(e)return e}},J=(e,t)=>{let n=k(e,[`id`]);if(!n||!t.itemCache)return;let r=t.itemCache.get(n);t.itemCache.set(n,r?{...r,...e}:{...e})},ae=(e,t)=>{let n=k(e,[`id`]);if(!n||!t.itemCache)return e;let r=t.itemCache.get(n);return t.itemCache.delete(n),r?{...r,...e}:e},oe=(e,t,n)=>{let r=D(e.item);if(!r)return{events:[]};switch(J(r,n),M(k(r,[`type`])??``)){case`command_execution`:return H(r,t,F(r),n);case`mcp_tool_call`:return H(r,t,I(r),n);case`web_search`:return H(r,t,L(r),n);default:return{events:[]}}},se=(e,t)=>{let n=D(e.item);return n&&J(n,t),{events:[]}},ce=(e,t,n)=>{let r=D(e.item);if(!r)return{events:[]};let a=ae(r,n);switch(M(k(a,[`type`])??``)){case`agent_message`:{let e=k(a,[`text`]);if(!e)return{events:[]};let r=t.schemaRequested&&(k(a,[`phase`])===void 0||k(a,[`phase`])===`final_answer`),o;if(r)try{o=i(e)}catch{}return{events:[s(t.runId,`message`,{sessionId:t.sessionId,model:n.model??null,role:`assistant`,content:[c(e)],text:e})],state:{output:{text:e,...o===void 0?{}:{value:o}}}}}case`reasoning`:{let e=q(a);return e?{events:[s(t.runId,`reasoning`,{sessionId:t.sessionId,model:n.model??null,content:[c(e)],text:e})]}:{events:[]}}case`command_execution`:return K(a,t,F(a),U(a),n);case`mcp_tool_call`:return K(a,t,I(a),W(a),n);case`web_search`:return K(a,t,L(a),G(a),n);default:return{events:[]}}};function le(e,t,n={}){let r=g.safeParse(e);if(r.success)return{batch:R(r.data),disposition:`mapped`};if(e.type===`turn.started`)return{batch:{events:[]},disposition:`known-ignored`};let i=_.safeParse(e);if(i.success)return{batch:z(i.data,t),disposition:`mapped`};let a=v.safeParse(e);if(a.success)return{batch:B(a.data),disposition:`mapped`};let o=C.safeParse(e);if(o.success)return{batch:V(o.data),disposition:`mapped`};let s=b.safeParse(e);if(s.success){let e=oe(s.data,t,n);return{batch:e,disposition:e.events.length>0||(e.toolCalls?.length??0)>0?`mapped`:`known-ignored`}}let c=x.safeParse(e);if(c.success)return{batch:se(c.data,n),disposition:`known-ignored`};let l=S.safeParse(e);if(l.success){let e=ce(l.data,t,n);return{batch:e,disposition:e.events.length>0||e.state!==void 0||(e.toolCalls?.length??0)>0||e.sessionId!==void 0?`mapped`:`known-ignored`}}switch(e.type){case`thread.started`:case`turn.started`:case`turn.completed`:case`turn.failed`:case`item.started`:case`item.updated`:case`item.completed`:case`error`:return{batch:{events:[]},disposition:`known-malformed`};default:return{batch:{events:[]},disposition:`unknown`}}}const ue=a(re),de={structuredOutput:!0,sessionResume:!0,imageInput:!1,mcp:!0,eventStreaming:!0},fe=e=>/^\w+$/.test(e),pe=e=>fe(e)?e:JSON.stringify(e),Y=(...e)=>e.map(pe).join(`.`),X=e=>JSON.stringify(e),me=e=>`[${e.map(e=>JSON.stringify(e)).join(`,`)}]`,Z=e=>{let t=[];for(let[n,r]of Object.entries(e)){let e=Y(`mcp_servers`,n);if(r.url&&t.push(`--config`,`${e}.url=${X(r.url)}`),r.command&&t.push(`--config`,`${e}.command=${X(r.command)}`),r.args&&r.args.length>0&&t.push(`--config`,`${e}.args=${me(r.args)}`),r.cwd&&t.push(`--config`,`${e}.cwd=${X(r.cwd)}`),r.headers)for(let[e,i]of Object.entries(r.headers))t.push(`--config`,`${Y(`mcp_servers`,n,`http_headers`,e)}=${X(i)}`);if(r.env)for(let[e,i]of Object.entries(r.env))t.push(`--config`,`${Y(`mcp_servers`,n,`env`,e)}=${X(i)}`)}return t},he=(t,n)=>{if(t!==void 0){if(!Array.isArray(t)||t.some(e=>typeof e!=`string`))throw new e(`${n} must be an array of strings.`);return[...t]}},Q=(t,n)=>{if(t===void 0)return;if(!r(t)||Array.isArray(t))throw new e(`${n} must be an object.`);let i={};for(let[r,a]of Object.entries(t)){if(typeof a!=`string`)throw new e(`${n}.${r} must be a string.`);i[r]=a}return i},ge=(t,n)=>{if(!r(t)||Array.isArray(t))throw new e(`${n} must be an object.`);let i=t.command,a=t.url,o=t.cwd;if(i!==void 0&&typeof i!=`string`)throw new e(`${n}.command must be a string.`);if(a!==void 0&&typeof a!=`string`)throw new e(`${n}.url must be a string.`);if(o!==void 0&&typeof o!=`string`)throw new e(`${n}.cwd must be a string.`);return{command:i,url:a,cwd:o,args:he(t.args,`${n}.args`),env:Q(t.env,`${n}.env`),headers:Q(t.headers,`${n}.headers`)}},$=t=>{let n;try{n=JSON.parse(ee(t,`utf8`))}catch(n){throw n instanceof Error&&`code`in n&&n.code===`ENOENT`?new e(`mcpConfig file not found: ${t}`):new e(`mcpConfig must be valid JSON: ${t}`)}if(!r(n)||Array.isArray(n))throw new e(`mcpConfig must contain a JSON object: ${t}`);let i=n.mcpServers;if(i===void 0)return;if(!r(i)||Array.isArray(i))throw new e(`mcpConfig.mcpServers must be an object: ${t}`);let a={};for(let[e,t]of Object.entries(i))a[e]=ge(t,`mcpConfig.mcpServers.${e}`);return a},_e=e=>{let t=$(e);return t?Z(t):[]};var ve=class extends u{type=`codex-cli`;creationOptions;runDefaults;schemaDirs=/* @__PURE__ */ new Map;runModels=/* @__PURE__ */ new Map;itemCaches=/* @__PURE__ */ new Map;constructor(e={}){super({type:`codex-cli`,capabilities:de,defaults:{cwd:e.cwd,env:e.env,command:t(e.command??`codex`),sessionId:e.sessionId,model:e.model},spawner:e.spawner,executionTarget:e.container??e.sandbox,logPath:e.logPath,onEvent:e.onEvent,onProviderEvent:e.onProviderEvent}),this.creationOptions=e,this.runDefaults={sandboxMode:e.sandboxMode,additionalDirectories:e.additionalDirectories?[...e.additionalDirectories]:void 0,skipGitRepoCheck:e.skipGitRepoCheck,permissionMode:e.permissionMode,ephemeral:e.ephemeral,mcpConfig:e.mcpConfig,mcpServers:e.mcpServers?{...e.mcpServers}:void 0,extraArgs:e.extraArgs?[...e.extraArgs]:void 0}}onValidateRun(e,t){let n=e.mcpConfig??this.runDefaults.mcpConfig;n&&$(n)}buildArgs(e,t){let n=[`exec`,`--json`],r=e.sandboxMode??this.runDefaults.sandboxMode,i=e.additionalDirectories??this.runDefaults.additionalDirectories,a=e.skipGitRepoCheck??this.runDefaults.skipGitRepoCheck,o=e.permissionMode??this.runDefaults.permissionMode,s=e.ephemeral??this.runDefaults.ephemeral,c=e.extraArgs??this.runDefaults.extraArgs;this.runModels.set(t.runId,e.model),e.model&&n.push(`--model`,e.model),o===`auto-approve`?n.push(`--approve-for-me`):o===`bypass-sandbox`?n.push(`--dangerously-bypass-approvals-and-sandbox`):r&&n.push(`--sandbox`,r),a&&n.push(`--skip-git-repo-check`),s&&n.push(`--ephemeral`);for(let e of i??[])n.push(`--add-dir`,e);e.schema.kind!==`none`&&n.push(`--output-schema`,this.createSchemaFile(t.runId,e.schema.jsonSchema));let l=e.mcpConfig??this.runDefaults.mcpConfig;l&&n.push(..._e(l));let u=e.mcpServers??this.runDefaults.mcpServers;return u&&n.push(...Z(u)),c&&c.length>0&&n.push(...c),t.requestedSessionId&&n.push(`resume`,t.requestedSessionId),n.push(`-`),n}buildEnv(e,t){return this.buildDefaultEnv(this.creationOptions.propagateEnv)}mapRawEvent(e,t){if(this.appendRawLog(e),this.hasProviderEventListeners){let n=E.safeParse(e);if(n.success){let e=n.data.type===`thread.started`?n.data.thread_id:t.sessionId;this.emitProviderEvent(n.data,t,e)}}let n=ue(e);if(!n)return this.onParseError(JSON.stringify(e).slice(0,200),/* @__PURE__ */ Error(`schema validation failed`)),{events:[]};let r=this.itemCaches.get(t.runId);r||(r=/* @__PURE__ */ new Map,this.itemCaches.set(t.runId,r));let i=le(n,t,{model:this.runModels.get(t.runId),itemCache:r});return i.disposition===`known-malformed`&&this.onParseError(JSON.stringify(e).slice(0,200),/* @__PURE__ */ Error(`known Codex event "${n.type}" did not match the expected payload shape`)),i.batch}getStdinInput(e){return o(e.input)}async onRunFinished(e){await super.onRunFinished(e),this.runModels.delete(e.runId),this.itemCaches.delete(e.runId);let t=this.schemaDirs.get(e.runId);t&&(this.schemaDirs.delete(e.runId),te(t,{recursive:!0,force:!0}))}createSchemaFile(e,t){let n=f(d(p(),`coding-agents-sdk-codex-cli-`)),r=d(n,`output-schema.json`);return ne(r,JSON.stringify(t,null,2),{encoding:`utf8`,mode:384}),this.schemaDirs.set(e,n),r}};const ye=e=>new ve(l(e));export{ye as createCodexCliAgent};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as CodexSdkItem, i as CodexSdkEvent, n as CodexSdkAgent, o as CodexSdkPermissionMode, r as CodexSdkAgentOptions, s as CodexSdkRunOptions, t as createCodexSdkAgent } from "../../index-
|
|
1
|
+
import { a as CodexSdkItem, i as CodexSdkEvent, n as CodexSdkAgent, o as CodexSdkPermissionMode, r as CodexSdkAgentOptions, s as CodexSdkRunOptions, t as createCodexSdkAgent } from "../../index-CQzF8Cli.mjs";
|
|
2
2
|
export { type CodexSdkAgent, type CodexSdkAgentOptions, type CodexSdkEvent, type CodexSdkItem, type CodexSdkPermissionMode, type CodexSdkRunOptions, createCodexSdkAgent };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as CursorCliRunOptions, i as CursorCliPermissionMode, n as CursorCliAgent, o as CursorCliSandboxMode, r as CursorCliAgentOptions, s as CursorCliEvent, t as createCursorCliAgent } from "../../index-
|
|
1
|
+
import { a as CursorCliRunOptions, i as CursorCliPermissionMode, n as CursorCliAgent, o as CursorCliSandboxMode, r as CursorCliAgentOptions, s as CursorCliEvent, t as createCursorCliAgent } from "../../index-m5Pqs8Jz.mjs";
|
|
2
2
|
export { type CursorCliAgent, type CursorCliAgentOptions, type CursorCliEvent, type CursorCliPermissionMode, type CursorCliRunOptions, type CursorCliSandboxMode, createCursorCliAgent };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as e,n as t}from"../../util-B4HTdOSc.mjs";import{c as n,l as r,o as i,s as a,u as o}from"../../classify-error-DOqkMCcy.mjs";import{t as s}from"../../execution-target-CdlYXh6Z.mjs";import{t as c}from"../../Agent-
|
|
1
|
+
import{a as e,n as t}from"../../util-B4HTdOSc.mjs";import{c as n,l as r,o as i,s as a,u as o}from"../../classify-error-DOqkMCcy.mjs";import{t as s}from"../../execution-target-CdlYXh6Z.mjs";import{t as c}from"../../Agent-BjaeRtLk.mjs";import{z as l}from"zod/v4";const u=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,d=e=>typeof e==`string`?e:void 0,f=e=>{if(!t(e))return;let[n,r]=Object.entries(e)[0]??[];if(n&&t(r))return{rawName:n,value:r}},p=e=>{let t=e.replace(/ToolCall$/,``).replace(/([\da-z])([A-Z])/g,`$1 $2`);return t.charAt(0).toUpperCase()+t.slice(1)},m=e=>t(e)?`success`in e?e.success:`error`in e?e.error:`failure`in e?e.failure:e:e??``,h=e=>{if(t(e)){if(`error`in e)return JSON.stringify(e.error);if(`failure`in e)return JSON.stringify(e.failure)}},g=e=>d(e.session_id)??d(e.sessionId),_=(e,n,r)=>{let i=e.message;return!t(i)||!Array.isArray(i.content)?{events:[]}:{events:i.content.flatMap(e=>!t(e)||e.type!==`text`||typeof e.text!=`string`?[]:[a(n.runId,`message`,{sessionId:n.sessionId,model:r??null,role:`assistant`,content:[o(e.text)],text:e.text})])}},v=(e,t,n)=>{let r=f(e.tool_call),i=d(e.call_id),o=d(e.subtype);if(!r||!i||!o)return{events:[]};let s=p(r.rawName),c=r.value.args;if(o===`started`)return{events:[a(t.runId,`tool-call`,{sessionId:t.sessionId,model:n??null,toolCallId:i,toolName:s,input:c})],toolCalls:[{toolCallId:i,toolName:s,input:c}]};if(o!==`completed`)return{events:[]};let l=t.toolCalls.get(i),u=l?.toolName??s,g=l?.input??c,_=r.value.result,v=m(_),y=h(_),b=[],x=[];return l||(b.push(a(t.runId,`tool-call`,{sessionId:t.sessionId,model:n??null,toolCallId:i,toolName:u,input:g})),x.push({toolCallId:i,toolName:u,input:g})),b.push(a(t.runId,`tool-result`,{sessionId:t.sessionId,toolCallId:i,toolName:u,input:g,output:v,isError:y!==void 0||void 0,error:y})),{events:b,toolCalls:x.length>0?x:void 0}},y=e=>{let t=u(e.duration_ms)??u(e.durationMs)??0,n=u(e.duration_api_ms)??t,r=d(e.result);return{events:[],state:{output:r===void 0?void 0:{text:r},stats:{durationMs:t,apiDurationMs:n,turns:1,costUsd:0},status:e.is_error===!0?`failed`:`completed`,error:e.is_error===!0?{kind:`provider`,message:r??`Cursor CLI run failed.`}:void 0}}},b=(e,t)=>{let n=d(e.message)??d(e.error)??`Cursor CLI emitted an error event.`;return{events:[a(t.runId,`stderr`,{sessionId:t.sessionId,text:n})]}},x=(e,t,n)=>{let r=e;switch(d(r.type)??``){case`assistant`:return _(r,t,n);case`tool_call`:return v(r,t,n);case`result`:return y(r);case`error`:return b(r,t);default:return{events:[]}}},S=l.object({type:l.string()}).passthrough(),C=n(S),w={structuredOutput:!1,sessionResume:!0,imageInput:!1,mcp:!0,eventStreaming:!0};var T=class extends c{type=`cursor-cli`;creationOptions;runDefaults;runModels=/* @__PURE__ */ new Map;runTextBuffers=/* @__PURE__ */ new Map;constructor(t={}){super({type:`cursor-cli`,capabilities:w,defaults:{cwd:t.cwd,env:t.env,command:e(t.command??`agent`),sessionId:t.sessionId,model:t.model},spawner:t.spawner,executionTarget:t.container??t.sandbox,logPath:t.logPath,onEvent:t.onEvent}),this.creationOptions=t,this.runDefaults={approveMcps:t.approveMcps,extraArgs:t.extraArgs?[...t.extraArgs]:void 0,force:t.force,permissionMode:t.permissionMode,sandboxMode:t.sandboxMode,trust:t.trust}}buildArgs(e,t){let n=[`--print`,`--output-format`,`stream-json`],i=e.permissionMode??this.runDefaults.permissionMode,a=e.force??this.runDefaults.force,o=e.sandboxMode??this.runDefaults.sandboxMode,s=e.approveMcps??this.runDefaults.approveMcps,c=e.trust??this.runDefaults.trust,l=e.extraArgs??this.runDefaults.extraArgs,u=r(e.input);return this.runModels.set(t.runId,e.model),e.cwd&&n.push(`--workspace`,e.cwd),e.model&&n.push(`--model`,e.model),i&&n.push(`--mode`,i),a&&n.push(`--force`),o&&n.push(`--sandbox`,o),s&&n.push(`--approve-mcps`),c&&n.push(`--trust`),t.requestedSessionId&&n.push(`--resume`,t.requestedSessionId),l&&l.length>0&&n.push(...l),n.push(`--`,u),n}buildEnv(e,t){return this.buildDefaultEnv(this.creationOptions.propagateEnv)}mapRawEvent(e,t){this.appendRawLog(e);let n=C(e);if(!n)return this.onParseError(JSON.stringify(e).slice(0,200),/* @__PURE__ */ Error(`schema validation failed`)),{events:[]};let r=g(n)??t.sessionId,a=x(n,{...t,sessionId:r},this.runModels.get(t.runId));return r&&a.sessionId===void 0&&(a.sessionId=r),i(a,n.type===`result`,this.runTextBuffers,t.runId)}async onRunFinished(e){await super.onRunFinished(e),this.runModels.delete(e.runId),this.runTextBuffers.delete(e.runId)}};const E=e=>new T(s(e));export{E as createCursorCliAgent};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as CursorSdkMcpHttpAuth, c as CursorSdkSettingSource, i as CursorSdkEvent, n as CursorSdkAgent, o as CursorSdkMcpServerConfig, r as CursorSdkAgentOptions, s as CursorSdkRunOptions, t as createCursorSdkAgent } from "../../index-
|
|
1
|
+
import { a as CursorSdkMcpHttpAuth, c as CursorSdkSettingSource, i as CursorSdkEvent, n as CursorSdkAgent, o as CursorSdkMcpServerConfig, r as CursorSdkAgentOptions, s as CursorSdkRunOptions, t as createCursorSdkAgent } from "../../index-CZbgTv8P.mjs";
|
|
2
2
|
export { type CursorSdkAgent, type CursorSdkAgentOptions, type CursorSdkEvent, type CursorSdkMcpHttpAuth, type CursorSdkMcpServerConfig, type CursorSdkRunOptions, type CursorSdkSettingSource, createCursorSdkAgent };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as GeminiCliRunOptions, i as GeminiCliPermissionMode, n as GeminiCliAgent, o as GeminiEvent, r as GeminiCliAgentOptions, t as createGeminiCliAgent } from "../../index-
|
|
1
|
+
import { a as GeminiCliRunOptions, i as GeminiCliPermissionMode, n as GeminiCliAgent, o as GeminiEvent, r as GeminiCliAgentOptions, t as createGeminiCliAgent } from "../../index-BbZPkmE-.mjs";
|
|
2
2
|
export { type GeminiCliAgent, type GeminiCliAgentOptions, type GeminiCliPermissionMode, type GeminiCliRunOptions, type GeminiEvent, createGeminiCliAgent };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as e,n as t}from"../../util-B4HTdOSc.mjs";import{c as n,l as r,o as i,s as a,u as o}from"../../classify-error-DOqkMCcy.mjs";import{t as s}from"../../execution-target-CdlYXh6Z.mjs";import{t as c}from"../../Agent-
|
|
1
|
+
import{a as e,n as t}from"../../util-B4HTdOSc.mjs";import{c as n,l as r,o as i,s as a,u as o}from"../../classify-error-DOqkMCcy.mjs";import{t as s}from"../../execution-target-CdlYXh6Z.mjs";import{t as c}from"../../Agent-BjaeRtLk.mjs";import{z as l}from"zod/v4";const u=e=>typeof e==`string`?e:void 0,d=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,f=e=>{if(typeof e==`string`)return e;if(Array.isArray(e))return e.map(f).join(``);if(t(e)){let t=u(e.text);if(t)return t;let n=e.parts??e.content;if(Array.isArray(n))return n.map(f).join(``)}return``},p=e=>{if(typeof e==`string`)return e;if(e==null)return``;try{return JSON.stringify(e)}catch{return String(e)}},m=()=>crypto.randomUUID(),h=e=>{let n=e,r=u(n.session_id)??u(n.sessionId);if(r)return r;if(t(n.message))return u(n.message.session_id)??u(n.message.sessionId)},g=(e,t)=>{let n=`[init]`;return{events:[a(t.runId,`message`,{sessionId:t.sessionId,model:null,role:`system`,content:[o(n)],text:n})]}},_=(e,n,r)=>{let i=t(e.message)?e.message:e,s=u(i.role)??u(e.role)??`assistant`,c=u(i.model)??u(e.model)??r.model??null,l=i.content??i.parts??i.text??e.content??e.text,d=f(l);return d?.trim()?s===`assistant`?{events:[a(n.runId,`message`,{sessionId:n.sessionId,model:c,role:`assistant`,content:[o(d)],text:d})]}:{events:[a(n.runId,`message`,{sessionId:n.sessionId,model:null,role:`user`,content:[o(d)],text:d})]}:{events:[]}},v=(e,t,n)=>{let r=u(e.thought)??u(e.text)??u(e.content)??``;return r.trim()?{events:[a(t.runId,`reasoning`,{sessionId:t.sessionId,model:n.model??null,content:[o(r)],text:r})]}:{events:[]}},y=(e,n,r)=>{let i=u(e.tool_id)??u(e.id)??m(),o=u(e.tool_name)??u(e.name)??`tool`,s=(t(e.parameters)?e.parameters:void 0)??(t(e.args)?e.args:void 0)??(t(e.input)?e.input:void 0)??{};return{events:[a(n.runId,`tool-call`,{sessionId:n.sessionId,model:r.model??null,toolCallId:i,toolName:o,input:s})],toolCalls:[{toolCallId:i,toolName:o,input:s}]}},b=(e,t)=>{let n=u(e.tool_id)??u(e.tool_use_id)??u(e.id)??m(),r=u(e.status),i=r?r!==`success`:!!e.error,o=e.output??e.result??e.content??e.message??(typeof e.error==`string`?e.error:void 0),s=p(o),c=t.toolCalls.get(n);return{events:[a(t.runId,`tool-result`,{sessionId:t.sessionId,toolCallId:n,toolName:c?.toolName,input:c?.input,output:s,isError:i||void 0,error:i?p(e.error??o):void 0})]}},x=e=>{let n=(t(e.token_count)?e.token_count:void 0)??(t(e.tokenCount)?e.tokenCount:void 0)??(t(e.usage)?e.usage:void 0)??(t(e.usage_metadata)?e.usage_metadata:void 0)??(t(e.usageMetadata)?e.usageMetadata:void 0)??(t(e.stats)?e.stats:void 0);if(!n)return;let r=d(n.prompt_tokens)??d(n.promptTokens)??d(n.input_tokens)??d(n.inputTokens)??d(n.prompt_token_count),i=d(n.completion_tokens)??d(n.output_tokens)??d(n.outputTokens)??d(n.candidates_token_count)??d(n.completion_token_count);if(r!==void 0||i!==void 0)return{inputTokens:r??0,outputTokens:i??0}},S=(e,n)=>{let r=u(e.status)??u(e.subtype)??`success`,i=r!==`success`||!!e.error||e.is_error===!0,a=e.result??e.output??e.text??e.content,o=d(e.duration_ms)??d(e.durationMs)??(t(e.stats)?d(e.stats.total_time_ms):void 0)??0,s=x(e),c=s?s.inputTokens+s.outputTokens:void 0,l={stats:{durationMs:o,apiDurationMs:o,turns:d(e.num_turns)??1,costUsd:d(e.total_cost_usd)??0,inputTokens:s?.inputTokens,outputTokens:s?.outputTokens,totalTokens:c}};return typeof a==`string`&&(l.output={text:a}),e.structured_output!==void 0&&(l.output={...l.output,value:e.structured_output}),i?(l.status=`failed`,l.error={kind:`provider`,message:u(e.error)??(typeof a==`string`&&a.trim()?a:p(e.error??a??r))}):l.status=`completed`,{events:[],state:l}},C=(e,t)=>{let n=u(e.message)??(e.error===void 0?void 0:p(e.error))??(e.details===void 0?void 0:p(e.details))??`Gemini emitted an error event.`;return{events:[a(t.runId,`stderr`,{sessionId:t.sessionId,text:n})]}},w=(e,t,n={})=>{let r=e;switch(e.type){case`init`:return g(r,t);case`message`:return _(r,t,n);case`thought`:return v(r,t,n);case`tool_use`:return y(r,t,n);case`tool_result`:return b(r,t);case`result`:return S(r,t);case`error`:return C(r,t);default:return{events:[]}}},T=l.object({type:l.string()}).passthrough(),E=n(T),D={structuredOutput:!1,sessionResume:!0,imageInput:!1,mcp:!0,eventStreaming:!0};var O=class extends c{type=`gemini-cli`;creationOptions;runDefaults;runModels=/* @__PURE__ */ new Map;runTextBuffers=/* @__PURE__ */ new Map;constructor(t={}){super({type:`gemini-cli`,capabilities:D,defaults:{cwd:t.cwd,env:t.env,command:e(t.command??`gemini`),sessionId:t.sessionId,model:t.model,systemPrompt:t.systemPrompt},spawner:t.spawner,executionTarget:t.container??t.sandbox,logPath:t.logPath,onEvent:t.onEvent}),this.creationOptions=t,this.runDefaults={allowedTools:t.allowedTools?[...t.allowedTools]:void 0,disallowedTools:t.disallowedTools?[...t.disallowedTools]:void 0,permissionMode:t.permissionMode,extraArgs:t.extraArgs?[...t.extraArgs]:void 0}}buildArgs(e,t){let n=[`--output-format`,`stream-json`],i=r(e.input),a=e.allowedTools??this.runDefaults.allowedTools,o=e.disallowedTools??this.runDefaults.disallowedTools,s=e.permissionMode??this.runDefaults.permissionMode,c=e.extraArgs??this.runDefaults.extraArgs;if(this.runModels.set(t.runId,e.model),e.model&&n.push(`--model`,e.model),e.systemPrompt&&n.push(`--system-prompt`,e.systemPrompt),s===`full`&&n.push(`--approval-mode`,`yolo`),a&&a.length>0){let e=new Set((o??[]).map(e=>e.toLowerCase())),t=a.filter(t=>!e.has(t.toLowerCase()));for(let e of t)n.push(`--allowed-tools`,e)}return t.requestedSessionId&&n.push(`--resume`,t.requestedSessionId),c&&c.length>0&&n.push(...c),i.trim().startsWith(`-`)?n.push(`--prompt`,i):n.push(i),n}buildEnv(e,t){return this.buildDefaultEnv(this.creationOptions.propagateEnv)}mapRawEvent(e,t){this.appendRawLog(e);let n=E(e);if(!n)return this.onParseError(JSON.stringify(e).slice(0,200),/* @__PURE__ */ Error(`schema validation failed`)),{events:[]};let r=h(n)??t.sessionId,a=w(n,{...t,sessionId:r},{model:this.runModels.get(t.runId)});return r&&a.sessionId===void 0&&(a.sessionId=r),i(a,n.type===`result`,this.runTextBuffers,t.runId)}async onRunFinished(e){await super.onRunFinished(e),this.runModels.delete(e.runId),this.runTextBuffers.delete(e.runId)}};const k=e=>new O(s(e));export{k as createGeminiCliAgent};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as OpencodeEvent, i as OpencodeCliRunOptions, n as OpencodeCliAgent, r as OpencodeCliAgentOptions, t as createOpencodeCliAgent } from "../../index-
|
|
1
|
+
import { a as OpencodeEvent, i as OpencodeCliRunOptions, n as OpencodeCliAgent, r as OpencodeCliAgentOptions, t as createOpencodeCliAgent } from "../../index-DmpVdnKm.mjs";
|
|
2
2
|
export { type OpencodeCliAgent, type OpencodeCliAgentOptions, type OpencodeCliRunOptions, type OpencodeEvent, createOpencodeCliAgent };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as e,i as t,n}from"../../util-B4HTdOSc.mjs";import{c as r,l as i,s as a,u as o}from"../../classify-error-DOqkMCcy.mjs";import{t as s}from"../../execution-target-CdlYXh6Z.mjs";import{t as c}from"../../Agent-
|
|
1
|
+
import{a as e,i as t,n}from"../../util-B4HTdOSc.mjs";import{c as r,l as i,s as a,u as o}from"../../classify-error-DOqkMCcy.mjs";import{t as s}from"../../execution-target-CdlYXh6Z.mjs";import{t as c}from"../../Agent-BjaeRtLk.mjs";import{z as l}from"zod/v4";const u=e=>typeof e==`string`?e:void 0,d=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,f=e=>{if(typeof e==`string`)return e;if(e===null)return``;try{return JSON.stringify(e)}catch{return String(e)}},p=()=>crypto.randomUUID(),m=()=>({steps:0,cost:0,inputTokens:0,outputTokens:0,reasoningTokens:0,cacheReadTokens:0,cacheWriteTokens:0}),h=e=>{let t=e;return u(t.sessionID)??u(t.session_id)},g=(e,t)=>{let r=n(e.part)?e.part:void 0,i=u(r?.text)??``;return i.trim()?{events:[a(t.runId,`message`,{sessionId:t.sessionId,model:null,role:`assistant`,content:[o(i)],text:i})]}:{events:[]}},_=(e,t)=>{let r=n(e.part)?e.part:void 0,i=u(r?.text)??``;return i.trim()?{events:[a(t.runId,`reasoning`,{sessionId:t.sessionId,model:null,content:[o(i)],text:i})]}:{events:[]}},v=(e,t)=>{let r=n(e.part)?e.part:void 0;if(!r)return{events:[]};let i=u(r.callID)??p(),o=u(r.tool)??`tool`,s=n(r.state)?r.state:void 0;if(!s)return{events:[]};let c=n(s.input)?s.input:void 0,l=s.status===`error`,d=l?u(s.error)??f(s.output)??`Tool call failed.`:f(s.output);return{events:[a(t.runId,`tool-call`,{sessionId:t.sessionId,model:null,toolCallId:i,toolName:o,input:c}),a(t.runId,`tool-result`,{sessionId:t.sessionId,toolCallId:i,toolName:o,input:c,output:d,isError:l||void 0,error:l?d:void 0})],toolCalls:[{toolCallId:i,toolName:o,input:c}]}},y=(e,r,i)=>{let a=n(e.part)?e.part:void 0;if(!a)return{events:[]};let o=u(a.reason),s=d(a.cost)??0,c=n(a.tokens)?a.tokens:void 0,l=n(c?.cache)?c.cache:void 0;return i.steps+=1,i.cost+=s,i.inputTokens+=d(c?.input)??0,i.outputTokens+=d(c?.output)??0,i.reasoningTokens+=d(c?.reasoning)??0,i.cacheReadTokens+=d(l?.read)??0,i.cacheWriteTokens+=d(l?.write)??0,o===`stop`?{events:[],state:{stats:{turns:i.steps,costUsd:i.cost,inputTokens:i.inputTokens,outputTokens:i.outputTokens,reasoningOutputTokens:i.reasoningTokens,cacheReadInputTokens:i.cacheReadTokens,cacheCreationInputTokens:i.cacheWriteTokens,totalTokens:t(i.inputTokens,i.outputTokens,i.cacheReadTokens,i.cacheWriteTokens)},status:`completed`}}:{events:[]}},b=(e,t)=>{let r=n(e.error)?e.error:void 0,i=n(r?.data)?r.data:void 0,o=u(i?.message)??u(r?.message)??u(r?.name)??`unknown error`;return{events:[a(t.runId,`stderr`,{sessionId:t.sessionId,text:o})],state:{status:`failed`,error:{kind:`provider`,message:o}}}},x=(e,t,n)=>{let r=e;switch(e.type){case`text`:return g(r,t);case`reasoning`:return _(r,t);case`tool_use`:return v(r,t);case`step_finish`:return y(r,t,n);case`error`:return b(r,t);default:return{events:[]}}},S=l.object({type:l.string()}).passthrough(),C=r(S),w={structuredOutput:!1,sessionResume:!0,sessionFork:!0,imageInput:!1,mcp:!0,eventStreaming:!0};var T=class extends c{type=`opencode-cli`;creationOptions;runDefaults;stepAccumulators=/* @__PURE__ */ new Map;constructor(t={}){super({type:`opencode-cli`,capabilities:w,defaults:{cwd:t.cwd,env:t.env,command:e(t.command??`opencode`),sessionId:t.sessionId,model:t.model},spawner:t.spawner,executionTarget:t.container??t.sandbox,logPath:t.logPath,onEvent:t.onEvent}),this.creationOptions=t,this.runDefaults={agent:t.agent,files:t.files?[...t.files]:void 0,forkSession:t.forkSession,share:t.share,thinking:t.thinking,title:t.title,variant:t.variant,extraArgs:t.extraArgs?[...t.extraArgs]:void 0}}buildArgs(e,t){let n=[`run`,`--format`,`json`],r=i(e.input),a=e.agent??this.runDefaults.agent,o=e.files??this.runDefaults.files,s=e.forkSession??this.runDefaults.forkSession,c=e.share??this.runDefaults.share,l=e.thinking??this.runDefaults.thinking,u=e.title??this.runDefaults.title,d=e.variant??this.runDefaults.variant,f=e.extraArgs??this.runDefaults.extraArgs;if(e.model&&n.push(`--model`,e.model),a&&n.push(`--agent`,a),o&&o.length>0)for(let e of o)n.push(`--file`,e);return t.requestedSessionId&&(n.push(`--session`,t.requestedSessionId),s&&n.push(`--fork`)),c&&n.push(`--share`),l&&n.push(`--thinking`),u!==void 0&&n.push(`--title`,u),d&&n.push(`--variant`,d),f&&f.length>0&&n.push(...f),n.push(`--`,r),n}buildEnv(e,t){return this.buildDefaultEnv(this.creationOptions.propagateEnv)}mapRawEvent(e,t){this.appendRawLog(e);let n=C(e);if(!n)return this.onParseError(JSON.stringify(e).slice(0,200),/* @__PURE__ */ Error(`schema validation failed`)),{events:[]};let r=h(n)??t.sessionId,i=this.stepAccumulators.get(t.runId);i||(i=m(),this.stepAccumulators.set(t.runId,i));let a=x(n,{...t,sessionId:r},i);return r&&a.sessionId===void 0&&(a.sessionId=r),a}async onRunFinished(e){await super.onRunFinished(e),this.stepAccumulators.delete(e.runId)}};const E=e=>new T(s(e));export{E as createOpencodeCliAgent};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as PiCliThinkingLevel, i as PiCliRunOptions, n as PiCliAgent, o as PiEvent, r as PiCliAgentOptions, t as createPiCliAgent } from "../../index-
|
|
1
|
+
import { a as PiCliThinkingLevel, i as PiCliRunOptions, n as PiCliAgent, o as PiEvent, r as PiCliAgentOptions, t as createPiCliAgent } from "../../index-BiUoRRsR.mjs";
|
|
2
2
|
export { type PiCliAgent, type PiCliAgentOptions, type PiCliRunOptions, type PiCliThinkingLevel, type PiEvent, createPiCliAgent };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e}from"../../types-B72tDMEZ.mjs";import{a as t,n}from"../../util-B4HTdOSc.mjs";import{c as r,l as i,s as a,u as o}from"../../classify-error-DOqkMCcy.mjs";import{t as s}from"../../execution-target-CdlYXh6Z.mjs";import{t as c}from"../../Agent-
|
|
1
|
+
import{n as e}from"../../types-B72tDMEZ.mjs";import{a as t,n}from"../../util-B4HTdOSc.mjs";import{c as r,l as i,s as a,u as o}from"../../classify-error-DOqkMCcy.mjs";import{t as s}from"../../execution-target-CdlYXh6Z.mjs";import{t as c}from"../../Agent-BjaeRtLk.mjs";import{z as l}from"zod/v4";const u=e=>typeof e==`string`?e:void 0,d=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,f=()=>crypto.randomUUID(),p=e=>{if(typeof e==`string`)return e;if(e==null)return``;try{return JSON.stringify(e)}catch{return String(e)}},m=e=>{if(typeof e==`string`)return e;if(!Array.isArray(e))return``;let t=[];for(let r of e)n(r)&&r.type===`text`&&typeof r.text==`string`&&t.push(r.text);return t.join(``)},h=e=>{let t=e;if(t.type===`session`)return u(t.id)},g=e=>({events:[],sessionId:u(e.id)??void 0}),_=()=>({events:[]}),v=(e,t,r)=>{let i=n(e.message)?e.message:void 0;if(!i||u(i.role)!==`assistant`)return{events:[]};let s=m(i.content),c=u(i.model)??r.model??null,l=[];return r.reasoningText&&l.push(a(t.runId,`reasoning`,{sessionId:t.sessionId,model:c,content:[o(r.reasoningText)],text:r.reasoningText})),s&&l.push(a(t.runId,`message`,{sessionId:t.sessionId,model:c,role:`assistant`,content:[o(s)],text:s})),u(i.stopReason)===`error`?{events:l,state:{output:{text:s||void 0},status:`failed`,error:{kind:`provider`,message:`Pi model returned an error stop reason.`}}}:s?{events:l,state:{output:{text:s}}}:{events:l}},y=(e,t,n)=>{let r=u(e.toolCallId)??f(),i=u(e.toolName)??`tool`,o=e.args===void 0?void 0:e.args;return{events:[a(t.runId,`tool-call`,{sessionId:t.sessionId,model:n.model??null,toolCallId:r,toolName:i,input:o})],toolCalls:[{toolCallId:r,toolName:i,input:o}]}},b=(e,t)=>{let n=u(e.toolCallId)??f(),r=!!e.isError,i=e.result,o=t.toolCalls.get(n),s=u(e.toolName)??o?.toolName;return{events:[a(t.runId,`tool-result`,{sessionId:t.sessionId,toolCallId:n,toolName:s,input:o?.input,output:i,isError:r||void 0,error:r?p(i):void 0})]}},x=e=>{let t=n(e.message)?e.message:void 0;if(!t)return;let r=n(t.usage)?t.usage:void 0;if(!r)return;let i=d(r.input),a=d(r.output),o=d(r.cacheRead)||void 0,s=d(r.cacheWrite)||void 0;return{turns:1,durationMs:0,costUsd:n(r.cost)?d(r.cost.total)??0:d(r.cost)??0,inputTokens:i,outputTokens:a,cacheReadInputTokens:o,cacheCreationInputTokens:s,totalTokens:(i??0)+(a??0)+(o??0)+(s??0)||void 0}},S=e=>{let t=x(e);return t?{events:[],state:{stats:t}}:{events:[]}},C=(e,t,n={})=>{let r=e;switch(e.type){case`session`:return g(r);case`message_update`:return _();case`message_end`:return v(r,t,n);case`tool_execution_start`:return y(r,t,n);case`tool_execution_end`:return b(r,t);case`turn_end`:return S(r);default:return{events:[]}}},w=l.object({type:l.string()}).passthrough(),T=r(w),E={structuredOutput:!1,sessionResume:!0,imageInput:!0,mcp:!1,eventStreaming:!0,sessionFork:!0},D=(e,t)=>({turns:(e?.turns??0)+t.turns,durationMs:(e?.durationMs??0)+(t.durationMs??0),apiDurationMs:(e?.apiDurationMs??0)+(t.apiDurationMs??0),costUsd:(e?.costUsd??0)+t.costUsd,inputTokens:t.inputTokens!==void 0||e?.inputTokens!==void 0?(e?.inputTokens??0)+(t.inputTokens??0):void 0,outputTokens:t.outputTokens!==void 0||e?.outputTokens!==void 0?(e?.outputTokens??0)+(t.outputTokens??0):void 0,cacheReadInputTokens:t.cacheReadInputTokens!==void 0||e?.cacheReadInputTokens!==void 0?(e?.cacheReadInputTokens??0)+(t.cacheReadInputTokens??0):void 0,cacheCreationInputTokens:t.cacheCreationInputTokens!==void 0||e?.cacheCreationInputTokens!==void 0?(e?.cacheCreationInputTokens??0)+(t.cacheCreationInputTokens??0):void 0,totalTokens:t.totalTokens!==void 0||e?.totalTokens!==void 0?(e?.totalTokens??0)+(t.totalTokens??0):void 0});var O=class n extends c{type=`pi-cli`;creationOptions;runDefaults;runTextBuffers=/* @__PURE__ */ new Map;runReasoningBuffers=/* @__PURE__ */ new Map;runAccumulatedStats=/* @__PURE__ */ new Map;forkOnNextRun;constructor(e={}){super({type:`pi-cli`,capabilities:E,defaults:{cwd:e.cwd,env:e.env,command:t(e.command??`pi`),sessionId:e.sessionId,model:e.model,systemPrompt:e.systemPrompt},spawner:e.spawner,executionTarget:e.container??e.sandbox,logPath:e.logPath,onEvent:e.onEvent}),this.creationOptions=e,this.runDefaults={provider:e.provider,thinking:e.thinking,appendSystemPrompt:e.appendSystemPrompt,allowedTools:e.allowedTools?[...e.allowedTools]:void 0,noTools:e.noTools,noSession:e.noSession,sessionDir:e.sessionDir,forkSession:e.forkSession,extraArgs:e.extraArgs?[...e.extraArgs]:void 0},this.forkOnNextRun=e.forkOnNextRun??!1}fork(){if(!this.sessionId)throw new e(`Cannot fork a Pi CLI agent before it has a sessionId.`);return new n({...this.creationOptions,sessionId:this.sessionId,forkSession:void 0,forkOnNextRun:!0})}onValidateRun(t,n){if((t.forkSession??this.runDefaults.forkSession??this.forkOnNextRun)&&!this.sessionId)throw new e(`forkSession requires an existing sessionId on the agent.`)}buildArgs(e,t){let n=[`--mode`,`json`],r=e.provider??this.runDefaults.provider,a=e.thinking??this.runDefaults.thinking,o=e.appendSystemPrompt??this.runDefaults.appendSystemPrompt,s=e.allowedTools??this.runDefaults.allowedTools,c=e.noTools??this.runDefaults.noTools,l=e.noSession??this.runDefaults.noSession,u=e.sessionDir??this.runDefaults.sessionDir,d=e.forkSession??this.runDefaults.forkSession??this.forkOnNextRun,f=e.extraArgs??this.runDefaults.extraArgs;e.model?r?n.push(`--model`,`${r}/${e.model}`):n.push(`--model`,e.model):r&&n.push(`--provider`,r),e.systemPrompt&&n.push(`--system-prompt`,e.systemPrompt),o&&n.push(`--append-system-prompt`,o),a&&n.push(`--thinking`,a),c?n.push(`--no-tools`):s&&s.length>0&&n.push(`--tools`,s.join(`,`)),t.requestedSessionId?d?n.push(`--fork`,t.requestedSessionId):n.push(`--session`,t.requestedSessionId):l?n.push(`--no-session`):u&&n.push(`--session-dir`,u),f&&f.length>0&&n.push(...f);for(let t of e.input)t.type===`image`&&n.push(`@${t.path}`);let p=i(e.input);return n.push(p),n}buildEnv(e,t){return this.buildDefaultEnv(this.creationOptions.propagateEnv)}mapRawEvent(e,t){this.appendRawLog(e);let n=T(e);if(!n)return this.onParseError(JSON.stringify(e).slice(0,200),/* @__PURE__ */ Error(`schema validation failed`)),{events:[]};let r=h(n)??t.sessionId;if(this.forkOnNextRun&&t.requestedSessionId&&r&&r!==t.requestedSessionId&&(this.forkOnNextRun=!1),n.type===`message_update`){let e=n.assistantMessageEvent,r=typeof e?.type==`string`?e.type:void 0,i=typeof e?.delta==`string`?e.delta:``;if(r===`text_delta`&&i){let e=`${this.runTextBuffers.get(t.runId)??``}${i}`;this.runTextBuffers.set(t.runId,e)}else if(r===`thinking_delta`&&i){let e=`${this.runReasoningBuffers.get(t.runId)??``}${i}`;this.runReasoningBuffers.set(t.runId,e)}}let i={model:void 0};n.type===`message_end`&&(i.reasoningText=this.runReasoningBuffers.get(t.runId),this.runReasoningBuffers.delete(t.runId));let a=C(n,{...t,sessionId:r},i);if(r&&a.sessionId===void 0&&(a.sessionId=r),a.state?.output?.text!==void 0&&this.runTextBuffers.set(t.runId,a.state.output.text),n.type===`turn_end`&&a.state?.stats){let e=this.runAccumulatedStats.get(t.runId),n=D(e,a.state.stats);this.runAccumulatedStats.set(t.runId,n),a.state.stats=n}return a}async onRunFinished(e){await super.onRunFinished(e),this.runTextBuffers.delete(e.runId),this.runReasoningBuffers.delete(e.runId),this.runAccumulatedStats.delete(e.runId)}};const k=e=>new O(s(e));export{k as createPiCliAgent};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { A as VolumeMount, C as DockerContainer, D as ExecOptions, E as ContainerType, F as WorkdirSnapshot, I as WorkdirSnapshotOptions, M as WorkdirDiff, N as WorkdirDiffStats, O as ExecResult, P as WorkdirFileChange, S as E2BProviderConfig, T as ContainerStatus, _ as E2BConnectConfig, a as ContainerDiffError, b as E2BContainerConfig, c as ContainerExecError, d as MountValidationError, f as PodmanContainer, g as NerdctlProviderConfig, h as NerdctlContainerConfig, i as ContainerCreateError, j as WorkdirChangeKind, k as PortMapping, l as ContainerNotRunningError, m as NerdctlContainer, n as ContainerConfig, o as ContainerDisposedError, p as PodmanContainerConfig, r as createContainer, s as ContainerError, t as Container, u as ContainerStartError, v as E2BConnectionConfig, w as DockerContainerConfig, x as E2BCreateConfig, y as E2BContainer } from "../index-
|
|
1
|
+
import { A as VolumeMount, C as DockerContainer, D as ExecOptions, E as ContainerType, F as WorkdirSnapshot, I as WorkdirSnapshotOptions, M as WorkdirDiff, N as WorkdirDiffStats, O as ExecResult, P as WorkdirFileChange, S as E2BProviderConfig, T as ContainerStatus, _ as E2BConnectConfig, a as ContainerDiffError, b as E2BContainerConfig, c as ContainerExecError, d as MountValidationError, f as PodmanContainer, g as NerdctlProviderConfig, h as NerdctlContainerConfig, i as ContainerCreateError, j as WorkdirChangeKind, k as PortMapping, l as ContainerNotRunningError, m as NerdctlContainer, n as ContainerConfig, o as ContainerDisposedError, p as PodmanContainerConfig, r as createContainer, s as ContainerError, t as Container, u as ContainerStartError, v as E2BConnectionConfig, w as DockerContainerConfig, x as E2BCreateConfig, y as E2BContainer } from "../index-kXfBtyJn.mjs";
|
|
2
2
|
export { Container, ContainerConfig, ContainerCreateError, ContainerDiffError, ContainerDisposedError, ContainerError, ContainerExecError, ContainerNotRunningError, ContainerStartError, type ContainerStatus, type ContainerType, type DockerContainer, type DockerContainerConfig, type E2BConnectConfig, type E2BConnectionConfig, type E2BContainer, type E2BContainerConfig, type E2BCreateConfig, type E2BProviderConfig, type ExecOptions, type ExecResult, MountValidationError, type NerdctlContainer, type NerdctlContainerConfig, type NerdctlProviderConfig, type PodmanContainer, type PodmanContainerConfig, type PortMapping, type VolumeMount, type WorkdirChangeKind, type WorkdirDiff, type WorkdirDiffStats, type WorkdirFileChange, type WorkdirSnapshot, type WorkdirSnapshotOptions, createContainer };
|
package/dist/container/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as e,c as t,i as n,l as r,n as i,o as a,r as o,s,t as c}from"../container-
|
|
1
|
+
import{a as e,c as t,i as n,l as r,n as i,o as a,r as o,s,t as c}from"../container-DMFxf-kn.mjs";export{i as ContainerCreateError,o as ContainerDiffError,n as ContainerDisposedError,e as ContainerError,a as ContainerExecError,s as ContainerNotRunningError,t as ContainerStartError,r as MountValidationError,c as createContainer};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e,t}from"./oci-
|
|
1
|
+
import{n as e,t}from"./oci-DTNwW-WH.mjs";const n=async n=>{let r={binary:n.binary??`docker`},i=await e(r,n);return t(`docker`,{commandContext:r,containerName:n.name,workdir:n.workdir,user:n.user,network:n.network,platform:n.platform,env:n.env,ports:n.ports,mounts:n.mounts,mountCwd:n.mountCwd,extraArgs:n.extraArgs,image:i,builtImage:n.build!==void 0&&!n.build.tag},n)};export{n as createDockerContainer};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=class extends Error{constructor(e){super(e),this.name=`ContainerError`}},t=class extends e{constructor(e){super(e),this.name=`ContainerCreateError`}},n=class extends e{constructor(e){super(e),this.name=`MountValidationError`}},r=class extends e{constructor(e){super(e),this.name=`ContainerStartError`}},i=class extends e{constructor(e){super(e),this.name=`ContainerExecError`}},a=class extends e{constructor(e=`Container is not running.`){super(e),this.name=`ContainerNotRunningError`}},o=class extends e{constructor(e=`Container has been disposed.`){super(e),this.name=`ContainerDisposedError`}},s=class extends e{constructor(e){super(e),this.name=`ContainerDiffError`}};async function c(e){switch(e.type){case`docker`:{let{createDockerContainer:t}=await import(`./container-
|
|
1
|
+
var e=class extends Error{constructor(e){super(e),this.name=`ContainerError`}},t=class extends e{constructor(e){super(e),this.name=`ContainerCreateError`}},n=class extends e{constructor(e){super(e),this.name=`MountValidationError`}},r=class extends e{constructor(e){super(e),this.name=`ContainerStartError`}},i=class extends e{constructor(e){super(e),this.name=`ContainerExecError`}},a=class extends e{constructor(e=`Container is not running.`){super(e),this.name=`ContainerNotRunningError`}},o=class extends e{constructor(e=`Container has been disposed.`){super(e),this.name=`ContainerDisposedError`}},s=class extends e{constructor(e){super(e),this.name=`ContainerDiffError`}};async function c(e){switch(e.type){case`docker`:{let{createDockerContainer:t}=await import(`./container-Bdb90GJb.mjs`);return t(e)}case`e2b`:try{let{createE2BContainer:t}=await import(`./container-w0rl1QMH.mjs`);return await t(e)}catch(e){throw e instanceof Error&&e.message.includes(`e2b`)&&(e.code===`ERR_MODULE_NOT_FOUND`||e.code===`MODULE_NOT_FOUND`)?new t(`Container type "e2b" requires the optional peer dependency "e2b". Install it to use this provider.`):e}case`nerdctl`:{let{createNerdctlContainer:t}=await import(`./container-dCRMBvQw.mjs`);return t(e)}case`podman`:{let{createPodmanContainer:t}=await import(`./container-Dvr-p53c.mjs`);return t(e)}default:throw new t(`Unsupported container type.`)}}export{e as a,r as c,o as i,n as l,t as n,i as o,s as r,a as s,c as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e,t}from"./oci-
|
|
1
|
+
import{n as e,t}from"./oci-DTNwW-WH.mjs";const n=async n=>{let r={binary:n.binary??`podman`},i=await e(r,n);return t(`podman`,{commandContext:r,containerName:n.name,workdir:n.workdir,user:n.user,network:n.network,platform:n.platform,env:n.env,ports:n.ports,mounts:n.mounts,mountCwd:n.mountCwd,extraArgs:n.extraArgs,image:i,builtImage:n.build!==void 0&&!n.build.tag},n)};export{n as createPodmanContainer};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e,t}from"./oci-
|
|
1
|
+
import{n as e,t}from"./oci-DTNwW-WH.mjs";const n=e=>{let t={};return e.address&&(t.CONTAINERD_ADDRESS=e.address),e.namespace&&(t.CONTAINERD_NAMESPACE=e.namespace),e.buildkitHost&&(t.BUILDKIT_HOST=e.buildkitHost),Object.keys(t).length>0?t:void 0},r=e=>{let t=[];return e.namespace&&t.push(`--namespace`,e.namespace),e.address&&t.push(`--address`,e.address),e.snapshotter&&t.push(`--snapshotter`,e.snapshotter),e.args&&t.push(...e.args),t.length>0?t:void 0},i=e=>({binary:e.binary??`nerdctl`,baseArgs:r(e),env:n(e)}),a=async n=>{let r=i(n),a=await e(r,n);return t(`nerdctl`,{commandContext:r,containerName:n.name,workdir:n.workdir,user:n.user,network:n.network,platform:n.platform,env:n.env,ports:n.ports,mounts:n.mounts,mountCwd:n.mountCwd,extraArgs:n.extraArgs,image:a,builtImage:n.build!==void 0&&!n.build.tag},n)};export{a as createNerdctlContainer};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./util-B4HTdOSc.mjs";import{c as t,i as n,n as r,r as i,s as a}from"./container-DMFxf-kn.mjs";import{t as o}from"./errors-aYGbvsaq.mjs";import{t as s}from"./shell-DvWFuFKb.mjs";import{n as c}from"./diff-Dqyk2cdt.mjs";import{basename as l,dirname as u,join as d,posix as f}from"node:path";import{mkdir as p,readFile as m,readdir as h,stat as g,writeFile as _}from"node:fs/promises";import{CommandExitError as v,FileType as y,Sandbox as b}from"e2b";const x=(e,t)=>[e,...t].map(s).join(` `),S=e=>e.user,C=(e,t)=>{let n={...e.env,...t};return Object.keys(n).length>0?n:void 0},w=(e,t)=>t??e.workdir,T=new TextEncoder,E=e=>e instanceof Error?e:Error(String(e)),D=e=>typeof e==`string`?e:`SIGKILL`,O=(e,t)=>{let n=e?.stdio?.[t];return n===`ignore`||n===`inherit`||n===`pipe`?n:n===void 0?`pipe`:`ignore`},k=()=>{let e=[],t=[],n=!1,r,i=()=>{for(;t.length>0&&e.length>0;)t.shift().resolve({done:!1,value:e.shift()});if(r){for(;t.length>0;)t.shift().reject(r);return}if(n)for(;t.length>0;)t.shift().resolve({done:!0,value:void 0})};return{iterable:{async*[Symbol.asyncIterator](){for(;;){if(e.length>0){yield e.shift();continue}if(r)throw E(r);if(n)return;let i=await new Promise((e,n)=>{t.push({resolve:e,reject:n})});if(i.done)return;yield i.value}}},push(t){t.length===0||n||r||(e.push(T.encode(t)),i())},end(){n||r||(n=!0,i())},fail(e){n||r||(r=e,i())}}},A=(e,t)=>({spawn:(n,r,i={})=>{let a=O(i,0),s=O(i,1),c=O(i,2),l=s===`pipe`?k():void 0,u=c===`pipe`?k():void 0,d=null,f={background:!0,stdin:a===`pipe`,cwd:w(t,i.cwd),envs:C(t,i.env),user:S(t),requestTimeoutMs:t.requestTimeoutMs,onStdout:e=>{if(s===`inherit`){process.stdout.write(e);return}l?.push(e)},onStderr:e=>{if(c===`inherit`){process.stderr.write(e);return}u?.push(e)}},p=e.commands.run(x(n,r),f),m=Promise.resolve(),h,g=e=>{let t=m.then(async()=>{await e((await p).pid)});return m=t.catch(e=>{h??=new o(e)}),t};return p.catch(e=>{l?.fail(e),u?.fail(e)}),{stdout:l?.iterable??null,stderr:u?.iterable??null,stdin:a===`pipe`?{write:n=>g(r=>e.commands.sendStdin(r,n,{requestTimeoutMs:t.requestTimeoutMs})),end:()=>g(n=>e.commands.closeStdin(n,{requestTimeoutMs:t.requestTimeoutMs}))}:null,kill:e=>{d=D(e),p.then(e=>e.kill()).catch(()=>{})},wait:async()=>{try{let e=await(await p).wait();if(await m,h)throw h;return l?.end(),u?.end(),d?{exitCode:null,signal:d}:{exitCode:e.exitCode,signal:null}}catch(e){if(l?.end(),u?.end(),e instanceof v)return d?{exitCode:null,signal:d}:{exitCode:e.exitCode,signal:null};throw e}}}}}),j=e=>({apiKey:e.apiKey,domain:e.domain,requestTimeoutMs:e.requestTimeoutMs,apiHeaders:e.headers}),M=e=>`sandboxId`in e&&typeof e.sandboxId==`string`,N=e=>{let t=j(e);return M(e)?t:{...t,envs:e.env,timeoutMs:e.timeoutMs,metadata:e.metadata,secure:e.secure,allowInternetAccess:e.allowInternetAccess,network:e.network,lifecycle:e.lifecycle}},P=async(e,t)=>{await e.files.makeDir(t.workdir,{user:S(t)})},F=e=>e instanceof Error&&e.name===`AbortError`,I=e=>Uint8Array.from(e).buffer,L=e=>{let t=e.endsWith(`/`)&&e!==`/`?e.slice(0,-1):e;return f.basename(t)},R=async e=>{try{return await g(e)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}},z=async(e,t,n)=>{if(await e.files.exists(t,{user:n}))return e.files.getInfo(t,{user:n})},B=async(e,t,n,r)=>(await z(e,n,r))?.type===y.DIR?f.join(n,l(t)):n,V=async(e,t)=>(await R(t))?.isDirectory()?d(t,L(e)):t,H=async(e,t,n,r)=>{let i=await g(t);if(i.isDirectory()){await e.files.makeDir(n,{user:r});let i=await h(t);await Promise.all(i.map(i=>H(e,d(t,i),f.join(n,i),r)));return}if(!i.isFile())throw Error(`Unsupported local filesystem entry at ${t}.`);let a=await m(t);await e.files.write(n,I(a),{user:r})},U=async(e,t,n,r)=>{if((await e.files.getInfo(t,{user:r})).type===y.DIR){await p(n,{recursive:!0});let i=await e.files.list(t,{user:r});await Promise.all(i.map(t=>U(e,t.path,d(n,t.name),r)));return}let i=await e.files.read(t,{format:`bytes`,user:r});await p(u(n),{recursive:!0}),await _(n,i)},W=async e=>{if(M(e))return b.connect(e.sandboxId,j(e));let t=N(e);return e.template?b.create(e.template,t):b.create(t)},G=async(e,t)=>e.connect(j(t)),K=async(e,t)=>{let n=t.signal;if(n?.aborted){let e=n.reason;throw e instanceof Error?e:new DOMException(`The operation was aborted.`,`AbortError`)}let r=!1,i=()=>{r=!0,e.kill()};n?.addEventListener(`abort`,i,{once:!0});try{let t=await e.wait();if(r)throw new DOMException(`The operation was aborted.`,`AbortError`);return{exitCode:t.exitCode,stdout:t.stdout,stderr:t.stderr}}catch(e){if(r||F(e))throw new DOMException(`The operation was aborted.`,`AbortError`);if(e instanceof v)return{exitCode:e.exitCode,stdout:e.stdout,stderr:e.stderr};throw e}finally{n?.removeEventListener(`abort`,i)}},q=async o=>{let s;try{s=await W(o),await P(s,o)}catch(t){throw new r(`E2B create failed: ${e(t)}`)}let l=o.name??s.sandboxId,u=`running`,f=A(s,o),m={},h=()=>{if(u===`disposed`)throw new n},g=()=>{if(h(),u!==`running`)throw new a},_=c({owner:m,workdir:o.workdir,materialize:async(e,t)=>{g();let n=S(o),r=await z(s,e,n);if(!r)throw new i(`Target path does not exist: ${e}`);if(r.type!==y.DIR)throw new i(`Target path is not a directory: ${e}`);await p(t,{recursive:!0});for(let r of await s.files.list(e,{user:n}))await U(s,r.path,d(t,r.name),n)}}),v={get type(){return`e2b`},get id(){return s.sandboxId},get name(){return l},get config(){return o},get status(){return u},get workdir(){return o.workdir},get spawner(){return f},async start(){if(h(),u!==`running`)try{s=await G(s,o),await P(s,o),f=A(s,o),u=`running`}catch(n){throw new t(`E2B start failed: ${e(n)}`)}},async stop(){h(),u===`running`&&(await s.pause({requestTimeoutMs:o.requestTimeoutMs}),u=`stopped`)},async dispose(){if(u!==`disposed`){try{await s.kill({requestTimeoutMs:o.requestTimeoutMs})}catch{}await _.disposeSnapshots().catch(()=>{}),u=`disposed`}},async exec(e,t,n={}){g();let r={background:!0,cwd:w(o,n.cwd),envs:C(o,n.env),user:S(o),timeoutMs:n.timeoutMs,requestTimeoutMs:o.requestTimeoutMs},i=await s.commands.run(x(e,t),r);return K(i,n)},async copyTo(e,t){g();let n=await B(s,e,t,S(o));await H(s,e,n,S(o))},async copyFrom(e,t){g();let n=await V(e,t);await U(s,e,n,S(o))},async writeFile(e,t){g(),await s.files.write(e,typeof t==`string`?t:I(t),{user:S(o)})},async readFile(e){return g(),s.files.read(e,{format:`text`,user:S(o)})},async fileExists(e){return g(),s.files.exists(e,{user:S(o)})},async mkdir(e){g(),await s.files.makeDir(e,{user:S(o)})},async execShell(e,t={}){return v.exec(`sh`,[`-c`,e],t)},async logs(){return``},async syncStatus(){return u},async snapshotWorkdir(e={}){return _.snapshotWorkdir(e)},async diffWorkdir(e){return _.diffWorkdir(e)},async releaseWorkdirSnapshot(e){return _.releaseWorkdirSnapshot(e)},getHost(e){return g(),s.getHost(e)},[Symbol.asyncDispose](){return v.dispose()}};return v};export{q as createE2BContainer};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { a as SpawnOptions, i as ProcessSpawner, n as ProcessResult, r as ProcessSignal, t as AgentProcess } from "../../types-COmjfh8B.mjs";
|
|
2
|
+
import { n as spawnProcess, t as ProcessStdinError } from "../../index-DvwVRB7K.mjs";
|
|
3
|
+
export { type AgentProcess, type ProcessResult, type ProcessSignal, type ProcessSpawner, ProcessStdinError, type SpawnOptions, spawnProcess };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"../../errors-aYGbvsaq.mjs";import{n as t}from"../../spawner-CgfyvnR4.mjs";export{e as ProcessStdinError,t as spawnProcess};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./util-B4HTdOSc.mjs";import{i as t,r as n,s as r}from"./container-DMFxf-kn.mjs";import{n as i}from"./errors-aYGbvsaq.mjs";import{execFile as a}from"node:child_process";import{dirname as o,isAbsolute as s,join as c,posix as l,relative as u,sep as d}from"node:path";import{promisify as f}from"node:util";import{createReadStream as p}from"node:fs";import{tmpdir as m}from"node:os";import{copyFile as h,lstat as g,mkdir as _,mkdtemp as v,readdir as y,readlink as b,rm as x,stat as S,symlink as C}from"node:fs/promises";import{createHash as w}from"node:crypto";import{pipeline as T}from"node:stream/promises";const E=f(a),D=e=>e!==`..`&&!e.startsWith(`..${d}`)&&!s(e),O=(e,t)=>{let n=u(e,t);if(D(n))return n.split(d).join(l.sep)},k=(e,t,r)=>{let i=O(t,e);if(i!==void 0)return i;let a=O(r,e);if(a!==void 0)return a;throw new n(`Git diff produced a path outside the materialized trees: ${e}`)},A=e=>e.sort((e,t)=>e.path===t.path?(e.previousPath??``).localeCompare(t.previousPath??``):e.path.localeCompare(t.path)),j=async e=>{let t=await y(e,{withFileTypes:!0});for(let n of t){let t=c(e,n.name);if(n.name===`.git`){await x(t,{recursive:!0,force:!0});continue}n.isDirectory()&&await j(t)}},M=()=>v(c(m(),`cw-workdir-diff-`)),N=async e=>{e&&await x(e,{recursive:!0,force:!0}).catch(()=>{})},P=(e,t)=>{let n={cwd:e.cwd,createdAt:/* @__PURE__ */ new Date};return t.set(n,e),n},F=(e,t,r)=>{if(typeof t!=`object`||!t)throw new n(`Invalid workdir snapshot.`);let i=r.get(t);if(!i)throw new n(`Invalid workdir snapshot.`);if(i.owner!==e)throw new n(`Workdir snapshot was created by a different container instance.`);return i},I=(e,t)=>{if(!t.has(e))throw new n(`Workdir snapshot has been released.`)},L=e=>w(`sha256`).update(e).digest(`hex`),R=e=>Buffer.isBuffer(e)?e:Buffer.from(e,`utf8`),z=async e=>{let t=w(`sha256`);return await T(p(e),t),t.digest(`hex`)},B=async(e,t,r)=>{let i=`${e}:${t}`;if(r.has(i))return r.get(i);let a=c(e,...t.split(l.sep));try{let e=await g(a),t,o;if(e.isSymbolicLink()){let e=Buffer.from(await b(a));t=L(e),o=e.byteLength}else if(e.isFile())t=await z(a),o=e.size;else throw new n(`Unsupported filesystem entry in diff metadata: ${a}`);let s={hash:t,size:o};return r.set(i,s),s}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`){r.set(i,void 0);return}throw e}},V=(e,t,r)=>{if(e.byteLength===0)return[];let i=e.toString(`utf8`).split(`\0`);i[i.length-1]===``&&i.pop();let a=[];for(let e=0;e<i.length;){let o=i[e++];if(!o)continue;if(o.startsWith(`R`)){let o=i[e++],s=i[e++];if(!o||!s)throw new n(`Failed to parse git rename entry.`);a.push({kind:`renamed`,previousPath:k(o,t,r),path:k(s,t,r)});continue}let s=i[e++];if(!s)throw new n(`Failed to parse git diff entry.`);switch(o){case`A`:a.push({kind:`added`,path:k(s,t,r)});break;case`D`:a.push({kind:`deleted`,path:k(s,t,r)});break;case`M`:a.push({kind:`modified`,path:k(s,t,r)});break;case`T`:a.push({kind:`modified`,path:k(s,t,r)});break;default:throw new n(`Unsupported git diff change kind: ${o}`)}}return a},H=async(t,r)=>{try{let e=await E(`git`,[`diff`,`--no-index`,`-z`,`--name-status`,`-M`,`--find-renames=100%`,t,r],{cwd:m(),encoding:`buffer`,maxBuffer:52428800});return V(R(e.stdout),t,r)}catch(a){if(!i(a))throw new n(`Failed to run git diff: ${e(a)}`);let o=a.code??1,s=Buffer.isBuffer(a.stdout)?a.stdout:Buffer.from(String(a.stdout??``),`utf8`),c=Buffer.isBuffer(a.stderr)?a.stderr:Buffer.from(String(a.stderr??``),`utf8`);if(o===0||o===1)return V(s,t,r);let l=c.toString(`utf8`).trim()||s.toString(`utf8`).trim()||`exit code ${o}`;throw new n(`Failed to run git diff: ${l}`)}},U=async(e,t,n)=>{let r=/* @__PURE__ */ new Map,i=await Promise.all(e.map(async e=>{let i;i=e.kind===`added`?void 0:e.kind===`renamed`?e.previousPath:e.path;let a=e.kind===`deleted`?void 0:e.path,[o,s]=await Promise.all([i===void 0?void 0:B(t,i,r),a===void 0?void 0:B(n,a,r)]);return{path:e.path,previousPath:e.previousPath,kind:e.kind,beforeHash:o?.hash,afterHash:s?.hash,beforeSize:o?.size,afterSize:s?.size}}));return A(i)},W=e=>{let t=/* @__PURE__ */ new Set;for(let n of e)t.add(n.path),n.kind===`renamed`&&n.previousPath&&t.add(n.previousPath);return[...t].sort((e,t)=>e.localeCompare(t))},G=(i,a)=>{throw a instanceof n||a instanceof t||a instanceof r?a:new n(`${i}: ${e(a)}`)},K=async(e,t)=>{if(!(await S(e)).isDirectory())throw new n(`Target path is not a directory: ${e}`);await _(t,{recursive:!0});let r=await y(e,{withFileTypes:!0});await Promise.all(r.filter(e=>e.name!==`.git`).map(async r=>{let i=c(e,r.name),a=c(t,r.name);if(r.isDirectory()){await K(i,a);return}if(r.isSymbolicLink()){await _(o(a),{recursive:!0}),await C(await b(i),a);return}if(r.isFile()){await _(o(a),{recursive:!0}),await h(i,a);return}throw new n(`Unsupported filesystem entry in workdir diff: ${i}`)}))},q=e=>{let t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new WeakMap,r=async(r={})=>{let i=r.cwd??e.workdir,a;try{a=await M(),await e.materialize(i,a),await j(a);let r={owner:e.owner,tempDir:a,cwd:i,inFlightDiffs:0,released:!1};return t.add(r),a=void 0,P(r,n)}catch(e){return await N(a),G(`Failed to materialize workdir snapshot`,e)}},i=async r=>{let i=Date.now(),a=F(e.owner,r,n);I(a,t),a.inFlightDiffs++;let o;try{o=await M(),await e.materialize(a.cwd,o),await j(o);let t=await H(a.tempDir,o),n=await U(t,a.tempDir,o),r=W(n);return{cwd:a.cwd,changedFiles:r,fileChanges:n,stats:{durationMs:Date.now()-i,filesCompared:r.length}}}catch(e){return G(`Failed to diff workdir snapshot`,e)}finally{a.inFlightDiffs--,a.inFlightDiffs===0&&(a.resolveIdle?.(),a.resolveIdle=void 0),await N(o)}},a=e=>{let n=e;return n.releasePromise?n.releasePromise:(n.released=!0,t.delete(n),n.releasePromise=(async()=>{n.inFlightDiffs>0&&await new Promise(e=>{n.resolveIdle=e}),await N(n.tempDir)})(),n.releasePromise)};return{snapshotWorkdir:r,diffWorkdir:i,releaseWorkdirSnapshot:async t=>{let r=F(e.owner,t,n);await a(r)},disposeSnapshots:async()=>{await Promise.all(Array.from(t).map(a))}}};export{q as n,K as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./util-B4HTdOSc.mjs";const t=e=>e instanceof Error&&`code`in e&&(`stdout`in e||`stderr`in e);var n=class extends Error{constructor(t){super(e(t),{cause:t}),this.name=`ProcessStdinError`}};export{t as n,n as t};
|