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
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { i as ProcessSpawner } from "./types-BetgZysV.mjs";
|
|
2
|
+
import { t as Container } from "./index-Q5jNyQHD.mjs";
|
|
3
|
+
import { f as EnsureDisjoint, l as BaseAgent, p as ExclusiveExecutionTargetOptions, t as AgentEventHandler } from "./types-D_QP9PC-.mjs";
|
|
4
|
+
import { l as Sandbox } from "./index-CZiWvyn3.mjs";
|
|
5
|
+
/**
|
|
6
|
+
* How Drac settles a tool call that needs a decision. A call the mode asks about goes to the handler
|
|
7
|
+
* registered with `agent.onPermissionRequest(...)`, and is denied when none is registered.
|
|
8
|
+
* - `"normal"`: reads and edits inside the working directory run; Drac asks about commands and other file access.
|
|
9
|
+
* - `"auto"`: the configured classifier model reviews commands and outside edits, and Drac asks when the classifier needs input.
|
|
10
|
+
* - `"plan"`: like `"read-only"`, except that Drac may write its plan file. Prefer `startsInPlanMode`, which also says which mode an approved plan returns to.
|
|
11
|
+
* - `"read-only"`: reads run, Drac asks about reads outside the allowed directories, and edits and commands are denied.
|
|
12
|
+
* - `"dangerous"`: runs every call without review.
|
|
13
|
+
*/
|
|
14
|
+
type DracPermissionMode = "auto" | "dangerous" | "normal" | "plan" | "read-only";
|
|
15
|
+
interface DracCliRunOptions {
|
|
16
|
+
/** Drac configuration mode whose headless configuration runs, such as `"code"`. A resumed session keeps the mode it recorded. */
|
|
17
|
+
mode?: string;
|
|
18
|
+
/** Overrides for the model's generation options, such as `{ effort: "high" }`. The keys a model takes depend on its Drac provider. */
|
|
19
|
+
modelOptions?: Record<string, unknown>;
|
|
20
|
+
/** Permission mode for the run. Drac's configuration decides it when omitted. */
|
|
21
|
+
permissionMode?: DracPermissionMode;
|
|
22
|
+
/**
|
|
23
|
+
* Plan before changing anything. The run starts in Drac's plan mode: Drac writes a plan and changes nothing else.
|
|
24
|
+
* When the plan is ready, the handler registered with `agent.onPermissionRequest(...)` gets a request for the tool
|
|
25
|
+
* `exit_plan_mode` whose input holds `plan`, `planFile`, and `mode`, the permission mode an approval returns to.
|
|
26
|
+
* Allowing it starts the implementation in the same run, in `permissionMode` or in the configured mode when that is
|
|
27
|
+
* omitted. An allow that carries `updatedInput` or `permissionMode` leaves the plan undecided, and the run ends with
|
|
28
|
+
* the plan. Denying it keeps plan mode on: with a `message`, Drac revises the plan and asks again; without one, Drac
|
|
29
|
+
* stops and the run ends with the plan unapproved.
|
|
30
|
+
* The option applies to one run. A later run of the same session without it leaves plan mode when it passes a
|
|
31
|
+
* `permissionMode`, and stays in plan mode when it passes none.
|
|
32
|
+
*/
|
|
33
|
+
startsInPlanMode?: boolean;
|
|
34
|
+
/** Text appended to Drac's configured instructions, sent with every run, resumed runs included. */
|
|
35
|
+
appendSystemPrompt?: string;
|
|
36
|
+
/** Extra `drac exec` flags appended verbatim. */
|
|
37
|
+
extraArgs?: string[];
|
|
38
|
+
/** Not supported: Drac's configuration owns its instructions. Use `appendSystemPrompt` to add to them. */
|
|
39
|
+
systemPrompt?: never;
|
|
40
|
+
}
|
|
41
|
+
type DracCliAgentOptions = ExclusiveExecutionTargetOptions<Container, Sandbox> & DracCliRunOptions & {
|
|
42
|
+
/** Path or argv to the `drac` binary. */
|
|
43
|
+
command?: string[] | string;
|
|
44
|
+
cwd?: string;
|
|
45
|
+
env?: Record<string, string>;
|
|
46
|
+
/** Default `true`: `process.env` is inherited and `env` overlays it. Set `false` to suppress host-env propagation. */
|
|
47
|
+
propagateEnv?: boolean;
|
|
48
|
+
/** Existing Drac session ID to resume. */
|
|
49
|
+
sessionId?: string;
|
|
50
|
+
/** Drac model as `<provider>/<modelId>`, such as `"codex/gpt-6-sol"`. Drac's configuration decides it when omitted. */
|
|
51
|
+
model?: string;
|
|
52
|
+
/** Emit `message-delta` and `reasoning-delta` events while Drac generates text. */
|
|
53
|
+
streamText?: boolean;
|
|
54
|
+
/** File path to write the raw CLI log to (useful for debugging). */
|
|
55
|
+
logPath?: string;
|
|
56
|
+
/** Custom process spawner; set by `createContainer`/`createSandbox`, rarely needed manually. */
|
|
57
|
+
spawner?: ProcessSpawner;
|
|
58
|
+
/** Convenience: equivalent to calling `agent.onEvent(handler)` post-construction. */
|
|
59
|
+
onEvent?: AgentEventHandler;
|
|
60
|
+
};
|
|
61
|
+
interface DracCliAgent extends BaseAgent<EnsureDisjoint<DracCliRunOptions>> {
|
|
62
|
+
readonly type: "drac-cli";
|
|
63
|
+
}
|
|
64
|
+
declare const createDracCliAgent: (options?: DracCliAgentOptions) => DracCliAgent;
|
|
65
|
+
export { DracPermissionMode as a, DracCliRunOptions as i, DracCliAgent as n, DracCliAgentOptions as r, createDracCliAgent as t };
|
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import { i as ProcessSpawner } from "./types-
|
|
2
|
-
import "./types-
|
|
3
|
-
//#region src/container/types.d.ts
|
|
1
|
+
import { i as ProcessSpawner } from "./types-BetgZysV.mjs";
|
|
2
|
+
import "./types-D_QP9PC-.mjs";
|
|
4
3
|
/** Which provider backs a container. Selects which CLI/SDK the adapter speaks. */
|
|
5
4
|
type ContainerType = "docker" | "e2b" | "nerdctl" | "podman";
|
|
6
5
|
/** Container port → host port mapping for `start`/`run`. */
|
|
@@ -106,7 +105,10 @@ interface ContainerLifecycle {
|
|
|
106
105
|
start: () => Promise<void>;
|
|
107
106
|
/** Stop the container without removing it. */
|
|
108
107
|
stop: () => Promise<void>;
|
|
109
|
-
/**
|
|
108
|
+
/**
|
|
109
|
+
* Stop and remove a container made by `createContainer`. A container obtained with `attachContainer`
|
|
110
|
+
* is left as it is, neither stopped nor removed. Idempotent.
|
|
111
|
+
*/
|
|
110
112
|
dispose: () => Promise<void>;
|
|
111
113
|
[Symbol.asyncDispose]: () => Promise<void>;
|
|
112
114
|
}
|
|
@@ -155,8 +157,6 @@ interface ContainerObservability {
|
|
|
155
157
|
}
|
|
156
158
|
/** Composed shape of every concrete container instance. */
|
|
157
159
|
interface ContainerBase<TType extends ContainerType, TConfig extends ContainerConfigBase<TType>> extends ContainerExecution, ContainerFileSystem, ContainerIdentity<TType, TConfig>, ContainerLifecycle, ContainerObservability {}
|
|
158
|
-
//#endregion
|
|
159
|
-
//#region src/container/oci.d.ts
|
|
160
160
|
interface OciBuildBase {
|
|
161
161
|
context?: string;
|
|
162
162
|
args?: Record<string, string>;
|
|
@@ -186,8 +186,24 @@ type OciProviderConfig = OciProviderBase & ({
|
|
|
186
186
|
image?: never;
|
|
187
187
|
build: OciBuildConfig;
|
|
188
188
|
});
|
|
189
|
-
|
|
190
|
-
|
|
189
|
+
interface OciAttachConfig<TType extends ContainerType> extends ContainerConfigBase<TType> {
|
|
190
|
+
/** ID or name of the existing container. */
|
|
191
|
+
containerId: string;
|
|
192
|
+
binary?: string;
|
|
193
|
+
/** An existing container keeps the name and environment it was created with. */
|
|
194
|
+
name?: never;
|
|
195
|
+
env?: never;
|
|
196
|
+
}
|
|
197
|
+
interface AttachedOciContainer<TType extends ContainerType> extends ContainerBase<TType, OciAttachConfig<TType>> {
|
|
198
|
+
/**
|
|
199
|
+
* Stop the container if it is running, remove it and its anonymous volumes from the provider, and dispose
|
|
200
|
+
* this object. Succeeds when the container is already gone, so it can be called again, and also after
|
|
201
|
+
* `dispose()`. The container's image and its named volumes stay.
|
|
202
|
+
*
|
|
203
|
+
* @throws {ContainerRemoveError} If the provider could not remove the container. The object is then not disposed, so the call can be retried.
|
|
204
|
+
*/
|
|
205
|
+
remove: () => Promise<void>;
|
|
206
|
+
}
|
|
191
207
|
/** Full config passed to `createContainer({ type: "docker", ... })`. */
|
|
192
208
|
type DockerContainerConfig = ContainerConfigBase<"docker"> & OciProviderConfig;
|
|
193
209
|
/** Docker container instance. */
|
|
@@ -195,8 +211,9 @@ interface DockerContainer extends ContainerBase<"docker", DockerContainerConfig>
|
|
|
195
211
|
/** Resolve the host port bound to a container port from {@link PortMapping}, or `undefined` if unmapped. */
|
|
196
212
|
getMappedPort: (containerPort: number) => number | undefined;
|
|
197
213
|
}
|
|
198
|
-
|
|
199
|
-
|
|
214
|
+
type DockerAttachConfig = OciAttachConfig<"docker">;
|
|
215
|
+
/** Docker container instance obtained with `attachContainer(...)`. Disposing it leaves the container as it is. */
|
|
216
|
+
type AttachedDockerContainer = AttachedOciContainer<"docker">;
|
|
200
217
|
interface E2BSandboxNetworkOptions {
|
|
201
218
|
allowOut?: string[];
|
|
202
219
|
denyOut?: string[];
|
|
@@ -268,8 +285,6 @@ interface E2BContainer extends ContainerBase<"e2b", E2BContainerConfig> {
|
|
|
268
285
|
/** Resolve the externally-reachable hostname for a sandbox port. */
|
|
269
286
|
getHost: (port: number) => string;
|
|
270
287
|
}
|
|
271
|
-
//#endregion
|
|
272
|
-
//#region src/container/nerdctl/types.d.ts
|
|
273
288
|
/** Provider-specific fields for nerdctl, layered on top of generic OCI provider options. */
|
|
274
289
|
interface NerdctlProviderBase extends OciProviderBase {
|
|
275
290
|
/** containerd namespace. Defaults to `"default"`. */
|
|
@@ -292,8 +307,6 @@ interface NerdctlContainer extends ContainerBase<"nerdctl", NerdctlContainerConf
|
|
|
292
307
|
/** Resolve the host port bound to a container port from {@link PortMapping}, or `undefined` if unmapped. */
|
|
293
308
|
getMappedPort: (containerPort: number) => number | undefined;
|
|
294
309
|
}
|
|
295
|
-
//#endregion
|
|
296
|
-
//#region src/container/podman/types.d.ts
|
|
297
310
|
/** Full config passed to `createContainer({ type: "podman", ... })`. */
|
|
298
311
|
type PodmanContainerConfig = ContainerConfigBase<"podman"> & OciProviderConfig;
|
|
299
312
|
/** Podman container instance. */
|
|
@@ -301,12 +314,13 @@ interface PodmanContainer extends ContainerBase<"podman", PodmanContainerConfig>
|
|
|
301
314
|
/** Resolve the host port bound to a container port from {@link PortMapping}, or `undefined` if unmapped. */
|
|
302
315
|
getMappedPort: (containerPort: number) => number | undefined;
|
|
303
316
|
}
|
|
304
|
-
|
|
305
|
-
|
|
317
|
+
type PodmanAttachConfig = OciAttachConfig<"podman">;
|
|
318
|
+
/** Podman container instance obtained with `attachContainer(...)`. Disposing it leaves the container as it is. */
|
|
319
|
+
type AttachedPodmanContainer = AttachedOciContainer<"podman">;
|
|
306
320
|
/**
|
|
307
|
-
* Base class for every error thrown by `createContainer(...)
|
|
308
|
-
* resulting container instance. Catch this
|
|
309
|
-
* container failure uniformly.
|
|
321
|
+
* Base class for every error thrown by `createContainer(...)`,
|
|
322
|
+
* `attachContainer(...)`, and the resulting container instance. Catch this
|
|
323
|
+
* if you want to handle any container failure uniformly.
|
|
310
324
|
*/
|
|
311
325
|
declare class ContainerError extends Error {
|
|
312
326
|
constructor(message: string);
|
|
@@ -319,6 +333,29 @@ declare class ContainerError extends Error {
|
|
|
319
333
|
declare class ContainerCreateError extends ContainerError {
|
|
320
334
|
constructor(message: string);
|
|
321
335
|
}
|
|
336
|
+
/**
|
|
337
|
+
* Thrown by `attachContainer(...)` when the provider reports no container
|
|
338
|
+
* with the given ID or name.
|
|
339
|
+
*/
|
|
340
|
+
declare class ContainerNotFoundError extends ContainerError {
|
|
341
|
+
constructor(message: string);
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* Thrown by `attachContainer(...)` for every failure other than a missing
|
|
345
|
+
* container — e.g. the configured provider isn't available, or the working
|
|
346
|
+
* directory can't be created inside a running container.
|
|
347
|
+
*/
|
|
348
|
+
declare class ContainerAttachError extends ContainerError {
|
|
349
|
+
constructor(message: string);
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* Thrown by `remove()` on an attached container when the provider could not
|
|
353
|
+
* remove it — e.g. the provider isn't available. The container object is not
|
|
354
|
+
* disposed, so the call can be retried.
|
|
355
|
+
*/
|
|
356
|
+
declare class ContainerRemoveError extends ContainerError {
|
|
357
|
+
constructor(message: string);
|
|
358
|
+
}
|
|
322
359
|
/**
|
|
323
360
|
* Thrown when a configured `mounts` entry fails pre-flight validation —
|
|
324
361
|
* typically a missing or unreadable source path on the host.
|
|
@@ -363,12 +400,10 @@ declare class ContainerDisposedError extends ContainerError {
|
|
|
363
400
|
declare class ContainerDiffError extends ContainerError {
|
|
364
401
|
constructor(message: string);
|
|
365
402
|
}
|
|
366
|
-
//#endregion
|
|
367
|
-
//#region src/container/index.d.ts
|
|
368
403
|
/** Union of every provider config accepted by `createContainer(...)`. Narrow on `type` to pick a provider. */
|
|
369
404
|
type ContainerConfig = DockerContainerConfig | E2BContainerConfig | NerdctlContainerConfig | PodmanContainerConfig;
|
|
370
|
-
/** Union of every provider's
|
|
371
|
-
type Container = DockerContainer | E2BContainer | NerdctlContainer | PodmanContainer;
|
|
405
|
+
/** Union of every provider's container instance, created or attached. Narrow on `container.type` to pick a provider; a provider's created and attached instances have different extra methods. */
|
|
406
|
+
type Container = AttachedDockerContainer | AttachedPodmanContainer | DockerContainer | E2BContainer | NerdctlContainer | PodmanContainer;
|
|
372
407
|
/**
|
|
373
408
|
* Create a container for sandboxed agent execution.
|
|
374
409
|
*
|
|
@@ -401,5 +436,33 @@ declare function createContainer(config: DockerContainerConfig): Promise<DockerC
|
|
|
401
436
|
declare function createContainer(config: E2BContainerConfig): Promise<E2BContainer>;
|
|
402
437
|
declare function createContainer(config: NerdctlContainerConfig): Promise<NerdctlContainer>;
|
|
403
438
|
declare function createContainer(config: PodmanContainerConfig): Promise<PodmanContainer>;
|
|
404
|
-
|
|
405
|
-
|
|
439
|
+
/**
|
|
440
|
+
* Attach to an existing Docker or Podman container, identified by ID or name,
|
|
441
|
+
* without taking ownership of it.
|
|
442
|
+
*
|
|
443
|
+
* The result has the same execution, filesystem, and observability methods as
|
|
444
|
+
* a created container, and can be passed to a cli-adapter's `container`
|
|
445
|
+
* option. Attaching does not start a stopped container; call `start()` for
|
|
446
|
+
* that.
|
|
447
|
+
*
|
|
448
|
+
* Disposing the result, including through `await using`, neither stops nor
|
|
449
|
+
* removes the container. Call `stop()` to stop it, or `remove()` to stop and
|
|
450
|
+
* remove it.
|
|
451
|
+
*
|
|
452
|
+
* ```ts
|
|
453
|
+
* const container = await attachContainer({
|
|
454
|
+
* type: "docker",
|
|
455
|
+
* containerId: "my-workspace",
|
|
456
|
+
* workdir: "/workspace",
|
|
457
|
+
* });
|
|
458
|
+
* await container.exec("npm", ["test"]);
|
|
459
|
+
* ```
|
|
460
|
+
*
|
|
461
|
+
* @param config The provider, the container's ID or name, and the working directory to use inside it. A running container gets that directory created if it is missing.
|
|
462
|
+
* @returns A promise that resolves to a container in the state the provider reports: running, stopped, or created.
|
|
463
|
+
* @throws {ContainerNotFoundError} If the provider reports no container with that ID or name.
|
|
464
|
+
* @throws {ContainerAttachError} For every other failure, such as an unavailable provider.
|
|
465
|
+
*/
|
|
466
|
+
declare function attachContainer(config: DockerAttachConfig): Promise<AttachedDockerContainer>;
|
|
467
|
+
declare function attachContainer(config: PodmanAttachConfig): Promise<AttachedPodmanContainer>;
|
|
468
|
+
export { DockerAttachConfig as A, WorkdirDiff as B, E2BConnectConfig as C, E2BCreateConfig as D, E2BContainerConfig as E, ExecOptions as F, WorkdirFileChange as H, ExecResult as I, PortMapping as L, DockerContainerConfig as M, ContainerStatus as N, E2BProviderConfig as O, ContainerType as P, VolumeMount as R, NerdctlProviderConfig as S, E2BContainer as T, WorkdirSnapshot as U, WorkdirDiffStats as V, WorkdirSnapshotOptions as W, PodmanAttachConfig as _, ContainerAttachError as a, NerdctlContainer as b, ContainerDisposedError as c, ContainerNotFoundError as d, ContainerNotRunningError as f, AttachedPodmanContainer as g, MountValidationError as h, createContainer as i, DockerContainer as j, AttachedDockerContainer as k, ContainerError as l, ContainerStartError as m, ContainerConfig as n, ContainerCreateError as o, ContainerRemoveError as p, attachContainer as r, ContainerDiffError as s, Container as t, ContainerExecError as u, PodmanContainer as v, E2BConnectionConfig as w, NerdctlContainerConfig as x, PodmanContainerConfig as y, WorkdirChangeKind as z };
|
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { N as ClaudePermissionMode, f as EnsureDisjoint, l as BaseAgent, t as AgentEventHandler } from "./types-D_QP9PC-.mjs";
|
|
2
|
+
import { A as McpServerConfig } from "./events-DmlAPVpd.mjs";
|
|
3
3
|
import "@anthropic-ai/claude-agent-sdk";
|
|
4
|
-
//#region src/adapters/claude-code-sdk/types.d.ts
|
|
5
4
|
/**
|
|
6
5
|
* How Claude Code handles tool-permission prompts.
|
|
7
6
|
* - `"default"`: stop and ask via the permission handler.
|
|
@@ -11,7 +10,7 @@ import "@anthropic-ai/claude-agent-sdk";
|
|
|
11
10
|
* - `"bypassPermissions"`: disable the permission system entirely (dangerous).
|
|
12
11
|
* - `"plan"`: read-only planning mode; no edits, no shell.
|
|
13
12
|
*/
|
|
14
|
-
type ClaudeCodeSdkPermissionMode =
|
|
13
|
+
type ClaudeCodeSdkPermissionMode = ClaudePermissionMode;
|
|
15
14
|
/** Which runtime to use when spawning the Claude Code SDK subprocess. */
|
|
16
15
|
type ClaudeCodeSdkExecutable = "bun" | "deno" | "node";
|
|
17
16
|
/** Which Claude Code settings layers to load from the local filesystem. */
|
|
@@ -91,8 +90,5 @@ interface ClaudeCodeSdkEvent {
|
|
|
91
90
|
session_id?: string;
|
|
92
91
|
[key: string]: unknown;
|
|
93
92
|
}
|
|
94
|
-
//#endregion
|
|
95
|
-
//#region src/adapters/claude-code-sdk/adapter.d.ts
|
|
96
93
|
declare const createClaudeCodeSdkAgent: (options?: ClaudeCodeSdkAgentOptions) => ClaudeCodeSdkAgent;
|
|
97
|
-
//#endregion
|
|
98
94
|
export { ClaudeCodeSdkExecutable as a, ClaudeCodeSdkSettingSource as c, ClaudeCodeSdkEvent as i, ClaudeCodeSdkSettings as l, ClaudeCodeSdkAgent as n, ClaudeCodeSdkPermissionMode as o, ClaudeCodeSdkAgentOptions as r, ClaudeCodeSdkRunOptions as s, createClaudeCodeSdkAgent as t };
|
|
@@ -1,9 +1,8 @@
|
|
|
1
|
-
import { i as ProcessSpawner } from "./types-
|
|
2
|
-
import {
|
|
3
|
-
import { t as
|
|
4
|
-
import { l as Sandbox } from "./index-
|
|
1
|
+
import { i as ProcessSpawner } from "./types-BetgZysV.mjs";
|
|
2
|
+
import { t as Container } from "./index-Q5jNyQHD.mjs";
|
|
3
|
+
import { f as EnsureDisjoint, l as BaseAgent, p as ExclusiveExecutionTargetOptions, t as AgentEventHandler } from "./types-D_QP9PC-.mjs";
|
|
4
|
+
import { l as Sandbox } from "./index-CZiWvyn3.mjs";
|
|
5
5
|
import { z } from "zod/v4";
|
|
6
|
-
//#region src/adapters/pi-cli/events/schemas.d.ts
|
|
7
6
|
/**
|
|
8
7
|
* Permissive raw-event shape for Pi CLI: `{ type: string }` plus arbitrary
|
|
9
8
|
* additional fields the CLI may emit.
|
|
@@ -12,8 +11,6 @@ declare const piEventSchema: z.ZodObject<{
|
|
|
12
11
|
type: z.ZodString;
|
|
13
12
|
}, z.core.$loose>;
|
|
14
13
|
type PiEvent = z.infer<typeof piEventSchema>;
|
|
15
|
-
//#endregion
|
|
16
|
-
//#region src/adapters/pi-cli/types.d.ts
|
|
17
14
|
/** How much hidden reasoning Pi should perform per turn. */
|
|
18
15
|
type PiCliThinkingLevel = "high" | "low" | "medium" | "minimal" | "off" | "xhigh";
|
|
19
16
|
/** Per-run options for the `pi-cli` adapter. */
|
|
@@ -71,8 +68,5 @@ interface PiCliAgent extends BaseAgent<EnsureDisjoint<PiCliRunOptions>> {
|
|
|
71
68
|
*/
|
|
72
69
|
fork: () => PiCliAgent;
|
|
73
70
|
}
|
|
74
|
-
//#endregion
|
|
75
|
-
//#region src/adapters/pi-cli/adapter.d.ts
|
|
76
71
|
declare const createPiCliAgent: (options?: PiCliAgentOptions) => PiCliAgent;
|
|
77
|
-
//#endregion
|
|
78
72
|
export { PiCliThinkingLevel as a, PiCliRunOptions as i, PiCliAgent as n, PiEvent as o, PiCliAgentOptions as r, createPiCliAgent as t };
|
package/dist/index.d.mts
CHANGED
|
@@ -1,22 +1,24 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { a as SpawnOptions, i as ProcessSpawner, n as ProcessResult, r as ProcessSignal, t as AgentProcess } from "./types-
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import { a as
|
|
6
|
-
import { a as
|
|
7
|
-
import { a as
|
|
8
|
-
import { a as
|
|
9
|
-
import { a as
|
|
10
|
-
import { a as
|
|
11
|
-
import { a as
|
|
12
|
-
import { a as
|
|
13
|
-
import { a as
|
|
14
|
-
import { a as
|
|
15
|
-
import { a as
|
|
16
|
-
import { n as
|
|
1
|
+
import { a as AntigravityMode, i as AntigravityCliRunOptions, n as AntigravityCliAgent, o as AntigravityThoughtLevel, r as AntigravityCliAgentOptions, s as AntigravityProviderEvent } from "./index-DUTtolch.mjs";
|
|
2
|
+
import { a as SpawnOptions, i as ProcessSpawner, n as ProcessResult, r as ProcessSignal, t as AgentProcess } from "./types-BetgZysV.mjs";
|
|
3
|
+
import { C as ClaudeControlRequestPayload, S as ClaudeControlRequestFailure, _ as ClaudeRateLimitEvent, a as ClaudeBackgroundTaskChange, b as ClaudeUserEvent, c as ClaudeBackgroundTaskStatus, d as ClaudeCodeCliAgentOptions, f as ClaudeCodeCliPermissionMode, g as ClaudeProviderEvent, h as ClaudeEvent, i as ClaudeBackgroundTask, l as ClaudeBackgroundTaskUsage, m as ClaudeAssistantEvent, n as ClaudeAgentRun, o as ClaudeBackgroundTaskEnd, p as ClaudeCodeCliRunOptions, r as ClaudeBackgroundSubagent, s as ClaudeBackgroundTaskProgress, u as ClaudeCodeCliAgent, v as ClaudeResultEvent, x as ClaudeControlRequestError, y as ClaudeSystemEvent } from "./index-DilMV_1s.mjs";
|
|
4
|
+
import { a as ClaudeCodeCliPtyPermissionMode, i as ClaudeCodeCliPtyModule, n as ClaudeCodeCliPtyAgent, o as ClaudeCodeCliPtyProcess, r as ClaudeCodeCliPtyAgentOptions, s as ClaudeCodeCliPtyRunOptions } from "./index-5XiyFBcK.mjs";
|
|
5
|
+
import { a as ClaudeCodeSdkExecutable, c as ClaudeCodeSdkSettingSource, i as ClaudeCodeSdkEvent, l as ClaudeCodeSdkSettings, n as ClaudeCodeSdkAgent, o as ClaudeCodeSdkPermissionMode, r as ClaudeCodeSdkAgentOptions, s as ClaudeCodeSdkRunOptions } from "./index-X-W5isMp.mjs";
|
|
6
|
+
import { a as CodexCliRunOptions, c as CodexEvent, d as CodexItemUpdatedEvent, f as CodexProviderEvent, g as CodexTurnFailedEvent, h as CodexTurnCompletedEvent, i as CodexCliPermissionMode, l as CodexItemCompletedEvent, m as CodexThreadStartedEvent, n as CodexCliAgent, o as CodexCliSandboxMode, p as CodexProviderItem, r as CodexCliAgentOptions, s as CodexErrorEvent, u as CodexItemStartedEvent } from "./index-DpG9mouj.mjs";
|
|
7
|
+
import { a as CodexSdkItem, i as CodexSdkEvent, n as CodexSdkAgent, o as CodexSdkPermissionMode, r as CodexSdkAgentOptions, s as CodexSdkRunOptions } from "./index-CCsw4G4N.mjs";
|
|
8
|
+
import { a as CursorCliRunOptions, i as CursorCliPermissionMode, n as CursorCliAgent, o as CursorCliSandboxMode, r as CursorCliAgentOptions, s as CursorCliEvent } from "./index-Brx5CEx7.mjs";
|
|
9
|
+
import { a as CursorSdkMcpHttpAuth, c as CursorSdkSettingSource, i as CursorSdkEvent, n as CursorSdkAgent, o as CursorSdkMcpServerConfig, r as CursorSdkAgentOptions, s as CursorSdkRunOptions } from "./index-DqNl8zYj.mjs";
|
|
10
|
+
import { a as DracPermissionMode, i as DracCliRunOptions, n as DracCliAgent, r as DracCliAgentOptions } from "./index-Du99OLj6.mjs";
|
|
11
|
+
import { a as GeminiCliRunOptions, i as GeminiCliPermissionMode, n as GeminiCliAgent, o as GeminiEvent, r as GeminiCliAgentOptions } from "./index-DQYRy7xl.mjs";
|
|
12
|
+
import { a as OpencodeEvent, i as OpencodeCliRunOptions, n as OpencodeCliAgent, r as OpencodeCliAgentOptions } from "./index-Bl9DtOcy.mjs";
|
|
13
|
+
import { a as PiCliThinkingLevel, i as PiCliRunOptions, n as PiCliAgent, o as PiEvent, r as PiCliAgentOptions } from "./index-oUIMXZIp.mjs";
|
|
14
|
+
import { A as QuestionHandler, C as RunStatus, D as ZodRunRequest, E as StructuredRunRequest, F as PermissionHandler, I as PermissionRequest, M as QuestionRequest, N as ClaudePermissionMode, O as Question, P as PermissionDecision, S as RunStats, T as StopReason, _ as ProviderEventHandler, a as AgentValidationError, b as RunRequest, c as AnyRunResult, d as CompletedRunResult, g as ProviderEvent, h as JsonSchemaRunRequest, i as AgentType, j as QuestionOption, k as QuestionAnswers, l as BaseAgent, m as FailedRunResult, n as AgentMetrics, o as AnyCompletedRunResult, r as AgentRunError, s as AnyRunRequest, t as AgentEventHandler, u as CancelledRunResult, v as RunError, w as RunTiming, x as RunResult, y as RunProcessInfo } from "./types-D_QP9PC-.mjs";
|
|
15
|
+
import { A as DockerAttachConfig, B as WorkdirDiff, C as E2BConnectConfig, D as E2BCreateConfig, E as E2BContainerConfig, F as ExecOptions, H as WorkdirFileChange, I as ExecResult, L as PortMapping, M as DockerContainerConfig, N as ContainerStatus, O as E2BProviderConfig, P as ContainerType, R as VolumeMount, S as NerdctlProviderConfig, T as E2BContainer, U as WorkdirSnapshot, V as WorkdirDiffStats, W as WorkdirSnapshotOptions, _ as PodmanAttachConfig, a as ContainerAttachError, b as NerdctlContainer, c as ContainerDisposedError, d as ContainerNotFoundError, f as ContainerNotRunningError, g as AttachedPodmanContainer, h as MountValidationError, i as createContainer, j as DockerContainer, k as AttachedDockerContainer, l as ContainerError, m as ContainerStartError, n as ContainerConfig, o as ContainerCreateError, p as ContainerRemoveError, r as attachContainer, s as ContainerDiffError, t as Container, u as ContainerExecError, v as PodmanContainer, w as E2BConnectionConfig, x as NerdctlContainerConfig, y as PodmanContainerConfig, z as WorkdirChangeKind } from "./index-Q5jNyQHD.mjs";
|
|
16
|
+
import { a as FirejailSandbox, c as NsjailSandboxConfig, d as SandboxStatus, f as SandboxType, i as BubblewrapSandboxConfig, l as Sandbox, n as createSandbox, o as FirejailSandboxConfig, r as BubblewrapSandbox, s as NsjailSandbox, t as SandboxCreateError, u as SandboxConfig } from "./index-CZiWvyn3.mjs";
|
|
17
|
+
import { n as spawnProcess, t as ProcessStdinError } from "./index-BimeR91j.mjs";
|
|
17
18
|
import "./schemas/index.mjs";
|
|
18
|
-
|
|
19
|
+
import { A as McpServerConfig, D as ContentPart, E as AgentCapabilities, M as agentCapabilitiesSchema, O as ImageContentPart, a as RateLimitEvent, c as SessionEndEvent, d as ToolCallEvent, f as ToolResultEvent, i as NoticeEvent, j as TextContentPart, k as JsonSchema, l as SessionStartEvent, m as eventSchema, n as MessageDeltaEvent, o as ReasoningDeltaEvent, r as MessageEvent, s as ReasoningEvent, t as AgentEvent, u as StderrEvent } from "./events-DmlAPVpd.mjs";
|
|
19
20
|
interface AgentOptionsByType {
|
|
21
|
+
"antigravity-cli": AntigravityCliAgentOptions;
|
|
20
22
|
"claude-code-cli-pty": ClaudeCodeCliPtyAgentOptions;
|
|
21
23
|
"claude-code-cli": ClaudeCodeCliAgentOptions;
|
|
22
24
|
"claude-code-sdk": ClaudeCodeSdkAgentOptions;
|
|
@@ -24,11 +26,13 @@ interface AgentOptionsByType {
|
|
|
24
26
|
"codex-sdk": CodexSdkAgentOptions;
|
|
25
27
|
"cursor-cli": CursorCliAgentOptions;
|
|
26
28
|
"cursor-sdk": CursorSdkAgentOptions;
|
|
29
|
+
"drac-cli": DracCliAgentOptions;
|
|
27
30
|
"gemini-cli": GeminiCliAgentOptions;
|
|
28
31
|
"opencode-cli": OpencodeCliAgentOptions;
|
|
29
32
|
"pi-cli": PiCliAgentOptions;
|
|
30
33
|
}
|
|
31
34
|
interface AgentInstanceByType {
|
|
35
|
+
"antigravity-cli": AntigravityCliAgent;
|
|
32
36
|
"claude-code-cli-pty": ClaudeCodeCliPtyAgent;
|
|
33
37
|
"claude-code-cli": ClaudeCodeCliAgent;
|
|
34
38
|
"claude-code-sdk": ClaudeCodeSdkAgent;
|
|
@@ -36,6 +40,7 @@ interface AgentInstanceByType {
|
|
|
36
40
|
"codex-sdk": CodexSdkAgent;
|
|
37
41
|
"cursor-cli": CursorCliAgent;
|
|
38
42
|
"cursor-sdk": CursorSdkAgent;
|
|
43
|
+
"drac-cli": DracCliAgent;
|
|
39
44
|
"gemini-cli": GeminiCliAgent;
|
|
40
45
|
"opencode-cli": OpencodeCliAgent;
|
|
41
46
|
"pi-cli": PiCliAgent;
|
|
@@ -45,8 +50,9 @@ interface AgentInstanceByType {
|
|
|
45
50
|
*
|
|
46
51
|
* The `type` literal selects the adapter and narrows `options` to that
|
|
47
52
|
* adapter's `*AgentOptions` shape and the returned agent to its instance type.
|
|
48
|
-
* Each adapter wraps a third-party coding agent (Claude Code,
|
|
49
|
-
* Gemini, OpenCode, Pi) behind a uniform `BaseAgent`
|
|
53
|
+
* Each adapter wraps a third-party coding agent (Antigravity, Claude Code,
|
|
54
|
+
* Codex, Cursor, Drac, Gemini, OpenCode, Pi) behind a uniform `BaseAgent`
|
|
55
|
+
* surface.
|
|
50
56
|
*
|
|
51
57
|
* SDK-backed adapters (`claude-code-sdk`, `codex-sdk`, `cursor-sdk`) require
|
|
52
58
|
* their respective peer package to be installed; a missing package throws
|
|
@@ -68,6 +74,7 @@ interface AgentInstanceByType {
|
|
|
68
74
|
* @returns A promise that resolves to the typed agent instance.
|
|
69
75
|
* @throws {AgentValidationError} If a required peer dependency is missing or required options are absent.
|
|
70
76
|
*/
|
|
77
|
+
export declare function createAgent(type: "antigravity-cli", options?: AntigravityCliAgentOptions): Promise<AntigravityCliAgent>;
|
|
71
78
|
export declare function createAgent(type: "claude-code-cli-pty", options?: ClaudeCodeCliPtyAgentOptions): Promise<ClaudeCodeCliPtyAgent>;
|
|
72
79
|
export declare function createAgent(type: "claude-code-cli", options?: ClaudeCodeCliAgentOptions): Promise<ClaudeCodeCliAgent>;
|
|
73
80
|
export declare function createAgent(type: "claude-code-sdk", options?: ClaudeCodeSdkAgentOptions): Promise<ClaudeCodeSdkAgent>;
|
|
@@ -75,9 +82,9 @@ export declare function createAgent(type: "codex-cli", options?: CodexCliAgentOp
|
|
|
75
82
|
export declare function createAgent(type: "codex-sdk", options?: CodexSdkAgentOptions): Promise<CodexSdkAgent>;
|
|
76
83
|
export declare function createAgent(type: "cursor-cli", options?: CursorCliAgentOptions): Promise<CursorCliAgent>;
|
|
77
84
|
export declare function createAgent(type: "cursor-sdk", options?: CursorSdkAgentOptions): Promise<CursorSdkAgent>;
|
|
85
|
+
export declare function createAgent(type: "drac-cli", options?: DracCliAgentOptions): Promise<DracCliAgent>;
|
|
78
86
|
export declare function createAgent(type: "gemini-cli", options?: GeminiCliAgentOptions): Promise<GeminiCliAgent>;
|
|
79
87
|
export declare function createAgent(type: "opencode-cli", options?: OpencodeCliAgentOptions): Promise<OpencodeCliAgent>;
|
|
80
88
|
export declare function createAgent(type: "pi-cli", options?: PiCliAgentOptions): Promise<PiCliAgent>;
|
|
81
89
|
export declare function createAgent<T extends AgentType>(type: T, options?: AgentOptionsByType[T]): Promise<AgentInstanceByType[T]>;
|
|
82
|
-
|
|
83
|
-
export { type AgentCapabilities, type AgentEvent, type AgentEventHandler, type AgentMetrics, type AgentProcess, AgentRunError, type AgentType, AgentValidationError, type AnyCompletedRunResult, type AnyRunRequest, type AnyRunResult, type BaseAgent, type BubblewrapSandbox, type BubblewrapSandboxConfig, type CancelledRunResult, type ClaudeAssistantEvent, type ClaudeCodeCliAgent, type ClaudeCodeCliAgentOptions, type ClaudeCodeCliPermissionMode, type ClaudeCodeCliPtyAgent, type ClaudeCodeCliPtyAgentOptions, type ClaudeCodeCliPtyModule, type ClaudeCodeCliPtyPermissionMode, type ClaudeCodeCliPtyProcess, type ClaudeCodeCliPtyRunOptions, type ClaudeCodeCliRunOptions, type ClaudeCodeSdkAgent, type ClaudeCodeSdkAgentOptions, type ClaudeCodeSdkEvent, type ClaudeCodeSdkExecutable, type ClaudeCodeSdkPermissionMode, type ClaudeCodeSdkRunOptions, type ClaudeCodeSdkSettingSource, type ClaudeCodeSdkSettings, type ClaudeEvent, type ClaudeProviderEvent, type ClaudeRateLimitEvent, type ClaudeResultEvent, type ClaudeSystemEvent, type ClaudeUserEvent, type CodexCliAgent, type CodexCliAgentOptions, type CodexCliPermissionMode, type CodexCliRunOptions, type CodexCliSandboxMode, type CodexErrorEvent, type CodexEvent, type CodexItemCompletedEvent, type CodexItemStartedEvent, type CodexItemUpdatedEvent, type CodexProviderEvent, type CodexProviderItem, type CodexSdkAgent, type CodexSdkAgentOptions, type CodexSdkEvent, type CodexSdkItem, type CodexSdkPermissionMode, type CodexSdkRunOptions, type CodexThreadStartedEvent, type CodexTurnCompletedEvent, type CodexTurnFailedEvent, type CompletedRunResult, type Container, type ContainerConfig, ContainerCreateError, ContainerDiffError, ContainerDisposedError, ContainerError, ContainerExecError, ContainerNotRunningError, ContainerStartError, type ContainerStatus, type ContainerType, type ContentPart, type CursorCliAgent, type CursorCliAgentOptions, type CursorCliEvent, type CursorCliPermissionMode, type CursorCliRunOptions, type CursorCliSandboxMode, type CursorSdkAgent, type CursorSdkAgentOptions, type CursorSdkEvent, type CursorSdkMcpHttpAuth, type CursorSdkMcpServerConfig, type CursorSdkRunOptions, type CursorSdkSettingSource, type DockerContainer, type DockerContainerConfig, type E2BConnectConfig, type E2BConnectionConfig, type E2BContainer, type E2BContainerConfig, type E2BCreateConfig, type E2BProviderConfig, type ExecOptions, type ExecResult, type FailedRunResult, type FirejailSandbox, type FirejailSandboxConfig, type GeminiCliAgent, type GeminiCliAgentOptions, type GeminiCliPermissionMode, type GeminiCliRunOptions, type GeminiEvent, type ImageContentPart, type JsonSchema, type JsonSchemaRunRequest, type McpServerConfig, type MessageEvent, MountValidationError, type NerdctlContainer, type NerdctlContainerConfig, type NerdctlProviderConfig, type NsjailSandbox, type NsjailSandboxConfig, type OpencodeCliAgent, type OpencodeCliAgentOptions, type OpencodeCliRunOptions, type OpencodeEvent, type PermissionDecision, type PermissionHandler, type PermissionRequest, type PiCliAgent, type PiCliAgentOptions, type PiCliRunOptions, type PiCliThinkingLevel, type PiEvent, type PodmanContainer, type PodmanContainerConfig, type PortMapping, type ProcessResult, type ProcessSignal, type ProcessSpawner, ProcessStdinError, type ProviderEvent, type ProviderEventHandler, type ReasoningEvent, type RunError, type RunProcessInfo, type RunRequest, type RunResult, type RunStats, type RunStatus, type RunTiming, type Sandbox, type SandboxConfig, SandboxCreateError, type SandboxStatus, type SandboxType, type SessionEndEvent, type SessionStartEvent, type SpawnOptions, type StderrEvent, type StopReason, type StructuredRunRequest, type TextContentPart, type ToolCallEvent, type ToolResultEvent, type VolumeMount, type WorkdirChangeKind, type WorkdirDiff, type WorkdirDiffStats, type WorkdirFileChange, type WorkdirSnapshot, type WorkdirSnapshotOptions, type ZodRunRequest, agentCapabilitiesSchema, createContainer, createSandbox, eventSchema, spawnProcess };
|
|
90
|
+
export { type AgentCapabilities, type AgentEvent, type AgentEventHandler, type AgentMetrics, type AgentProcess, AgentRunError, type AgentType, AgentValidationError, type AntigravityCliAgent, type AntigravityCliAgentOptions, type AntigravityCliRunOptions, type AntigravityMode, type AntigravityProviderEvent, type AntigravityThoughtLevel, type AnyCompletedRunResult, type AnyRunRequest, type AnyRunResult, type AttachedDockerContainer, type AttachedPodmanContainer, type BaseAgent, type BubblewrapSandbox, type BubblewrapSandboxConfig, type CancelledRunResult, type ClaudeAgentRun, type ClaudeAssistantEvent, type ClaudeBackgroundSubagent, type ClaudeBackgroundTask, type ClaudeBackgroundTaskChange, type ClaudeBackgroundTaskEnd, type ClaudeBackgroundTaskProgress, type ClaudeBackgroundTaskStatus, type ClaudeBackgroundTaskUsage, type ClaudeCodeCliAgent, type ClaudeCodeCliAgentOptions, type ClaudeCodeCliPermissionMode, type ClaudeCodeCliPtyAgent, type ClaudeCodeCliPtyAgentOptions, type ClaudeCodeCliPtyModule, type ClaudeCodeCliPtyPermissionMode, type ClaudeCodeCliPtyProcess, type ClaudeCodeCliPtyRunOptions, type ClaudeCodeCliRunOptions, type ClaudeCodeSdkAgent, type ClaudeCodeSdkAgentOptions, type ClaudeCodeSdkEvent, type ClaudeCodeSdkExecutable, type ClaudeCodeSdkPermissionMode, type ClaudeCodeSdkRunOptions, type ClaudeCodeSdkSettingSource, type ClaudeCodeSdkSettings, ClaudeControlRequestError, type ClaudeControlRequestFailure, type ClaudeControlRequestPayload, type ClaudeEvent, type ClaudePermissionMode, type ClaudeProviderEvent, type ClaudeRateLimitEvent, type ClaudeResultEvent, type ClaudeSystemEvent, type ClaudeUserEvent, type CodexCliAgent, type CodexCliAgentOptions, type CodexCliPermissionMode, type CodexCliRunOptions, type CodexCliSandboxMode, type CodexErrorEvent, type CodexEvent, type CodexItemCompletedEvent, type CodexItemStartedEvent, type CodexItemUpdatedEvent, type CodexProviderEvent, type CodexProviderItem, type CodexSdkAgent, type CodexSdkAgentOptions, type CodexSdkEvent, type CodexSdkItem, type CodexSdkPermissionMode, type CodexSdkRunOptions, type CodexThreadStartedEvent, type CodexTurnCompletedEvent, type CodexTurnFailedEvent, type CompletedRunResult, type Container, ContainerAttachError, type ContainerConfig, ContainerCreateError, ContainerDiffError, ContainerDisposedError, ContainerError, ContainerExecError, ContainerNotFoundError, ContainerNotRunningError, ContainerRemoveError, ContainerStartError, type ContainerStatus, type ContainerType, type ContentPart, type CursorCliAgent, type CursorCliAgentOptions, type CursorCliEvent, type CursorCliPermissionMode, type CursorCliRunOptions, type CursorCliSandboxMode, type CursorSdkAgent, type CursorSdkAgentOptions, type CursorSdkEvent, type CursorSdkMcpHttpAuth, type CursorSdkMcpServerConfig, type CursorSdkRunOptions, type CursorSdkSettingSource, type DockerAttachConfig, type DockerContainer, type DockerContainerConfig, type DracCliAgent, type DracCliAgentOptions, type DracCliRunOptions, type DracPermissionMode, type E2BConnectConfig, type E2BConnectionConfig, type E2BContainer, type E2BContainerConfig, type E2BCreateConfig, type E2BProviderConfig, type ExecOptions, type ExecResult, type FailedRunResult, type FirejailSandbox, type FirejailSandboxConfig, type GeminiCliAgent, type GeminiCliAgentOptions, type GeminiCliPermissionMode, type GeminiCliRunOptions, type GeminiEvent, type ImageContentPart, type JsonSchema, type JsonSchemaRunRequest, type McpServerConfig, type MessageDeltaEvent, type MessageEvent, MountValidationError, type NerdctlContainer, type NerdctlContainerConfig, type NerdctlProviderConfig, type NoticeEvent, type NsjailSandbox, type NsjailSandboxConfig, type OpencodeCliAgent, type OpencodeCliAgentOptions, type OpencodeCliRunOptions, type OpencodeEvent, type PermissionDecision, type PermissionHandler, type PermissionRequest, type PiCliAgent, type PiCliAgentOptions, type PiCliRunOptions, type PiCliThinkingLevel, type PiEvent, type PodmanAttachConfig, type PodmanContainer, type PodmanContainerConfig, type PortMapping, type ProcessResult, type ProcessSignal, type ProcessSpawner, ProcessStdinError, type ProviderEvent, type ProviderEventHandler, type Question, type QuestionAnswers, type QuestionHandler, type QuestionOption, type QuestionRequest, type RateLimitEvent, type ReasoningDeltaEvent, type ReasoningEvent, type RunError, type RunProcessInfo, type RunRequest, type RunResult, type RunStats, type RunStatus, type RunTiming, type Sandbox, type SandboxConfig, SandboxCreateError, type SandboxStatus, type SandboxType, type SessionEndEvent, type SessionStartEvent, type SpawnOptions, type StderrEvent, type StopReason, type StructuredRunRequest, type TextContentPart, type ToolCallEvent, type ToolResultEvent, type VolumeMount, type WorkdirChangeKind, type WorkdirDiff, type WorkdirDiffStats, type WorkdirFileChange, type WorkdirSnapshot, type WorkdirSnapshotOptions, type ZodRunRequest, agentCapabilitiesSchema, attachContainer, createContainer, createSandbox, eventSchema, spawnProcess };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e,t}from"./types-B72tDMEZ.mjs";import{a as n,c as r,i,
|
|
1
|
+
import{n as e,t}from"./types-B72tDMEZ.mjs";import{a as n,c as r,d as i,f as a,i as o,l as s,n as c,o as l,p as u,r as d,s as f,t as p,u as m}from"./container-DUoj_mnh.mjs";import{n as h,t as g}from"./sandbox-BemAIoIo.mjs";import{n as _}from"./spawner-CYAQQABs.mjs";import{t as v}from"./errors-BauhTL3l.mjs";import"./core/process/index.mjs";import{t as y}from"./control-requests-DtjV0e4o.mjs";import{m as b,n as x}from"./schemas-CzJM9p-0.mjs";const S=(e,t)=>{if(!(e instanceof Error)||!e.message.includes(t))return!1;let n=typeof e==`object`&&e&&`code`in e?e.code:void 0;return n===`ERR_MODULE_NOT_FOUND`||n===`MODULE_NOT_FOUND`},C=(t,n,r)=>{throw S(r,n)?new e(`Agent type "${t}" requires the optional peer dependency "${n}". Install it to use this adapter.`):r};async function w(t,n){switch(t){case`antigravity-cli`:{let{createAntigravityCliAgent:e}=await import(`./adapters/antigravity-cli/index.mjs`);return e(n)}case`claude-code-cli-pty`:{let{createClaudeCodeCliPtyAgent:e}=await import(`./adapters/claude-code-cli-pty/index.mjs`);return e(n)}case`claude-code-cli`:{let{createClaudeCodeCliAgent:e}=await import(`./adapters/claude-code-cli/index.mjs`);return e(n)}case`claude-code-sdk`:{let e=n;try{let{createClaudeCodeSdkAgent:t}=await import(`./adapters/claude-code-sdk/index.mjs`);return t(e)}catch(e){return C(`claude-code-sdk`,`@anthropic-ai/claude-agent-sdk`,e)}}case`codex-cli`:{let{createCodexCliAgent:e}=await import(`./adapters/codex-cli/index.mjs`);return e(n)}case`codex-sdk`:{let e=n;try{let{createCodexSdkAgent:t}=await import(`./adapters/codex-sdk/index.mjs`);return t(e)}catch(e){return C(`codex-sdk`,`@openai/codex-sdk`,e)}}case`cursor-cli`:{let{createCursorCliAgent:e}=await import(`./adapters/cursor-cli/index.mjs`);return e(n)}case`cursor-sdk`:{let e=n;try{let{createCursorSdkAgent:t}=await import(`./adapters/cursor-sdk/index.mjs`);return t(e)}catch(e){return C(`cursor-sdk`,`@cursor/sdk`,e)}}case`drac-cli`:{let{createDracCliAgent:e}=await import(`./adapters/drac-cli/index.mjs`);return e(n)}case`gemini-cli`:{let{createGeminiCliAgent:e}=await import(`./adapters/gemini-cli/index.mjs`);return e(n)}case`opencode-cli`:{let{createOpencodeCliAgent:e}=await import(`./adapters/opencode-cli/index.mjs`);return e(n)}case`pi-cli`:{let{createPiCliAgent:e}=await import(`./adapters/pi-cli/index.mjs`);return e(n)}default:throw new e(`Unsupported agent type.`)}}export{t as AgentRunError,e as AgentValidationError,y as ClaudeControlRequestError,d as ContainerAttachError,o as ContainerCreateError,n as ContainerDiffError,l as ContainerDisposedError,f as ContainerError,r as ContainerExecError,s as ContainerNotFoundError,m as ContainerNotRunningError,i as ContainerRemoveError,a as ContainerStartError,u as MountValidationError,v as ProcessStdinError,g as SandboxCreateError,b as agentCapabilitiesSchema,p as attachContainer,w as createAgent,c as createContainer,h as createSandbox,x as eventSchema,_ as spawnProcess};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{t as e}from"./util-CCXryPDO.mjs";import{n as t}from"./env-Cb8MIvH7.mjs";import{n}from"./errors-BauhTL3l.mjs";import{t as r}from"./shell-DvWFuFKb.mjs";import{t as i}from"./spawner-CYAQQABs.mjs";import{n as a,t as o}from"./diff-CMWH9a0d.mjs";import{a as s,c,d as l,f as u,i as d,l as f,o as p,p as m,r as h,u as g}from"./container-DUoj_mnh.mjs";import{execFile as _}from"node:child_process";import{isAbsolute as v,join as y,posix as b,resolve as x}from"node:path";import{promisify as S}from"node:util";import{existsSync as C,mkdtempSync as w,rmSync as T,writeFileSync as E}from"node:fs";import{tmpdir as D}from"node:os";import{mkdtemp as O,rm as k,writeFile as A}from"node:fs/promises";import{randomBytes as j}from"node:crypto";const M=/[\s=\0]/,N=/[\r\n\0]/,P=65536,F=`\\t\\n\\v\\f\\r \\u0085\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000`,I=RegExp(`^[${F}]|[${F}]$`),L=(e,t)=>{for(let[n,r]of e){if(n===``||n.startsWith(`#`)||M.test(n))return`The environment variable name ${JSON.stringify(n)} cannot be passed to the container engine.`;if(N.test(r))return`The value of the environment variable ${n} contains a line break or a NUL character, which the container engine cannot receive.`;let e=`${n}=${r}`,i=Buffer.byteLength(`${e}\n`);if(i>P){let e=Buffer.byteLength(r);return`The value of the environment variable ${n} is ${e} bytes, more than the ${e-(i-P)} bytes the container engine can receive for it.`}if(t===`nerdctl`&&I.test(e))return`The environment variable ${n} has whitespace at the start of its name or the end of its value, which nerdctl removes.`}},R=(e,t,n)=>{let r=Object.entries(e??{});if(r.length===0)return;let i=L(r,t);if(i!==void 0)throw n(i);let a=w(y(D(),`cw-oci-env-`)),o=y(a,`env`);try{E(o,r.map(([e,t])=>`${e}=${t}\n`).join(``),{mode:384})}catch(e){throw T(a,{recursive:!0,force:!0}),e}return{path:o,remove:()=>T(a,{recursive:!0,force:!0})}},z=(e,t)=>{let n=b.relative(e,t);return n===``||!n.startsWith(`..`)&&!b.isAbsolute(n)},B=(e,t)=>{if(!e||e.length===0)return;let n=b.normalize(t),r;for(let t of e){if(!v(t.source))continue;let e=b.normalize(t.target);z(e,n)&&(!r||e.length>b.normalize(r.target).length)&&(r=t)}if(!r)return;let i=b.relative(b.normalize(r.target),n);return i===``?r.source:b.join(r.source,...i.split(`/`))},V=(e,t)=>{let n=v(e.source)?e.source:x(t.cwd,e.source);if(!C(n))throw new m(`Mount source does not exist: ${n}`);return{...e,source:n}},H=S(_),U=()=>`cw-${j(6).toString(`hex`)}`,W=(e,t)=>e.baseArgs?[...e.baseArgs,...t]:t,G=e=>{if(e.env)return{...t(),...e.env}},K=async(e,t,n)=>{let r=await H(e.binary,W(e,t),{encoding:`utf8`,env:G(e),timeout:n?.timeoutMs,signal:n?.signal,maxBuffer:52428800});return{stdout:r.stdout,stderr:r.stderr}},q=e=>e===`running`?`running`:e===`created`?`created`:`stopped`,J=async(t,n)=>{let r=n.tag??`cw-build-${j(4).toString(`hex`)}`,i=[`build`,`-t`,r];if(n.args)for(let[e,t]of Object.entries(n.args))i.push(`--build-arg`,`${e}=${t}`);`dockerfile`in n&&n.dockerfile&&(i.push(`-f`,n.dockerfile),i.push(n.context??`.`));let a;if(`content`in n&&n.content){a=await O(y(D(),`cw-oci-build-`));let e=y(a,`Dockerfile`);await A(e,n.content,{encoding:`utf8`,mode:384}),i.push(`-f`,e),i.push(n.context??a)}try{await K(t,i)}catch(t){throw new d(`Image build failed: ${e(t)}`)}finally{a&&await k(a,{recursive:!0,force:!0}).catch(()=>{})}return r},Y=async(e,t,n)=>{let r=await Promise.all(n.map(async n=>{try{let{container:r,protocol:i=`tcp`}=n,{stdout:a}=await K(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},X=(e,t,n)=>({spawn:(r,a,o={})=>{let s=[`exec`,`-i`];o.cwd&&s.push(`-w`,o.cwd);let l=R(o.env,e,e=>new c(e));l&&s.push(`--env-file`,l.path),s.push(t,r,...a);let u;try{u=i.spawn(n.binary,W(n,s),{env:G(n),stdio:o.stdio})}catch(e){throw l?.remove(),e}if(l===void 0)return u;let d=u.wait().finally(l.remove);return{...u,wait:()=>d}}}),Z=async(e,t,n)=>{try{await K(e,[`stop`,`-t`,`0`,t])}catch{}let r=n.anonymousVolumes===`remove`?[`-v`]:[];await K(e,[`rm`,`-f`,...r,t])},Q=async(t,n,r)=>{let{commandContext:i,builtImage:a,containerName:o,workdir:s,user:c,network:l,platform:u,env:f,ports:p,mounts:m,mountCwd:h,extraArgs:g,image:_}=n,v=o??U(),y=m?.map(e=>V(e,{cwd:h??process.cwd()})),b=[`create`,`--name`,v];if(c&&b.push(`--user`,c),l&&b.push(`--network`,l),u&&b.push(`--platform`,u),p)for(let e of p){let{host:t,container:n,protocol:r=`tcp`}=e;b.push(`-p`,`${t??``}:${n}/${r}`)}if(y)for(let e of y){let{readonly:t,source:n,target:r}=e,i=t?`ro`:`rw`;b.push(`-v`,`${n}:${r}:${i}`)}g&&b.push(...g);let x=R(f,t,e=>new d(e));x&&b.push(`--env-file`,x.path),b.push(_,`sleep`,`infinity`);let S;try{let{stdout:e}=await K(i,b);S=e.trim()}catch(t){throw new d(`Container create failed: ${e(t)}`)}finally{x?.remove()}return $(t,{commandContext:i,containerId:S,containerName:v,status:`created`,workdir:s,user:c,ports:p,normalizedMounts:y,removeOnDispose:async()=>{try{await Z(i,S,{anonymousVolumes:`keep`})}catch{}a&&await K(i,[`rmi`,_]).catch(()=>{})}},r)},$=(t,l,d)=>{let{commandContext:f,containerId:m,containerName:h,workdir:_,user:v,ports:y,normalizedMounts:x,removeOnDispose:S}=l,C=l.status,w=/* @__PURE__ */ new Map,T=()=>{if(C===`disposed`)throw new p},E=()=>{if(T(),C!==`running`)throw new g},D=X(t,m,f),O=a({owner:{},workdir:_,materialize:async(t,n)=>{T();let i=B(x,t);if(i)await o(i,n);else{E();try{await K(f,[`exec`,m,`sh`,`-c`,`test -d ${r(t)}`])}catch{throw new s(`Target path is not a directory: ${t}`)}try{await K(f,[`cp`,`${m}:${t}/.`,n])}catch(n){throw new s(`Failed to materialize container path ${t}: ${e(n)}`)}}}}),k={get type(){return t},get id(){return m},get name(){return h},get config(){return d},get status(){return C},get workdir(){return _},get spawner(){return D},async start(){if(T(),C!==`running`){try{await K(f,[`start`,m])}catch(t){throw new u(`Container start failed: ${e(t)}`)}try{await K(f,[`exec`,m,`mkdir`,`-p`,_])}catch(t){try{await K(f,[`stop`,`-t`,`0`,m]),C=`stopped`}catch{try{let{stdout:e}=await K(f,[`inspect`,`--format`,`{{.State.Status}}`,m]);C=e.trim()===`running`?`running`:`stopped`}catch{C=`disposed`}}throw new u(`Container start failed: ${e(t)}`)}C=`running`,y?.length&&(w=await Y(f,m,y))}},async stop(){if(T(),C===`running`){try{await K(f,[`stop`,`-t`,`2`,m])}catch{try{let{stdout:e}=await K(f,[`inspect`,`--format`,`{{.State.Status}}`,m]);if(e.trim()===`running`)return}catch{C=`disposed`;return}}C=`stopped`}},async dispose(){C!==`disposed`&&(await S?.(),await O.disposeSnapshots().catch(()=>{}),C=`disposed`)},async exec(e,r,i={}){E();let a=[`exec`];i.cwd&&a.push(`-w`,i.cwd);let o=R(i.env,t,e=>new c(e));o&&a.push(`--env-file`,o.path),a.push(m,e,...r);try{let{stdout:e,stderr:t}=await K(f,a,{timeoutMs:i.timeoutMs,signal:i.signal});return{exitCode:0,stdout:e,stderr:t}}catch(e){if(n(e))return{exitCode:typeof e.code==`number`?e.code:-1,stdout:String(e.stdout??``),stderr:String(e.stderr??``)};throw e}finally{o?.remove()}},async copyTo(e,t){E(),await K(f,[`cp`,e,`${m}:${t}`])},async copyFrom(e,t){E(),await K(f,[`cp`,`${m}:${e}`,t])},async writeFile(t,n){E();let a=b.isAbsolute(t)?t:b.resolve(_,t),o=b.dirname(a),s=typeof n==`string`?Buffer.from(n,`utf8`):n,l=[`exec`,`-i`];v&&l.push(`--user`,v),l.push(m,`sh`,`-c`,`mkdir -p ${r(o)} && cat > ${r(a)}`);let u=i.spawn(f.binary,W(f,l),{env:G(f),stdio:[`pipe`,`ignore`,`ignore`]}),d;try{u.stdin?.write?.(s),u.stdin?.end(),d=await u.wait()}catch(t){throw u.kill(),u.wait().catch(()=>{}),new c(`writeFile failed for ${a}: ${e(t)}`)}if(d.exitCode!==0)throw new c(`writeFile failed for ${a} (exit ${d.exitCode})`)},async readFile(e){E();let t=b.isAbsolute(e)?e:b.resolve(_,e),{stdout:n}=await K(f,[`exec`,m,`cat`,t]);return n},async fileExists(e){E();let t=b.isAbsolute(e)?e:b.resolve(_,e);try{return await K(f,[`exec`,m,`test`,`-e`,t]),!0}catch{return!1}},async mkdir(e){E();let t=b.isAbsolute(e)?e:b.resolve(_,e);await K(f,[`exec`,m,`mkdir`,`-p`,t])},async execShell(e,t={}){return k.exec(`sh`,[`-c`,e],t)},async logs(e={}){T();let t=[`logs`];e.tail!==void 0&&t.push(`--tail`,String(e.tail)),t.push(m);let{stdout:n}=await K(f,t);return n},async syncStatus(){T();try{let{stdout:e}=await K(f,[`inspect`,`--format`,`{{.State.Status}}`,m]);C=q(e.trim())}catch{C=`disposed`}return C},async snapshotWorkdir(e={}){return O.snapshotWorkdir(e)},async diffWorkdir(e){return O.diffWorkdir(e)},async releaseWorkdirSnapshot(e){return O.releaseWorkdirSnapshot(e)},getMappedPort(e){return w.get(e)},[Symbol.asyncDispose](){return k.dispose()}};return k},ee=async(e,t)=>{let{stdout:n}=await K(e,[`ps`,`--all`,`--no-trunc`,`--format`,`{{.ID}} {{.Names}}`]);return n.split(`
|
|
2
|
+
`).some(e=>{let[n=``,r=``]=e.split(` `);return n.startsWith(t)||r.split(`,`).includes(t)})},te=async(e,t)=>{let n;try{({stdout:n}=await K(e,[`inspect`,`--type`,`container`,`--format`,`{{.Id}} {{.Name}} {{.State.Status}}`,`--`,t]))}catch(n){throw await ee(e,t)?n:new f(`Container not found: ${t}`)}let[r,i,a]=n.trim().split(` `);if(!r||!i||!a)throw Error(`Unexpected inspect output: ${n.trim()}`);return{containerId:r,containerName:i.replace(/^\//,``),status:q(a)}},ne=async(t,n)=>{try{let r=await te(t,n.containerId),i=$(n.type,{commandContext:t,...r,workdir:n.workdir},n);return i.status===`running`&&await i.mkdir(n.workdir),Object.assign(i,{async remove(){try{await Z(t,r.containerId,{anonymousVolumes:`remove`})}catch(t){throw new l(`Container remove failed: ${e(t)}`)}await i.dispose()}})}catch(t){throw t instanceof f?t:new h(`Container attach failed: ${e(t)}`)}},re=async(e,t)=>{if(t.image)return t.image;if(t.build)return J(e,t.build);throw new d(`Either image or build must be provided.`)};export{Q as n,re as r,ne as t};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{l as e,p as t,u as n}from"./classify-error-_WNZMhMY.mjs";import{a as r,i,o as a,s as o}from"./permission-updates-CkFvevWQ.mjs";import{z as s}from"zod/v4";const c=e=>`session_id`in e?e.session_id:void 0,l=e=>typeof e.content==`string`?e.content:e.content.map(e=>e.text).join(`
|
|
2
|
+
`),u=e=>typeof e.result==`string`&&e.result.trim()!==``?e.result:e.subtype,d=e=>{switch(e.subtype){case`init`:{let t=[`[init]`];if(e.tools&&t.push(`tools: ${e.tools.length}`),e.mcp_servers){let n=e.mcp_servers.filter(e=>e.status===`connected`).length;t.push(`mcp: ${n}/${e.mcp_servers.length} connected`)}return t.join(` `)}case`hook_response`:case`hook_started`:case`hook_finished`:case`hook_failed`:case`hook_skipped`:{let t=[`[${e.subtype}]`];return e.hook_name&&(t.push(e.hook_name),e.exit_code!==void 0&&t.push(`exit: ${e.exit_code}`)),t.join(` `)}case`session_state_changed`:case`task_started`:case`task_progress`:return;default:throw Error(`Unhandled Claude system event subtype: ${e.subtype}`)}},f=(n,i)=>{let a=r(i.runId,i.sessionId,n),o=d(n);return o===void 0?{events:a}:{events:[e(i.runId,`message`,{sessionId:i.sessionId,model:n.model??null,role:`system`,content:[t(o)],text:o}),...a]}},p=(n,r,i)=>{let a=[],o=[],s=n.parent_tool_use_id??void 0;for(let c of n.message.content)switch(c.type){case`text`:{let o=i?.takeReservedEventId(`message`,n.message.id,s);a.push(e(r.runId,`message`,{...o===void 0?{}:{id:o},sessionId:r.sessionId,parentToolCallId:s,model:n.message.model??null,role:`assistant`,content:[t(c.text)],text:c.text}));break}case`thinking`:{let o=i?.takeReservedEventId(`reasoning`,n.message.id,s);a.push(e(r.runId,`reasoning`,{...o===void 0?{}:{id:o},sessionId:r.sessionId,parentToolCallId:s,model:n.message.model??null,content:[t(c.thinking)],text:c.thinking}));break}case`tool_use`:o.push({toolCallId:c.id,toolName:c.name,input:c.input}),a.push(e(r.runId,`tool-call`,{sessionId:r.sessionId,parentToolCallId:s,model:n.message.model??null,toolCallId:c.id,toolName:c.name,input:c.input}))}return{events:a,toolCalls:o}},m=(n,r)=>{let i=[],a=n.parent_tool_use_id??void 0;for(let o of n.message.content)switch(o.type){case`text`:i.push(e(r.runId,`message`,{sessionId:r.sessionId,parentToolCallId:a,model:null,role:`user`,content:[t(o.text)],text:o.text}));break;case`tool_result`:{let t=r.toolCalls.get(o.tool_use_id),n=l(o);i.push(e(r.runId,`tool-result`,{sessionId:r.sessionId,parentToolCallId:a,toolCallId:o.tool_use_id,toolName:t?.toolName,input:t?.input,output:n,isError:o.is_error,error:o.is_error?n:void 0}));break}}return{events:i}},h=(e,t,n)=>{let r={stats:(n??new a(t)).addResult(e)};typeof e.result==`string`&&(r.output={...r.output,text:e.result});let i=!e.is_error&&e.subtype===`success`,s=o(e.structured_output,{schemaRequested:t.schemaRequested,toolCalls:t.toolCalls,allowToolCallFallback:!1},{isSuccess:i},`Structured output was requested but Claude did not return structured_output.`);return s.value!==void 0&&(r.output={...r.output,value:s.value}),s.error&&(r.status=`failed`,r.error=s.error),e.is_error||e.subtype!==`success`?(r.status=`failed`,r.error={kind:`provider`,message:u(e)}):r.error||=(r.status=`completed`,void 0),{events:[],state:r}},g=(e,t,n={})=>{switch(e.type){case`system`:return f(e,t);case`assistant`:return n.statsAccumulator?.recordMessageModel(e.message.model),p(e,t,n.textStream);case`user`:return m(e,t);case`result`:return h(e,t,n.statsAccumulator);case`rate_limit_event`:return{events:i(t.runId,t.sessionId,e.rate_limit_info)};default:return{events:[]}}},_=s.enum([`init`,`hook_response`,`hook_started`,`hook_finished`,`hook_failed`,`hook_skipped`,`session_state_changed`,`task_started`,`task_progress`]),v=s.enum([`idle`,`running`,`requires_action`]),y=s.object({name:s.string(),status:s.string()}),b=s.object({type:s.literal(`system`),session_id:s.string(),subtype:_,uuid:s.string(),tools:s.array(s.string()).optional(),mcp_servers:s.array(y).optional(),model:s.string().optional(),cwd:s.string().optional(),hook_name:s.string().optional(),hook_event:s.string().optional(),stdout:s.string().optional(),stderr:s.string().optional(),exit_code:s.number().optional(),outcome:s.string().optional(),state:v.optional(),task_id:s.string().optional(),tool_use_id:s.string().optional()}),x=s.looseObject({type:s.literal(`system`),subtype:s.string().refine(e=>!_.safeParse(e).success)}),S=s.object({type:s.literal(`assistant`),session_id:s.string(),uuid:s.string(),parent_tool_use_id:s.string().nullable().optional(),message:s.object({id:s.string(),type:s.literal(`message`),role:s.literal(`assistant`),model:s.string(),content:s.array(s.union([s.object({type:s.literal(`text`),text:s.string()}),s.object({type:s.literal(`tool_use`),id:s.string(),name:s.string(),input:s.record(s.string(),s.unknown())}),s.object({type:s.literal(`thinking`),thinking:s.string(),signature:s.string().optional()})])),stop_reason:s.enum([`end_turn`,`max_tokens`,`tool_use`,`stop_sequence`]).nullable(),stop_sequence:s.string().nullable().optional(),context_management:s.unknown().nullable().optional(),usage:s.object({input_tokens:s.number(),output_tokens:s.number(),cache_creation_input_tokens:s.number().optional(),cache_read_input_tokens:s.number().optional(),service_tier:s.enum([`premium`,`standard`]).nullable().optional()}),ttftMs:s.number().optional()})}),C=s.object({type:s.literal(`user`),session_id:s.string(),message:s.object({role:s.literal(`user`),content:s.array(s.union([s.object({type:s.literal(`tool_result`),tool_use_id:s.string(),content:s.union([s.string(),s.array(s.object({type:s.literal(`text`),text:s.string()}))]),is_error:s.boolean().optional()}),s.object({type:s.literal(`text`),text:s.string()})]))}),parent_tool_use_id:s.string().nullable().optional(),uuid:s.string(),isSynthetic:s.boolean().optional()}),w=s.object({type:s.literal(`result`),session_id:s.string(),uuid:s.string(),subtype:s.enum([`success`,`error_max_turns`,`error_during_execution`,`error_max_budget_usd`,`error_max_structured_output_retries`]),duration_ms:s.number(),duration_api_ms:s.number(),is_error:s.boolean(),num_turns:s.number(),result:s.unknown().optional(),structured_output:s.unknown().optional(),total_cost_usd:s.number(),usage:s.object({input_tokens:s.number(),cache_creation_input_tokens:s.number().optional(),cache_read_input_tokens:s.number().optional(),output_tokens:s.number(),server_tool_use:s.object({web_search_requests:s.number()}).optional()}).optional(),modelUsage:s.record(s.string(),s.object({inputTokens:s.number(),outputTokens:s.number(),cacheReadInputTokens:s.number(),cacheCreationInputTokens:s.number()})).optional()}),T=s.discriminatedUnion(`type`,[w.pick({type:!0}).extend({user_message_uuids:s.array(s.string()).optional()}),s.object({type:s.literal(`system`),subtype:s.literal(`session_state_changed`),state:v})]),E=s.looseObject({type:s.literal(`command_lifecycle`)}),D=s.looseObject({type:s.literal(`system`),subtype:s.literal(`task_started`),task_id:s.string(),tool_use_id:s.string().optional(),description:s.string(),is_backgrounded:s.boolean().optional(),task_type:s.string().optional(),subagent_type:s.string().optional(),parent_task_id:s.string().optional()}),O=s.looseObject({type:s.enum([`assistant`,`user`,`stream_event`]),parent_tool_use_id:s.null().optional()}),k=s.looseObject({total_tokens:s.number(),tool_uses:s.number()}),A=s.looseObject({type:s.literal(`system`),subtype:s.literal(`task_progress`),task_id:s.string(),usage:k,last_tool_name:s.string().optional(),summary:s.string().optional()}),j=s.looseObject({type:s.literal(`system`),subtype:s.literal(`task_notification`),task_id:s.string(),status:s.string(),summary:s.string().optional(),usage:k.optional()}),M=s.object({type:s.literal(`rate_limit_event`),uuid:s.string(),session_id:s.string().optional(),rate_limit_info:s.object({status:s.string(),resetsAt:s.number().optional(),rateLimitType:s.string().optional(),utilization:s.number().optional(),overageStatus:s.string().optional(),overageDisabledReason:s.string().optional(),isUsingOverage:s.boolean().optional(),unifiedWindows:s.record(s.string(),s.object({utilization:s.number().optional()})).optional()})}),N=s.discriminatedUnion(`type`,[b,S,C,w,M]),P=s.discriminatedUnion(`type`,[b.extend({subtype:s.string(),uuid:s.string().optional(),mcp_servers:s.array(y.loose()).optional()}).loose(),S.extend({uuid:s.string().optional()}),C.extend({uuid:s.string().optional()}),w.extend({uuid:s.string().optional(),subtype:s.string()}),M]),F=s.object({type:s.literal(`stream_event`),session_id:s.string(),parent_tool_use_id:s.string().nullable().optional(),event:s.looseObject({type:s.string()})}),I=s.object({message:s.object({id:s.string()})}),L=s.object({index:s.number(),delta:s.looseObject({type:s.string()})}),R=s.object({text:s.string()}),z=s.object({thinking:s.string()}),B=s.object({subtype:s.literal(`can_use_tool`),tool_name:s.string(),input:s.record(s.string(),s.unknown()),tool_use_id:s.string(),decision_reason:s.string().optional(),blocked_path:s.string().optional(),title:s.string().optional(),description:s.string().optional()}),V=s.discriminatedUnion(`type`,[s.object({type:s.literal(`control_request`),request_id:s.string(),request:s.looseObject({subtype:s.string()})}),s.looseObject({type:s.literal(`control_response`)}),s.looseObject({type:s.literal(`control_cancel_request`),request_id:s.string()})]),H=s.object({type:s.literal(`control_response`),response:s.discriminatedUnion(`subtype`,[s.object({subtype:s.literal(`success`),request_id:s.string(),response:s.unknown().optional()}),s.object({subtype:s.literal(`error`),request_id:s.string(),error:s.string()})])}),U=n(N);export{x as _,V as a,P as c,j as d,A as f,O as g,z as h,L as i,T as l,R as m,B as n,H as o,D as p,E as r,I as s,U as t,F as u,c as v,g as y};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{i as e}from"./util-CCXryPDO.mjs";import{l as t,p as n}from"./classify-error-_WNZMhMY.mjs";const r=`SendUserMessage`,i=e=>e?.includes(r)?[...e]:[...e??[],r],a=e=>{let t;for(let[,n]of e)n.toolName===`StructuredOutput`&&n.input!==void 0&&(t=n.input);return t},o=(e,t,n,r)=>{if(e!=null)return{value:e};if(!t.schemaRequested)return{};if(t.allowToolCallFallback??!0){let e=a(t.toolCalls);if(e!==void 0)return{value:e}}return n.isSuccess?{error:{kind:`parse`,message:r}}:{}},s=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)}},c=e=>e.inputTokens+e.cacheCreationInputTokens+e.cacheReadInputTokens+e.outputTokens,l=(e,t)=>e>=t?e-t:e,u=(e,t)=>({inputTokens:l(e.inputTokens,t?.inputTokens??0),cacheCreationInputTokens:l(e.cacheCreationInputTokens,t?.cacheCreationInputTokens??0),cacheReadInputTokens:l(e.cacheReadInputTokens,t?.cacheReadInputTokens??0),outputTokens:l(e.outputTokens,t?.outputTokens??0)});var d=class{canUseModelUsage;restoredTotals;latestResult;durationMs=0;turns=0;inputTokens;cacheCreationInputTokens;cacheReadInputTokens;outputTokens;models=/* @__PURE__ */ new Set;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}recordMessageModel(e){e!==void 0&&e!==`<synthetic>`&&this.models.add(e)}recordModelUsage(e){for(let[t,n]of Object.entries(e??{})){let e=this.restoredTotals?.modelUsage?.[t];(e===void 0||c(n)>c(e))&&this.models.add(t)}}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};this.canUseModelUsage&&this.recordModelUsage(t.modelUsage);let r=this.canUseModelUsage?s(t.modelUsage):void 0,i=s(this.restoredTotals?.modelUsage),a=r?u(r,i):n;return{durationMs:this.durationMs,apiDurationMs:l(t.duration_api_ms,this.restoredTotals?.apiDurationMs??0),turns:this.turns,...a,totalTokens:e(a.inputTokens,a.cacheCreationInputTokens,a.cacheReadInputTokens,a.outputTokens),costUsd:l(t.total_cost_usd,this.restoredTotals?.costUsd??0),models:this.models.size===0?void 0:[...this.models]}}};const f=/* @__PURE__ */ new Map([[`allowed`,`allowed`],[`allowed_warning`,`warning`],[`rejected`,`rejected`]]),p=/* @__PURE__ */ new Set([`failed`,`error`]),m=({utilization:e,rateLimitType:t,unifiedWindows:n})=>{if(e!==void 0)return e;if(t!==void 0)return n?.[t]?.utilization},h=e=>{if(e!==void 0)return f.get(e)},g=(e,r,i)=>{let a=h(i.status);if(a===void 0){let a=`rate limited: ${i.status}`;return[t(e,`message`,{sessionId:r,model:null,role:`system`,content:[n(a)],text:a})]}return[t(e,`rate-limit`,{sessionId:r,status:a,limitType:i.rateLimitType,utilization:m(i),resetsAt:i.resetsAt===void 0?void 0:/* @__PURE__ */ new Date(i.resetsAt*1e3),overageStatus:h(i.overageStatus),isUsingOverage:i.isUsingOverage,overageDisabledReason:i.overageDisabledReason})]},_=(e,n,r)=>r.filter(({status:e})=>p.has(e)).map(({name:r})=>t(e,`notice`,{sessionId:n,notice:{kind:`mcp-server-failed`,server:r}})),v=({subtype:e,outcome:t})=>e===`hook_failed`||e===`hook_response`&&t===`error`,y=(e,n,{hook:r,exitCode:i})=>t(e,`notice`,{sessionId:n,notice:{kind:`hook-failed`,hook:r,exitCode:i}}),b=(e,t,n)=>{if(n.subtype===`init`)return _(e,t,n.mcp_servers??[]);let r=n.hook_name;return r!==void 0&&v(n)?[y(e,t,{hook:r,exitCode:n.exit_code})]:[]},x=e=>{let t={...e};return delete t.$schema,t},S=[`CLAUDECODE`,`CLAUDE_CODE_CHILD_SESSION`],C=e=>{for(let t of S)delete e[t]},w=e=>{if(e.permissionMode!==void 0)return[{type:`setMode`,mode:e.permissionMode,destination:`session`}]};export{b as a,i as c,g as i,C as n,d as o,x as r,o as s,w as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e}from"./types-B72tDMEZ.mjs";import{t}from"./util-CCXryPDO.mjs";import{basename as n,extname as r}from"node:path";import{readFileSync as i}from"node:fs";const a={".png":`image/png`,".jpg":`image/jpeg`,".jpeg":`image/jpeg`,".gif":`image/gif`,".webp":`image/webp`},o=e=>e.some(e=>e.type===`image`),s=t=>{if(t.mediaType!==void 0)return t.mediaType;let n=a[r(t.path).toLowerCase()];if(n!==void 0)return n;throw new e(`Cannot infer image mediaType from "${t.path}"; specify mediaType explicitly.`)},c=e=>{let t=s(e);return{data:i(e.path).toString(`base64`),mediaType:t,filename:n(e.path)}},l=`No permission handler is registered.`,u=async(e,n)=>{if(e===void 0)return{decision:`deny`,message:l};try{return await e(n)}catch(e){return{decision:`deny`,message:t(e)}}},d=e=>e.decision===`allow`?e.updatedInput!==void 0||e.permissionMode!==void 0:!1,f=e=>`${e} cannot change tool input or the session permission mode.`;export{o as a,f as i,d as n,c as o,u as r,l as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=()=>{let e=[],t=!1,n,r=r=>{t||(e.push(`${JSON.stringify(r)}\n`),n?.())},i=()=>{t=!0,n?.()};async function*a(){for(;;){let r=e.shift();if(r!==void 0)yield r;else{if(t)return;await new Promise(e=>{n=e})}}}return{send:r,close:i,lines:a(),get isClosed(){return t}}},t=(e,t)=>{let n=new Set(t);return{selectedLabels:e.filter(e=>n.has(e)),freeFormText:e.filter(e=>!n.has(e)).join(`, `)}};export{e as n,t};
|
package/dist/sandbox/index.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as FirejailSandbox, c as NsjailSandboxConfig, d as SandboxStatus, f as SandboxType, i as BubblewrapSandboxConfig, l as Sandbox, n as createSandbox, o as FirejailSandboxConfig, r as BubblewrapSandbox, s as NsjailSandbox, t as SandboxCreateError, u as SandboxConfig } from "../index-
|
|
1
|
+
import { a as FirejailSandbox, c as NsjailSandboxConfig, d as SandboxStatus, f as SandboxType, i as BubblewrapSandboxConfig, l as Sandbox, n as createSandbox, o as FirejailSandboxConfig, r as BubblewrapSandbox, s as NsjailSandbox, t as SandboxCreateError, u as SandboxConfig } from "../index-CZiWvyn3.mjs";
|
|
2
2
|
export { type BubblewrapSandbox, type BubblewrapSandboxConfig, type FirejailSandbox, type FirejailSandboxConfig, type NsjailSandbox, type NsjailSandboxConfig, type Sandbox, type SandboxConfig, SandboxCreateError, type SandboxStatus, type SandboxType, createSandbox };
|
package/dist/sandbox/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export{t as SandboxCreateError,n as createSandbox}from"../sandbox-BemAIoIo.mjs";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{t as
|
|
1
|
+
import{n as e,r as t,t as n}from"./env-Cb8MIvH7.mjs";import{t as r}from"./spawner-CYAQQABs.mjs";import{t as i}from"./util-CCXryPDO.mjs";import{t as a}from"./shell-DvWFuFKb.mjs";import{execFile as o}from"node:child_process";import{delimiter as s,isAbsolute as c,join as l,posix as u,resolve as d}from"node:path";import{promisify as f}from"node:util";import{accessSync as p,constants as m,mkdtempSync as h,realpathSync as g,rmSync as _,writeFileSync as v}from"node:fs";import{tmpdir as y}from"node:os";const b=e=>{let t=e.type.charAt(0).toUpperCase()+e.type.slice(1),n=`created`,r=/* @__PURE__ */ new Set,i=()=>{if(n===`disposed`)throw Error(`${t} sandbox has been disposed.`)},a=()=>{if(i(),n!==`running`)throw Error(`${t} sandbox is not running.`)},o=e=>{let t={process:e,waitPromise:e.wait().finally(()=>{r.delete(t)})};return r.add(t),{...e,wait:()=>t.waitPromise}},s=async()=>{let e=Array.from(r,e=>(e.process.kill(`SIGKILL`),e.waitPromise));await Promise.allSettled(e)},c=e.createSpawner(a,o),l={type:e.type,config:e.config,get status(){return n},get workdir(){return e.config.workdir},get spawner(){return c},async start(){i(),n!==`running`&&(await e.onValidate(),n=`running`)},async stop(){i(),n===`running`&&(n=`stopped`,await s())},async dispose(){n!==`disposed`&&(n=`disposed`,await s(),await e.onDispose?.())},[Symbol.asyncDispose](){return l.dispose()}};return e.extend?e.extend(l):l},x=`bwrap`,S=[`/tmp`],C=f(o),w=(e,t)=>e.binds?.some(e=>e.target===t)??!1,T=(e,t)=>{let n=u.relative(e,t);return n===``||!n.startsWith(`..`)&&!u.isAbsolute(n)},E=(e,t)=>e.target.length-t.target.length,ee=e=>{let t=w(e,e.workdir)?[...e.binds??[]]:[{source:e.workdir,target:e.workdir},...e.binds??[]],n=e.tmpfs??S,r=t.filter(e=>!n.some(t=>T(t,e.target))).toSorted(E),i=t.filter(e=>n.some(t=>T(t,e.target))).toSorted(E);return[...r,...i]},te=e=>{let t=[`--ro-bind`,`/`,`/`];for(let n of ee(e))t.push(n.readonly?`--ro-bind`:`--bind`,n.source,n.target);return t},ne=(e,t)=>{let n=[];(e.clearEnv??!0)&&n.push(`--clearenv`);for(let t of e.unsetEnv??[])n.push(`--unsetenv`,t);let r={...e.setEnv,...t.env};for(let[e,t]of Object.entries(r))n.push(`--setenv`,e,t);return n},re=e=>{let t=[`--die-with-parent`,`--new-session`];return(e.unshareAll??!0)&&t.push(`--unshare-all`),e.shareNetwork&&t.push(`--share-net`),e.uid!==void 0&&t.push(`--uid`,String(e.uid)),e.gid!==void 0&&t.push(`--gid`,String(e.gid)),e.hostname&&t.push(`--hostname`,e.hostname),t},ie=e=>{let t=[`--ro-bind`,`/`,`/`];e.proc!==!1&&t.push(`--proc`,e.proc??`/proc`),e.dev!==!1&&t.push(`--dev`,e.dev??`/dev`);for(let n of e.tmpfs??S)t.push(`--tmpfs`,n);t.push(...te(e).slice(3));for(let n of e.remountReadonly??[])t.push(`--remount-ro`,n);return t},ae=(e,t,n,r={})=>[...re(e),...ie(e),...ne(e,r),`--chdir`,r.cwd??e.workdir,...e.args??[],`--`,t,...n],oe=async e=>{try{await C(e,[`--version`],{env:n(),encoding:`utf8`})}catch(e){throw Error(`Bubblewrap start failed: ${i(e)}`)}},D=(e,t,r,i)=>({spawn(a,o,s={}){return t(),r(i.spawn(e.binary??x,ae(e,a,o,s),{env:n(),stdio:s.stdio}))}}),O=async(e,t=r)=>b({type:`bubblewrap`,config:e,onValidate:()=>oe(e.binary??x),createSpawner:(n,r)=>D(e,n,r,t)}),k=e=>new Set((e??[]).flatMap(e=>[e,e.toUpperCase(),e.toLowerCase()])),A=(e,t)=>{let n=k(t);return n.size===0?e:Object.fromEntries(Object.entries(e).filter(([e])=>!n.has(e)))},j=e=>{try{return p(e,m.X_OK),!0}catch{return!1}},M=(e,t)=>c(e)?e:d(t,e),N=(e,n,r)=>{if(c(e)||e.includes(`/`))return e;let i=n[t(n)];if(!i)return e;for(let t of i.split(s)){let n=l(M(t,r),e);if(j(n))return n}return e},P=(n,r)=>{if((r??[]).some(e=>e.toLowerCase()===`path`))return;let i=t(n);if(i in n)return;let a=e(),o=a[t(a)];o&&Object.assign(n,{[i]:o})},F=[`/run/wrappers/bin`,`/usr/local/bin`,`/usr/bin`,`/bin`],I=f(o),L=e=>e.binary??`firejail`,R=()=>{let n=e();return n[t(n)]},z=e=>{if(e.clearEnv===!1)return n({extraPaths:F});let r=n({propagateEnv:!1,extraPaths:F}),i=R();return i&&(r[t(r)]=[...F,i].filter(Boolean).join(s)),r},B=(e,t,n)=>{let r=A({...n,...e.setEnv,...t.env},e.unsetEnv);return P(r,e.unsetEnv),r},V=(e,t,n)=>{let r=[];for(let t of e.unsetEnv??[])r.push(`--rmenv=${t}`);let i={...e.setEnv,...t.env};for(let[e,t]of Object.entries(i))n[e]!==t&&r.push(`--env=${e}=${t}`);return r},H=(e,t,n,r={},i={})=>{let a=[`--noprofile`];e.shareNetwork||a.push(`--net=none`);for(let t of e.whitelist??[])a.push(`--whitelist=${t}`);for(let t of e.blacklist??[])a.push(`--blacklist=${t}`);for(let t of e.readOnly??[])a.push(`--read-only=${t}`);for(let t of e.readWrite??[])a.push(`--read-write=${t}`);return e.privateTmp&&a.push(`--private-tmp`),a.push(...V(e,r,i)),e.args?.length&&a.push(...e.args),a.push(`--`,t,...n),a},U=async e=>{try{await I(e,[`--version`],{env:n({extraPaths:F}),encoding:`utf8`})}catch(e){throw Error(`Firejail start failed: ${i(e)}`)}},W=(e,t,n,r)=>({spawn(i,o,s={}){t();let c=s.cwd??e.workdir,l=z(e),u=`exec ${[N(i,B(e,s,l),c),...o].map(a).join(` `)}`;return n(r.spawn(L(e),H(e,`sh`,[`-c`,u],s,l),{cwd:c,env:l,stdio:s.stdio}))}}),G=async(e,t=r)=>b({type:`firejail`,config:e,onValidate:()=>U(L(e)),createSpawner:(n,r)=>W(e,n,r,t)}),K=`nsjail`,se=[`/tmp`],ce=f(o),q=e=>JSON.stringify(e),J=(e,t)=>e.target.length-t.target.length||Number(!!e.readonly)-Number(!!t.readonly),le=(e,t)=>e.binds?.some(e=>e.target===t)??!1,Y=e=>e.tmpfs??[...se],ue=(e,t)=>Y(e).includes(t),de=e=>{let t=le(e,e.workdir)?[...e.binds??[]]:[{source:e.workdir,target:e.workdir},...e.binds??[]],n=(e.readOnly??[]).map(e=>({source:e,target:e,readonly:!0,type:`bind`}));return[...t.map(e=>({source:e.source,target:e.target,readonly:e.readonly,type:`bind`})),...n].filter(t=>!ue(e,t.target)).toSorted(J)},fe=e=>Y(e).map(t=>({target:t,readonly:e.readOnly?.includes(t),type:`tmpfs`})).toSorted(J),pe=e=>[{source:`/`,target:`/`,readonly:!0,type:`bind`},...fe(e),...de(e)],X=(e,t)=>{let r=A(e.clearEnv===!1?n():n({propagateEnv:!1}),e.unsetEnv);return Object.assign(r,e.setEnv,t.env),P(r,e.unsetEnv),r},Z=(e,t,n)=>[`${e} {`,` inside_id: ${q(String(t))}`,` outside_id: ${q(String(n))}`,` count: 1`,`}`].join(`
|
|
2
2
|
`),me=e=>{if(e!==void 0)try{return g(e)}catch{return e}},Q=e=>{let t=[`mount {`],n=me(e.source);return n!==void 0&&t.push(` src: ${q(n)}`),t.push(` dst: ${q(e.target)}`),e.type===`tmpfs`?t.push(` fstype: ${q(`tmpfs`)}`):t.push(` is_bind: true`),t.push(` rw: ${e.readonly?`false`:`true`}`),t.push(` mandatory: true`),t.push(`}`),t.join(`
|
|
3
3
|
`)},he=(e,t,n)=>{let r=t.cwd??e.workdir,i=n??X(e,t),a=e.hostname??`NSJAIL`,o=typeof process.getuid==`function`?process.getuid():0,s=typeof process.getgid==`function`?process.getgid():0,c=e.uid??o,l=e.gid??s,u=e.clearEnv===!1&&(e.unsetEnv?.length??0)===0,d=[`name: "coding-agents-sdk"`,`mode: ONCE`,`hostname: ${q(a)}`,`cwd: ${q(r)}`,`keep_env: ${u?`true`:`false`}`,`clone_newnet: ${e.shareNetwork?`false`:`true`}`,`clone_newuser: true`,`clone_newns: true`,`clone_newpid: true`,`clone_newipc: true`,`clone_newuts: true`,`mount_proc: true`,`time_limit: ${String(e.timeLimitSec??0)}`,Z(`uidmap`,c,o),Z(`gidmap`,l,s)];e.seccompString&&d.push(`seccomp_string: ${q(e.seccompString)}`);for(let[e,t]of Object.entries(i)){let n=`${e}=${t}`;d.push(`envar: ${q(n)}`)}for(let t of pe(e))d.push(Q(t));return`${d.join(`
|
|
4
|
-
`)}\n`},ge=(e,t,n,r)=>{let i=[`-C`,t];return(e.disableRlimits??!0)&&i.push(`--disable_rlimits`),i.push(...e.args??[],`--`,n,...r),i},_e=async
|
|
4
|
+
`)}\n`},ge=(e,t,n,r)=>{let i=[`-C`,t];return(e.disableRlimits??!0)&&i.push(`--disable_rlimits`),i.push(...e.args??[],`--`,n,...r),i},_e=async e=>{try{await ce(e,[`--help`],{env:n(),encoding:`utf8`})}catch(e){throw Error(`Nsjail start failed: ${i(e)}`)}},ve=(e,t,r,i,a)=>({spawn(o,s,c={}){r();let u=t(),d=X(e,c),f=c.cwd??e.workdir,p=N(o,d,f),m=l(u.configDir,`spawn-${Date.now()}-${Math.random().toString(16).slice(2)}.cfg`);v(m,he(e,c,d),{encoding:`utf8`,mode:384});try{let t=i(a.spawn(e.binary??K,ge(e,m,p,s),{env:n(),stdio:c.stdio})),r=t.wait().finally(()=>{_(m,{force:!0})});return{...t,wait:()=>r}}catch(e){throw _(m,{force:!0}),e}}}),ye=async(e,t=r)=>{let n,i=()=>{if(!n)throw Error(`Nsjail sandbox has not been started.`);return n};return b({type:`nsjail`,config:e,async onValidate(){await _e(e.binary??K),n??={configDir:h(l(y(),`cw-nsjail-`))}},onDispose(){n&&_(n.configDir,{recursive:!0,force:!0})},createSpawner:(n,r)=>ve(e,i,n,r,t)})};var $=class extends Error{constructor(e){super(e),this.name=`SandboxCreateError`}};async function be(e){switch(e.type){case`bubblewrap`:return O(e);case`firejail`:return G(e);case`nsjail`:return ye(e);default:throw new $(`Unsupported sandbox type.`)}}export{be as n,$ as t};
|