coding-agents-sdk 0.15.0 → 0.17.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 +74 -9
- 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/claude-code-sdk/index.mjs +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 +15 -11
- 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
|
@@ -17,6 +17,9 @@ bun add @anthropic-ai/claude-agent-sdk
|
|
|
17
17
|
# for codex-sdk
|
|
18
18
|
bun add @openai/codex-sdk
|
|
19
19
|
|
|
20
|
+
# for cursor-sdk
|
|
21
|
+
bun add @cursor/sdk
|
|
22
|
+
|
|
20
23
|
# for createContainer({ type: "e2b", ... })
|
|
21
24
|
bun add e2b
|
|
22
25
|
```
|
|
@@ -38,7 +41,11 @@ Before you call `await createAgent(...)`, make sure the runtime for that adapter
|
|
|
38
41
|
|
|
39
42
|
SDK adapters and the `e2b` container provider are optional peer dependencies. Install only the ones you use.
|
|
40
43
|
|
|
41
|
-
|
|
44
|
+
Missing SDK peers reject `createAgent()` with an installation hint. A missing `e2b` peer rejects `createContainer()`. Missing CLI binaries are generally reported by the first `run()` as a failed result.
|
|
45
|
+
|
|
46
|
+
For `cursor-sdk`, pass `apiKey` explicitly and supply a `model` for a new local agent; `sessionId` resumes an existing one. It does not accept this library's `container` or `sandbox` options, nor `env` or `propagateEnv`.
|
|
47
|
+
|
|
48
|
+
The package supports TypeScript `^6.0.3 || ^7.0.0`. The examples use ESM, top-level `await`, and `await using`; use Bun or a Node setup that supports those features.
|
|
42
49
|
|
|
43
50
|
Set `cwd` when the agent should run somewhere other than the current working directory.
|
|
44
51
|
|
|
@@ -46,7 +53,7 @@ Use `agent.capabilities` when you need to branch on features at runtime.
|
|
|
46
53
|
|
|
47
54
|
Option names shared across adapters (like `permissionMode`) take adapter-specific values — check the adapter's `*RunOptions` type for the valid set.
|
|
48
55
|
|
|
49
|
-
Claude and Codex CLI both keep automatic review separate from dangerous bypass
|
|
56
|
+
Claude and Codex CLI both keep automatic review separate from dangerous bypass. The Claude SDK adapter defaults `permissionMode` to `"default"` when omitted, rather than opting into the upstream runtime's automatic mode.
|
|
50
57
|
|
|
51
58
|
- Claude `"auto"` and Codex CLI `"auto-approve"` use model-based review to approve or deny permission requests; Codex uses its `workspace-write` sandbox
|
|
52
59
|
- Claude `"bypassPermissions"` and Codex CLI `"bypass-sandbox"` disable permission checks; the Codex mode also disables its sandbox
|
|
@@ -120,6 +127,8 @@ TypeScript infers the completed-result shape from your request:
|
|
|
120
127
|
|
|
121
128
|
Most calls just use a string. If you need richer input, pass parts instead.
|
|
122
129
|
|
|
130
|
+
`claude-code-cli` and `codex-cli` send prompt text through stdin rather than command-line arguments, including when resuming a session.
|
|
131
|
+
|
|
123
132
|
Image input is currently supported by `codex-sdk` and `pi-cli`.
|
|
124
133
|
|
|
125
134
|
```ts
|
|
@@ -185,6 +194,13 @@ Useful bits:
|
|
|
185
194
|
- pass `sessionId` to `await createAgent(type, { sessionId })` to resume one explicitly
|
|
186
195
|
- `reset()` forgets the stored session
|
|
187
196
|
- Claude adapters and `pi-cli` support `fork()`
|
|
197
|
+
- `opencode-cli` supports `forkSession: true` on a run, not a `fork()` method
|
|
198
|
+
|
|
199
|
+
## Permission requests
|
|
200
|
+
|
|
201
|
+
The Claude adapters support `onPermissionRequest()`. Register a handler before the run and return `{ decision: "allow" }` or `{ decision: "deny", message }`. An allow decision can include `updatedInput` to replace the tool input. Check `agent.capabilities.permissionRequests` before relying on a handler with another adapter.
|
|
202
|
+
|
|
203
|
+
`claude-code-cli-pty` uses a run-local hook for permission requests. Its callback bridge is not supported inside a container.
|
|
188
204
|
|
|
189
205
|
## Events
|
|
190
206
|
|
|
@@ -206,6 +222,50 @@ unsubscribe();
|
|
|
206
222
|
|
|
207
223
|
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
224
|
|
|
225
|
+
### Provider events
|
|
226
|
+
|
|
227
|
+
Use `onProviderEvent()` on `claude-code-cli` or `codex-cli` for provider-specific details not included in normalized events.
|
|
228
|
+
|
|
229
|
+
```ts
|
|
230
|
+
import { createClaudeCodeCliAgent } from "coding-agents-sdk/adapters/claude-code-cli";
|
|
231
|
+
|
|
232
|
+
await using claude = createClaudeCodeCliAgent();
|
|
233
|
+
const unsubscribe = claude.onProviderEvent(({ runId, sessionId, event }) => {
|
|
234
|
+
if (event.type === "system" && event.subtype === "init") {
|
|
235
|
+
console.log(runId, sessionId, event.tools, event.mcp_servers);
|
|
236
|
+
}
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
await claude.run({ input: "Explain the package layout." });
|
|
240
|
+
unsubscribe();
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
For Codex, import `createCodexCliAgent` from `coding-agents-sdk/adapters/codex-cli`.
|
|
244
|
+
|
|
245
|
+
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.
|
|
246
|
+
|
|
247
|
+
## Custom process launchers
|
|
248
|
+
|
|
249
|
+
Wrap `spawnProcess` with a `ProcessSpawner` to customize how a CLI agent launches:
|
|
250
|
+
|
|
251
|
+
```ts
|
|
252
|
+
import { spawnProcess, type ProcessSpawner } from "coding-agents-sdk/process";
|
|
253
|
+
|
|
254
|
+
const spawner: ProcessSpawner = {
|
|
255
|
+
spawn(command, args, options) {
|
|
256
|
+
const child = spawnProcess(command, args, options);
|
|
257
|
+
console.log("Agent process launched");
|
|
258
|
+
return child;
|
|
259
|
+
},
|
|
260
|
+
};
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
Pass `spawner` when creating a non-PTY CLI agent. `claude-code-cli-pty` instead accepts a `pty` backend override. For `claude-code-cli` and `codex-cli`, the returned process must provide `stdin.write` and `stdin.end`.
|
|
264
|
+
|
|
265
|
+
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.
|
|
266
|
+
|
|
267
|
+
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.
|
|
268
|
+
|
|
209
269
|
## MCP
|
|
210
270
|
|
|
211
271
|
MCP tool calls can show up in the event stream when the underlying runtime supports them.
|
|
@@ -216,13 +276,15 @@ This wrapper exposes MCP configuration directly on:
|
|
|
216
276
|
- `claude-code-cli-pty`: `mcpConfig`, `mcpServers`
|
|
217
277
|
- `claude-code-sdk`: `mcpServers`
|
|
218
278
|
- `codex-cli`: `mcpConfig`, `mcpServers`
|
|
219
|
-
- `
|
|
279
|
+
- `cursor-sdk`: `mcpServers` using `CursorSdkMcpServerConfig`
|
|
280
|
+
|
|
281
|
+
For `codex-sdk`, `cursor-cli`, `gemini-cli`, and `opencode-cli`, use the runtime's own MCP setup. This wrapper does not add dedicated MCP configuration options for them. `pi-cli` reports `mcp: false`.
|
|
220
282
|
|
|
221
|
-
|
|
283
|
+
Claude CLI adapters pass `mcpConfig` paths to the CLI, so those files must be visible inside the execution target. `codex-cli` reads its single `mcpConfig` JSON file in the host process and converts its `mcpServers` entries to CLI configuration arguments; use a host-readable path there.
|
|
222
284
|
|
|
223
285
|
## Containers
|
|
224
286
|
|
|
225
|
-
Containers are supported on
|
|
287
|
+
Containers are supported on every CLI adapter, including `cursor-cli`. SDK adapters launch their vendor runtimes locally and do not support this library's `container` or `sandbox` options.
|
|
226
288
|
Built-in container providers are:
|
|
227
289
|
|
|
228
290
|
- `docker`
|
|
@@ -270,7 +332,9 @@ if (result.status === "completed") {
|
|
|
270
332
|
|
|
271
333
|
Your image needs the runtime for the adapter you picked available inside the container. For `claude-code-cli-pty`, install both `claude` and `socat` in the image; the Stop hook also expects `sh` and `cat`.
|
|
272
334
|
|
|
273
|
-
If you omit `cwd`, the agent uses `container.workdir`. The
|
|
335
|
+
If you omit `cwd`, the agent uses `container.workdir`. The agent starts a stopped or created execution target before a run. E2B creates or connects to its remote sandbox during `createContainer()`. Dispose the container separately from the agent; `await using` handles that when declared in the order shown above.
|
|
336
|
+
|
|
337
|
+
Use `snapshotWorkdir()`, `diffWorkdir()`, and `releaseWorkdirSnapshot()` when you need a before/after file diff. Start the container before taking the first snapshot.
|
|
274
338
|
|
|
275
339
|
`propagateEnv` defaults depend on the execution target:
|
|
276
340
|
|
|
@@ -295,6 +359,7 @@ import { createAgent, createSandbox } from "coding-agents-sdk";
|
|
|
295
359
|
await using sandbox = await createSandbox({
|
|
296
360
|
type: "bubblewrap",
|
|
297
361
|
workdir: process.cwd(),
|
|
362
|
+
shareNetwork: true,
|
|
298
363
|
setEnv: {
|
|
299
364
|
OPENAI_API_KEY: process.env.OPENAI_API_KEY ?? "",
|
|
300
365
|
},
|
|
@@ -318,8 +383,8 @@ Notes:
|
|
|
318
383
|
- `codex-cli`'s `sandboxMode` sets the Codex CLI `--sandbox` policy only when `permissionMode` is omitted or `"default"`; it is independent of the `sandbox` execution target option
|
|
319
384
|
- if you omit `cwd`, the agent uses `sandbox.workdir`
|
|
320
385
|
- keep network access enabled when the sandboxed CLI still needs to reach a hosted model API
|
|
321
|
-
-
|
|
322
|
-
- `nsjail` preserves `PATH` by default
|
|
323
|
-
- `bubblewrap` and `nsjail`
|
|
386
|
+
- all built-in sandbox providers require Linux and the corresponding host binary (`bwrap`, `firejail`, or `nsjail`); [Bubblewrap's documentation](https://github.com/containers/bubblewrap) describes its Linux namespace requirements
|
|
387
|
+
- `nsjail` clears its base environment and preserves `PATH` by default, then merges `setEnv` and the agent's process environment; suppress host variables with `propagateEnv: false` on the agent as well as the sandbox's default `clearEnv: true`
|
|
388
|
+
- `bubblewrap` and `nsjail` use a private `/tmp` by default; expose host-generated helper files through a bind mount or a shared temporary directory. For an exact `/tmp` bind with `nsjail`, also set `tmpfs: []` so its private tmpfs does not suppress the bind
|
|
324
389
|
- `firejail` is more host-dependent than `bubblewrap`; `readOnly` plus `readWrite` tune path permissions inside Firejail's base filesystem, while allowlist-style confinement needs explicit `whitelist` / `blacklist` rules. Setting a synthetic `HOME` only redirects CLI state files; it does not hide the real host home by itself
|
|
325
390
|
- in particular, `codex-cli` structured output (`schema`) and `claude-code-cli` `mcpServers` create helper files that should live on a sandbox-visible `/tmp`
|
|
@@ -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,4 +1,4 @@
|
|
|
1
1
|
import{n as e}from"../../types-B72tDMEZ.mjs";import{i as t,n,r}from"../../util-B4HTdOSc.mjs";import{t as i}from"../../env-Cb8MIvH7.mjs";import{i as a,l as o,s,u as c}from"../../classify-error-DOqkMCcy.mjs";import{i as l,n as u,r as d,t as f}from"../../session-markers-Dt7TWdKY.mjs";import{t as p}from"../../SdkAgent-Dtsr8Ycr.mjs";import{query as m}from"@anthropic-ai/claude-agent-sdk";const h=(e,t)=>{if(n(e)&&typeof e[t]==`string`)return e[t]},g=(e,t)=>{if(n(e)&&typeof e[t]==`number`)return e[t]},_=e=>n(e)&&e.type===`text`&&typeof e.text==`string`,v=e=>n(e)&&e.type===`thinking`&&typeof e.thinking==`string`,y=e=>n(e)&&e.type===`tool_use`&&typeof e.id==`string`&&typeof e.name==`string`,b=e=>n(e)&&e.type===`tool_result`&&typeof e.tool_use_id==`string`,x=e=>{let t=n(e.message)?e.message.content:void 0;return Array.isArray(t)?t:[]},S=(e,t)=>h(e.message,`model`)??t.model??null,C=e=>{let t=n(e.message)?e.message.content:void 0;return typeof t==`string`?[t]:Array.isArray(t)?t:[]},w=e=>{if(typeof e==`string`||!Array.isArray(e))return e;let t=e.flatMap(e=>_(e)?[e.text]:[]);return t.length===e.length?t.join(`
|
|
2
2
|
`):e},T=e=>{if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return}},E=e=>{let n=g(e.usage,`input_tokens`),r=g(e.usage,`cache_creation_input_tokens`),i=g(e.usage,`cache_read_input_tokens`),a=g(e.usage,`output_tokens`),o=t(n,r,i,a);return{durationMs:e.duration_ms,apiDurationMs:e.duration_api_ms,turns:e.num_turns,costUsd:e.total_cost_usd,inputTokens:n,cacheCreationInputTokens:r,cacheReadInputTokens:i,outputTokens:a,totalTokens:o}},D=e=>{if(`errors`in e&&Array.isArray(e.errors)){let t=e.errors.filter(e=>typeof e==`string`&&e.trim()!==``);if(t.length>0)return t.join(`
|
|
3
|
-
`)}return e.subtype===`error_max_structured_output_retries`?`Structured output retries were exhausted.`:e.subtype},O=e=>`session_id`in e?e.session_id:void 0,k=(e,t,n)=>s(e,`message`,{sessionId:t,model:null,role:`system`,content:[c(n)],text:n}),A=(e,t,n)=>{let r=[],i=[],a=S(e,n);for(let n of x(e)){if(_(n)){r.push(s(t.runId,`message`,{sessionId:t.sessionId,model:a,role:`assistant`,content:[c(n.text)],text:n.text}));continue}if(v(n)){r.push(s(t.runId,`reasoning`,{sessionId:t.sessionId,model:a,content:[c(n.thinking)],text:n.thinking}));continue}y(n)&&(i.push({toolCallId:n.id,toolName:n.name,input:n.input}),r.push(s(t.runId,`tool-call`,{sessionId:t.sessionId,model:a,toolCallId:n.id,toolName:n.name,input:n.input})))}return{events:r,toolCalls:i}},j=(e,t)=>{let n=[];for(let r of C(e)){if(typeof r==`string`){n.push(s(t.runId,`message`,{sessionId:t.sessionId,model:null,role:`user`,content:[c(r)],text:r}));continue}if(_(r)){n.push(s(t.runId,`message`,{sessionId:t.sessionId,model:null,role:`user`,content:[c(r.text)],text:r.text}));continue}if(b(r)){let e=t.toolCalls.get(r.tool_use_id),i=w(r.content);n.push(s(t.runId,`tool-result`,{sessionId:t.sessionId,toolCallId:r.tool_use_id,toolName:e?.toolName,input:e?.input,output:i,isError:r.is_error,error:r.is_error?T(i):void 0}))}}return{events:n}},M=(e,t,n)=>t.toolCalls.has(e.tool_use_id)?{events:[]}:{events:[s(t.runId,`tool-call`,{sessionId:t.sessionId,model:n.model??null,toolCallId:e.tool_use_id,toolName:e.tool_name,input:void 0})],toolCalls:[{toolCallId:e.tool_use_id,toolName:e.tool_name}]},N=e=>{switch(e.subtype){case`init`:return;case`status`:return`status: ${e.status??`idle`}`;case`local_command_output`:return e.content;case`hook_started`:return`[hook_started] ${e.hook_name}`;case`hook_progress`:return`[hook_progress] ${e.hook_name}`;case`hook_response`:return`[hook_response] ${e.hook_name}: ${e.outcome}`;case`task_started`:return`[task_started] ${e.description}`;case`task_progress`:return`[task_progress] ${e.summary??e.description}`;case`task_notification`:return`[task_${e.status}] ${e.summary}`;case`compact_boundary`:return`[compact_boundary] ${e.compact_metadata.trigger}`;case`files_persisted`:return`[files_persisted] ${e.files.length} file${e.files.length===1?``:`s`}`;default:return}},P=(e,t)=>{let n=N(e);return n?{events:[k(t.runId,t.sessionId,n)]}:{events:[]}},F=(e,t)=>{switch(e.type){case`auth_status`:{let n=`authenticated`;return e.error?n=`auth error: ${e.error}`:e.isAuthenticating&&(n=`authenticating`),{events:[k(t.runId,t.sessionId,n)]}}case`prompt_suggestion`:return{events:[k(t.runId,t.sessionId,`prompt suggestion: ${e.suggestion}`)]};case`rate_limit_event`:return{events:[k(t.runId,t.sessionId,`rate limited: ${e.rate_limit_info.status}`)]};case`tool_use_summary`:return{events:[k(t.runId,t.sessionId,e.summary)]};default:return{events:[]}}},I=(e,t)=>{let n={stats:E(e)},i=`result`in e?e.result:void 0,a=e.subtype===`success`&&!e.is_error;typeof i==`string`&&(n.output={...n.output,text:i});let o=d(`structured_output`in e?e.structured_output:void 0,t,{isSuccess:a},`Structured output was requested but Claude Agent SDK did not return structured_output.`);if(o.value===void 0&&a&&t.schemaRequested&&typeof i==`string`)try{o.value=r(i),o.error=void 0}catch{}return o.value!==void 0&&(n.output={...n.output,value:o.value}),o.error&&(n.status=`failed`,n.error=o.error),a?n.error||(n.status=`completed`):(n.status=`failed`,n.error={kind:`provider`,message:D(e)}),{events:[],state:n}},L=(e,t,n={})=>{let r;switch(e.type){case`assistant`:r=A(e,t,n);break;case`result`:r=I(e,t);break;case`system`:r=P(e,t);break;case`tool_progress`:r=M(e,t,n);break;case`user`:r=j(e,t);break;case`auth_status`:case`prompt_suggestion`:case`rate_limit_event`:case`tool_use_summary`:r=F(e,t);break;default:r={events:[]}}let i=O(e);return i&&r.sessionId===void 0&&(r.sessionId=i),r},R={structuredOutput:!0,sessionResume:!0,imageInput:!1,mcp:!0,eventStreaming:!0,sessionFork:!0,permissionRequests:!0},z=e=>async(t,n,r)=>{let i=await e({toolName:t,input:n,toolUseId:r.toolUseID,signal:r.signal,reason:r.decisionReason,blockedPath:r.blockedPath,title:r.title,description:r.description});return i.decision===`allow`?{behavior:`allow`,updatedInput:i.updatedInput??n}:{behavior:`deny`,message:i.message??`Tool call denied.`}},B=(e,t)=>e?t?`${e}\n\n${t}`:e:t?{type:`preset`,preset:`claude_code`,append:t}:void 0,V=({prompt:e,options:t})=>m({prompt:e,options:t}),H=t=>{if(t===void 0||typeof t==`string`)return t;if(Array.isArray(t))throw new e(`settings must be an object or a path string.`);return t},U=(t,n)=>{if(n.command){if(n.url)throw new e(`mcpServers.${t} cannot set both command and url.`);if(n.headers)throw new e(`mcpServers.${t}.headers is only supported with url transports.`);if(n.cwd)throw new e(`mcpServers.${t}.cwd is not supported by claude-code-sdk.`);return{type:`stdio`,command:n.command,args:n.args,env:n.env}}if(n.url){if(n.args)throw new e(`mcpServers.${t}.args is only supported with command transports.`);if(n.env)throw new e(`mcpServers.${t}.env is only supported with command transports.`);if(n.cwd)throw new e(`mcpServers.${t}.cwd is not supported by claude-code-sdk.`);return{type:`http`,url:n.url,headers:n.headers}}throw new e(`mcpServers.${t} must set either command or url.`)},W=e=>{if(e)return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,U(e,t)]))};var G=class t extends p{type=`claude-code-sdk`;defaults;creationOptions;runDefaults;createQueryFn;command;forkOnNextRun;currentQuery;constructor(e={}){super({type:`claude-code-sdk`,capabilities:R,sessionId:e.sessionId,onEvent:e.onEvent}),this.command=e.command,this.defaults={cwd:e.cwd,model:e.model,systemPrompt:e.systemPrompt},this.creationOptions={...e,command:e.command,env:e.env?{...e.env}:void 0,executableArgs:e.executableArgs?[...e.executableArgs]:void 0,mcpServers:e.mcpServers?{...e.mcpServers}:void 0,settingSources:e.settingSources?[...e.settingSources]:void 0},this.runDefaults={allowedTools:e.allowedTools?[...e.allowedTools]:void 0,disallowedTools:e.disallowedTools?[...e.disallowedTools]:void 0,appendSystemPrompt:e.appendSystemPrompt,permissionMode:e.permissionMode,mcpServers:e.mcpServers?{...e.mcpServers}:void 0,forkSession:e.forkSession,maxTurns:e.maxTurns},this.createQueryFn=e.createQuery??V,this.forkOnNextRun=e.forkOnNextRun??!1}fork(){if(!this.sessionId)throw new e(`Cannot fork a Claude Code SDK agent before it has a sessionId.`);return new t({...this.creationOptions,sessionId:this.sessionId,forkSession:void 0,forkOnNextRun:!0})}get runRequestDefaults(){return this.defaults}onValidateRun(t,n){if((t.forkSession??this.runDefaults.forkSession??this.forkOnNextRun)&&!this.sessionId)throw new e(`forkSession requires an existing sessionId on the agent.`);if(t.maxTurns!==void 0&&(!Number.isInteger(t.maxTurns)||t.maxTurns<=0))throw new e(`maxTurns must be a positive integer.`)}onStopRequested(e){this.currentQuery?.interrupt?.().catch(()=>{}),super.onStopRequested(e)}async onDispose(){this.cleanupSdkResources()}cleanupSdkResources(){this.currentQuery?.close?.(),this.currentQuery=void 0}async executeSdkRun(e,t,n){let r=this.createQueryFn({prompt:o(e.normalizedRequest.input),options:this.buildQueryOptions(t,e,n)});this.currentQuery=r;for await(let t of r){let n=O(t)??e.sessionId;n&&e.sessionId!==n&&(e.sessionId=n,this.setSessionId(n),this.forkOnNextRun&&e.requestedSessionId&&n!==e.requestedSessionId&&(this.forkOnNextRun=!1));let r=L(t,a(e),{model:e.normalizedRequest.model});this.applyBatch(e,r)}}buildQueryOptions(e,t,n){let r=e.permissionMode??this.runDefaults.permissionMode
|
|
3
|
+
`)}return e.subtype===`error_max_structured_output_retries`?`Structured output retries were exhausted.`:e.subtype},O=e=>`session_id`in e?e.session_id:void 0,k=(e,t,n)=>s(e,`message`,{sessionId:t,model:null,role:`system`,content:[c(n)],text:n}),A=(e,t,n)=>{let r=[],i=[],a=S(e,n);for(let n of x(e)){if(_(n)){r.push(s(t.runId,`message`,{sessionId:t.sessionId,model:a,role:`assistant`,content:[c(n.text)],text:n.text}));continue}if(v(n)){r.push(s(t.runId,`reasoning`,{sessionId:t.sessionId,model:a,content:[c(n.thinking)],text:n.thinking}));continue}y(n)&&(i.push({toolCallId:n.id,toolName:n.name,input:n.input}),r.push(s(t.runId,`tool-call`,{sessionId:t.sessionId,model:a,toolCallId:n.id,toolName:n.name,input:n.input})))}return{events:r,toolCalls:i}},j=(e,t)=>{let n=[];for(let r of C(e)){if(typeof r==`string`){n.push(s(t.runId,`message`,{sessionId:t.sessionId,model:null,role:`user`,content:[c(r)],text:r}));continue}if(_(r)){n.push(s(t.runId,`message`,{sessionId:t.sessionId,model:null,role:`user`,content:[c(r.text)],text:r.text}));continue}if(b(r)){let e=t.toolCalls.get(r.tool_use_id),i=w(r.content);n.push(s(t.runId,`tool-result`,{sessionId:t.sessionId,toolCallId:r.tool_use_id,toolName:e?.toolName,input:e?.input,output:i,isError:r.is_error,error:r.is_error?T(i):void 0}))}}return{events:n}},M=(e,t,n)=>t.toolCalls.has(e.tool_use_id)?{events:[]}:{events:[s(t.runId,`tool-call`,{sessionId:t.sessionId,model:n.model??null,toolCallId:e.tool_use_id,toolName:e.tool_name,input:void 0})],toolCalls:[{toolCallId:e.tool_use_id,toolName:e.tool_name}]},N=e=>{switch(e.subtype){case`init`:return;case`status`:return`status: ${e.status??`idle`}`;case`local_command_output`:return e.content;case`hook_started`:return`[hook_started] ${e.hook_name}`;case`hook_progress`:return`[hook_progress] ${e.hook_name}`;case`hook_response`:return`[hook_response] ${e.hook_name}: ${e.outcome}`;case`task_started`:return`[task_started] ${e.description}`;case`task_progress`:return`[task_progress] ${e.summary??e.description}`;case`task_notification`:return`[task_${e.status}] ${e.summary}`;case`compact_boundary`:return`[compact_boundary] ${e.compact_metadata.trigger}`;case`files_persisted`:return`[files_persisted] ${e.files.length} file${e.files.length===1?``:`s`}`;default:return}},P=(e,t)=>{let n=N(e);return n?{events:[k(t.runId,t.sessionId,n)]}:{events:[]}},F=(e,t)=>{switch(e.type){case`auth_status`:{let n=`authenticated`;return e.error?n=`auth error: ${e.error}`:e.isAuthenticating&&(n=`authenticating`),{events:[k(t.runId,t.sessionId,n)]}}case`prompt_suggestion`:return{events:[k(t.runId,t.sessionId,`prompt suggestion: ${e.suggestion}`)]};case`rate_limit_event`:return{events:[k(t.runId,t.sessionId,`rate limited: ${e.rate_limit_info.status}`)]};case`tool_use_summary`:return{events:[k(t.runId,t.sessionId,e.summary)]};default:return{events:[]}}},I=(e,t)=>{let n={stats:E(e)},i=`result`in e?e.result:void 0,a=e.subtype===`success`&&!e.is_error;typeof i==`string`&&(n.output={...n.output,text:i});let o=d(`structured_output`in e?e.structured_output:void 0,t,{isSuccess:a},`Structured output was requested but Claude Agent SDK did not return structured_output.`);if(o.value===void 0&&a&&t.schemaRequested&&typeof i==`string`)try{o.value=r(i),o.error=void 0}catch{}return o.value!==void 0&&(n.output={...n.output,value:o.value}),o.error&&(n.status=`failed`,n.error=o.error),a?n.error||(n.status=`completed`):(n.status=`failed`,n.error={kind:`provider`,message:D(e)}),{events:[],state:n}},L=(e,t,n={})=>{let r;switch(e.type){case`assistant`:r=A(e,t,n);break;case`result`:r=I(e,t);break;case`system`:r=P(e,t);break;case`tool_progress`:r=M(e,t,n);break;case`user`:r=j(e,t);break;case`auth_status`:case`prompt_suggestion`:case`rate_limit_event`:case`tool_use_summary`:r=F(e,t);break;default:r={events:[]}}let i=O(e);return i&&r.sessionId===void 0&&(r.sessionId=i),r},R={structuredOutput:!0,sessionResume:!0,imageInput:!1,mcp:!0,eventStreaming:!0,sessionFork:!0,permissionRequests:!0},z=e=>async(t,n,r)=>{let i=await e({toolName:t,input:n,toolUseId:r.toolUseID,signal:r.signal,reason:r.decisionReason,blockedPath:r.blockedPath,title:r.title,description:r.description});return i.decision===`allow`?{behavior:`allow`,updatedInput:i.updatedInput??n}:{behavior:`deny`,message:i.message??`Tool call denied.`}},B=(e,t)=>e?t?`${e}\n\n${t}`:e:t?{type:`preset`,preset:`claude_code`,append:t}:void 0,V=({prompt:e,options:t})=>m({prompt:e,options:t}),H=t=>{if(t===void 0||typeof t==`string`)return t;if(Array.isArray(t))throw new e(`settings must be an object or a path string.`);return t},U=(t,n)=>{if(n.command){if(n.url)throw new e(`mcpServers.${t} cannot set both command and url.`);if(n.headers)throw new e(`mcpServers.${t}.headers is only supported with url transports.`);if(n.cwd)throw new e(`mcpServers.${t}.cwd is not supported by claude-code-sdk.`);return{type:`stdio`,command:n.command,args:n.args,env:n.env}}if(n.url){if(n.args)throw new e(`mcpServers.${t}.args is only supported with command transports.`);if(n.env)throw new e(`mcpServers.${t}.env is only supported with command transports.`);if(n.cwd)throw new e(`mcpServers.${t}.cwd is not supported by claude-code-sdk.`);return{type:`http`,url:n.url,headers:n.headers}}throw new e(`mcpServers.${t} must set either command or url.`)},W=e=>{if(e)return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,U(e,t)]))};var G=class t extends p{type=`claude-code-sdk`;defaults;creationOptions;runDefaults;createQueryFn;command;forkOnNextRun;currentQuery;constructor(e={}){super({type:`claude-code-sdk`,capabilities:R,sessionId:e.sessionId,onEvent:e.onEvent}),this.command=e.command,this.defaults={cwd:e.cwd,model:e.model,systemPrompt:e.systemPrompt},this.creationOptions={...e,command:e.command,env:e.env?{...e.env}:void 0,executableArgs:e.executableArgs?[...e.executableArgs]:void 0,mcpServers:e.mcpServers?{...e.mcpServers}:void 0,settingSources:e.settingSources?[...e.settingSources]:void 0},this.runDefaults={allowedTools:e.allowedTools?[...e.allowedTools]:void 0,disallowedTools:e.disallowedTools?[...e.disallowedTools]:void 0,appendSystemPrompt:e.appendSystemPrompt,permissionMode:e.permissionMode,mcpServers:e.mcpServers?{...e.mcpServers}:void 0,forkSession:e.forkSession,maxTurns:e.maxTurns},this.createQueryFn=e.createQuery??V,this.forkOnNextRun=e.forkOnNextRun??!1}fork(){if(!this.sessionId)throw new e(`Cannot fork a Claude Code SDK agent before it has a sessionId.`);return new t({...this.creationOptions,sessionId:this.sessionId,forkSession:void 0,forkOnNextRun:!0})}get runRequestDefaults(){return this.defaults}onValidateRun(t,n){if((t.forkSession??this.runDefaults.forkSession??this.forkOnNextRun)&&!this.sessionId)throw new e(`forkSession requires an existing sessionId on the agent.`);if(t.maxTurns!==void 0&&(!Number.isInteger(t.maxTurns)||t.maxTurns<=0))throw new e(`maxTurns must be a positive integer.`)}onStopRequested(e){this.currentQuery?.interrupt?.().catch(()=>{}),super.onStopRequested(e)}async onDispose(){this.cleanupSdkResources()}cleanupSdkResources(){this.currentQuery?.close?.(),this.currentQuery=void 0}async executeSdkRun(e,t,n){let r=this.createQueryFn({prompt:o(e.normalizedRequest.input),options:this.buildQueryOptions(t,e,n)});this.currentQuery=r;for await(let t of r){let n=O(t)??e.sessionId;n&&e.sessionId!==n&&(e.sessionId=n,this.setSessionId(n),this.forkOnNextRun&&e.requestedSessionId&&n!==e.requestedSessionId&&(this.forkOnNextRun=!1));let r=L(t,a(e),{model:e.normalizedRequest.model});this.applyBatch(e,r)}}buildQueryOptions(e,t,n){let r=e.permissionMode??this.runDefaults.permissionMode??`default`,a=e.forkSession??this.runDefaults.forkSession??this.forkOnNextRun,o=e.appendSystemPrompt??this.runDefaults.appendSystemPrompt,c=i({propagateEnv:this.creationOptions.propagateEnv});this.creationOptions.env&&Object.assign(c,this.creationOptions.env),f(c);let d=this.getPermissionHandler();return{abortController:n,canUseTool:d?z(d):void 0,cwd:t.normalizedRequest.cwd,model:t.normalizedRequest.model,systemPrompt:B(t.normalizedRequest.systemPrompt,o),allowedTools:e.allowedTools??this.runDefaults.allowedTools,disallowedTools:l(e.disallowedTools??this.runDefaults.disallowedTools),mcpServers:W(e.mcpServers??this.runDefaults.mcpServers),maxTurns:e.maxTurns??this.runDefaults.maxTurns,outputFormat:t.normalizedRequest.schema.kind===`none`?void 0:{type:`json_schema`,schema:u(t.normalizedRequest.schema.jsonSchema)},permissionMode:r,allowDangerouslySkipPermissions:r===`bypassPermissions`||void 0,resume:t.requestedSessionId,forkSession:t.requestedSessionId?a:void 0,env:c,executable:this.creationOptions.executable,executableArgs:this.creationOptions.executableArgs,pathToClaudeCodeExecutable:this.command,settings:H(this.creationOptions.settings),settingSources:this.creationOptions.settingSources,stderr:e=>{for(let n of e.split(`
|
|
4
4
|
`))n&&(t.stderrLines.push(n),this.emit(t,s(t.runId,`stderr`,{sessionId:t.sessionId,text:n})))}}}};const K=e=>new G(e);export{K as 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 };
|