coding-agents-sdk 0.2.0 → 0.4.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 +56 -1
- package/dist/SdkAgent-Coq-LSHU.mjs +1 -0
- package/dist/adapters/claude-code-cli/index.d.mts +1 -1
- package/dist/adapters/claude-code-cli/index.mjs +2 -490
- package/dist/adapters/claude-code-sdk/index.d.mts +1 -1
- package/dist/adapters/claude-code-sdk/index.mjs +4 -483
- package/dist/adapters/codex-cli/index.d.mts +1 -1
- package/dist/adapters/codex-cli/index.mjs +2 -626
- package/dist/adapters/codex-sdk/index.d.mts +1 -1
- package/dist/adapters/codex-sdk/index.mjs +1 -286
- package/dist/adapters/gemini-cli/index.d.mts +1 -1
- package/dist/adapters/gemini-cli/index.mjs +1 -292
- package/dist/classify-error-DXvCSvRY.mjs +8 -0
- package/dist/container/index.d.mts +2 -2
- package/dist/container/index.mjs +1 -24
- package/dist/container--0TOW4sB.mjs +1 -0
- package/dist/container-BuaAmhBf.mjs +1 -0
- package/dist/container-C5h5Bdf_.mjs +1 -0
- package/dist/container-RMYjapoN.mjs +1 -0
- package/dist/diff-DkMPJCxL.mjs +1 -0
- package/dist/env-DIXTVzTs.mjs +1 -0
- package/dist/errors-XV0frS3r.mjs +1 -0
- package/dist/execution-target-DdEbRqUx.mjs +4 -0
- package/dist/{index-C3ZxLAd0.d.mts → index-BDJms3ZX.d.mts} +6 -6
- package/dist/{index-nzo1sBiK.d.mts → index-BWtmcPDz.d.mts} +8 -8
- package/dist/{index-ByAOGMUM.d.mts → index-BgsYjENi.d.mts} +23 -5
- package/dist/{index-CFpNOmdA.d.mts → index-C-uiS3g-.d.mts} +2 -1
- package/dist/{index-dRVpEAr8.d.mts → index-CZbHe6Xs.d.mts} +5 -5
- package/dist/{index-B3YqrgIp.d.mts → index-CmVxarAz.d.mts} +3 -2
- package/dist/index-DbXtKldz.d.mts +85 -0
- package/dist/index.d.mts +10 -9
- package/dist/index.mjs +1 -61
- package/dist/oci-BVYPHn7b.mjs +1 -0
- package/dist/sandbox/index.d.mts +2 -0
- package/dist/sandbox/index.mjs +1 -0
- package/dist/sandbox-_As0qZWn.mjs +4 -0
- package/dist/schemas/index.d.mts +1 -1
- package/dist/schemas/index.mjs +1 -2
- package/dist/schemas-CXVWDOoT.mjs +1 -0
- package/dist/shell-Dewbmt9R.mjs +1 -0
- package/dist/spawner-BJesLc8I.mjs +1 -0
- package/dist/structured-output-nPFh_ZoY.mjs +1 -0
- package/dist/{types-Cb_EXIEe.d.mts → types-BHP0wiJg.d.mts} +9 -24
- package/dist/types-CwvWHEpy.mjs +1 -0
- package/dist/util-CGg8cK92.mjs +1 -0
- package/package.json +7 -3
- package/dist/Agent-D8WkUilj.mjs +0 -262
- package/dist/SdkAgent-B47mJiIE.mjs +0 -38
- package/dist/classify-error-pL6jeu4T.mjs +0 -456
- package/dist/container-2UmPZ0CI.mjs +0 -22
- package/dist/container-CHxKIonn.mjs +0 -440
- package/dist/container-D2Z0ITDJ.mjs +0 -22
- package/dist/diff-De8d3MVb.mjs +0 -333
- package/dist/errors-BAmHDQu8.mjs +0 -45
- package/dist/oci-DMZZQZ47.mjs +0 -438
- package/dist/schemas-DwD4pwJB.mjs +0 -96
- package/dist/spawner-Bw9UBEGX.mjs +0 -54
- package/dist/structured-output-BHtr_zpz.mjs +0 -19
- package/dist/types-aNMD8h3x.mjs +0 -19
- package/dist/util-B4RQZkKr.mjs +0 -77
- /package/dist/{events-nxuRbYIu.d.mts → events-BE9s04ko.d.mts} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as AgentEvent, v as AgentCapabilities, x as JsonSchema, y as ContentPart } from "./events-
|
|
1
|
+
import { t as AgentEvent, v as AgentCapabilities, x as JsonSchema, y as ContentPart } from "./events-BE9s04ko.mjs";
|
|
2
2
|
import { ZodType } from "zod/v4";
|
|
3
3
|
|
|
4
4
|
//#region src/core/process/types.d.ts
|
|
@@ -28,13 +28,9 @@ interface ProcessSpawner {
|
|
|
28
28
|
}
|
|
29
29
|
//#endregion
|
|
30
30
|
//#region src/core/agent/types.d.ts
|
|
31
|
-
/** Supported agents */
|
|
32
31
|
type AgentType = "claude-code-cli" | "claude-code-sdk" | "codex-cli" | "codex-sdk" | "gemini-cli";
|
|
33
|
-
/** Terminal status of a completed agent run */
|
|
34
32
|
type RunStatus = "cancelled" | "completed" | "failed";
|
|
35
|
-
/** Reason an agent run was stopped before completion */
|
|
36
33
|
type StopReason = "abort" | "timeout" | "user";
|
|
37
|
-
/** Usage and performance statistics from an agent run */
|
|
38
34
|
interface RunStats {
|
|
39
35
|
durationMs?: number;
|
|
40
36
|
apiDurationMs?: number;
|
|
@@ -46,13 +42,10 @@ interface RunStats {
|
|
|
46
42
|
outputTokens?: number;
|
|
47
43
|
totalTokens?: number;
|
|
48
44
|
}
|
|
49
|
-
/** Structured error from a failed or cancelled agent run */
|
|
50
45
|
interface RunError {
|
|
51
|
-
/** Error classification: abort (externally stopped), parse (output parsing), process (non-zero exit), provider (api error), spawn (binary not found) */
|
|
52
46
|
kind: "abort" | "parse" | "process" | "provider" | "spawn";
|
|
53
47
|
message: string;
|
|
54
48
|
}
|
|
55
|
-
/** Input parameters for a plain-text agent run. */
|
|
56
49
|
interface RunRequest {
|
|
57
50
|
input: ContentPart[] | string;
|
|
58
51
|
cwd?: string;
|
|
@@ -61,17 +54,13 @@ interface RunRequest {
|
|
|
61
54
|
timeoutMs?: number;
|
|
62
55
|
signal?: AbortSignal;
|
|
63
56
|
}
|
|
64
|
-
/** Input parameters for a raw-JSON-Schema structured-output run. */
|
|
65
57
|
interface JsonSchemaRunRequest extends RunRequest {
|
|
66
58
|
schema: JsonSchema;
|
|
67
59
|
}
|
|
68
|
-
/** Input parameters for a Zod-backed structured-output run. */
|
|
69
60
|
interface ZodRunRequest<TOutput = unknown> extends RunRequest {
|
|
70
61
|
schema: ZodType<TOutput>;
|
|
71
62
|
}
|
|
72
|
-
/** Input parameters for a structured-output run. */
|
|
73
63
|
type StructuredRunRequest<TOutput = unknown> = JsonSchemaRunRequest | ZodRunRequest<TOutput>;
|
|
74
|
-
/** Any supported run request shape. */
|
|
75
64
|
type AnyRunRequest = RunRequest | StructuredRunRequest;
|
|
76
65
|
interface RunTiming {
|
|
77
66
|
startedAt: Date;
|
|
@@ -112,11 +101,8 @@ type CompletedRunResult<TOutput = never> = RunResultBase & ([TOutput] extends [n
|
|
|
112
101
|
error?: undefined;
|
|
113
102
|
cancelReason?: undefined;
|
|
114
103
|
};
|
|
115
|
-
/** Discriminated union result of an agent run. narrow on `status` to access variant-specific fields. */
|
|
116
104
|
type RunResult<TOutput = never> = CancelledRunResult | CompletedRunResult<TOutput> | FailedRunResult;
|
|
117
|
-
/** Result of a run when the request shape is not known ahead of time. */
|
|
118
105
|
type AnyRunResult = RunResult | RunResult<unknown>;
|
|
119
|
-
/** Completed result of a run when the request shape is not known ahead of time. */
|
|
120
106
|
type AnyCompletedRunResult = CompletedRunResult | CompletedRunResult<unknown>;
|
|
121
107
|
type AgentRun<TRunOptions extends object = {}> = {
|
|
122
108
|
<TOutput>(request: TRunOptions & ZodRunRequest<TOutput>): Promise<RunResult<TOutput>>;
|
|
@@ -128,7 +114,6 @@ type AgentRunOrThrow<TRunOptions extends object = {}> = {
|
|
|
128
114
|
(request: JsonSchemaRunRequest & TRunOptions): Promise<CompletedRunResult<unknown>>;
|
|
129
115
|
(request: RunRequest & TRunOptions): Promise<CompletedRunResult>;
|
|
130
116
|
};
|
|
131
|
-
/** Thrown by `runOrThrow()` when the run does not complete successfully. carries the full `RunResult` on `.result`. */
|
|
132
117
|
declare class AgentRunError<TOutput = never> extends Error {
|
|
133
118
|
readonly result: RunResult<TOutput> & {
|
|
134
119
|
status: "cancelled" | "failed";
|
|
@@ -137,7 +122,6 @@ declare class AgentRunError<TOutput = never> extends Error {
|
|
|
137
122
|
status: "cancelled" | "failed";
|
|
138
123
|
});
|
|
139
124
|
}
|
|
140
|
-
/** Thrown when agent configuration or request parameters are invalid (e.g. unsupported capability, empty input) */
|
|
141
125
|
declare class AgentValidationError extends Error {
|
|
142
126
|
constructor(message: string);
|
|
143
127
|
}
|
|
@@ -150,14 +134,15 @@ interface AgentMetrics {
|
|
|
150
134
|
startedAt: Date;
|
|
151
135
|
lastActivityAt: Date;
|
|
152
136
|
}
|
|
153
|
-
/** Excludes keys typed as never (e.g. `systemPrompt?: never` blocker fields) */
|
|
154
137
|
type EffectiveKeys<T> = keyof { [K in keyof T as Required<T>[K] extends never ? never : K]: unknown };
|
|
155
|
-
/** Resolves to T if T has no effective keys overlapping with RunRequest, otherwise never */
|
|
156
138
|
type EnsureDisjoint<T extends object> = EffectiveKeys<T> & keyof RunRequest extends never ? T : never;
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
139
|
+
type ExclusiveExecutionTargetOptions<TContainer, TSandbox> = {
|
|
140
|
+
container?: never;
|
|
141
|
+
sandbox?: TSandbox;
|
|
142
|
+
} | {
|
|
143
|
+
container?: TContainer;
|
|
144
|
+
sandbox?: never;
|
|
145
|
+
};
|
|
161
146
|
interface BaseAgent<TRunOptions extends object = {}> {
|
|
162
147
|
readonly type: AgentType;
|
|
163
148
|
readonly capabilities: Readonly<AgentCapabilities>;
|
|
@@ -174,4 +159,4 @@ interface BaseAgent<TRunOptions extends object = {}> {
|
|
|
174
159
|
onEvent: (handler: AgentEventHandler) => () => void;
|
|
175
160
|
}
|
|
176
161
|
//#endregion
|
|
177
|
-
export {
|
|
162
|
+
export { RunTiming as C, ProcessSpawner as D, ZodRunRequest as E, RunStatus as S, StructuredRunRequest as T, RunProcessInfo as _, AgentValidationError as a, RunResultBase as b, AnyRunResult as c, CompletedRunResult as d, EnsureDisjoint as f, RunError as g, JsonSchemaRunRequest as h, AgentType as i, 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, RunRequest as v, StopReason as w, RunStats as x, RunResult as y };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=class extends Error{result;constructor(e){super(e.error.message),this.name=`AgentRunError`,this.result=e}},t=class extends Error{constructor(e){super(e),this.name=`AgentValidationError`}};export{t as n,e as t};
|
|
@@ -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)=>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: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.4.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"types": "./dist/index.d.mts",
|
|
6
6
|
"exports": {
|
|
@@ -16,6 +16,10 @@
|
|
|
16
16
|
"types": "./dist/container/index.d.mts",
|
|
17
17
|
"default": "./dist/container/index.mjs"
|
|
18
18
|
},
|
|
19
|
+
"./sandbox": {
|
|
20
|
+
"types": "./dist/sandbox/index.d.mts",
|
|
21
|
+
"default": "./dist/sandbox/index.mjs"
|
|
22
|
+
},
|
|
19
23
|
"./adapters/claude-code-cli": {
|
|
20
24
|
"types": "./dist/adapters/claude-code-cli/index.d.mts",
|
|
21
25
|
"default": "./dist/adapters/claude-code-cli/index.mjs"
|
|
@@ -44,7 +48,7 @@
|
|
|
44
48
|
],
|
|
45
49
|
"sideEffects": false,
|
|
46
50
|
"scripts": {
|
|
47
|
-
"build": "tsdown && bun run test:package",
|
|
51
|
+
"build": "bun run typecheck && tsdown && bun run test:package",
|
|
48
52
|
"start": "bun run examples/claude-code-cli/simple.ts",
|
|
49
53
|
"test": "bun test",
|
|
50
54
|
"test:agent": "bun test ./tests",
|
|
@@ -60,7 +64,7 @@
|
|
|
60
64
|
"typecheck": "bun run tsc"
|
|
61
65
|
},
|
|
62
66
|
"devDependencies": {
|
|
63
|
-
"@anthropic-ai/claude-agent-sdk": "
|
|
67
|
+
"@anthropic-ai/claude-agent-sdk": "0.2.74",
|
|
64
68
|
"@openai/codex-sdk": "^0.114.0",
|
|
65
69
|
"@types/bun": "latest",
|
|
66
70
|
"@types/node": "^25.5.0",
|
package/dist/Agent-D8WkUilj.mjs
DELETED
|
@@ -1,262 +0,0 @@
|
|
|
1
|
-
import { t as formatError } from "./util-B4RQZkKr.mjs";
|
|
2
|
-
import { a as buildBaseProcessEnv, i as hasMeaningfulEvent, n as AgentCore, o as createAgentEvent, t as classifyRunError } from "./classify-error-pL6jeu4T.mjs";
|
|
3
|
-
import { t as DEFAULT_SPAWNER } from "./spawner-Bw9UBEGX.mjs";
|
|
4
|
-
import { createWriteStream, mkdirSync } from "node:fs";
|
|
5
|
-
import { dirname } from "node:path";
|
|
6
|
-
//#region src/core/process/read-lines.ts
|
|
7
|
-
async function* readDecodedLines(stream) {
|
|
8
|
-
const decoder = new TextDecoder();
|
|
9
|
-
let buffer = "";
|
|
10
|
-
for await (const chunk of stream) {
|
|
11
|
-
const text = decoder.decode(chunk, { stream: true });
|
|
12
|
-
buffer += text;
|
|
13
|
-
const lines = buffer.split("\n");
|
|
14
|
-
buffer = lines.pop() ?? "";
|
|
15
|
-
for (const line of lines) {
|
|
16
|
-
const trimmed = line.trim();
|
|
17
|
-
if (trimmed) yield trimmed;
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
const tail = decoder.decode();
|
|
21
|
-
if (tail) buffer += tail;
|
|
22
|
-
const remaining = buffer.trim();
|
|
23
|
-
if (remaining) yield remaining;
|
|
24
|
-
}
|
|
25
|
-
//#endregion
|
|
26
|
-
//#region src/core/agent/Agent.ts
|
|
27
|
-
const SIGKILL_TIMEOUT_MS = 5e3;
|
|
28
|
-
const rejectedMessage = (result) => {
|
|
29
|
-
return result.status === "rejected" ? formatError(result.reason) : void 0;
|
|
30
|
-
};
|
|
31
|
-
const resolveFatalError = (run, settled) => {
|
|
32
|
-
if (run.stopReason) return void 0;
|
|
33
|
-
const stdoutError = rejectedMessage(settled.stdoutResult);
|
|
34
|
-
if (stdoutError) return {
|
|
35
|
-
kind: "process",
|
|
36
|
-
message: stdoutError
|
|
37
|
-
};
|
|
38
|
-
const stderrError = rejectedMessage(settled.stderrResult);
|
|
39
|
-
if (stderrError) return {
|
|
40
|
-
kind: "process",
|
|
41
|
-
message: stderrError
|
|
42
|
-
};
|
|
43
|
-
const spawnError = rejectedMessage(settled.processResult);
|
|
44
|
-
if (spawnError) return {
|
|
45
|
-
kind: "spawn",
|
|
46
|
-
message: spawnError
|
|
47
|
-
};
|
|
48
|
-
if (!run.status && !run.error) {
|
|
49
|
-
const processResult = run.processResult;
|
|
50
|
-
const stderrText = run.stderrLines.join("\n");
|
|
51
|
-
if (processResult && processResult.exitCode !== null && processResult.exitCode !== 0) return {
|
|
52
|
-
kind: "process",
|
|
53
|
-
message: stderrText || `Process exited with code ${processResult.exitCode}.`
|
|
54
|
-
};
|
|
55
|
-
if (!hasMeaningfulEvent(run) && run.stderrLines.length > 0) return {
|
|
56
|
-
kind: "process",
|
|
57
|
-
message: stderrText
|
|
58
|
-
};
|
|
59
|
-
}
|
|
60
|
-
};
|
|
61
|
-
const classifyAgentRuntimeError = (error) => {
|
|
62
|
-
const classified = classifyRunError(error);
|
|
63
|
-
return classified.kind === "provider" ? {
|
|
64
|
-
kind: "process",
|
|
65
|
-
message: classified.message
|
|
66
|
-
} : classified;
|
|
67
|
-
};
|
|
68
|
-
var Agent = class extends AgentCore {
|
|
69
|
-
spawner;
|
|
70
|
-
defaults;
|
|
71
|
-
containerRef;
|
|
72
|
-
autoStartContainer;
|
|
73
|
-
autoStopContainer;
|
|
74
|
-
containerStopPromise;
|
|
75
|
-
logStream;
|
|
76
|
-
sigkillTimer;
|
|
77
|
-
constructor(options) {
|
|
78
|
-
super({
|
|
79
|
-
type: options.type,
|
|
80
|
-
capabilities: options.capabilities,
|
|
81
|
-
sessionId: options.defaults?.sessionId,
|
|
82
|
-
onEvent: options.onEvent
|
|
83
|
-
});
|
|
84
|
-
this.spawner = options.spawner ?? DEFAULT_SPAWNER;
|
|
85
|
-
this.defaults = options.defaults ?? {};
|
|
86
|
-
this.containerRef = options.container;
|
|
87
|
-
this.autoStartContainer = options.autoStartContainer ?? true;
|
|
88
|
-
this.autoStopContainer = options.autoStopContainer ?? false;
|
|
89
|
-
if (options.logPath) this.initLogStream(options.logPath);
|
|
90
|
-
}
|
|
91
|
-
onParseError(line, error) {
|
|
92
|
-
this.appendRawLog(`[parse-error] ${formatError(error)} ${line.slice(0, 200)}`);
|
|
93
|
-
}
|
|
94
|
-
buildDefaultEnv(propagateEnv) {
|
|
95
|
-
const env = buildBaseProcessEnv({ propagateEnv });
|
|
96
|
-
env.CI = env.CI ?? "true";
|
|
97
|
-
if (this.defaults.env) Object.assign(env, this.defaults.env);
|
|
98
|
-
return env;
|
|
99
|
-
}
|
|
100
|
-
async executeRunCore(run, request) {
|
|
101
|
-
const lifecycle = this.setupRunLifecycle(run);
|
|
102
|
-
try {
|
|
103
|
-
if (lifecycle.abortedBeforeStart) return this.buildResult(run, /* @__PURE__ */ new Date());
|
|
104
|
-
try {
|
|
105
|
-
await this.onBeforeRun(run);
|
|
106
|
-
const mergedRequest = {
|
|
107
|
-
...request,
|
|
108
|
-
...run.normalizedRequest
|
|
109
|
-
};
|
|
110
|
-
const args = this.buildArgs(mergedRequest, run);
|
|
111
|
-
const env = this.buildEnv(mergedRequest, run);
|
|
112
|
-
const command = this.defaults.command?.[0] ?? "claude";
|
|
113
|
-
const commandArgs = [...this.defaults.command?.slice(1) ?? [], ...args];
|
|
114
|
-
if (run.stopReason) return this.buildResult(run, /* @__PURE__ */ new Date());
|
|
115
|
-
this.emitSessionStart(run);
|
|
116
|
-
run.process = this.spawner.spawn(command, commandArgs, {
|
|
117
|
-
cwd: run.normalizedRequest.cwd,
|
|
118
|
-
env,
|
|
119
|
-
stdio: [
|
|
120
|
-
"pipe",
|
|
121
|
-
"pipe",
|
|
122
|
-
"pipe"
|
|
123
|
-
]
|
|
124
|
-
});
|
|
125
|
-
run.process.stdin?.end();
|
|
126
|
-
const [stdoutResult, stderrResult, processResult] = await Promise.allSettled([
|
|
127
|
-
this.watchStdout(run),
|
|
128
|
-
this.watchStderr(run),
|
|
129
|
-
run.process.wait()
|
|
130
|
-
]);
|
|
131
|
-
if (processResult.status === "fulfilled") run.processResult = processResult.value;
|
|
132
|
-
const fatalError = resolveFatalError(run, {
|
|
133
|
-
stdoutResult,
|
|
134
|
-
stderrResult,
|
|
135
|
-
processResult
|
|
136
|
-
});
|
|
137
|
-
if (fatalError) run.error = fatalError;
|
|
138
|
-
} catch (error) {
|
|
139
|
-
if (!run.stopReason && !run.error) run.error = classifyAgentRuntimeError(error);
|
|
140
|
-
}
|
|
141
|
-
return this.buildResult(run, /* @__PURE__ */ new Date());
|
|
142
|
-
} finally {
|
|
143
|
-
lifecycle.cleanup();
|
|
144
|
-
if (this.sigkillTimer) {
|
|
145
|
-
clearTimeout(this.sigkillTimer);
|
|
146
|
-
this.sigkillTimer = void 0;
|
|
147
|
-
}
|
|
148
|
-
try {
|
|
149
|
-
await this.onRunFinished(run);
|
|
150
|
-
} catch (error) {
|
|
151
|
-
this.appendRawLog(`[cleanup-error] ${formatError(error)}`);
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
async watchStdout(run) {
|
|
156
|
-
const stdout = run.process?.stdout;
|
|
157
|
-
if (!stdout) return;
|
|
158
|
-
for await (const line of readDecodedLines(stdout)) {
|
|
159
|
-
this.appendLog("stdout", line);
|
|
160
|
-
this.processLine(run, line);
|
|
161
|
-
}
|
|
162
|
-
}
|
|
163
|
-
async watchStderr(run) {
|
|
164
|
-
const stderr = run.process?.stderr;
|
|
165
|
-
if (!stderr) return;
|
|
166
|
-
for await (const line of readDecodedLines(stderr)) {
|
|
167
|
-
this.appendLog("stderr", line);
|
|
168
|
-
run.stderrLines.push(line);
|
|
169
|
-
this.emit(run, createAgentEvent(run.runId, "stderr", {
|
|
170
|
-
sessionId: run.sessionId,
|
|
171
|
-
text: line
|
|
172
|
-
}));
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
processLine(run, line) {
|
|
176
|
-
let parsed;
|
|
177
|
-
try {
|
|
178
|
-
parsed = JSON.parse(line);
|
|
179
|
-
} catch (error) {
|
|
180
|
-
this.onParseError(line, error);
|
|
181
|
-
return;
|
|
182
|
-
}
|
|
183
|
-
let batch;
|
|
184
|
-
try {
|
|
185
|
-
batch = this.mapRawEvent(parsed, {
|
|
186
|
-
runId: run.runId,
|
|
187
|
-
requestedSessionId: run.requestedSessionId,
|
|
188
|
-
sessionId: run.sessionId,
|
|
189
|
-
schemaRequested: run.normalizedRequest.schema.kind !== "none",
|
|
190
|
-
toolCalls: run.toolCalls
|
|
191
|
-
});
|
|
192
|
-
} catch (error) {
|
|
193
|
-
this.onParseError(line, error);
|
|
194
|
-
return;
|
|
195
|
-
}
|
|
196
|
-
this.applyBatch(run, batch);
|
|
197
|
-
}
|
|
198
|
-
get runRequestDefaults() {
|
|
199
|
-
return this.defaults;
|
|
200
|
-
}
|
|
201
|
-
onHandlerError(error) {
|
|
202
|
-
this.appendRawLog(`[handler-error] ${formatError(error)}`);
|
|
203
|
-
}
|
|
204
|
-
async onDispose() {
|
|
205
|
-
const logStream = this.logStream;
|
|
206
|
-
this.logStream = void 0;
|
|
207
|
-
if (!logStream) return;
|
|
208
|
-
await new Promise((resolve) => {
|
|
209
|
-
logStream.end(resolve);
|
|
210
|
-
});
|
|
211
|
-
}
|
|
212
|
-
onStopRequested(run) {
|
|
213
|
-
run.process?.kill();
|
|
214
|
-
this.sigkillTimer = setTimeout(() => {
|
|
215
|
-
run.process?.kill("SIGKILL");
|
|
216
|
-
}, SIGKILL_TIMEOUT_MS);
|
|
217
|
-
this.sigkillTimer.unref?.();
|
|
218
|
-
}
|
|
219
|
-
onBeforeRun(_run) {
|
|
220
|
-
return this.ensureContainer();
|
|
221
|
-
}
|
|
222
|
-
async onRunFinished(_run) {
|
|
223
|
-
if (this.autoStopContainer && this.containerRef && this.containerRef.status === "running") {
|
|
224
|
-
this.containerStopPromise = this.containerRef.stop().catch((error) => {
|
|
225
|
-
this.appendRawLog(`[auto-stop-error] ${formatError(error)}`);
|
|
226
|
-
});
|
|
227
|
-
await this.containerStopPromise;
|
|
228
|
-
}
|
|
229
|
-
}
|
|
230
|
-
appendRawLog(data) {
|
|
231
|
-
if (!this.logStream) return;
|
|
232
|
-
const text = typeof data === "string" ? data : JSON.stringify(data);
|
|
233
|
-
this.logStream.write(`${text}\n`);
|
|
234
|
-
}
|
|
235
|
-
initLogStream(logPath) {
|
|
236
|
-
try {
|
|
237
|
-
mkdirSync(dirname(logPath), { recursive: true });
|
|
238
|
-
this.logStream = createWriteStream(logPath, { flags: "a" });
|
|
239
|
-
this.logStream.write(`\n--- ${(/* @__PURE__ */ new Date()).toISOString()} ---\n`);
|
|
240
|
-
} catch {
|
|
241
|
-
this.logStream = void 0;
|
|
242
|
-
}
|
|
243
|
-
}
|
|
244
|
-
appendLog(source, chunk) {
|
|
245
|
-
if (!this.logStream || !chunk) return;
|
|
246
|
-
const label = source === "stderr" ? "STDERR" : "STDOUT";
|
|
247
|
-
const ts = (/* @__PURE__ */ new Date()).toISOString();
|
|
248
|
-
for (const line of chunk.split("\n")) {
|
|
249
|
-
if (!line) continue;
|
|
250
|
-
this.logStream.write(`[${ts}] ${label} ${line}\n`);
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
async ensureContainer() {
|
|
254
|
-
if (this.containerStopPromise) {
|
|
255
|
-
await this.containerStopPromise;
|
|
256
|
-
this.containerStopPromise = void 0;
|
|
257
|
-
}
|
|
258
|
-
if (this.autoStartContainer && this.containerRef && this.containerRef.status !== "running") await this.containerRef.start();
|
|
259
|
-
}
|
|
260
|
-
};
|
|
261
|
-
//#endregion
|
|
262
|
-
export { Agent as t };
|
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
import { n as AgentCore, t as classifyRunError } from "./classify-error-pL6jeu4T.mjs";
|
|
2
|
-
//#region src/core/agent/SdkAgent.ts
|
|
3
|
-
/**
|
|
4
|
-
* Base class for SDK-based agent adapters (claude-code-sdk, codex-sdk).
|
|
5
|
-
* Provides the shared run lifecycle: abort/timeout wiring, session-start/end emission,
|
|
6
|
-
* error classification, and cleanup. Subclasses implement only the SDK-specific iteration.
|
|
7
|
-
*/
|
|
8
|
-
var SdkAgent = class extends AgentCore {
|
|
9
|
-
currentAbortController;
|
|
10
|
-
/** optional cleanup called in finally block (e.g. close SDK query) */
|
|
11
|
-
cleanupSdkResources() {}
|
|
12
|
-
onStopRequested(_run) {
|
|
13
|
-
this.currentAbortController?.abort();
|
|
14
|
-
}
|
|
15
|
-
async executeRunCore(run, request) {
|
|
16
|
-
const runAbortController = new AbortController();
|
|
17
|
-
this.currentAbortController = runAbortController;
|
|
18
|
-
const lifecycle = this.setupRunLifecycle(run);
|
|
19
|
-
try {
|
|
20
|
-
if (lifecycle.abortedBeforeStart) return this.buildResult(run, /* @__PURE__ */ new Date());
|
|
21
|
-
if (run.stopReason) return this.buildResult(run, /* @__PURE__ */ new Date());
|
|
22
|
-
this.emitSessionStart(run);
|
|
23
|
-
await this.executeSdkRun(run, request, runAbortController);
|
|
24
|
-
return this.buildResult(run, /* @__PURE__ */ new Date());
|
|
25
|
-
} catch (error) {
|
|
26
|
-
if (!run.stopReason && !run.error) run.error = classifyRunError(error);
|
|
27
|
-
return this.buildResult(run, /* @__PURE__ */ new Date());
|
|
28
|
-
} finally {
|
|
29
|
-
lifecycle.cleanup();
|
|
30
|
-
try {
|
|
31
|
-
await this.cleanupSdkResources();
|
|
32
|
-
} catch {}
|
|
33
|
-
if (this.currentAbortController === runAbortController) this.currentAbortController = void 0;
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
};
|
|
37
|
-
//#endregion
|
|
38
|
-
export { SdkAgent as t };
|