coding-agents-sdk 0.18.0 → 0.21.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 +292 -7
- package/dist/Agent-BsDJsgJa.mjs +4 -0
- package/dist/SdkAgent-jwighP_b.mjs +1 -0
- package/dist/adapters/antigravity-cli/index.d.mts +2 -0
- package/dist/adapters/antigravity-cli/index.mjs +2 -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 +5 -5
- package/dist/adapters/claude-code-sdk/index.d.mts +1 -1
- package/dist/adapters/claude-code-sdk/index.mjs +4 -4
- package/dist/adapters/codex-cli/index.d.mts +1 -1
- package/dist/adapters/codex-cli/index.mjs +4 -2
- package/dist/adapters/codex-sdk/index.d.mts +1 -1
- package/dist/adapters/codex-sdk/index.mjs +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/cursor-sdk/index.mjs +1 -1
- package/dist/adapters/drac-cli/index.d.mts +2 -0
- package/dist/adapters/drac-cli/index.mjs +1 -0
- 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/classify-error-_WNZMhMY.mjs +8 -0
- package/dist/container/index.d.mts +2 -2
- package/dist/container/index.mjs +1 -1
- package/dist/container-BlsSoBe1.mjs +1 -0
- package/dist/container-C7oWwLGK.mjs +1 -0
- package/dist/container-DUoj_mnh.mjs +1 -0
- package/dist/container-DXQ92RVu.mjs +1 -0
- package/dist/container-MazMFZg8.mjs +1 -0
- package/dist/control-requests-DtjV0e4o.mjs +1 -0
- package/dist/core/process/index.d.mts +2 -2
- package/dist/core/process/index.mjs +1 -1
- package/dist/diff-CMWH9a0d.mjs +1 -0
- package/dist/{errors-aYGbvsaq.mjs → errors-BauhTL3l.mjs} +1 -1
- package/dist/{events-BxEB6zHt.d.mts → events-DmlAPVpd.d.mts} +172 -5
- package/dist/{index-DH2vDD3l.d.mts → index-5XiyFBcK.d.mts} +5 -9
- package/dist/index-BimeR91j.d.mts +6 -0
- package/dist/{index-DWv7tLOX.d.mts → index-Bl9DtOcy.d.mts} +4 -10
- package/dist/{index-BWAsLSN3.d.mts → index-Brx5CEx7.d.mts} +4 -10
- package/dist/{index-DB0fLwpu.d.mts → index-CCsw4G4N.d.mts} +1 -5
- package/dist/{index-CmRm10Lo.d.mts → index-CZiWvyn3.d.mts} +3 -7
- package/dist/{index-CPhcEEAp.d.mts → index-DQYRy7xl.d.mts} +4 -10
- package/dist/index-DUTtolch.d.mts +63 -0
- package/dist/{index-DCQu5ZAu.d.mts → index-DilMV_1s.d.mts} +182 -36
- package/dist/{index-DpPNo3dX.d.mts → index-DpG9mouj.d.mts} +33 -18
- package/dist/{index-Ssb7kE6D.d.mts → index-DqNl8zYj.d.mts} +1 -5
- package/dist/index-Du99OLj6.d.mts +65 -0
- package/dist/{index-DWmHDEQL.d.mts → index-Q5jNyQHD.d.mts} +88 -25
- package/dist/{index-BrFs4M0Z.d.mts → index-X-W5isMp.d.mts} +3 -7
- package/dist/{index-BEEVpHOg.d.mts → index-oUIMXZIp.d.mts} +4 -10
- package/dist/index.d.mts +28 -21
- package/dist/index.mjs +1 -1
- package/dist/oci-t88M5ODN.mjs +2 -0
- package/dist/parser-BY3CZGmc.mjs +2 -0
- package/dist/permission-updates-CkFvevWQ.mjs +1 -0
- package/dist/permissions-BjNU9GCH.mjs +1 -0
- package/dist/questions-CaEwN4JQ.mjs +1 -0
- package/dist/sandbox/index.d.mts +1 -1
- package/dist/sandbox/index.mjs +1 -1
- package/dist/{sandbox-CYA69miM.mjs → sandbox-BemAIoIo.mjs} +2 -2
- package/dist/schemas/index.d.mts +2 -2
- package/dist/schemas/index.mjs +1 -1
- package/dist/schemas-CzJM9p-0.mjs +1 -0
- package/dist/spawner-CYAQQABs.mjs +1 -0
- package/dist/{types-COmjfh8B.d.mts → types-BetgZysV.d.mts} +0 -2
- package/dist/{types-D0ejXDa9.d.mts → types-D_QP9PC-.d.mts} +98 -17
- package/dist/util-CCXryPDO.mjs +1 -0
- package/package.json +20 -10
- package/dist/Agent-WqGee5TR.mjs +0 -4
- package/dist/SdkAgent-BjdSrtFe.mjs +0 -1
- package/dist/classify-error-DK2WpxiL.mjs +0 -8
- package/dist/container-Bdb90GJb.mjs +0 -1
- package/dist/container-DMFxf-kn.mjs +0 -1
- package/dist/container-Dvr-p53c.mjs +0 -1
- package/dist/container-dCRMBvQw.mjs +0 -1
- package/dist/container-w0rl1QMH.mjs +0 -1
- package/dist/diff-Dqyk2cdt.mjs +0 -1
- package/dist/index-DvwVRB7K.d.mts +0 -10
- package/dist/oci-DTNwW-WH.mjs +0 -1
- package/dist/parser-jSS5vOTN.mjs +0 -2
- package/dist/schemas-CkdQXAep.mjs +0 -1
- package/dist/session-markers-BHsJLWJk.mjs +0 -1
- package/dist/spawner-CgfyvnR4.mjs +0 -1
- package/dist/util-B4HTdOSc.mjs +0 -1
package/dist/schemas/index.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { C as
|
|
2
|
-
export { type AgentCapabilities, type AgentEvent, type ContentPart, type ImageContentPart, type JsonSchema, type McpServerConfig, type MessageEvent, type ReasoningEvent, type SessionEndEvent, type SessionStartEvent, type StderrEvent, type TextContentPart, type ToolCallEvent, type ToolResultEvent, agentCapabilitiesSchema, baseEventSchema, contentPartSchema, eventSchema, imageContentPartSchema, messageEventSchema, reasoningEventSchema, sessionEndEventSchema, sessionStartEventSchema, stderrEventSchema, textContentPartSchema, toolCallEventSchema, toolResultEventSchema };
|
|
1
|
+
import { A as McpServerConfig, C as stderrEventSchema, D as ContentPart, E as AgentCapabilities, F as textContentPartSchema, M as agentCapabilitiesSchema, N as contentPartSchema, O as ImageContentPart, P as imageContentPartSchema, S as sessionStartEventSchema, T as toolResultEventSchema, _ as noticeEventSchema, a as RateLimitEvent, b as reasoningEventSchema, c as SessionEndEvent, d as ToolCallEvent, f as ToolResultEvent, g as messageEventSchema, h as messageDeltaEventSchema, i as NoticeEvent, j as TextContentPart, k as JsonSchema, l as SessionStartEvent, m as eventSchema, n as MessageDeltaEvent, o as ReasoningDeltaEvent, p as baseEventSchema, r as MessageEvent, s as ReasoningEvent, t as AgentEvent, u as StderrEvent, v as rateLimitEventSchema, w as toolCallEventSchema, x as sessionEndEventSchema, y as reasoningDeltaEventSchema } from "../events-DmlAPVpd.mjs";
|
|
2
|
+
export { type AgentCapabilities, type AgentEvent, type ContentPart, type ImageContentPart, type JsonSchema, type McpServerConfig, type MessageDeltaEvent, type MessageEvent, type NoticeEvent, type RateLimitEvent, type ReasoningDeltaEvent, type ReasoningEvent, type SessionEndEvent, type SessionStartEvent, type StderrEvent, type TextContentPart, type ToolCallEvent, type ToolResultEvent, agentCapabilitiesSchema, baseEventSchema, contentPartSchema, eventSchema, imageContentPartSchema, messageDeltaEventSchema, messageEventSchema, noticeEventSchema, rateLimitEventSchema, reasoningDeltaEventSchema, reasoningEventSchema, sessionEndEventSchema, sessionStartEventSchema, stderrEventSchema, textContentPartSchema, toolCallEventSchema, toolResultEventSchema };
|
package/dist/schemas/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export{m as agentCapabilitiesSchema,t as baseEventSchema,h as contentPartSchema,n as eventSchema,g as imageContentPartSchema,r as messageDeltaEventSchema,i as messageEventSchema,a as noticeEventSchema,o as rateLimitEventSchema,s as reasoningDeltaEventSchema,c as reasoningEventSchema,l as sessionEndEventSchema,u as sessionStartEventSchema,d as stderrEventSchema,_ as textContentPartSchema,f as toolCallEventSchema,p as toolResultEventSchema}from"../schemas-CzJM9p-0.mjs";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{z as e}from"zod/v4";const t=e.object({type:e.literal(`text`),text:e.string()}),n=e.object({type:e.literal(`image`),path:e.string(),mediaType:e.string().optional()}),r=e.discriminatedUnion(`type`,[t,n]),i=e.object({structuredOutput:e.boolean(),sessionResume:e.boolean(),imageInput:e.boolean(),mcp:e.boolean(),eventStreaming:e.boolean(),sessionFork:e.boolean().optional(),permissionRequests:e.boolean().optional(),textStreaming:e.boolean().optional(),midRunInput:e.boolean().optional(),questionRequests:e.boolean().optional()}),a=e.object({id:e.string(),runId:e.string(),timestamp:e.date()}),o={parentToolCallId:e.string().optional()},s=a.extend({type:e.literal(`session-start`),requestedSessionId:e.string().optional(),sessionId:e.string().optional(),resumed:e.boolean()}),c=a.extend({type:e.literal(`message`),sessionId:e.string().optional(),...o,model:e.string().nullable(),role:e.enum([`system`,`user`,`assistant`]),content:e.array(r),text:e.string().optional()}),l=a.extend({type:e.literal(`reasoning`),sessionId:e.string().optional(),...o,model:e.string().nullable(),content:e.array(r),text:e.string().optional()}),u=a.extend({type:e.literal(`message-delta`),sessionId:e.string().optional(),...o,messageId:e.string(),text:e.string()}),d=a.extend({type:e.literal(`reasoning-delta`),sessionId:e.string().optional(),...o,reasoningId:e.string(),text:e.string()}),f=a.extend({type:e.literal(`tool-call`),sessionId:e.string().optional(),...o,model:e.string().nullable(),toolCallId:e.string(),toolName:e.string(),input:e.unknown().optional()}),p=a.extend({type:e.literal(`tool-result`),sessionId:e.string().optional(),...o,toolCallId:e.string(),toolName:e.string().optional(),input:e.unknown().optional(),output:e.unknown(),isError:e.boolean().optional(),error:e.string().optional()}),m=a.extend({type:e.literal(`stderr`),sessionId:e.string().optional(),text:e.string()}),h=e.enum([`allowed`,`warning`,`rejected`]),g=a.extend({type:e.literal(`rate-limit`),sessionId:e.string().optional(),status:h,limitType:e.string().optional(),windowMinutes:e.number().optional(),utilization:e.number().optional(),resetsAt:e.date().optional(),reason:e.string().optional(),overageStatus:h.optional(),isUsingOverage:e.boolean().optional(),overageDisabledReason:e.string().optional()}),_=a.extend({type:e.literal(`notice`),sessionId:e.string().optional(),notice:e.discriminatedUnion(`kind`,[e.object({kind:e.literal(`mcp-server-failed`),server:e.string()}),e.object({kind:e.literal(`hook-failed`),hook:e.string(),exitCode:e.number().optional()})])}),v=a.extend({type:e.literal(`session-end`),sessionId:e.string().optional(),status:e.enum([`completed`,`failed`,`cancelled`]),error:e.string().optional()}),y=e.discriminatedUnion(`type`,[s,c,l,u,d,f,p,m,g,_,v]);export{t as _,_ as a,l as c,m as d,f,n as g,r as h,c as i,v as l,i as m,y as n,g as o,p,u as r,d as s,a as t,s as u};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./errors-BauhTL3l.mjs";import{spawn as t}from"node:child_process";const n=e=>({async*[Symbol.asyncIterator](){for await(let t of e)if(t instanceof Buffer)yield new Uint8Array(t);else if(typeof t==`string`)yield new TextEncoder().encode(t);else if(t instanceof Uint8Array)yield t;else throw Error(`Unsupported stdout/stderr chunk type: ${typeof t}`)}}),r=(r,i,a={})=>{let o=t(r,i,{cwd:a.cwd,env:a.env,stdio:a.stdio,detached:!0}),s,c=t=>{s??=new e(t)};o.stdin?.on(`error`,c);let l=new Promise((e,t)=>{let n=(n,i)=>{o.removeListener(`error`,r),s?t(s):e({exitCode:n,signal:i})},r=e=>{o.removeListener(`close`,n),t(e)};o.once(`error`,r),o.once(`close`,n)}),u=o.stdin;return{stdout:o.stdout?n(o.stdout):null,stderr:o.stderr?n(o.stderr):null,stdin:u?{write:e=>{let t=new Promise((t,n)=>{u.write(e,e=>{e?n(e):t()})});return t.catch(c),t},end:()=>{let e=new Promise((e,t)=>{u.end(n=>{n?t(n):e()})});return e.catch(c),e}}:null,kill:e=>{if(o.pid===void 0)o.kill(e);else try{process.kill(-o.pid,e??`SIGTERM`)}catch{o.kill(e)}},wait:()=>l}},i={spawn:r};export{r as n,i as t};
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
//#region src/core/process/types.d.ts
|
|
2
1
|
type StdioOption = "ignore" | "inherit" | "pipe" | number;
|
|
3
2
|
/** POSIX signal name (re-export of `NodeJS.Signals`). */
|
|
4
3
|
type ProcessSignal = NodeJS.Signals;
|
|
@@ -53,5 +52,4 @@ interface ProcessSpawner {
|
|
|
53
52
|
/** Launch `command` with `args` and return a live {@link AgentProcess} handle. */
|
|
54
53
|
spawn: (command: string, args: string[], options?: SpawnOptions) => AgentProcess;
|
|
55
54
|
}
|
|
56
|
-
//#endregion
|
|
57
55
|
export { SpawnOptions as a, ProcessSpawner as i, ProcessResult as n, ProcessSignal as r, AgentProcess as t };
|
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { r as ProcessSignal } from "./types-
|
|
1
|
+
import { D as ContentPart, E as AgentCapabilities, k as JsonSchema, t as AgentEvent } from "./events-DmlAPVpd.mjs";
|
|
2
|
+
import { r as ProcessSignal } from "./types-BetgZysV.mjs";
|
|
3
3
|
import { ZodType } from "zod/v4";
|
|
4
|
-
//#region src/core/agent/permissions.d.ts
|
|
5
4
|
/**
|
|
6
5
|
* Information about a tool call the adapter is requesting permission for.
|
|
7
6
|
* Passed to the {@link PermissionHandler} registered via
|
|
@@ -26,23 +25,30 @@ interface PermissionRequest {
|
|
|
26
25
|
/** Longer description / justification suitable for a UI prompt. */
|
|
27
26
|
description?: string;
|
|
28
27
|
}
|
|
28
|
+
/** Permission mode of a Claude Code session. */
|
|
29
|
+
type ClaudePermissionMode = "acceptEdits" | "auto" | "bypassPermissions" | "default" | "dontAsk" | "plan";
|
|
29
30
|
/**
|
|
30
31
|
* Decision returned by a {@link PermissionHandler}.
|
|
31
32
|
*
|
|
32
|
-
* - `{ decision: "allow" }` lets the call proceed
|
|
33
|
-
* rewrite the tool arguments
|
|
33
|
+
* - `{ decision: "allow" }` lets the call proceed. On the Claude adapters it can
|
|
34
|
+
* also rewrite the tool arguments with `updatedInput` or switch the session's
|
|
35
|
+
* permission mode with `permissionMode`; the other adapters cannot apply either
|
|
36
|
+
* field and do not run a call whose allow carries one.
|
|
34
37
|
* - `{ decision: "deny" }` blocks the call; `message` is fed back to the
|
|
35
|
-
* model as the rejection reason
|
|
38
|
+
* model as the rejection reason, except on `antigravity-cli` and
|
|
39
|
+
* `codex-cli`, whose permission answers cannot carry it.
|
|
36
40
|
*/
|
|
37
41
|
type PermissionDecision = {
|
|
38
42
|
/** Approve the tool call. */
|
|
39
43
|
decision: "allow";
|
|
40
|
-
/**
|
|
44
|
+
/** Rewritten tool input; overrides {@link PermissionRequest.input}. Supported by the Claude adapters only. */
|
|
41
45
|
updatedInput?: Record<string, unknown>;
|
|
46
|
+
/** Optional permission mode the session switches to from this point on. Supported by the Claude adapters only. */
|
|
47
|
+
permissionMode?: ClaudePermissionMode;
|
|
42
48
|
} | {
|
|
43
49
|
/** Reject the tool call. */
|
|
44
50
|
decision: "deny";
|
|
45
|
-
/** Rejection reason sent back to the model. */
|
|
51
|
+
/** Rejection reason sent back to the model; `antigravity-cli` and `codex-cli` cannot send it. */
|
|
46
52
|
message?: string;
|
|
47
53
|
};
|
|
48
54
|
/**
|
|
@@ -52,8 +58,35 @@ type PermissionDecision = {
|
|
|
52
58
|
* a new one replaces the previous handler.
|
|
53
59
|
*/
|
|
54
60
|
type PermissionHandler = (request: PermissionRequest) => PermissionDecision | Promise<PermissionDecision>;
|
|
55
|
-
|
|
56
|
-
|
|
61
|
+
interface QuestionOption {
|
|
62
|
+
label: string;
|
|
63
|
+
description: string;
|
|
64
|
+
}
|
|
65
|
+
interface Question {
|
|
66
|
+
/** Identifies the question within its request. {@link QuestionAnswers} is keyed by it. */
|
|
67
|
+
id: string;
|
|
68
|
+
text: string;
|
|
69
|
+
header: string;
|
|
70
|
+
options: QuestionOption[];
|
|
71
|
+
allowsMultiple: boolean;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Questions the agent asks the user through its question tool. Passed to the {@link QuestionHandler} registered via
|
|
75
|
+
* `agent.onQuestionRequest(...)`. Only adapters that report `capabilities.questionRequests === true` issue these.
|
|
76
|
+
*/
|
|
77
|
+
interface QuestionRequest {
|
|
78
|
+
/** Unique ID of the tool call that asks. Tells outstanding requests apart. */
|
|
79
|
+
toolUseId: string;
|
|
80
|
+
questions: Question[];
|
|
81
|
+
/** Aborts when the run is cancelled or the provider withdraws the request. Honor it in long-running handlers. */
|
|
82
|
+
signal: AbortSignal;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Answers returned by a {@link QuestionHandler}, keyed by {@link Question.id}. Each answer lists the labels of the
|
|
86
|
+
* selected options, free-form text, or both. A question without an entry stays unanswered.
|
|
87
|
+
*/
|
|
88
|
+
type QuestionAnswers = Record<string, string[]>;
|
|
89
|
+
type QuestionHandler = (request: QuestionRequest) => Promise<QuestionAnswers> | QuestionAnswers;
|
|
57
90
|
/**
|
|
58
91
|
* Identifier for one of the supported coding-agent adapters.
|
|
59
92
|
*
|
|
@@ -61,7 +94,7 @@ type PermissionHandler = (request: PermissionRequest) => PermissionDecision | Pr
|
|
|
61
94
|
* agent backs the instance. CLI variants spawn a subprocess; SDK variants
|
|
62
95
|
* import an in-process SDK package.
|
|
63
96
|
*/
|
|
64
|
-
type AgentType = "claude-code-cli-pty" | "claude-code-cli" | "claude-code-sdk" | "codex-cli" | "codex-sdk" | "cursor-cli" | "cursor-sdk" | "gemini-cli" | "opencode-cli" | "pi-cli";
|
|
97
|
+
type AgentType = "antigravity-cli" | "claude-code-cli-pty" | "claude-code-cli" | "claude-code-sdk" | "codex-cli" | "codex-sdk" | "cursor-cli" | "cursor-sdk" | "drac-cli" | "gemini-cli" | "opencode-cli" | "pi-cli";
|
|
65
98
|
/**
|
|
66
99
|
* Terminal status of a run.
|
|
67
100
|
* - `"completed"`: the model produced a final response (and structured output if requested).
|
|
@@ -100,6 +133,11 @@ type StopReason = "abort" | "timeout" | "user";
|
|
|
100
133
|
* itself, through a `sessionId` option or a resume flag in `extraArgs` or `command`, reports the
|
|
101
134
|
* session's cumulative `costUsd` and `apiDurationMs`, and its token counts cover only the main
|
|
102
135
|
* agent, not subagents.
|
|
136
|
+
*
|
|
137
|
+
* `codex-cli` on the app-server transport reports the token counts of the run's own turn, also on a
|
|
138
|
+
* resumed session: Codex reports the session's earlier totals before the turn starts, and the adapter
|
|
139
|
+
* subtracts them. A forked app-server run, and a resumed run on the default `exec` transport, report
|
|
140
|
+
* the session's cumulative token counts, because Codex reports no earlier totals for them.
|
|
103
141
|
*/
|
|
104
142
|
interface RunStats {
|
|
105
143
|
/** Wall-clock duration of the run as reported by the provider, in milliseconds. */
|
|
@@ -122,6 +160,18 @@ interface RunStats {
|
|
|
122
160
|
reasoningOutputTokens?: number;
|
|
123
161
|
/** Sum of the disjoint token classes above. */
|
|
124
162
|
totalTokens?: number;
|
|
163
|
+
/**
|
|
164
|
+
* The models the provider reports the run used, in the order they were first reported.
|
|
165
|
+
*
|
|
166
|
+
* `claude-code-cli` and `claude-code-sdk` list the models of the run's assistant messages and, on a fresh run or a
|
|
167
|
+
* resume of a session the agent ran itself, the other models whose usage in Claude Code's `modelUsage` grew during
|
|
168
|
+
* the run, such as a subagent's. A run that resumes a session the agent has not run itself lists only the models of
|
|
169
|
+
* its own messages, because `modelUsage` there covers the whole session. `claude-code-cli-pty` lists only the
|
|
170
|
+
* `modelUsage` models of a fresh run. `codex-cli` on the app-server transport lists the thread's model and every
|
|
171
|
+
* model Codex rerouted the turn to. `antigravity-cli` lists the run's `model`, or the session's current model when
|
|
172
|
+
* the run sets none.
|
|
173
|
+
*/
|
|
174
|
+
models?: string[];
|
|
125
175
|
}
|
|
126
176
|
/**
|
|
127
177
|
* Structured failure reason attached to non-completed runs.
|
|
@@ -401,15 +451,22 @@ interface BaseAgent<TRunOptions extends object = {}> {
|
|
|
401
451
|
/**
|
|
402
452
|
* Reset adapter-internal state: clear the session, drop tool-call records,
|
|
403
453
|
* reset metrics. The next `run(...)` starts a fresh session/thread.
|
|
454
|
+
* Throws {@link AgentValidationError} while a run is active.
|
|
404
455
|
*
|
|
405
|
-
* Does not dispose the underlying SDK
|
|
406
|
-
* for that.
|
|
456
|
+
* Does not dispose the agent or the underlying SDK — use {@link dispose}
|
|
457
|
+
* for that. With `claude-code-cli`'s `backgroundTasks: "keep-running"`,
|
|
458
|
+
* it ends the Claude Code process the agent keeps between runs, with its
|
|
459
|
+
* background tasks, because they belong to the session it clears.
|
|
407
460
|
*/
|
|
408
461
|
reset: () => void;
|
|
409
462
|
/**
|
|
410
463
|
* Wait for the currently in-flight run to reach a terminal state and
|
|
411
|
-
* resolve with its result.
|
|
412
|
-
*
|
|
464
|
+
* resolve with its result. When no run is in flight, resolves with the
|
|
465
|
+
* result of the most recent run.
|
|
466
|
+
*
|
|
467
|
+
* Throws {@link AgentValidationError} when the agent has no run to wait
|
|
468
|
+
* for: before its first run, or after `reset()`. The call itself throws;
|
|
469
|
+
* it does not return a rejected promise.
|
|
413
470
|
*/
|
|
414
471
|
wait: () => Promise<AnyRunResult>;
|
|
415
472
|
/**
|
|
@@ -445,6 +502,30 @@ interface BaseAgent<TRunOptions extends object = {}> {
|
|
|
445
502
|
* support.
|
|
446
503
|
*/
|
|
447
504
|
onPermissionRequest: (handler: PermissionHandler) => () => void;
|
|
505
|
+
/**
|
|
506
|
+
* Register the (single) question handler. The handler returns the answers
|
|
507
|
+
* directly, and the adapter sends them back to the provider. Calling again
|
|
508
|
+
* replaces any previous handler. Returns an unsubscribe function.
|
|
509
|
+
*
|
|
510
|
+
* Only effective when `capabilities.questionRequests === true`. If the
|
|
511
|
+
* handler throws, the question stays unanswered and the run continues:
|
|
512
|
+
* `claude-code-cli` tells the agent so with the error's message,
|
|
513
|
+
* `codex-cli` gives the model no answer, `drac-cli` tells Drac the
|
|
514
|
+
* question went unanswered, and `antigravity-cli` answers Antigravity
|
|
515
|
+
* with the error; `drac-cli` and `antigravity-cli` also write the error
|
|
516
|
+
* to the agent's `logPath` log.
|
|
517
|
+
*/
|
|
518
|
+
onQuestionRequest: (handler: QuestionHandler) => () => void;
|
|
519
|
+
/**
|
|
520
|
+
* Send user input into the active run, without waiting for it to finish.
|
|
521
|
+
* Resolves once the provider has been handed the input; when and how the
|
|
522
|
+
* model reads it is up to the provider.
|
|
523
|
+
*
|
|
524
|
+
* Rejects with {@link AgentValidationError} when `capabilities.midRunInput`
|
|
525
|
+
* is not `true`, when no run is active, the active run is stopping, or it
|
|
526
|
+
* is not accepting input, and when the input is empty or has a part the
|
|
527
|
+
* adapter does not support.
|
|
528
|
+
*/
|
|
529
|
+
sendInput: (input: ContentPart[] | string) => Promise<void>;
|
|
448
530
|
}
|
|
449
|
-
|
|
450
|
-
export { PermissionRequest as A, RunStatus as C, ZodRunRequest as D, StructuredRunRequest as E, PermissionDecision as O, RunStats as S, StopReason as T, ProviderEventHandler as _, AgentValidationError as a, RunRequest as b, AnyRunResult as c, CompletedRunResult as d, EnsureDisjoint as f, ProviderEvent as g, JsonSchemaRunRequest as h, AgentType as i, PermissionHandler as k, BaseAgent as l, FailedRunResult as m, AgentMetrics as n, AnyCompletedRunResult as o, ExclusiveExecutionTargetOptions as p, AgentRunError as r, AnyRunRequest as s, AgentEventHandler as t, CancelledRunResult as u, RunError as v, RunTiming as w, RunResult as x, RunProcessInfo as y };
|
|
531
|
+
export { QuestionHandler as A, RunStatus as C, ZodRunRequest as D, StructuredRunRequest as E, PermissionHandler as F, PermissionRequest as I, QuestionRequest as M, ClaudePermissionMode as N, Question as O, PermissionDecision as P, RunStats as S, StopReason as T, ProviderEventHandler as _, AgentValidationError as a, RunRequest as b, AnyRunResult as c, CompletedRunResult as d, EnsureDisjoint as f, ProviderEvent as g, JsonSchemaRunRequest as h, AgentType as i, QuestionOption as j, QuestionAnswers as k, BaseAgent as l, FailedRunResult as m, AgentMetrics as n, AnyCompletedRunResult as o, ExclusiveExecutionTargetOptions as p, AgentRunError as r, AnyRunRequest as s, AgentEventHandler as t, CancelledRunResult as u, RunError as v, RunTiming as w, RunResult as x, RunProcessInfo as y };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=e=>Array.isArray(e)?e:[e],t=e=>e instanceof Error?e.message:String(e),n=e=>typeof e==`object`&&!!e,r=(...e)=>{if(!e.every(e=>e===void 0))return e.reduce((e,t)=>e+(t??0),0)},i=e=>{let t=e.trim();return t.startsWith("```")?t.replace(/^```[\w-]*\s*/i,``).replace(/\s*```$/i,``).trim():t},a=e=>/```[\w-]*\s*([\S\s]*?)\s*```/i.exec(e)?.[1]?.trim(),o=e=>{let t=-1,n=[],r=!1,i=!1;for(let a=0;a<e.length;a++){let o=e[a];if(o){if(t===-1)(o===`{`||o===`[`)&&(t=a,n.push(o));else if(r){if(i){i=!1;continue}if(o===`\\`){i=!0;continue}o===`"`&&(r=!1)}else if(o===`"`)r=!0;else if(o===`{`||o===`[`)n.push(o);else if(o===`}`||o===`]`){let r=n.pop();if(r===`{`&&o!==`}`||r===`[`&&o!==`]`)return;if(n.length===0)return e.slice(t,a+1).trim()}}}},s=e=>{let t=e.trim(),n=[i(t),a(t),o(t)],r;for(let e of new Set(n))if(e)try{return JSON.parse(e)}catch(e){r=e}throw r instanceof Error?r:/* @__PURE__ */ SyntaxError(`Failed to parse JSON response text.`)};export{e as a,r as i,n,s as r,t};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "coding-agents-sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.21.0",
|
|
4
4
|
"description": "Run coding agents behind one uniform TypeScript interface, with optional container and sandbox execution.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"coding-agent",
|
|
@@ -41,6 +41,10 @@
|
|
|
41
41
|
"types": "./dist/sandbox/index.d.mts",
|
|
42
42
|
"default": "./dist/sandbox/index.mjs"
|
|
43
43
|
},
|
|
44
|
+
"./adapters/antigravity-cli": {
|
|
45
|
+
"types": "./dist/adapters/antigravity-cli/index.d.mts",
|
|
46
|
+
"default": "./dist/adapters/antigravity-cli/index.mjs"
|
|
47
|
+
},
|
|
44
48
|
"./adapters/claude-code-cli-pty": {
|
|
45
49
|
"types": "./dist/adapters/claude-code-cli-pty/index.d.mts",
|
|
46
50
|
"default": "./dist/adapters/claude-code-cli-pty/index.mjs"
|
|
@@ -69,6 +73,10 @@
|
|
|
69
73
|
"types": "./dist/adapters/cursor-sdk/index.d.mts",
|
|
70
74
|
"default": "./dist/adapters/cursor-sdk/index.mjs"
|
|
71
75
|
},
|
|
76
|
+
"./adapters/drac-cli": {
|
|
77
|
+
"types": "./dist/adapters/drac-cli/index.d.mts",
|
|
78
|
+
"default": "./dist/adapters/drac-cli/index.mjs"
|
|
79
|
+
},
|
|
72
80
|
"./adapters/gemini-cli": {
|
|
73
81
|
"types": "./dist/adapters/gemini-cli/index.d.mts",
|
|
74
82
|
"default": "./dist/adapters/gemini-cli/index.mjs"
|
|
@@ -95,6 +103,7 @@
|
|
|
95
103
|
"test:agent": "bun test ./tests/features",
|
|
96
104
|
"test:package": "bun run test:package:runtime",
|
|
97
105
|
"test:package:runtime": "bun test ./tests/package-exports.smoke.ts",
|
|
106
|
+
"test:agent:antigravity-cli": "ADAPTERS=antigravity-cli bun run test:agent",
|
|
98
107
|
"test:agent:claude-code-cli-pty": "ADAPTERS=claude-code-cli-pty bun run test:agent",
|
|
99
108
|
"test:agent:claude-code-cli": "ADAPTERS=claude-code-cli bun run test:agent",
|
|
100
109
|
"test:agent:claude-code-sdk": "ADAPTERS=claude-code-sdk bun run test:agent",
|
|
@@ -102,6 +111,7 @@
|
|
|
102
111
|
"test:agent:codex-sdk": "ADAPTERS=codex-sdk bun run test:agent",
|
|
103
112
|
"test:agent:cursor-cli": "ADAPTERS=cursor-cli bun run test:agent",
|
|
104
113
|
"test:agent:cursor-sdk": "ADAPTERS=cursor-sdk bun run test:agent",
|
|
114
|
+
"test:agent:drac-cli": "ADAPTERS=drac-cli bun run test:agent",
|
|
105
115
|
"test:agent:gemini-cli": "ADAPTERS=gemini-cli bun run test:agent",
|
|
106
116
|
"test:agent:opencode-cli": "ADAPTERS=opencode-cli bun run test:agent",
|
|
107
117
|
"test:agent:pi-cli": "ADAPTERS=pi-cli bun run test:agent",
|
|
@@ -110,21 +120,21 @@
|
|
|
110
120
|
"typecheck": "bun run tsc"
|
|
111
121
|
},
|
|
112
122
|
"devDependencies": {
|
|
113
|
-
"@anthropic-ai/claude-agent-sdk": "^0.3.
|
|
114
|
-
"@cursor/sdk": "^1.
|
|
115
|
-
"@openai/codex-sdk": "^0.
|
|
116
|
-
"@types/bun": "^1.4.
|
|
117
|
-
"@types/node": "^26.6.
|
|
118
|
-
"e2b": "^2.
|
|
119
|
-
"knip": "^6.
|
|
123
|
+
"@anthropic-ai/claude-agent-sdk": "^0.3.321",
|
|
124
|
+
"@cursor/sdk": "^1.3.1",
|
|
125
|
+
"@openai/codex-sdk": "^0.167.0",
|
|
126
|
+
"@types/bun": "^1.4.4",
|
|
127
|
+
"@types/node": "^26.6.6",
|
|
128
|
+
"e2b": "^2.62.1",
|
|
129
|
+
"knip": "^6.44.1",
|
|
120
130
|
"picoprint": "^2.2.2",
|
|
121
|
-
"tsdown": "^0.23.
|
|
131
|
+
"tsdown": "^0.23.4",
|
|
122
132
|
"typescript": "^7.0.2"
|
|
123
133
|
},
|
|
124
134
|
"peerDependencies": {
|
|
125
135
|
"@anthropic-ai/claude-agent-sdk": "^0.3.170",
|
|
126
136
|
"@cursor/sdk": "^1.0.12",
|
|
127
|
-
"@openai/codex-sdk": ">=0.150.0 <0.
|
|
137
|
+
"@openai/codex-sdk": ">=0.150.0 <0.168.0",
|
|
128
138
|
"e2b": "^2.28.0",
|
|
129
139
|
"typescript": "^6.0.3 || ^7.0.0"
|
|
130
140
|
},
|
package/dist/Agent-WqGee5TR.mjs
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
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-DK2WpxiL.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=Symbol(`process exited`),m=t=>t.status===`rejected`?e(t.reason):void 0,h=(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=m(r.stdinResult);if(a)return{kind:`process`,message:a};let o=m(r.stdoutResult);if(o)return{kind:`process`,message:o};let s=m(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}}},g=async(e,t,n)=>{let r=e.stdin;if(!r?.write)throw Error(`The process spawner must provide a stdin writer for this adapter.`);let i=n.then(()=>p,()=>p),a=t[Symbol.asyncIterator]();for(;;){let e=await Promise.race([a.next(),i]);if(e===p){a.return?.();return}if(e.done)break;if(await Promise.race([r.write(e.value),i])===p)return}await Promise.race([r.end(),i])},_=e=>{let t=c(e);return t.kind===`provider`?{kind:`process`,message:t.message}:t};var v=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=t.process.wait(),[c,l,u,d]=await Promise.allSettled([this.watchStdout(t),this.watchStderr(t),s,this.deliverInput(t.process,this.getStdinInput(e),s)]);u.status===`fulfilled`&&(t.processResult=u.value);let f=h(t,{stdoutResult:c,stderrResult:l,processResult:u,stdinResult:d});f&&(t.error=f)}catch(e){!t.stopReason&&!t.error&&(t.error=_(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,n){try{if(typeof t==`object`){await g(e,t,n);return}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{v as t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{n as e,t}from"./classify-error-DK2WpxiL.mjs";var n=class extends e{currentAbortController;cleanupSdkResources(){}onStopRequested(e){this.currentAbortController?.abort()}async executeRunCore(e,n){let r=new AbortController;this.currentAbortController=r;let i=this.setupRunLifecycle(e);try{return i.abortedBeforeStart||e.stopReason?this.buildResult(e,/* @__PURE__ */ new Date):(e.sessionId&&this.emitSessionStart(e),await this.executeSdkRun(e,n,r),this.buildResult(e,/* @__PURE__ */ new Date))}catch(n){return!e.stopReason&&!e.error&&(e.error=t(n)),this.buildResult(e,/* @__PURE__ */ new Date)}finally{i.cleanup();try{await this.cleanupSdkResources()}catch{}this.currentAbortController===r&&(this.currentAbortController=void 0)}}};export{n as t};
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import{n as e,t}from"./types-B72tDMEZ.mjs";import{z as n}from"zod/v4";const r=()=>crypto.randomUUID(),i=()=>`evt_${crypto.randomUUID()}`,a=e=>({type:`text`,text:e}),o=e=>e.flatMap(e=>e.type===`text`?[e.text]:[]).join(`
|
|
2
|
-
`),s=e=>e.flatMap(e=>e.type===`text`?[e.text]:[]).join(`
|
|
3
|
-
|
|
4
|
-
`),c=e=>t=>{let n=e.safeParse(t);return n.success?n.data:null},l=(e,t,n,r)=>{let i;for(let t of e.events){if(t.type!==`message`||t.role!==`assistant`||!t.text)continue;let e=`${n.get(r)??``}${t.text}`;n.set(r,e),i=e}return t&&e.state?.output?.text!==void 0?n.set(r,e.state.output.text):i!==void 0&&(e.state={...e.state,output:{...e.state?.output,text:i}}),e},u=(e,t,n)=>({id:n.id??i(),runId:e,timestamp:/* @__PURE__ */ new Date,type:t,...n}),d=e=>e instanceof n.ZodType,f=e=>{if(!(`schema`in e))return{kind:`none`};let{schema:t}=e;return d(t)?{kind:`zod`,jsonSchema:n.toJSONSchema(t),zodSchema:t}:{kind:`json-schema`,jsonSchema:t}},p=(t,n,r,i)=>{let a=typeof i.input==`string`?[{type:`text`,text:i.input}]:i.input;if(a.length===0||a.every(e=>e.type===`text`&&e.text.trim()===``))throw new e(`Run input cannot be empty.`);if(!n.imageInput&&a.some(e=>e.type===`image`))throw new e(`${t} does not support image input.`);let o=f(i);if(!n.structuredOutput&&o.kind!==`none`)throw new e(`${t} does not support structured output.`);if(i.timeoutMs!==void 0&&(!Number.isFinite(i.timeoutMs)||i.timeoutMs<=0))throw new e(`timeoutMs must be a positive finite number.`);return{input:a,schema:o,cwd:i.cwd??r?.cwd,model:i.model??r?.model,systemPrompt:i.systemPrompt??r?.systemPrompt,timeoutMs:i.timeoutMs,signal:i.signal}},m=(e,t)=>({runId:e.runId,requestedSessionId:e.requestedSessionId,sessionId:e.sessionId,schemaRequested:e.normalizedRequest.schema.kind!==`none`,toolCalls:e.toolCalls,...t}),h=(e,t)=>{if(!e.stats)return;let n=Math.max(0,t.getTime()-e.startedAt.getTime());e.stats={...e.stats,durationMs:e.stats.durationMs??n,apiDurationMs:e.stats.apiDurationMs??n}},g=(e,t)=>{let n=e.normalizedRequest.schema;if(n.kind!==`none`){if(n.kind===`zod`){let r=n.zodSchema.safeParse(t);if(!r.success){e.status=`failed`,e.error={kind:`parse`,message:r.error.message};return}e.output.value=r.data;return}e.output.value=t}},_=(e,t)=>{if(e.events.push(t),t.type!==`message`||t.role!==`assistant`)return;let n=t.text??o(t.content);n&&e.assistantTexts.push(n)},v=(e,t,n={})=>{t.sessionId&&(e.sessionId=t.sessionId,n.onSessionId?.(t.sessionId));for(let n of t.toolCalls??[])e.toolCalls.set(n.toolCallId,{toolName:n.toolName,input:n.input});if(!t.state)return;let r=t.state;`error`in r&&r.error===void 0&&(e.error=void 0),r.output&&(`text`in r.output&&(e.output.text=r.output.text),`value`in r.output&&g(e,r.output.value)),`stats`in r&&(e.stats=r.stats),`status`in r&&(e.status=r.status),r.error&&(e.error=r.error)},y=e=>e.events.some(e=>e.type===`message`||e.type===`reasoning`||e.type===`tool-call`||e.type===`tool-result`),b=e=>{let t=e.normalizedRequest.schema.kind!==`none`&&e.output.value===void 0;return e.stopReason===`user`||e.stopReason===`abort`||e.stopReason===`timeout`?`cancelled`:e.error?e.error.kind===`abort`?`cancelled`:`failed`:e.status?e.status===`completed`&&t?`failed`:e.status:e.processResult&&e.processResult.exitCode!==null&&e.processResult.exitCode!==0||!y(e)&&e.stderrLines.length>0||t?`failed`:`completed`},x=(e,t)=>{let n=e.processResult,r=e.stderrLines.join(`
|
|
5
|
-
`);if(e.stopReason===`user`)return{kind:`abort`,message:`Run stopped by user.`};if(e.stopReason===`abort`)return{kind:`abort`,message:`Run aborted.`};if(e.stopReason===`timeout`)return{kind:`abort`,message:`Run timed out after ${e.normalizedRequest.timeoutMs}ms.`};if(e.error)return e.error;if(n&&n.exitCode!==null&&n.exitCode!==0)return{kind:`process`,message:r||`Process exited with code ${n.exitCode}.`};if(t===`failed`&&e.stderrLines.length>0)return{kind:`process`,message:r};if(t===`failed`&&e.normalizedRequest.schema.kind!==`none`&&e.output.value===void 0)return{kind:`parse`,message:`Structured output was requested but no structured output value was produced.`}},S=(e,t,n,r,i)=>{let a=t.stderrLines.join(`
|
|
6
|
-
`),o={type:e,runId:t.runId,sessionId:t.sessionId,text:t.output.text??t.assistantTexts.join(`
|
|
7
|
-
|
|
8
|
-
`),events:[...t.events],stats:t.stats,timing:{startedAt:t.startedAt,endedAt:n,durationMs:n.getTime()-t.startedAt.getTime()},process:t.processResult?{exitCode:t.processResult.exitCode,signal:t.processResult.signal,stderr:a}:void 0};switch(r){case`completed`:return t.normalizedRequest.schema.kind===`none`?{...o,status:r,error:void 0,cancelReason:void 0}:{...o,status:r,output:t.output.value,error:void 0,cancelReason:void 0};case`failed`:return{...o,status:r,output:void 0,error:i??{kind:`process`,message:`Unknown error.`},cancelReason:void 0};case`cancelled`:return{...o,status:r,output:void 0,error:i??{kind:`abort`,message:`Run cancelled.`},cancelReason:t.stopReason??`user`};default:throw Error(`Unsupported run status.`)}},C=()=>{let e=/* @__PURE__ */ new Date;return{runCount:0,messagesReceived:0,toolCalls:0,errors:0,startedAt:e,lastActivityAt:e}};var w=class{type;capabilities;currentRun;eventHandlers=[];permissionHandler;_sessionId;_metrics;constructor(e){this.type=e.type,this.capabilities=e.capabilities,this._sessionId=e.sessionId,this._metrics=C(),e.onEvent&&this.onEvent(e.onEvent)}onValidateRun(e,t){}async onDispose(){}onHandlerError(e){}get sessionId(){return this._sessionId}get metrics(){return this._metrics}get isRunning(){return this.currentRun?.running??!1}onEvent(e){return this.eventHandlers.push(e),()=>{let t=this.eventHandlers.indexOf(e);t>=0&&this.eventHandlers.splice(t,1)}}onPermissionRequest(e){return this.permissionHandler=e,()=>{this.permissionHandler===e&&(this.permissionHandler=void 0)}}getPermissionHandler(){return this.permissionHandler}async run(t){if(this.currentRun?.running)throw new e(`This agent is already running. Wait for it to finish first.`);let n=p(this.type,this.capabilities,this.runRequestDefaults,t);this.onValidateRun(t,n);let i={runId:r(),startedAt:/* @__PURE__ */ new Date,requestedSessionId:this._sessionId,sessionId:this._sessionId,normalizedRequest:n,events:[],stderrLines:[],assistantTexts:[],toolCalls:/* @__PURE__ */ new Map,output:{}},a={context:i,running:!0,promise:new Promise(()=>{})};this._metrics.runCount++;let o=Promise.resolve().then(()=>this.executeRunCore(i,t)).finally(()=>{a.running=!1});return a.promise=o,this.currentRun=a,o}async runOrThrow(e){let n=await this.run(e);if(n.status!==`completed`)throw new t(n);return n}async stop(){let e=this.currentRun?.context;if(e&&this.currentRun?.running){this.requestStop(e,`user`);try{return await this.currentRun.promise}catch{return}}}reset(){if(this.currentRun?.running)throw new e(`Cannot reset agent state while a run is active. Call stop() and wait() first.`);this.currentRun=void 0,this._sessionId=void 0,this._metrics=C()}wait(){if(!this.currentRun)throw new e(`There is no run to wait for.`);return this.currentRun.promise}async dispose(){if(this.currentRun?.running){this.requestStop(this.currentRun.context,`user`);try{await this.currentRun.promise}catch{}}await this.onDispose()}async[Symbol.asyncDispose](){await this.dispose()}applyBatch(e,t){v(e,t,{onSessionId:e=>{this.setSessionId(e)}}),e.sessionId&&this.emitSessionStart(e);for(let n of t.events)this.emit(e,n)}setupRunLifecycle(e){let t=!1,n=()=>{t||this.requestStop(e,`abort`)},r=e.normalizedRequest.timeoutMs===void 0?void 0:setTimeout(()=>{t||this.requestStop(e,`timeout`)},e.normalizedRequest.timeoutMs);r?.unref?.(),e.normalizedRequest.signal?.addEventListener(`abort`,n,{once:!0});let i=e.normalizedRequest.signal?.aborted===!0;return i&&this.requestStop(e,`abort`),{abortedBeforeStart:i,cleanup:()=>{t=!0,r&&clearTimeout(r),e.normalizedRequest.signal?.removeEventListener(`abort`,n)}}}emitSessionStart(e){e.sessionStarted||(e.sessionStarted=!0,this.emit(e,u(e.runId,`session-start`,{requestedSessionId:e.requestedSessionId,sessionId:e.sessionId,resumed:e.requestedSessionId!==void 0})))}emit(e,t){_(e,t),this.updateMetrics(t);for(let e of this.eventHandlers)try{e(t)}catch(e){this.onHandlerError(e)}}requestStop(e,t){e.stopReason||(e.stopReason=t,this.onStopRequested(e))}buildResult(e,t){h(e,t);let n=b(e),r=x(e,n);return e.sessionStarted&&this.emit(e,u(e.runId,`session-end`,{sessionId:e.sessionId,status:n,error:r?.message})),S(this.type,e,t,n,r)}setSessionId(e){this._sessionId=e}updateMetrics(e){switch(this._metrics.lastActivityAt=e.timestamp,e.type){case`message`:e.role===`assistant`&&this._metrics.messagesReceived++;break;case`tool-call`:this._metrics.toolCalls++;break;case`session-end`:e.status===`failed`&&this._metrics.errors++}}};const T=/* @__PURE__ */ new Set([`ENOENT`,`ERR_MODULE_NOT_FOUND`]),E=e=>`code`in e,D=(e,t)=>{let n=t??(e instanceof Error?e.message:String(e));if(e instanceof Error){if(e.name===`AbortError`)return{kind:`abort`,message:n};if(E(e)&&T.has(String(e.code)))return{kind:`spawn`,message:n};if(e instanceof SyntaxError)return{kind:`parse`,message:n}}return{kind:`provider`,message:n}};export{y as a,c,m as i,s as l,w as n,l as o,v as r,u as s,D as t,a as u};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{n as e,t}from"./oci-DTNwW-WH.mjs";const n=async n=>{let r={binary:n.binary??`docker`},i=await e(r,n);return t(`docker`,{commandContext:r,containerName:n.name,workdir:n.workdir,user:n.user,network:n.network,platform:n.platform,env:n.env,ports:n.ports,mounts:n.mounts,mountCwd:n.mountCwd,extraArgs:n.extraArgs,image:i,builtImage:n.build!==void 0&&!n.build.tag},n)};export{n as createDockerContainer};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var e=class extends Error{constructor(e){super(e),this.name=`ContainerError`}},t=class extends e{constructor(e){super(e),this.name=`ContainerCreateError`}},n=class extends e{constructor(e){super(e),this.name=`MountValidationError`}},r=class extends e{constructor(e){super(e),this.name=`ContainerStartError`}},i=class extends e{constructor(e){super(e),this.name=`ContainerExecError`}},a=class extends e{constructor(e=`Container is not running.`){super(e),this.name=`ContainerNotRunningError`}},o=class extends e{constructor(e=`Container has been disposed.`){super(e),this.name=`ContainerDisposedError`}},s=class extends e{constructor(e){super(e),this.name=`ContainerDiffError`}};async function c(e){switch(e.type){case`docker`:{let{createDockerContainer:t}=await import(`./container-Bdb90GJb.mjs`);return t(e)}case`e2b`:try{let{createE2BContainer:t}=await import(`./container-w0rl1QMH.mjs`);return await t(e)}catch(e){throw e instanceof Error&&e.message.includes(`e2b`)&&(e.code===`ERR_MODULE_NOT_FOUND`||e.code===`MODULE_NOT_FOUND`)?new t(`Container type "e2b" requires the optional peer dependency "e2b". Install it to use this provider.`):e}case`nerdctl`:{let{createNerdctlContainer:t}=await import(`./container-dCRMBvQw.mjs`);return t(e)}case`podman`:{let{createPodmanContainer:t}=await import(`./container-Dvr-p53c.mjs`);return t(e)}default:throw new t(`Unsupported container type.`)}}export{e as a,r as c,o as i,n as l,t as n,i as o,s as r,a as s,c as t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{n as e,t}from"./oci-DTNwW-WH.mjs";const n=async n=>{let r={binary:n.binary??`podman`},i=await e(r,n);return t(`podman`,{commandContext:r,containerName:n.name,workdir:n.workdir,user:n.user,network:n.network,platform:n.platform,env:n.env,ports:n.ports,mounts:n.mounts,mountCwd:n.mountCwd,extraArgs:n.extraArgs,image:i,builtImage:n.build!==void 0&&!n.build.tag},n)};export{n as createPodmanContainer};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{n as e,t}from"./oci-DTNwW-WH.mjs";const n=e=>{let t={};return e.address&&(t.CONTAINERD_ADDRESS=e.address),e.namespace&&(t.CONTAINERD_NAMESPACE=e.namespace),e.buildkitHost&&(t.BUILDKIT_HOST=e.buildkitHost),Object.keys(t).length>0?t:void 0},r=e=>{let t=[];return e.namespace&&t.push(`--namespace`,e.namespace),e.address&&t.push(`--address`,e.address),e.snapshotter&&t.push(`--snapshotter`,e.snapshotter),e.args&&t.push(...e.args),t.length>0?t:void 0},i=e=>({binary:e.binary??`nerdctl`,baseArgs:r(e),env:n(e)}),a=async n=>{let r=i(n),a=await e(r,n);return t(`nerdctl`,{commandContext:r,containerName:n.name,workdir:n.workdir,user:n.user,network:n.network,platform:n.platform,env:n.env,ports:n.ports,mounts:n.mounts,mountCwd:n.mountCwd,extraArgs:n.extraArgs,image:a,builtImage:n.build!==void 0&&!n.build.tag},n)};export{a as createNerdctlContainer};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./util-B4HTdOSc.mjs";import{c as t,i as n,n as r,r as i,s as a}from"./container-DMFxf-kn.mjs";import{t as o}from"./errors-aYGbvsaq.mjs";import{t as s}from"./shell-DvWFuFKb.mjs";import{n as c}from"./diff-Dqyk2cdt.mjs";import{basename as l,dirname as u,join as d,posix as f}from"node:path";import{mkdir as p,readFile as m,readdir as h,stat as g,writeFile as _}from"node:fs/promises";import{CommandExitError as v,FileType as y,Sandbox as b}from"e2b";const x=(e,t)=>[e,...t].map(s).join(` `),S=e=>e.user,C=(e,t)=>{let n={...e.env,...t};return Object.keys(n).length>0?n:void 0},w=(e,t)=>t??e.workdir,T=new TextEncoder,E=e=>e instanceof Error?e:Error(String(e)),D=e=>typeof e==`string`?e:`SIGKILL`,O=(e,t)=>{let n=e?.stdio?.[t];return n===`ignore`||n===`inherit`||n===`pipe`?n:n===void 0?`pipe`:`ignore`},k=()=>{let e=[],t=[],n=!1,r,i=()=>{for(;t.length>0&&e.length>0;)t.shift().resolve({done:!1,value:e.shift()});if(r){for(;t.length>0;)t.shift().reject(r);return}if(n)for(;t.length>0;)t.shift().resolve({done:!0,value:void 0})};return{iterable:{async*[Symbol.asyncIterator](){for(;;){if(e.length>0){yield e.shift();continue}if(r)throw E(r);if(n)return;let i=await new Promise((e,n)=>{t.push({resolve:e,reject:n})});if(i.done)return;yield i.value}}},push(t){t.length===0||n||r||(e.push(T.encode(t)),i())},end(){n||r||(n=!0,i())},fail(e){n||r||(r=e,i())}}},A=(e,t)=>({spawn:(n,r,i={})=>{let a=O(i,0),s=O(i,1),c=O(i,2),l=s===`pipe`?k():void 0,u=c===`pipe`?k():void 0,d=null,f={background:!0,stdin:a===`pipe`,cwd:w(t,i.cwd),envs:C(t,i.env),user:S(t),requestTimeoutMs:t.requestTimeoutMs,onStdout:e=>{if(s===`inherit`){process.stdout.write(e);return}l?.push(e)},onStderr:e=>{if(c===`inherit`){process.stderr.write(e);return}u?.push(e)}},p=e.commands.run(x(n,r),f),m=Promise.resolve(),h,g=e=>{let t=m.then(async()=>{await e((await p).pid)});return m=t.catch(e=>{h??=new o(e)}),t};return p.catch(e=>{l?.fail(e),u?.fail(e)}),{stdout:l?.iterable??null,stderr:u?.iterable??null,stdin:a===`pipe`?{write:n=>g(r=>e.commands.sendStdin(r,n,{requestTimeoutMs:t.requestTimeoutMs})),end:()=>g(n=>e.commands.closeStdin(n,{requestTimeoutMs:t.requestTimeoutMs}))}:null,kill:e=>{d=D(e),p.then(e=>e.kill()).catch(()=>{})},wait:async()=>{try{let e=await(await p).wait();if(await m,h)throw h;return l?.end(),u?.end(),d?{exitCode:null,signal:d}:{exitCode:e.exitCode,signal:null}}catch(e){if(l?.end(),u?.end(),e instanceof v)return d?{exitCode:null,signal:d}:{exitCode:e.exitCode,signal:null};throw e}}}}}),j=e=>({apiKey:e.apiKey,domain:e.domain,requestTimeoutMs:e.requestTimeoutMs,apiHeaders:e.headers}),M=e=>`sandboxId`in e&&typeof e.sandboxId==`string`,N=e=>{let t=j(e);return M(e)?t:{...t,envs:e.env,timeoutMs:e.timeoutMs,metadata:e.metadata,secure:e.secure,allowInternetAccess:e.allowInternetAccess,network:e.network,lifecycle:e.lifecycle}},P=async(e,t)=>{await e.files.makeDir(t.workdir,{user:S(t)})},F=e=>e instanceof Error&&e.name===`AbortError`,I=e=>Uint8Array.from(e).buffer,L=e=>{let t=e.endsWith(`/`)&&e!==`/`?e.slice(0,-1):e;return f.basename(t)},R=async e=>{try{return await g(e)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}},z=async(e,t,n)=>{if(await e.files.exists(t,{user:n}))return e.files.getInfo(t,{user:n})},B=async(e,t,n,r)=>(await z(e,n,r))?.type===y.DIR?f.join(n,l(t)):n,V=async(e,t)=>(await R(t))?.isDirectory()?d(t,L(e)):t,H=async(e,t,n,r)=>{let i=await g(t);if(i.isDirectory()){await e.files.makeDir(n,{user:r});let i=await h(t);await Promise.all(i.map(i=>H(e,d(t,i),f.join(n,i),r)));return}if(!i.isFile())throw Error(`Unsupported local filesystem entry at ${t}.`);let a=await m(t);await e.files.write(n,I(a),{user:r})},U=async(e,t,n,r)=>{if((await e.files.getInfo(t,{user:r})).type===y.DIR){await p(n,{recursive:!0});let i=await e.files.list(t,{user:r});await Promise.all(i.map(t=>U(e,t.path,d(n,t.name),r)));return}let i=await e.files.read(t,{format:`bytes`,user:r});await p(u(n),{recursive:!0}),await _(n,i)},W=async e=>{if(M(e))return b.connect(e.sandboxId,j(e));let t=N(e);return e.template?b.create(e.template,t):b.create(t)},G=async(e,t)=>e.connect(j(t)),K=async(e,t)=>{let n=t.signal;if(n?.aborted){let e=n.reason;throw e instanceof Error?e:new DOMException(`The operation was aborted.`,`AbortError`)}let r=!1,i=()=>{r=!0,e.kill()};n?.addEventListener(`abort`,i,{once:!0});try{let t=await e.wait();if(r)throw new DOMException(`The operation was aborted.`,`AbortError`);return{exitCode:t.exitCode,stdout:t.stdout,stderr:t.stderr}}catch(e){if(r||F(e))throw new DOMException(`The operation was aborted.`,`AbortError`);if(e instanceof v)return{exitCode:e.exitCode,stdout:e.stdout,stderr:e.stderr};throw e}finally{n?.removeEventListener(`abort`,i)}},q=async o=>{let s;try{s=await W(o),await P(s,o)}catch(t){throw new r(`E2B create failed: ${e(t)}`)}let l=o.name??s.sandboxId,u=`running`,f=A(s,o),m={},h=()=>{if(u===`disposed`)throw new n},g=()=>{if(h(),u!==`running`)throw new a},_=c({owner:m,workdir:o.workdir,materialize:async(e,t)=>{g();let n=S(o),r=await z(s,e,n);if(!r)throw new i(`Target path does not exist: ${e}`);if(r.type!==y.DIR)throw new i(`Target path is not a directory: ${e}`);await p(t,{recursive:!0});for(let r of await s.files.list(e,{user:n}))await U(s,r.path,d(t,r.name),n)}}),v={get type(){return`e2b`},get id(){return s.sandboxId},get name(){return l},get config(){return o},get status(){return u},get workdir(){return o.workdir},get spawner(){return f},async start(){if(h(),u!==`running`)try{s=await G(s,o),await P(s,o),f=A(s,o),u=`running`}catch(n){throw new t(`E2B start failed: ${e(n)}`)}},async stop(){h(),u===`running`&&(await s.pause({requestTimeoutMs:o.requestTimeoutMs}),u=`stopped`)},async dispose(){if(u!==`disposed`){try{await s.kill({requestTimeoutMs:o.requestTimeoutMs})}catch{}await _.disposeSnapshots().catch(()=>{}),u=`disposed`}},async exec(e,t,n={}){g();let r={background:!0,cwd:w(o,n.cwd),envs:C(o,n.env),user:S(o),timeoutMs:n.timeoutMs,requestTimeoutMs:o.requestTimeoutMs},i=await s.commands.run(x(e,t),r);return K(i,n)},async copyTo(e,t){g();let n=await B(s,e,t,S(o));await H(s,e,n,S(o))},async copyFrom(e,t){g();let n=await V(e,t);await U(s,e,n,S(o))},async writeFile(e,t){g(),await s.files.write(e,typeof t==`string`?t:I(t),{user:S(o)})},async readFile(e){return g(),s.files.read(e,{format:`text`,user:S(o)})},async fileExists(e){return g(),s.files.exists(e,{user:S(o)})},async mkdir(e){g(),await s.files.makeDir(e,{user:S(o)})},async execShell(e,t={}){return v.exec(`sh`,[`-c`,e],t)},async logs(){return``},async syncStatus(){return u},async snapshotWorkdir(e={}){return _.snapshotWorkdir(e)},async diffWorkdir(e){return _.diffWorkdir(e)},async releaseWorkdirSnapshot(e){return _.releaseWorkdirSnapshot(e)},getHost(e){return g(),s.getHost(e)},[Symbol.asyncDispose](){return v.dispose()}};return v};export{q as createE2BContainer};
|
package/dist/diff-Dqyk2cdt.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./util-B4HTdOSc.mjs";import{i as t,r as n,s as r}from"./container-DMFxf-kn.mjs";import{n as i}from"./errors-aYGbvsaq.mjs";import{execFile as a}from"node:child_process";import{dirname as o,isAbsolute as s,join as c,posix as l,relative as u,sep as d}from"node:path";import{promisify as f}from"node:util";import{createReadStream as p}from"node:fs";import{tmpdir as m}from"node:os";import{copyFile as h,lstat as g,mkdir as _,mkdtemp as v,readdir as y,readlink as b,rm as x,stat as S,symlink as C}from"node:fs/promises";import{createHash as w}from"node:crypto";import{pipeline as T}from"node:stream/promises";const E=f(a),D=e=>e!==`..`&&!e.startsWith(`..${d}`)&&!s(e),O=(e,t)=>{let n=u(e,t);if(D(n))return n.split(d).join(l.sep)},k=(e,t,r)=>{let i=O(t,e);if(i!==void 0)return i;let a=O(r,e);if(a!==void 0)return a;throw new n(`Git diff produced a path outside the materialized trees: ${e}`)},A=e=>e.sort((e,t)=>e.path===t.path?(e.previousPath??``).localeCompare(t.previousPath??``):e.path.localeCompare(t.path)),j=async e=>{let t=await y(e,{withFileTypes:!0});for(let n of t){let t=c(e,n.name);if(n.name===`.git`){await x(t,{recursive:!0,force:!0});continue}n.isDirectory()&&await j(t)}},M=()=>v(c(m(),`cw-workdir-diff-`)),N=async e=>{e&&await x(e,{recursive:!0,force:!0}).catch(()=>{})},P=(e,t)=>{let n={cwd:e.cwd,createdAt:/* @__PURE__ */ new Date};return t.set(n,e),n},F=(e,t,r)=>{if(typeof t!=`object`||!t)throw new n(`Invalid workdir snapshot.`);let i=r.get(t);if(!i)throw new n(`Invalid workdir snapshot.`);if(i.owner!==e)throw new n(`Workdir snapshot was created by a different container instance.`);return i},I=(e,t)=>{if(!t.has(e))throw new n(`Workdir snapshot has been released.`)},L=e=>w(`sha256`).update(e).digest(`hex`),R=e=>Buffer.isBuffer(e)?e:Buffer.from(e,`utf8`),z=async e=>{let t=w(`sha256`);return await T(p(e),t),t.digest(`hex`)},B=async(e,t,r)=>{let i=`${e}:${t}`;if(r.has(i))return r.get(i);let a=c(e,...t.split(l.sep));try{let e=await g(a),t,o;if(e.isSymbolicLink()){let e=Buffer.from(await b(a));t=L(e),o=e.byteLength}else if(e.isFile())t=await z(a),o=e.size;else throw new n(`Unsupported filesystem entry in diff metadata: ${a}`);let s={hash:t,size:o};return r.set(i,s),s}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`){r.set(i,void 0);return}throw e}},V=(e,t,r)=>{if(e.byteLength===0)return[];let i=e.toString(`utf8`).split(`\0`);i[i.length-1]===``&&i.pop();let a=[];for(let e=0;e<i.length;){let o=i[e++];if(!o)continue;if(o.startsWith(`R`)){let o=i[e++],s=i[e++];if(!o||!s)throw new n(`Failed to parse git rename entry.`);a.push({kind:`renamed`,previousPath:k(o,t,r),path:k(s,t,r)});continue}let s=i[e++];if(!s)throw new n(`Failed to parse git diff entry.`);switch(o){case`A`:a.push({kind:`added`,path:k(s,t,r)});break;case`D`:a.push({kind:`deleted`,path:k(s,t,r)});break;case`M`:a.push({kind:`modified`,path:k(s,t,r)});break;case`T`:a.push({kind:`modified`,path:k(s,t,r)});break;default:throw new n(`Unsupported git diff change kind: ${o}`)}}return a},H=async(t,r)=>{try{let e=await E(`git`,[`diff`,`--no-index`,`-z`,`--name-status`,`-M`,`--find-renames=100%`,t,r],{cwd:m(),encoding:`buffer`,maxBuffer:52428800});return V(R(e.stdout),t,r)}catch(a){if(!i(a))throw new n(`Failed to run git diff: ${e(a)}`);let o=a.code??1,s=Buffer.isBuffer(a.stdout)?a.stdout:Buffer.from(String(a.stdout??``),`utf8`),c=Buffer.isBuffer(a.stderr)?a.stderr:Buffer.from(String(a.stderr??``),`utf8`);if(o===0||o===1)return V(s,t,r);let l=c.toString(`utf8`).trim()||s.toString(`utf8`).trim()||`exit code ${o}`;throw new n(`Failed to run git diff: ${l}`)}},U=async(e,t,n)=>{let r=/* @__PURE__ */ new Map,i=await Promise.all(e.map(async e=>{let i;i=e.kind===`added`?void 0:e.kind===`renamed`?e.previousPath:e.path;let a=e.kind===`deleted`?void 0:e.path,[o,s]=await Promise.all([i===void 0?void 0:B(t,i,r),a===void 0?void 0:B(n,a,r)]);return{path:e.path,previousPath:e.previousPath,kind:e.kind,beforeHash:o?.hash,afterHash:s?.hash,beforeSize:o?.size,afterSize:s?.size}}));return A(i)},W=e=>{let t=/* @__PURE__ */ new Set;for(let n of e)t.add(n.path),n.kind===`renamed`&&n.previousPath&&t.add(n.previousPath);return[...t].sort((e,t)=>e.localeCompare(t))},G=(i,a)=>{throw a instanceof n||a instanceof t||a instanceof r?a:new n(`${i}: ${e(a)}`)},K=async(e,t)=>{if(!(await S(e)).isDirectory())throw new n(`Target path is not a directory: ${e}`);await _(t,{recursive:!0});let r=await y(e,{withFileTypes:!0});await Promise.all(r.filter(e=>e.name!==`.git`).map(async r=>{let i=c(e,r.name),a=c(t,r.name);if(r.isDirectory()){await K(i,a);return}if(r.isSymbolicLink()){await _(o(a),{recursive:!0}),await C(await b(i),a);return}if(r.isFile()){await _(o(a),{recursive:!0}),await h(i,a);return}throw new n(`Unsupported filesystem entry in workdir diff: ${i}`)}))},q=e=>{let t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new WeakMap,r=async(r={})=>{let i=r.cwd??e.workdir,a;try{a=await M(),await e.materialize(i,a),await j(a);let r={owner:e.owner,tempDir:a,cwd:i,inFlightDiffs:0,released:!1};return t.add(r),a=void 0,P(r,n)}catch(e){return await N(a),G(`Failed to materialize workdir snapshot`,e)}},i=async r=>{let i=Date.now(),a=F(e.owner,r,n);I(a,t),a.inFlightDiffs++;let o;try{o=await M(),await e.materialize(a.cwd,o),await j(o);let t=await H(a.tempDir,o),n=await U(t,a.tempDir,o),r=W(n);return{cwd:a.cwd,changedFiles:r,fileChanges:n,stats:{durationMs:Date.now()-i,filesCompared:r.length}}}catch(e){return G(`Failed to diff workdir snapshot`,e)}finally{a.inFlightDiffs--,a.inFlightDiffs===0&&(a.resolveIdle?.(),a.resolveIdle=void 0),await N(o)}},a=e=>{let n=e;return n.releasePromise?n.releasePromise:(n.released=!0,t.delete(n),n.releasePromise=(async()=>{n.inFlightDiffs>0&&await new Promise(e=>{n.resolveIdle=e}),await N(n.tempDir)})(),n.releasePromise)};return{snapshotWorkdir:r,diffWorkdir:i,releaseWorkdirSnapshot:async t=>{let r=F(e.owner,t,n);await a(r)},disposeSnapshots:async()=>{await Promise.all(Array.from(t).map(a))}}};export{q as n,K as t};
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import { a as SpawnOptions, t as AgentProcess } from "./types-COmjfh8B.mjs";
|
|
2
|
-
//#region src/core/process/spawner.d.ts
|
|
3
|
-
declare const spawnProcess: (command: string, args: string[], options?: SpawnOptions) => AgentProcess;
|
|
4
|
-
//#endregion
|
|
5
|
-
//#region src/core/process/errors.d.ts
|
|
6
|
-
declare class ProcessStdinError extends Error {
|
|
7
|
-
constructor(cause: unknown);
|
|
8
|
-
}
|
|
9
|
-
//#endregion
|
|
10
|
-
export { spawnProcess as n, ProcessStdinError as t };
|
package/dist/oci-DTNwW-WH.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./util-B4HTdOSc.mjs";import{c as t,i as n,l as r,n as i,o as a,r as o,s}from"./container-DMFxf-kn.mjs";import{n as c}from"./env-Cb8MIvH7.mjs";import{n as l}from"./errors-aYGbvsaq.mjs";import{t as u}from"./spawner-CgfyvnR4.mjs";import{t as d}from"./shell-DvWFuFKb.mjs";import{n as f,t as p}from"./diff-Dqyk2cdt.mjs";import{execFile as m}from"node:child_process";import{isAbsolute as h,join as g,posix as _,resolve as v}from"node:path";import{promisify as y}from"node:util";import{existsSync as b}from"node:fs";import{tmpdir as x}from"node:os";import{mkdtemp as S,rm as C,writeFile as w}from"node:fs/promises";import{randomBytes as T}from"node:crypto";const E=(e,t)=>{let n=_.relative(e,t);return n===``||!n.startsWith(`..`)&&!_.isAbsolute(n)},D=(e,t)=>{if(!e||e.length===0)return;let n=_.normalize(t),r;for(let t of e){if(!h(t.source))continue;let e=_.normalize(t.target);E(e,n)&&(!r||e.length>_.normalize(r.target).length)&&(r=t)}if(!r)return;let i=_.relative(_.normalize(r.target),n);return i===``?r.source:_.join(r.source,...i.split(`/`))},O=(e,t)=>{let n=h(e.source)?e.source:v(t.cwd,e.source);if(!b(n))throw new r(`Mount source does not exist: ${n}`);return{...e,source:n}},k=y(m),A=()=>`cw-${T(6).toString(`hex`)}`,j=(e,t)=>e.baseArgs?[...e.baseArgs,...t]:t,M=e=>{if(e.env)return{...c(),...e.env}},N=async(e,t,n)=>{let r=await k(e.binary,j(e,t),{encoding:`utf8`,env:M(e),timeout:n?.timeoutMs,signal:n?.signal,maxBuffer:52428800});return{stdout:r.stdout,stderr:r.stderr}},P=async(t,n)=>{let r=n.tag??`cw-build-${T(4).toString(`hex`)}`,a=[`build`,`-t`,r];if(n.args)for(let[e,t]of Object.entries(n.args))a.push(`--build-arg`,`${e}=${t}`);`dockerfile`in n&&n.dockerfile&&(a.push(`-f`,n.dockerfile),a.push(n.context??`.`));let o;if(`content`in n&&n.content){o=await S(g(x(),`cw-oci-build-`));let e=g(o,`Dockerfile`);await w(e,n.content,{encoding:`utf8`,mode:384}),a.push(`-f`,e),a.push(n.context??o)}try{await N(t,a)}catch(t){throw new i(`Image build failed: ${e(t)}`)}finally{o&&await C(o,{recursive:!0,force:!0}).catch(()=>{})}return r},F=async(e,t,n)=>{let r=await Promise.all(n.map(async n=>{try{let{container:r,protocol:i=`tcp`}=n,{stdout:a}=await N(e,[`port`,t,`${r}/${i}`]),o=/:(\d+)$/m.exec(a.trim());if(o?.[1])return[r,Number(o[1])]}catch{}})),i=/* @__PURE__ */ new Map;for(let e of r)e&&i.set(e[0],e[1]);return i},I=(e,t)=>({spawn:(n,r,i={})=>{let a=[`exec`,`-i`];if(i.cwd&&a.push(`-w`,i.cwd),i.env)for(let[e,t]of Object.entries(i.env))a.push(`-e`,`${e}=${t}`);return a.push(e,n,...r),u.spawn(t.binary,j(t,a),{env:M(t),stdio:i.stdio})}}),L=async(r,c,m)=>{let{commandContext:h,builtImage:g,containerName:v,workdir:y,user:b,network:x,platform:S,env:C,ports:w,mounts:T,mountCwd:E,extraArgs:k,image:P}=c,L=v??A(),R=T?.map(e=>O(e,{cwd:E??process.cwd()})),z=[`create`,`--name`,L];if(b&&z.push(`--user`,b),x&&z.push(`--network`,x),S&&z.push(`--platform`,S),C)for(let[e,t]of Object.entries(C))z.push(`-e`,`${e}=${t}`);if(w)for(let e of w){let{host:t,container:n,protocol:r=`tcp`}=e;z.push(`-p`,`${t??``}:${n}/${r}`)}if(R)for(let e of R){let{readonly:t,source:n,target:r}=e,i=t?`ro`:`rw`;z.push(`-v`,`${n}:${r}:${i}`)}k&&z.push(...k),z.push(P,`sleep`,`infinity`);let B;try{let{stdout:e}=await N(h,z);B=e.trim()}catch(t){throw new i(`Container create failed: ${e(t)}`)}let V=`created`,H=/* @__PURE__ */ new Map,U=()=>{if(V===`disposed`)throw new n},W=()=>{if(U(),V!==`running`)throw new s},G=I(B,h),K=f({owner:{},workdir:y,materialize:async(t,n)=>{U();let r=D(R,t);if(r){await p(r,n);return}W();try{await N(h,[`exec`,B,`sh`,`-c`,`test -d ${d(t)}`])}catch{throw new o(`Target path is not a directory: ${t}`)}try{await N(h,[`cp`,`${B}:${t}/.`,n])}catch(n){throw new o(`Failed to materialize container path ${t}: ${e(n)}`)}}}),q={get type(){return r},get id(){return B},get name(){return L},get config(){return m},get status(){return V},get workdir(){return y},get spawner(){return G},async start(){if(U(),V!==`running`){try{await N(h,[`start`,B])}catch(n){throw new t(`Container start failed: ${e(n)}`)}try{await N(h,[`exec`,B,`mkdir`,`-p`,y])}catch(n){try{await N(h,[`stop`,`-t`,`0`,B]),V=`stopped`}catch{try{let{stdout:e}=await N(h,[`inspect`,`--format`,`{{.State.Status}}`,B]);V=e.trim()===`running`?`running`:`stopped`}catch{V=`disposed`}}throw new t(`Container start failed: ${e(n)}`)}V=`running`,w?.length&&(H=await F(h,B,w))}},async stop(){if(U(),V===`running`){try{await N(h,[`stop`,`-t`,`2`,B])}catch{try{let{stdout:e}=await N(h,[`inspect`,`--format`,`{{.State.Status}}`,B]);if(e.trim()===`running`)return}catch{V=`disposed`;return}}V=`stopped`}},async dispose(){if(V!==`disposed`){try{await N(h,[`stop`,`-t`,`0`,B])}catch{}try{await N(h,[`rm`,`-f`,B])}catch{}g&&await N(h,[`rmi`,P]).catch(()=>{}),await K.disposeSnapshots().catch(()=>{}),V=`disposed`}},async exec(e,t,n={}){W();let r=[`exec`];if(n.cwd&&r.push(`-w`,n.cwd),n.env)for(let[e,t]of Object.entries(n.env))r.push(`-e`,`${e}=${t}`);r.push(B,e,...t);try{let{stdout:e,stderr:t}=await N(h,r,{timeoutMs:n.timeoutMs,signal:n.signal});return{exitCode:0,stdout:e,stderr:t}}catch(e){if(l(e))return{exitCode:typeof e.code==`number`?e.code:-1,stdout:String(e.stdout??``),stderr:String(e.stderr??``)};throw e}},async copyTo(e,t){W(),await N(h,[`cp`,e,`${B}:${t}`])},async copyFrom(e,t){W(),await N(h,[`cp`,`${B}:${e}`,t])},async writeFile(t,n){W();let r=_.isAbsolute(t)?t:_.resolve(y,t),i=_.dirname(r),o=typeof n==`string`?Buffer.from(n,`utf8`):n,s=[`exec`,`-i`];b&&s.push(`--user`,b),s.push(B,`sh`,`-c`,`mkdir -p ${d(i)} && cat > ${d(r)}`);let c=u.spawn(h.binary,j(h,s),{env:M(h),stdio:[`pipe`,`ignore`,`ignore`]}),l;try{c.stdin?.write?.(o),c.stdin?.end(),l=await c.wait()}catch(t){throw c.kill(),c.wait().catch(()=>{}),new a(`writeFile failed for ${r}: ${e(t)}`)}if(l.exitCode!==0)throw new a(`writeFile failed for ${r} (exit ${l.exitCode})`)},async readFile(e){W();let t=_.isAbsolute(e)?e:_.resolve(y,e),{stdout:n}=await N(h,[`exec`,B,`cat`,t]);return n},async fileExists(e){W();let t=_.isAbsolute(e)?e:_.resolve(y,e);try{return await N(h,[`exec`,B,`test`,`-e`,t]),!0}catch{return!1}},async mkdir(e){W();let t=_.isAbsolute(e)?e:_.resolve(y,e);await N(h,[`exec`,B,`mkdir`,`-p`,t])},async execShell(e,t={}){return q.exec(`sh`,[`-c`,e],t)},async logs(e={}){U();let t=[`logs`];e.tail!==void 0&&t.push(`--tail`,String(e.tail)),t.push(B);let{stdout:n}=await N(h,t);return n},async syncStatus(){U();try{let{stdout:e}=await N(h,[`inspect`,`--format`,`{{.State.Status}}`,B]),t=e.trim();V=t===`running`?`running`:t===`created`?`created`:`stopped`}catch{V=`disposed`}return V},async snapshotWorkdir(e={}){return K.snapshotWorkdir(e)},async diffWorkdir(e){return K.diffWorkdir(e)},async releaseWorkdirSnapshot(e){return K.releaseWorkdirSnapshot(e)},getMappedPort(e){return H.get(e)},[Symbol.asyncDispose](){return q.dispose()}};return q},R=async(e,t)=>{if(t.image)return t.image;if(t.build)return P(e,t.build);throw new i(`Either image or build must be provided.`)};export{R as n,L as t};
|
package/dist/parser-jSS5vOTN.mjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{c as e,s as t,u as n}from"./classify-error-DK2WpxiL.mjs";import{i as r,r as i}from"./session-markers-BHsJLWJk.mjs";import{z as a}from"zod/v4";const o=e=>`session_id`in e?e.session_id:void 0,s=e=>typeof e.content==`string`?e.content:e.content.map(e=>e.text).join(`
|
|
2
|
-
`),c=e=>typeof e.result==`string`&&e.result.trim()!==``?e.result:e.subtype,l=(e,r)=>{if(e.subtype===`session_state_changed`)return{events:[]};let i=[`[${e.subtype}]`];if(e.subtype===`init`){if(e.tools&&i.push(`tools: ${e.tools.length}`),e.mcp_servers){let t=e.mcp_servers.filter(e=>e.status===`connected`).length;i.push(`mcp: ${t}/${e.mcp_servers.length} connected`)}}else e.hook_name&&(i.push(e.hook_name),e.exit_code!==void 0&&i.push(`exit: ${e.exit_code}`));let a=i.join(` `);return{events:[t(r.runId,`message`,{sessionId:r.sessionId,model:e.model??null,role:`system`,content:[n(a)],text:a})]}},u=(e,r)=>{let i=[],a=[];for(let o of e.message.content)switch(o.type){case`text`:i.push(t(r.runId,`message`,{sessionId:r.sessionId,model:e.message.model??null,role:`assistant`,content:[n(o.text)],text:o.text}));break;case`thinking`:i.push(t(r.runId,`reasoning`,{sessionId:r.sessionId,model:e.message.model??null,content:[n(o.thinking)],text:o.thinking}));break;case`tool_use`:a.push({toolCallId:o.id,toolName:o.name,input:o.input}),i.push(t(r.runId,`tool-call`,{sessionId:r.sessionId,model:e.message.model??null,toolCallId:o.id,toolName:o.name,input:o.input}))}return{events:i,toolCalls:a}},d=(e,r)=>{let i=[];for(let a of e.message.content)switch(a.type){case`text`:i.push(t(r.runId,`message`,{sessionId:r.sessionId,model:null,role:`user`,content:[n(a.text)],text:a.text}));break;case`tool_result`:{let e=r.toolCalls.get(a.tool_use_id),n=s(a);i.push(t(r.runId,`tool-result`,{sessionId:r.sessionId,toolCallId:a.tool_use_id,toolName:e?.toolName,input:e?.input,output:n,isError:a.is_error,error:a.is_error?n:void 0}));break}}return{events:i}},f=(e,t,n)=>{let a={stats:(n??new i(t)).addResult(e)};typeof e.result==`string`&&(a.output={...a.output,text:e.result});let o=!e.is_error&&e.subtype===`success`,s=r(e.structured_output,{schemaRequested:t.schemaRequested,toolCalls:t.toolCalls,allowToolCallFallback:!1},{isSuccess:o},`Structured output was requested but Claude did not return structured_output.`);return s.value!==void 0&&(a.output={...a.output,value:s.value}),s.error&&(a.status=`failed`,a.error=s.error),e.is_error||e.subtype!==`success`?(a.status=`failed`,a.error={kind:`provider`,message:c(e)}):a.error||=(a.status=`completed`,void 0),{events:[],state:a}},p=(e,r)=>{let i=`rate limited: ${e.rate_limit_info.status}`;return{events:[t(r.runId,`message`,{sessionId:r.sessionId,model:null,role:`system`,content:[n(i)],text:i})]}},m=(e,t,n={})=>{switch(e.type){case`system`:return l(e,t);case`assistant`:return u(e,t);case`user`:return d(e,t);case`result`:return f(e,t,n.statsAccumulator);case`rate_limit_event`:return p(e,t);default:return{events:[]}}},h=a.enum([`init`,`hook_response`,`hook_started`,`hook_finished`,`hook_failed`,`hook_skipped`,`session_state_changed`]),g=a.enum([`idle`,`running`,`requires_action`]),_=a.object({name:a.string(),status:a.string()}),v=a.object({type:a.literal(`system`),session_id:a.string(),subtype:h,uuid:a.string(),tools:a.array(a.string()).optional(),mcp_servers:a.array(_.extend({status:a.enum([`connected`,`disconnected`,`error`,`failed`])})).optional(),model:a.string().optional(),cwd:a.string().optional(),hook_name:a.string().optional(),hook_event:a.string().optional(),stdout:a.string().optional(),stderr:a.string().optional(),exit_code:a.number().optional(),state:g.optional()}),y=a.object({type:a.literal(`assistant`),session_id:a.string(),uuid:a.string(),parent_tool_use_id:a.string().nullable().optional(),message:a.object({id:a.string(),type:a.literal(`message`),role:a.literal(`assistant`),model:a.string(),content:a.array(a.union([a.object({type:a.literal(`text`),text:a.string()}),a.object({type:a.literal(`tool_use`),id:a.string(),name:a.string(),input:a.record(a.string(),a.unknown())}),a.object({type:a.literal(`thinking`),thinking:a.string(),signature:a.string().optional()})])),stop_reason:a.enum([`end_turn`,`max_tokens`,`tool_use`,`stop_sequence`]).nullable(),stop_sequence:a.string().nullable().optional(),context_management:a.unknown().nullable().optional(),usage:a.object({input_tokens:a.number(),output_tokens:a.number(),cache_creation_input_tokens:a.number().optional(),cache_read_input_tokens:a.number().optional(),service_tier:a.enum([`premium`,`standard`]).nullable().optional()}),ttftMs:a.number().optional()})}),b=a.object({type:a.literal(`user`),session_id:a.string(),message:a.object({role:a.literal(`user`),content:a.array(a.union([a.object({type:a.literal(`tool_result`),tool_use_id:a.string(),content:a.union([a.string(),a.array(a.object({type:a.literal(`text`),text:a.string()}))]),is_error:a.boolean().optional()}),a.object({type:a.literal(`text`),text:a.string()})]))}),parent_tool_use_id:a.string().nullable().optional(),uuid:a.string(),isSynthetic:a.boolean().optional()}),x=a.object({type:a.literal(`result`),session_id:a.string(),uuid:a.string(),subtype:a.enum([`success`,`error_max_turns`,`error_during_execution`,`error_max_budget_usd`,`error_max_structured_output_retries`]),duration_ms:a.number(),duration_api_ms:a.number(),is_error:a.boolean(),num_turns:a.number(),result:a.unknown().optional(),structured_output:a.unknown().optional(),total_cost_usd:a.number(),usage:a.object({input_tokens:a.number(),cache_creation_input_tokens:a.number().optional(),cache_read_input_tokens:a.number().optional(),output_tokens:a.number(),server_tool_use:a.object({web_search_requests:a.number()}).optional()}).optional(),modelUsage:a.record(a.string(),a.object({inputTokens:a.number(),outputTokens:a.number(),cacheReadInputTokens:a.number(),cacheCreationInputTokens:a.number()})).optional()}),S=a.discriminatedUnion(`type`,[x.pick({type:!0}),a.object({type:a.literal(`system`),subtype:a.literal(`session_state_changed`),state:g})]),C=a.object({type:a.literal(`rate_limit_event`),uuid:a.string(),session_id:a.string().optional(),rate_limit_info:a.object({status:a.string(),resetsAt:a.number().optional(),rateLimitType:a.string().optional(),overageStatus:a.string().optional(),overageDisabledReason:a.string().optional(),isUsingOverage:a.boolean().optional()})}),w=a.discriminatedUnion(`type`,[v,y,b,x,C]),T=a.discriminatedUnion(`type`,[v.extend({uuid:a.string().optional(),mcp_servers:a.array(_).optional()}),y.extend({uuid:a.string().optional()}),b.extend({uuid:a.string().optional()}),x.extend({uuid:a.string().optional(),subtype:a.string()}),C]),E=a.object({subtype:a.literal(`can_use_tool`),tool_name:a.string(),input:a.record(a.string(),a.unknown()),tool_use_id:a.string(),decision_reason:a.string().optional(),blocked_path:a.string().optional(),title:a.string().optional(),description:a.string().optional()}),D=a.discriminatedUnion(`type`,[a.object({type:a.literal(`control_request`),request_id:a.string(),request:a.looseObject({subtype:a.string()})}),a.looseObject({type:a.literal(`control_response`)}),a.looseObject({type:a.literal(`control_cancel_request`),request_id:a.string()})]),O=e(w);export{S as a,T as i,E as n,o,D as r,m as s,O as t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{z as e}from"zod/v4";const t=e.object({type:e.literal(`text`),text:e.string()}),n=e.object({type:e.literal(`image`),path:e.string(),mediaType:e.string().optional()}),r=e.discriminatedUnion(`type`,[t,n]),i=e.object({structuredOutput:e.boolean(),sessionResume:e.boolean(),imageInput:e.boolean(),mcp:e.boolean(),eventStreaming:e.boolean(),sessionFork:e.boolean().optional(),permissionRequests:e.boolean().optional()}),a=e.object({id:e.string(),runId:e.string(),timestamp:e.date()}),o=a.extend({type:e.literal(`session-start`),requestedSessionId:e.string().optional(),sessionId:e.string().optional(),resumed:e.boolean()}),s=a.extend({type:e.literal(`message`),sessionId:e.string().optional(),model:e.string().nullable(),role:e.enum([`system`,`user`,`assistant`]),content:e.array(r),text:e.string().optional()}),c=a.extend({type:e.literal(`reasoning`),sessionId:e.string().optional(),model:e.string().nullable(),content:e.array(r),text:e.string().optional()}),l=a.extend({type:e.literal(`tool-call`),sessionId:e.string().optional(),model:e.string().nullable(),toolCallId:e.string(),toolName:e.string(),input:e.unknown().optional()}),u=a.extend({type:e.literal(`tool-result`),sessionId:e.string().optional(),toolCallId:e.string(),toolName:e.string().optional(),input:e.unknown().optional(),output:e.unknown(),isError:e.boolean().optional(),error:e.string().optional()}),d=a.extend({type:e.literal(`stderr`),sessionId:e.string().optional(),text:e.string()}),f=a.extend({type:e.literal(`session-end`),sessionId:e.string().optional(),status:e.enum([`completed`,`failed`,`cancelled`]),error:e.string().optional()}),p=e.discriminatedUnion(`type`,[o,s,c,l,u,d,f]);export{f as a,l as c,r as d,n as f,c as i,u as l,p as n,o,t as p,s as r,d as s,a as t,i as u};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{i as e}from"./util-B4HTdOSc.mjs";const t=`SendUserMessage`,n=e=>e?.includes(t)?[...e]:[...e??[],t],r=e=>{let t;for(let[,n]of e)n.toolName===`StructuredOutput`&&n.input!==void 0&&(t=n.input);return t},i=(e,t,n,i)=>{if(e!=null)return{value:e};if(!t.schemaRequested)return{};if(t.allowToolCallFallback??!0){let e=r(t.toolCalls);if(e!==void 0)return{value:e}}return n.isSuccess?{error:{kind:`parse`,message:i}}:{}},a=e=>{let t=Object.values(e??{});if(t.length!==0)return{inputTokens:t.reduce((e,t)=>e+t.inputTokens,0),cacheCreationInputTokens:t.reduce((e,t)=>e+t.cacheCreationInputTokens,0),cacheReadInputTokens:t.reduce((e,t)=>e+t.cacheReadInputTokens,0),outputTokens:t.reduce((e,t)=>e+t.outputTokens,0)}},o=(e,t)=>e>=t?e-t:e,s=(e,t)=>({inputTokens:o(e.inputTokens,t?.inputTokens??0),cacheCreationInputTokens:o(e.cacheCreationInputTokens,t?.cacheCreationInputTokens??0),cacheReadInputTokens:o(e.cacheReadInputTokens,t?.cacheReadInputTokens??0),outputTokens:o(e.outputTokens,t?.outputTokens??0)});var c=class{canUseModelUsage;restoredTotals;latestResult;durationMs=0;turns=0;inputTokens;cacheCreationInputTokens;cacheReadInputTokens;outputTokens;constructor({requestedSessionId:e,recordedSessionTotals:t,mayResumeUntrackedSession:n=!1}){let r=!n&&e===void 0,i=!n&&e!==void 0&&t?.sessionId===e;this.restoredTotals=i?t:void 0,this.canUseModelUsage=r||i}get sessionTotals(){if(!this.latestResult)return;let e={sessionId:this.latestResult.session_id,apiDurationMs:this.latestResult.duration_api_ms,costUsd:this.latestResult.total_cost_usd,modelUsage:this.latestResult.modelUsage},t=this.restoredTotals;return t!==void 0&&(e.costUsd<t.costUsd||e.apiDurationMs<t.apiDurationMs)?t:e}addResult(t){this.latestResult=t,this.durationMs+=t.duration_ms,this.turns+=t.num_turns,this.inputTokens=e(this.inputTokens,t.usage?.input_tokens),this.cacheCreationInputTokens=e(this.cacheCreationInputTokens,t.usage?.cache_creation_input_tokens),this.cacheReadInputTokens=e(this.cacheReadInputTokens,t.usage?.cache_read_input_tokens),this.outputTokens=e(this.outputTokens,t.usage?.output_tokens);let n={inputTokens:this.inputTokens,cacheCreationInputTokens:this.cacheCreationInputTokens,cacheReadInputTokens:this.cacheReadInputTokens,outputTokens:this.outputTokens},r=this.canUseModelUsage?a(t.modelUsage):void 0,i=a(this.restoredTotals?.modelUsage),c=r?s(r,i):n;return{durationMs:this.durationMs,apiDurationMs:o(t.duration_api_ms,this.restoredTotals?.apiDurationMs??0),turns:this.turns,...c,totalTokens:e(c.inputTokens,c.cacheCreationInputTokens,c.cacheReadInputTokens,c.outputTokens),costUsd:o(t.total_cost_usd,this.restoredTotals?.costUsd??0)}}};const l=e=>{let t={...e};return delete t.$schema,t},u=[`CLAUDECODE`,`CLAUDE_CODE_CHILD_SESSION`],d=e=>{for(let t of u)delete e[t]};export{n as a,i,l as n,c as r,d as t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./errors-aYGbvsaq.mjs";import{spawn as t}from"node:child_process";const n=e=>({async*[Symbol.asyncIterator](){for await(let t of e){if(t instanceof Buffer){yield new Uint8Array(t);continue}if(typeof t==`string`){yield new TextEncoder().encode(t);continue}if(t instanceof Uint8Array){yield t;continue}throw Error(`Unsupported stdout/stderr chunk type: ${typeof t}`)}}}),r=(r,i,a={})=>{let o=t(r,i,{cwd:a.cwd,env:a.env,stdio:a.stdio,detached:!0}),s,c=t=>{s??=new e(t)};o.stdin?.on(`error`,c);let l=new Promise((e,t)=>{let n=(n,i)=>{if(o.removeListener(`error`,r),s){t(s);return}e({exitCode:n,signal:i})},r=e=>{o.removeListener(`close`,n),t(e)};o.once(`error`,r),o.once(`close`,n)}),u=o.stdin;return{stdout:o.stdout?n(o.stdout):null,stderr:o.stderr?n(o.stderr):null,stdin:u?{write:e=>{let t=new Promise((t,n)=>{u.write(e,e=>{if(e){n(e);return}t()})});return t.catch(c),t},end:()=>{let e=new Promise((e,t)=>{u.end(n=>{if(n){t(n);return}e()})});return e.catch(c),e}}:null,kill:e=>{if(o.pid===void 0){o.kill(e);return}try{process.kill(-o.pid,e??`SIGTERM`)}catch{o.kill(e)}},wait:()=>l}},i={spawn:r};export{r as n,i as t};
|
package/dist/util-B4HTdOSc.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const e=e=>Array.isArray(e)?e:[e],t=e=>e instanceof Error?e.message:String(e),n=e=>typeof e==`object`&&!!e,r=(...e)=>{if(!e.every(e=>e===void 0))return e.reduce((e,t)=>e+(t??0),0)},i=e=>{let t=e.trim();return t.startsWith("```")?t.replace(/^```[\w-]*\s*/i,``).replace(/\s*```$/i,``).trim():t},a=e=>/```[\w-]*\s*([\S\s]*?)\s*```/i.exec(e)?.[1]?.trim(),o=e=>{let t=-1,n=[],r=!1,i=!1;for(let a=0;a<e.length;a++){let o=e[a];if(o){if(t===-1){(o===`{`||o===`[`)&&(t=a,n.push(o));continue}if(r){if(i){i=!1;continue}if(o===`\\`){i=!0;continue}o===`"`&&(r=!1);continue}if(o===`"`){r=!0;continue}if(o===`{`||o===`[`){n.push(o);continue}if(o===`}`||o===`]`){let r=n.pop();if(r===`{`&&o!==`}`||r===`[`&&o!==`]`)return;if(n.length===0)return e.slice(t,a+1).trim()}}}},s=e=>{let t=e.trim(),n=[i(t),a(t),o(t)],r;for(let e of new Set(n))if(e)try{return JSON.parse(e)}catch(e){r=e}throw r instanceof Error?r:/* @__PURE__ */ SyntaxError(`Failed to parse JSON response text.`)};export{e as a,r as i,n,s as r,t};
|