@clearideas/agent-runtime-execution-modal 0.1.0 → 0.2.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 CHANGED
@@ -1,14 +1,62 @@
1
1
  # `@clearideas/agent-runtime-execution-modal`
2
2
 
3
- Implements `RemoteComputeLauncher` for Modal. The package maps worker
4
- invocations to Modal function calls and uses the configured
5
- `RemoteExecutionControlPlane` for status, ordered events, and results.
3
+ Implements `RemoteComputeLauncher` for Modal Functions and Modal Sandboxes.
4
+ Both use the configured `RemoteExecutionControlPlane` for status, ordered
5
+ events, and results.
6
6
 
7
- Applications provide `ModalGateway`, credentials, function lookup, application
8
- names, environment names, and a `WorkerInvocationEnvelopeCodec`.
7
+ `ModalExecutionEngine` retains the Function-and-Queue transport.
8
+ `ModalSandboxExecutionEngine` runs the whole worker in a Modal Sandbox and
9
+ uses the portable NDJSON worker protocol over Sandbox stdin/stdout.
9
10
 
10
11
  Modal execution fails closed without an invocation codec. The launcher sends
11
12
  an authenticated encrypted envelope and the worker decodes it with
12
13
  `decodeModalWorkerInvocation`. Plaintext invocation requires the explicit
13
14
  `allowPlaintextInvocationForDevelopment` option and is only intended for a
14
15
  trusted, isolated development worker.
16
+
17
+ The package installs `agent-runtime-modal-worker`. A worker image can use this
18
+ as its entrypoint; it opens the invocation envelope and starts
19
+ `agent-runtime worker`. Provide the keyring through a Modal Secret using:
20
+
21
+ - `AGENT_RUNTIME_MODAL_INVOCATION_ACTIVE_KEY_ID`;
22
+ - `AGENT_RUNTIME_MODAL_INVOCATION_KEYS`;
23
+ - optionally, `AGENT_RUNTIME_MODAL_INVOCATION_AUDIENCE`.
24
+
25
+ The bootstrap removes the keyring variables before starting the neutral
26
+ worker child process.
27
+
28
+ ## Egress resolution
29
+
30
+ `resolveAgentRunnerEgressPolicy` walks the portable agent manifest but obtains
31
+ model, connection, tool, and referenced-agent endpoints from trusted host
32
+ callbacks. The manifest can directly contribute only explicit webhook URLs.
33
+ It returns normalized HTTPS origins with portable source names:
34
+ `control_plane`, `model`, `connection`, `tool`, and `webhook`.
35
+
36
+ The host chooses one Modal network mode per run:
37
+
38
+ - `block` sets `blockNetwork`;
39
+ - `proxy-only` accepts exact proxy CIDRs or TLS hostnames supplied by the host;
40
+ - `direct-domains` derives direct Modal domain entries from resolved HTTPS
41
+ origins.
42
+
43
+ Agent Runtime performs no DNS lookup and no CIDR discovery. Domain mode avoids
44
+ pinning provider or CDN endpoints to regional IP addresses. Modal domain
45
+ allowlists represent TLS traffic on port 443, so the resolver rejects other
46
+ ports instead of silently broadening access.
47
+
48
+ CIDR and domain allowlists are additive in Modal. To preserve a signed-proxy
49
+ boundary, `proxy-only` accepts only proxy endpoints—exact host CIDRs or exact
50
+ TLS proxy hostnames. Do not include downstream service domains, because those
51
+ become direct egress paths around the proxy.
52
+
53
+ Treat the resolved egress policy and the Modal network policy as separate
54
+ artifacts. The resolved policy authorizes downstream destinations at the
55
+ trusted proxy. The Modal policy makes only that proxy reachable. If the host
56
+ does not use an external proxy, `direct-domains` mode can map the resolved
57
+ HTTPS origins to Modal's domain allowlist. In that mode, Modal enforces the
58
+ resolved domain set directly.
59
+
60
+ A host-managed sub-run may return `null` from `resolveManifestRef` when the
61
+ child is launched through the control plane and adds no direct destination to
62
+ the current worker. An unresolved reference otherwise fails closed.
@@ -0,0 +1,68 @@
1
+ import type { AgentConnectionBinding, AgentManifest, ModelReference } from "@clearideas/agent-runtime-contracts";
2
+ export type AgentRunnerEgressOriginType = "control_plane" | "model" | "connection" | "webhook" | "tool";
3
+ export interface AgentRunnerEgressOrigin {
4
+ type: AgentRunnerEgressOriginType;
5
+ origin: string;
6
+ provider?: string;
7
+ step?: string;
8
+ connectionRef?: string;
9
+ tool?: string;
10
+ }
11
+ export interface AgentRunnerEgressPolicy {
12
+ mode: "enforce";
13
+ allowedOrigins: AgentRunnerEgressOrigin[];
14
+ }
15
+ export interface AgentRunnerEgressPolicyDecision {
16
+ allowed: boolean;
17
+ reason: string;
18
+ policyId?: string;
19
+ }
20
+ export type ResolvedAgentRunnerEgressOrigin = string | Omit<AgentRunnerEgressOrigin, "type"> | AgentRunnerEgressOrigin;
21
+ interface AgentRunnerEgressResolutionContext {
22
+ manifest: AgentManifest;
23
+ path: string[];
24
+ }
25
+ export interface AgentRunnerEgressPolicyResolver {
26
+ /** Trusted control-plane endpoints required by the worker. */
27
+ controlPlaneOrigins?: readonly ResolvedAgentRunnerEgressOrigin[];
28
+ /** Host default used when a prompt and its manifest omit a model. */
29
+ defaultModel?: ModelReference;
30
+ /**
31
+ * Resolves a credential-free model reference through the host's model
32
+ * catalog. The manifest never supplies provider endpoint URLs.
33
+ */
34
+ resolveModelOrigins?: (model: ModelReference, context: AgentRunnerEgressResolutionContext & {
35
+ step: string;
36
+ }) => readonly ResolvedAgentRunnerEgressOrigin[] | Promise<readonly ResolvedAgentRunnerEgressOrigin[]>;
37
+ /**
38
+ * Resolves a connection ref through the host's connection registry. The
39
+ * manifest may narrow a binding but cannot provide its endpoint.
40
+ */
41
+ resolveConnectionOrigins?: (binding: AgentConnectionBinding, context: AgentRunnerEgressResolutionContext) => readonly ResolvedAgentRunnerEgressOrigin[] | Promise<readonly ResolvedAgentRunnerEgressOrigin[]>;
42
+ /** Resolves host-registered tools such as managed web search/retrieval. */
43
+ resolveToolOrigins?: (tool: string, context: AgentRunnerEgressResolutionContext & {
44
+ step: string;
45
+ }) => readonly ResolvedAgentRunnerEgressOrigin[] | Promise<readonly ResolvedAgentRunnerEgressOrigin[]>;
46
+ /** Resolves host-owned sub-run references before recursively inspecting them. */
47
+ resolveManifestRef?: (ref: string, context: AgentRunnerEgressResolutionContext & {
48
+ step: string;
49
+ }) => AgentManifest | null | Promise<AgentManifest | null>;
50
+ /** Additional host-owned grants, for example a configured retrieval service. */
51
+ additionalOrigins?: readonly ResolvedAgentRunnerEgressOrigin[];
52
+ /** Invalid origins are omitted (fail closed) and may be reported by the host. */
53
+ onInvalidOrigin?: (origin: string) => void;
54
+ }
55
+ /**
56
+ * Builds a run egress policy using host-owned endpoint resolvers.
57
+ *
58
+ * This deliberately does not add egress fields to AgentManifest. Model,
59
+ * connection, tool, and referenced-manifest endpoints are resolved by the
60
+ * trusted host. Only an explicit webhook URL is read directly from a manifest
61
+ * because it is already an endpoint-bearing step.
62
+ */
63
+ export declare const resolveAgentRunnerEgressPolicy: (manifestInput: AgentManifest, resolver: AgentRunnerEgressPolicyResolver) => Promise<AgentRunnerEgressPolicy>;
64
+ /** Proxy-side exact host-and-port evaluator for the resolved portable policy. */
65
+ export declare const evaluateAgentRunnerEgressPolicyDestination: (policy: AgentRunnerEgressPolicy | undefined, targetHost: string, targetPort: number, options?: {
66
+ onInvalidOrigin?: (origin: string) => void;
67
+ }) => AgentRunnerEgressPolicyDecision;
68
+ export {};
@@ -0,0 +1,151 @@
1
+ import { parseAgentManifest } from "@clearideas/agent-runtime-contracts";
2
+ const normalizeEgressOrigin = (value) => {
3
+ if (typeof value !== "string" || !value.trim())
4
+ return null;
5
+ try {
6
+ const url = new URL(value.trim());
7
+ if (url.protocol !== "https:")
8
+ return null;
9
+ return url.origin;
10
+ }
11
+ catch {
12
+ return null;
13
+ }
14
+ };
15
+ const normalizeEgressHost = (value) => typeof value === "string"
16
+ ? value.trim().toLowerCase().replace(/\.$/u, "")
17
+ : "";
18
+ const getOriginPort = (url) => url.port ? Number(url.port) : url.protocol === "https:" ? 443 : 80;
19
+ const originKey = (item) => [
20
+ item.type,
21
+ item.provider ?? "",
22
+ item.connectionRef ?? "",
23
+ item.tool ?? "",
24
+ item.step ?? "",
25
+ item.origin,
26
+ ].join(":");
27
+ const addOrigin = (origins, item, onInvalidOrigin) => {
28
+ const origin = normalizeEgressOrigin(item.origin);
29
+ if (!origin) {
30
+ onInvalidOrigin?.(item.origin);
31
+ return;
32
+ }
33
+ const normalized = { ...item, origin };
34
+ origins.set(originKey(normalized), normalized);
35
+ };
36
+ const addResolvedOrigins = (origins, items, defaults, onInvalidOrigin) => {
37
+ for (const item of items) {
38
+ addOrigin(origins, typeof item === "string"
39
+ ? { ...defaults, origin: item }
40
+ : { ...defaults, ...item }, onInvalidOrigin);
41
+ }
42
+ };
43
+ const stepLabel = (step) => step.name ?? step.id;
44
+ /**
45
+ * Builds a run egress policy using host-owned endpoint resolvers.
46
+ *
47
+ * This deliberately does not add egress fields to AgentManifest. Model,
48
+ * connection, tool, and referenced-manifest endpoints are resolved by the
49
+ * trusted host. Only an explicit webhook URL is read directly from a manifest
50
+ * because it is already an endpoint-bearing step.
51
+ */
52
+ export const resolveAgentRunnerEgressPolicy = async (manifestInput, resolver) => {
53
+ const origins = new Map();
54
+ const rootManifest = parseAgentManifest(manifestInput);
55
+ addResolvedOrigins(origins, resolver.controlPlaneOrigins ?? [], { type: "control_plane" }, resolver.onInvalidOrigin);
56
+ addResolvedOrigins(origins, resolver.additionalOrigins ?? [], { type: "tool" }, resolver.onInvalidOrigin);
57
+ const visitManifest = async (manifest, path) => {
58
+ const context = { manifest, path };
59
+ for (const binding of manifest.connections ?? []) {
60
+ const resolved = (await resolver.resolveConnectionOrigins?.(binding, context)) ?? [];
61
+ addResolvedOrigins(origins, resolved, { type: "connection", connectionRef: binding.ref }, resolver.onInvalidOrigin);
62
+ }
63
+ const visitSteps = async (steps, inheritedModel) => {
64
+ for (const step of steps) {
65
+ const label = stepLabel(step);
66
+ const stepPath = [...path, step.id];
67
+ const stepContext = { manifest, path: stepPath, step: label };
68
+ if (step.type === "prompt") {
69
+ const model = step.model ?? inheritedModel ?? resolver.defaultModel;
70
+ if (model && resolver.resolveModelOrigins) {
71
+ const resolved = await resolver.resolveModelOrigins(model, stepContext);
72
+ addResolvedOrigins(origins, resolved, {
73
+ type: "model",
74
+ ...("provider" in model ? { provider: model.provider } : {}),
75
+ }, resolver.onInvalidOrigin);
76
+ }
77
+ for (const tool of step.tools ?? []) {
78
+ const resolved = (await resolver.resolveToolOrigins?.(tool, stepContext)) ?? [];
79
+ addResolvedOrigins(origins, resolved, { type: "tool", tool }, resolver.onInvalidOrigin);
80
+ }
81
+ continue;
82
+ }
83
+ if (step.type === "webhook") {
84
+ addOrigin(origins, { type: "webhook", origin: step.url, step: label }, resolver.onInvalidOrigin);
85
+ continue;
86
+ }
87
+ if (step.type === "loop") {
88
+ await visitSteps(step.steps, inheritedModel);
89
+ continue;
90
+ }
91
+ if (step.type === "sub-run") {
92
+ const resolved = step.manifest
93
+ ? step.manifest
94
+ : step.manifestRef && resolver.resolveManifestRef
95
+ ? await resolver.resolveManifestRef(step.manifestRef, stepContext)
96
+ : undefined;
97
+ const nested = resolved ? parseAgentManifest(resolved) : resolved;
98
+ if (!nested && step.manifestRef) {
99
+ if (nested === null)
100
+ continue;
101
+ throw new Error(`Cannot resolve egress for sub-run manifest ref ${step.manifestRef}.`);
102
+ }
103
+ if (nested)
104
+ await visitManifest(nested, stepPath);
105
+ }
106
+ }
107
+ };
108
+ await visitSteps(manifest.steps, manifest.model);
109
+ };
110
+ await visitManifest(rootManifest, []);
111
+ return { mode: "enforce", allowedOrigins: [...origins.values()] };
112
+ };
113
+ /** Proxy-side exact host-and-port evaluator for the resolved portable policy. */
114
+ export const evaluateAgentRunnerEgressPolicyDestination = (policy, targetHost, targetPort, options = {}) => {
115
+ const normalizedTargetHost = normalizeEgressHost(targetHost);
116
+ if (!policy || !Array.isArray(policy.allowedOrigins)) {
117
+ return { allowed: false, reason: "agent runner egress policy is missing" };
118
+ }
119
+ if (!normalizedTargetHost ||
120
+ !Number.isSafeInteger(targetPort) ||
121
+ targetPort < 1 ||
122
+ targetPort > 65_535) {
123
+ return { allowed: false, reason: "agent runner egress target is invalid" };
124
+ }
125
+ for (const item of policy.allowedOrigins) {
126
+ try {
127
+ const origin = new URL(item.origin);
128
+ const allowedHost = normalizeEgressHost(origin.hostname);
129
+ const isWildcardHost = allowedHost.startsWith("*.");
130
+ const wildcardSuffix = isWildcardHost ? allowedHost.slice(2) : "";
131
+ if ((allowedHost === normalizedTargetHost ||
132
+ (isWildcardHost &&
133
+ (normalizedTargetHost === wildcardSuffix ||
134
+ normalizedTargetHost.endsWith(`.${wildcardSuffix}`)))) &&
135
+ getOriginPort(origin) === targetPort) {
136
+ return {
137
+ allowed: true,
138
+ reason: `agent runner egress policy allows ${item.type}`,
139
+ policyId: `${item.type}:${item.provider ?? item.connectionRef ?? item.tool ?? item.step ?? origin.origin}`,
140
+ };
141
+ }
142
+ }
143
+ catch {
144
+ options.onInvalidOrigin?.(item.origin);
145
+ }
146
+ }
147
+ return {
148
+ allowed: false,
149
+ reason: `agent runner egress policy does not allow ${normalizedTargetHost}:${targetPort}`,
150
+ };
151
+ };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import type { JsonObject } from "@clearideas/agent-runtime-contracts";
2
2
  import { type ExecutionHandle, type OpenWorkerInvocationOptions, type RemoteComputeLauncher, type RemoteExecutionControlPlane, type RemoteExecutionReporter, RemoteExecutionEngine, type SecureInvocationEnvelope, type WorkerInvocation, type WorkerInvocationEnvelopeCodec, type WorkerMessage } from "@clearideas/agent-runtime-execution";
3
+ import type { AgentRunnerEgressPolicy } from "./egress-policy.js";
4
+ export * from "./egress-policy.js";
3
5
  interface ModalSpawnRequestBase {
4
6
  executionId: string;
5
7
  runId: string;
@@ -99,6 +101,152 @@ export interface ModalSdkGatewayOptions {
99
101
  allowPlaintextInvocationForDevelopment?: boolean;
100
102
  now?: () => number;
101
103
  }
104
+ export type ModalSandboxNetworkPolicy = {
105
+ mode: "block";
106
+ blockNetwork: true;
107
+ } | {
108
+ mode: "proxy-only";
109
+ outboundCidrAllowlist: string[];
110
+ /**
111
+ * Exact TLS proxy hostnames only. Never include downstream model, tool,
112
+ * connection, webhook, or control-plane domains.
113
+ */
114
+ outboundDomainAllowlist: string[];
115
+ } | {
116
+ /**
117
+ * Direct domain egress derived from the host-resolved origin policy.
118
+ * Modal enforces domain entries for TLS traffic on port 443.
119
+ */
120
+ mode: "direct-domains";
121
+ outboundCidrAllowlist: [];
122
+ outboundDomainAllowlist: string[];
123
+ };
124
+ /**
125
+ * Converts the host-resolved HTTPS origin policy to Modal's stable domain
126
+ * allowlist. It intentionally performs no DNS or CIDR resolution.
127
+ */
128
+ export declare const resolveModalSandboxDomainAllowlist: (egressPolicy: AgentRunnerEgressPolicy) => string[];
129
+ /**
130
+ * Resolves hardened Modal networking from host-owned policy: no network,
131
+ * proxy-only endpoints, or direct HTTPS domains derived from resolved origins.
132
+ */
133
+ export declare const resolveModalSandboxNetworkPolicy: (input: {
134
+ mode: "block";
135
+ } | {
136
+ mode: "proxy-only";
137
+ proxyCidrs?: readonly string[];
138
+ proxyDomains?: readonly string[];
139
+ } | {
140
+ mode: "direct-domains";
141
+ egressPolicy: AgentRunnerEgressPolicy;
142
+ }) => ModalSandboxNetworkPolicy;
143
+ export interface ModalSandboxLaunchConfig {
144
+ networkPolicy: ModalSandboxNetworkPolicy;
145
+ /** Entrypoint that reads one ModalSpawnRequest from stdin and emits NDJSON. */
146
+ command?: string[];
147
+ /** Trusted per-run environment. It is never persisted in providerData. */
148
+ environment?: Record<string, string>;
149
+ /**
150
+ * Opaque Modal Secret handles injected as environment variables. `any` is
151
+ * intentional here because Modal Secret uses a private nominal SDK type.
152
+ */
153
+ secrets?: any[];
154
+ timeoutMs?: number;
155
+ idleTimeoutMs?: number;
156
+ workdir?: string;
157
+ cpu?: number;
158
+ cpuLimit?: number;
159
+ memoryMiB?: number;
160
+ memoryLimitMiB?: number;
161
+ regions?: string[];
162
+ cloud?: string;
163
+ metadata?: JsonObject;
164
+ }
165
+ export type ResolveModalSandboxLaunchConfig = (invocation: WorkerInvocation, context: {
166
+ executionId: string;
167
+ runId: string;
168
+ }) => ModalSandboxLaunchConfig | Promise<ModalSandboxLaunchConfig>;
169
+ export type ModalSandboxSpawnRequest = ModalSpawnRequest & {
170
+ sandbox: ModalSandboxLaunchConfig;
171
+ };
172
+ export interface ModalSandboxSpawnResult {
173
+ sandboxId: string;
174
+ metadata?: JsonObject;
175
+ }
176
+ export interface ModalSandboxGateway {
177
+ spawn(request: ModalSandboxSpawnRequest): Promise<ModalSandboxSpawnResult>;
178
+ cancel(sandboxId: string): Promise<void>;
179
+ }
180
+ export interface ModalSandboxStreamingGateway extends ModalSandboxGateway {
181
+ messages(handle: ExecutionHandle, options?: {
182
+ signal?: AbortSignal;
183
+ }): AsyncIterable<WorkerMessage>;
184
+ }
185
+ export interface ModalSdkSandboxReaderLike {
186
+ read(): Promise<{
187
+ done: boolean;
188
+ value?: string;
189
+ }>;
190
+ cancel?(reason?: unknown): Promise<void>;
191
+ releaseLock?(): void;
192
+ }
193
+ export interface ModalSdkSandboxLike {
194
+ sandboxId: string;
195
+ stdin: {
196
+ writeText(text: string): Promise<void>;
197
+ close(): Promise<void>;
198
+ };
199
+ stdout: {
200
+ getReader(): ModalSdkSandboxReaderLike;
201
+ };
202
+ wait(): Promise<number>;
203
+ terminate(): Promise<void>;
204
+ }
205
+ /** Structural boundary matching the Modal TypeScript SDK Sandbox services. */
206
+ export interface ModalSandboxSdkClientLike {
207
+ apps: {
208
+ fromName(name: string, options?: {
209
+ environment?: string;
210
+ createIfMissing?: boolean;
211
+ }): Promise<any>;
212
+ };
213
+ images: {
214
+ fromName(name: string, options?: {
215
+ environment?: string;
216
+ }): Promise<any>;
217
+ };
218
+ sandboxes: {
219
+ create(app: any, image: any, options: {
220
+ command: string[];
221
+ env?: Record<string, string>;
222
+ secrets?: any[];
223
+ timeoutMs?: number;
224
+ idleTimeoutMs?: number;
225
+ workdir?: string;
226
+ cpu?: number;
227
+ cpuLimit?: number;
228
+ memoryMiB?: number;
229
+ memoryLimitMiB?: number;
230
+ regions?: string[];
231
+ cloud?: string;
232
+ blockNetwork?: boolean;
233
+ outboundCidrAllowlist?: string[];
234
+ outboundDomainAllowlist?: string[];
235
+ tags?: Record<string, string>;
236
+ }): Promise<ModalSdkSandboxLike>;
237
+ fromId(sandboxId: string): Promise<ModalSdkSandboxLike>;
238
+ };
239
+ }
240
+ export interface ModalSandboxSdkGatewayOptions {
241
+ appName?: string;
242
+ imageName: string;
243
+ environment?: string;
244
+ command?: string[];
245
+ baseEnvironment?: Record<string, string>;
246
+ startupTimeoutMs?: number;
247
+ maximumProtocolLineBytes?: number;
248
+ allowPlaintextInvocationForDevelopment?: boolean;
249
+ }
102
250
  /** Concrete Modal SDK transport using a per-execution named Queue. */
103
251
  export declare class ModalSdkGateway implements ModalStreamingGateway {
104
252
  #private;
@@ -112,6 +260,19 @@ export declare class ModalSdkGateway implements ModalStreamingGateway {
112
260
  signal?: AbortSignal;
113
261
  }): AsyncIterable<WorkerMessage>;
114
262
  }
263
+ /**
264
+ * Concrete Modal SDK transport that runs the entire worker in a Sandbox and
265
+ * carries the portable worker protocol over stdin/stdout.
266
+ */
267
+ export declare class ModalSandboxSdkGateway implements ModalSandboxStreamingGateway {
268
+ #private;
269
+ constructor(client: ModalSandboxSdkClientLike, options: ModalSandboxSdkGatewayOptions);
270
+ spawn(request: ModalSandboxSpawnRequest): Promise<ModalSandboxSpawnResult>;
271
+ cancel(sandboxId: string): Promise<void>;
272
+ messages(handle: ExecutionHandle, options?: {
273
+ signal?: AbortSignal;
274
+ }): AsyncIterable<WorkerMessage>;
275
+ }
115
276
  export declare class ModalComputeLauncher implements RemoteComputeLauncher {
116
277
  #private;
117
278
  readonly name: string;
@@ -122,7 +283,26 @@ export declare class ModalComputeLauncher implements RemoteComputeLauncher {
122
283
  cancel(handle: ExecutionHandle): Promise<void>;
123
284
  observe(handle: ExecutionHandle): Promise<void>;
124
285
  }
286
+ export interface ModalSandboxComputeLauncherOptions extends ModalComputeLauncherOptions {
287
+ /**
288
+ * Trusted host callback. It may inspect the invocation to resolve host-owned
289
+ * policy, but only the resulting sandbox configuration crosses into Modal.
290
+ */
291
+ resolveSandbox: ResolveModalSandboxLaunchConfig;
292
+ }
293
+ export declare class ModalSandboxComputeLauncher implements RemoteComputeLauncher {
294
+ #private;
295
+ readonly name: string;
296
+ constructor(gateway: ModalSandboxGateway, options: ModalSandboxComputeLauncherOptions, reporter?: RemoteExecutionReporter);
297
+ launch(invocation: WorkerInvocation, context: {
298
+ handle: ExecutionHandle;
299
+ }): Promise<JsonObject>;
300
+ cancel(handle: ExecutionHandle): Promise<void>;
301
+ observe(handle: ExecutionHandle): Promise<void>;
302
+ }
125
303
  export declare class ModalExecutionEngine extends RemoteExecutionEngine {
126
304
  constructor(gateway: ModalGateway, controlPlane: RemoteExecutionControlPlane, options?: ModalComputeLauncherOptions);
127
305
  }
128
- export {};
306
+ export declare class ModalSandboxExecutionEngine extends RemoteExecutionEngine {
307
+ constructor(gateway: ModalSandboxGateway, controlPlane: RemoteExecutionControlPlane, options: ModalSandboxComputeLauncherOptions);
308
+ }
package/dist/index.js CHANGED
@@ -1,5 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
+ import { isIP } from "node:net";
2
3
  import { RemoteExecutionEngine, parseWorkerInvocation, parseWorkerMessage, } from "@clearideas/agent-runtime-execution";
4
+ export * from "./egress-policy.js";
3
5
  export const DEFAULT_MODAL_WORKER_AUDIENCE = "agent-runtime-modal-worker";
4
6
  const modalSpawnPayloadKind = (request) => {
5
7
  if (typeof request.executionId !== "string" ||
@@ -43,6 +45,107 @@ export const decodeModalWorkerInvocation = (request, codec, options) => {
43
45
  }
44
46
  return invocation;
45
47
  };
48
+ const normalizeExactProxyCidr = (value) => {
49
+ const candidate = value.trim();
50
+ const separator = candidate.lastIndexOf("/");
51
+ if (separator <= 0) {
52
+ throw new Error(`Modal proxy address must be an exact CIDR: ${candidate}`);
53
+ }
54
+ const address = candidate.slice(0, separator);
55
+ const prefix = Number(candidate.slice(separator + 1));
56
+ const family = isIP(address);
57
+ if ((family === 4 && prefix !== 32) ||
58
+ (family === 6 && prefix !== 128) ||
59
+ family === 0) {
60
+ throw new Error(`Modal proxy CIDR must identify exactly one IPv4 or IPv6 address: ${candidate}`);
61
+ }
62
+ return `${address}/${prefix}`;
63
+ };
64
+ const normalizeExactProxyDomain = (value) => {
65
+ const candidate = value.trim().toLowerCase().replace(/\.$/u, "");
66
+ if (!candidate ||
67
+ candidate.startsWith("*.") ||
68
+ isIP(candidate) !== 0 ||
69
+ !/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/u.test(candidate)) {
70
+ throw new Error(`Modal proxy domain must be one exact hostname: ${value}`);
71
+ }
72
+ return candidate;
73
+ };
74
+ /**
75
+ * Converts the host-resolved HTTPS origin policy to Modal's stable domain
76
+ * allowlist. It intentionally performs no DNS or CIDR resolution.
77
+ */
78
+ export const resolveModalSandboxDomainAllowlist = (egressPolicy) => {
79
+ const domains = new Set();
80
+ for (const item of egressPolicy.allowedOrigins) {
81
+ const url = new URL(item.origin);
82
+ const port = url.port ? Number(url.port) : 443;
83
+ if (url.protocol !== "https:" || port !== 443) {
84
+ throw new Error(`Modal domain egress can express only HTTPS port 443 origins: ${item.origin}`);
85
+ }
86
+ const hostname = url.hostname.toLowerCase().replace(/\.$/u, "");
87
+ if (isIP(hostname)) {
88
+ throw new Error(`IP origin ${item.origin} must be supplied by the host as a CIDR policy.`);
89
+ }
90
+ if (!/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/u.test(hostname)) {
91
+ throw new Error(`Invalid Modal egress domain: ${hostname}`);
92
+ }
93
+ domains.add(hostname);
94
+ }
95
+ return [...domains].sort();
96
+ };
97
+ /**
98
+ * Resolves hardened Modal networking from host-owned policy: no network,
99
+ * proxy-only endpoints, or direct HTTPS domains derived from resolved origins.
100
+ */
101
+ export const resolveModalSandboxNetworkPolicy = (input) => {
102
+ if (input.mode === "block")
103
+ return { mode: "block", blockNetwork: true };
104
+ if (input.mode === "proxy-only") {
105
+ const cidrs = [
106
+ ...new Set((input.proxyCidrs ?? []).map(normalizeExactProxyCidr)),
107
+ ].sort();
108
+ const domains = [
109
+ ...new Set((input.proxyDomains ?? []).map(normalizeExactProxyDomain)),
110
+ ].sort();
111
+ if (cidrs.length === 0 && domains.length === 0) {
112
+ throw new Error("Proxy-only Modal networking requires an exact proxy CIDR or domain.");
113
+ }
114
+ return {
115
+ mode: "proxy-only",
116
+ outboundCidrAllowlist: cidrs,
117
+ outboundDomainAllowlist: domains,
118
+ };
119
+ }
120
+ return {
121
+ mode: "direct-domains",
122
+ outboundCidrAllowlist: [],
123
+ outboundDomainAllowlist: resolveModalSandboxDomainAllowlist(input.egressPolicy),
124
+ };
125
+ };
126
+ const normalizeModalSandboxNetworkPolicy = (policy) => {
127
+ if (policy.mode === "block") {
128
+ return resolveModalSandboxNetworkPolicy({ mode: "block" });
129
+ }
130
+ if (policy.mode === "proxy-only") {
131
+ return resolveModalSandboxNetworkPolicy({
132
+ mode: "proxy-only",
133
+ proxyCidrs: policy.outboundCidrAllowlist,
134
+ proxyDomains: policy.outboundDomainAllowlist,
135
+ });
136
+ }
137
+ return {
138
+ mode: "direct-domains",
139
+ outboundCidrAllowlist: [],
140
+ outboundDomainAllowlist: resolveModalSandboxDomainAllowlist({
141
+ mode: "enforce",
142
+ allowedOrigins: policy.outboundDomainAllowlist.map((domain) => ({
143
+ type: "tool",
144
+ origin: `https://${domain}`,
145
+ })),
146
+ }),
147
+ };
148
+ };
46
149
  const isTransportClosed = (value) => value != null &&
47
150
  typeof value === "object" &&
48
151
  !Array.isArray(value) &&
@@ -187,6 +290,237 @@ export class ModalSdkGateway {
187
290
  });
188
291
  }
189
292
  }
293
+ const sandboxSupportsMessages = (gateway) => typeof gateway.messages ===
294
+ "function";
295
+ const readSandboxChunk = async (reader, timeoutMs, signal) => {
296
+ if (signal?.aborted)
297
+ throw signal.reason ?? new Error("Operation aborted.");
298
+ if (timeoutMs == null && !signal)
299
+ return reader.read();
300
+ return new Promise((resolve, reject) => {
301
+ let settled = false;
302
+ const finish = (action, timeout) => {
303
+ if (settled)
304
+ return;
305
+ settled = true;
306
+ if (timeout)
307
+ clearTimeout(timeout);
308
+ signal?.removeEventListener("abort", onAbort);
309
+ action();
310
+ };
311
+ const onAbort = () => finish(() => reject(signal?.reason ?? new Error("Operation aborted.")), timeout);
312
+ const timeout = timeoutMs == null
313
+ ? undefined
314
+ : setTimeout(() => finish(() => reject(new Error(`Modal Sandbox worker did not produce a protocol message within ${timeoutMs}ms.`)), timeout), timeoutMs);
315
+ signal?.addEventListener("abort", onAbort, { once: true });
316
+ void reader.read().then((value) => finish(() => resolve(value), timeout), (error) => finish(() => reject(error), timeout));
317
+ });
318
+ };
319
+ /**
320
+ * Concrete Modal SDK transport that runs the entire worker in a Sandbox and
321
+ * carries the portable worker protocol over stdin/stdout.
322
+ */
323
+ export class ModalSandboxSdkGateway {
324
+ #client;
325
+ #appName;
326
+ #imageName;
327
+ #environment;
328
+ #command;
329
+ #baseEnvironment;
330
+ #startupTimeoutMs;
331
+ #maximumProtocolLineBytes;
332
+ #allowPlaintextInvocationForDevelopment;
333
+ constructor(client, options) {
334
+ if (!options.imageName.trim()) {
335
+ throw new Error("Modal Sandbox imageName must be a non-empty string.");
336
+ }
337
+ this.#client = client;
338
+ this.#appName = options.appName ?? "agent-runtime-dev";
339
+ this.#imageName = options.imageName;
340
+ this.#environment = options.environment;
341
+ this.#command = options.command ?? ["agent-runtime-modal-worker"];
342
+ if (this.#command.length === 0 ||
343
+ this.#command.some((part) => !part.trim())) {
344
+ throw new Error("Modal Sandbox command must contain non-empty arguments.");
345
+ }
346
+ this.#baseEnvironment = { ...(options.baseEnvironment ?? {}) };
347
+ this.#startupTimeoutMs = options.startupTimeoutMs ?? 120_000;
348
+ this.#maximumProtocolLineBytes =
349
+ options.maximumProtocolLineBytes ?? 4 * 1024 * 1024;
350
+ if (!Number.isSafeInteger(this.#maximumProtocolLineBytes) ||
351
+ this.#maximumProtocolLineBytes < 1) {
352
+ throw new Error("Modal Sandbox maximumProtocolLineBytes must be a positive integer.");
353
+ }
354
+ this.#allowPlaintextInvocationForDevelopment =
355
+ options.allowPlaintextInvocationForDevelopment ?? false;
356
+ }
357
+ async spawn(request) {
358
+ const payloadKind = modalSpawnPayloadKind(request);
359
+ if (payloadKind === "plaintext" &&
360
+ !this.#allowPlaintextInvocationForDevelopment) {
361
+ throw new Error("Plaintext Modal invocation is disabled.");
362
+ }
363
+ const network = normalizeModalSandboxNetworkPolicy(request.sandbox.networkPolicy);
364
+ const app = await this.#client.apps.fromName(this.#appName, {
365
+ createIfMissing: true,
366
+ ...(this.#environment ? { environment: this.#environment } : {}),
367
+ });
368
+ const image = await this.#client.images.fromName(this.#imageName, {
369
+ ...(this.#environment ? { environment: this.#environment } : {}),
370
+ });
371
+ const sandbox = await this.#client.sandboxes.create(app, image, {
372
+ command: request.sandbox.command ?? this.#command,
373
+ env: {
374
+ ...this.#baseEnvironment,
375
+ ...(request.sandbox.environment ?? {}),
376
+ AGENT_RUNTIME_MODAL_EXECUTION_ID: request.executionId,
377
+ AGENT_RUNTIME_MODAL_RUN_ID: request.runId,
378
+ },
379
+ ...(request.sandbox.secrets == null
380
+ ? {}
381
+ : { secrets: request.sandbox.secrets }),
382
+ ...(request.sandbox.timeoutMs == null
383
+ ? {}
384
+ : { timeoutMs: request.sandbox.timeoutMs }),
385
+ ...(request.sandbox.idleTimeoutMs == null
386
+ ? {}
387
+ : { idleTimeoutMs: request.sandbox.idleTimeoutMs }),
388
+ ...(request.sandbox.workdir == null
389
+ ? {}
390
+ : { workdir: request.sandbox.workdir }),
391
+ ...(request.sandbox.cpu == null ? {} : { cpu: request.sandbox.cpu }),
392
+ ...(request.sandbox.cpuLimit == null
393
+ ? {}
394
+ : { cpuLimit: request.sandbox.cpuLimit }),
395
+ ...(request.sandbox.memoryMiB == null
396
+ ? {}
397
+ : { memoryMiB: request.sandbox.memoryMiB }),
398
+ ...(request.sandbox.memoryLimitMiB == null
399
+ ? {}
400
+ : { memoryLimitMiB: request.sandbox.memoryLimitMiB }),
401
+ ...(request.sandbox.regions == null
402
+ ? {}
403
+ : { regions: request.sandbox.regions }),
404
+ ...(request.sandbox.cloud == null
405
+ ? {}
406
+ : { cloud: request.sandbox.cloud }),
407
+ ...(network.mode === "block"
408
+ ? { blockNetwork: true }
409
+ : {
410
+ outboundCidrAllowlist: network.outboundCidrAllowlist,
411
+ outboundDomainAllowlist: network.outboundDomainAllowlist,
412
+ }),
413
+ tags: {
414
+ "agent-runtime-execution-id": request.executionId,
415
+ "agent-runtime-run-id": request.runId,
416
+ },
417
+ });
418
+ const workerRequest = "invocationEnvelope" in request && request.invocationEnvelope != null
419
+ ? {
420
+ executionId: request.executionId,
421
+ runId: request.runId,
422
+ invocationEnvelope: request.invocationEnvelope,
423
+ }
424
+ : {
425
+ executionId: request.executionId,
426
+ runId: request.runId,
427
+ invocation: request.invocation,
428
+ };
429
+ try {
430
+ await sandbox.stdin.writeText(`${JSON.stringify(workerRequest)}\n`);
431
+ await sandbox.stdin.close();
432
+ }
433
+ catch (error) {
434
+ await sandbox.terminate().catch(() => undefined);
435
+ throw new Error("Failed to deliver the Modal Sandbox invocation.", {
436
+ cause: error,
437
+ });
438
+ }
439
+ return {
440
+ sandboxId: sandbox.sandboxId,
441
+ ...(request.sandbox.metadata
442
+ ? { metadata: request.sandbox.metadata }
443
+ : {}),
444
+ };
445
+ }
446
+ async cancel(sandboxId) {
447
+ const sandbox = await this.#client.sandboxes.fromId(sandboxId);
448
+ await sandbox.terminate();
449
+ }
450
+ async *messages(handle, options = {}) {
451
+ const sandboxId = handle.providerData?.sandboxId;
452
+ if (typeof sandboxId !== "string" || !sandboxId.trim()) {
453
+ throw new Error("Modal execution handle is missing its sandbox ID.");
454
+ }
455
+ const sandbox = await this.#client.sandboxes.fromId(sandboxId);
456
+ const reader = sandbox.stdout.getReader();
457
+ let buffer = "";
458
+ let receivedMessage = false;
459
+ let terminal = false;
460
+ const startupStartedAt = Date.now();
461
+ try {
462
+ while (!options.signal?.aborted) {
463
+ const startupTimeoutMs = receivedMessage
464
+ ? undefined
465
+ : Math.max(1, this.#startupTimeoutMs - (Date.now() - startupStartedAt));
466
+ const chunk = await readSandboxChunk(reader, startupTimeoutMs, options.signal);
467
+ if (chunk.value)
468
+ buffer += chunk.value;
469
+ let newline = buffer.indexOf("\n");
470
+ while (newline >= 0) {
471
+ const rawLine = buffer.slice(0, newline);
472
+ buffer = buffer.slice(newline + 1);
473
+ newline = buffer.indexOf("\n");
474
+ if (Buffer.byteLength(rawLine, "utf8") > this.#maximumProtocolLineBytes) {
475
+ throw new Error("Modal Sandbox worker protocol line is too large.");
476
+ }
477
+ const line = rawLine.trim();
478
+ if (!line)
479
+ continue;
480
+ const message = parseWorkerMessage(line);
481
+ receivedMessage = true;
482
+ if (message.type === "result" || message.type === "error") {
483
+ terminal = true;
484
+ await sandbox.terminate().catch(() => undefined);
485
+ }
486
+ yield message;
487
+ if (terminal)
488
+ return;
489
+ }
490
+ if (Buffer.byteLength(buffer, "utf8") > this.#maximumProtocolLineBytes) {
491
+ throw new Error("Modal Sandbox worker protocol line is too large.");
492
+ }
493
+ if (!chunk.done)
494
+ continue;
495
+ const finalLine = buffer.trim();
496
+ if (finalLine) {
497
+ const message = parseWorkerMessage(finalLine);
498
+ receivedMessage = true;
499
+ if (message.type === "result" || message.type === "error") {
500
+ terminal = true;
501
+ await sandbox.terminate().catch(() => undefined);
502
+ }
503
+ yield message;
504
+ if (terminal)
505
+ return;
506
+ }
507
+ const exitCode = await sandbox.wait();
508
+ throw new Error(`Modal Sandbox worker exited with code ${exitCode} without a terminal protocol message.`);
509
+ }
510
+ }
511
+ catch (error) {
512
+ await reader.cancel?.(error).catch(() => undefined);
513
+ await sandbox.terminate().catch(() => undefined);
514
+ throw error;
515
+ }
516
+ finally {
517
+ if (options.signal?.aborted) {
518
+ await reader.cancel?.(options.signal.reason).catch(() => undefined);
519
+ }
520
+ reader.releaseLock?.();
521
+ }
522
+ }
523
+ }
190
524
  const supportsMessages = (gateway) => typeof gateway.messages === "function";
191
525
  const supportsReporting = (controlPlane) => {
192
526
  const candidate = controlPlane;
@@ -323,8 +657,147 @@ export class ModalComputeLauncher {
323
657
  }
324
658
  }
325
659
  }
660
+ export class ModalSandboxComputeLauncher {
661
+ name;
662
+ #gateway;
663
+ #reporter;
664
+ #invocationCodec;
665
+ #audience;
666
+ #envelopeTtlMs;
667
+ #allowPlaintextInvocationForDevelopment;
668
+ #resolveSandbox;
669
+ #observers = new Map();
670
+ constructor(gateway, options, reporter) {
671
+ this.#gateway = gateway;
672
+ this.name = options.name ?? "modal-sandbox";
673
+ this.#reporter = reporter;
674
+ this.#invocationCodec = options.invocationCodec;
675
+ this.#audience = options.audience ?? DEFAULT_MODAL_WORKER_AUDIENCE;
676
+ this.#envelopeTtlMs = options.envelopeTtlMs;
677
+ this.#allowPlaintextInvocationForDevelopment =
678
+ options.allowPlaintextInvocationForDevelopment ?? false;
679
+ this.#resolveSandbox = options.resolveSandbox;
680
+ if (!this.#invocationCodec &&
681
+ !this.#allowPlaintextInvocationForDevelopment) {
682
+ throw new Error("Modal Sandbox remote execution requires an invocation envelope codec. Plaintext invocation is available only through allowPlaintextInvocationForDevelopment.");
683
+ }
684
+ }
685
+ async launch(invocation, context) {
686
+ const boundInvocation = invocation.request.runId == null
687
+ ? {
688
+ ...invocation,
689
+ request: {
690
+ ...invocation.request,
691
+ runId: context.handle.runId,
692
+ },
693
+ }
694
+ : invocation;
695
+ const sandbox = await this.#resolveSandbox(boundInvocation, {
696
+ executionId: context.handle.id,
697
+ runId: context.handle.runId,
698
+ });
699
+ const networkPolicy = normalizeModalSandboxNetworkPolicy(sandbox.networkPolicy);
700
+ const protectedInvocation = this.#invocationCodec
701
+ ? {
702
+ invocationEnvelope: this.#invocationCodec.seal(boundInvocation, {
703
+ executionId: context.handle.id,
704
+ runId: context.handle.runId,
705
+ audience: this.#audience,
706
+ ...(this.#envelopeTtlMs == null
707
+ ? {}
708
+ : { ttlMs: this.#envelopeTtlMs }),
709
+ }),
710
+ }
711
+ : { invocation: boundInvocation };
712
+ let spawned;
713
+ try {
714
+ spawned = await this.#gateway.spawn({
715
+ ...protectedInvocation,
716
+ executionId: context.handle.id,
717
+ runId: context.handle.runId,
718
+ sandbox: { ...sandbox, networkPolicy },
719
+ });
720
+ }
721
+ catch (error) {
722
+ throw new Error("Modal failed to start the Sandbox execution.", {
723
+ cause: error,
724
+ });
725
+ }
726
+ if (!spawned.sandboxId.trim()) {
727
+ throw new Error("Modal returned an empty sandbox ID.");
728
+ }
729
+ return {
730
+ ...(spawned.metadata ?? {}),
731
+ sandboxId: spawned.sandboxId,
732
+ };
733
+ }
734
+ async cancel(handle) {
735
+ const observer = this.#observers.get(handle.id);
736
+ observer?.abort(new Error("Modal Sandbox execution cancelled."));
737
+ const sandboxId = handle.providerData?.sandboxId;
738
+ if (typeof sandboxId !== "string" || !sandboxId.trim())
739
+ return;
740
+ await this.#gateway.cancel(sandboxId);
741
+ }
742
+ async observe(handle) {
743
+ if (!sandboxSupportsMessages(this.#gateway) || !this.#reporter)
744
+ return;
745
+ const controller = new AbortController();
746
+ this.#observers.set(handle.id, controller);
747
+ let terminal = false;
748
+ try {
749
+ for await (const message of this.#gateway.messages(handle, {
750
+ signal: controller.signal,
751
+ })) {
752
+ if (message.type === "event") {
753
+ await this.#reporter.acceptEvent(handle, message.event);
754
+ }
755
+ else if (message.type === "result") {
756
+ terminal = true;
757
+ await this.#reporter.complete(handle, message.result);
758
+ return;
759
+ }
760
+ else if (message.type === "error") {
761
+ terminal = true;
762
+ await this.#reporter.fail(handle, {
763
+ code: message.error.code,
764
+ message: "Modal Sandbox worker reported an execution failure.",
765
+ ...(message.error.retryable == null
766
+ ? {}
767
+ : { retryable: message.error.retryable }),
768
+ });
769
+ return;
770
+ }
771
+ }
772
+ if (!terminal) {
773
+ await this.#reporter.fail(handle, {
774
+ code: "MODAL_SANDBOX_MESSAGE_STREAM_ENDED",
775
+ message: "Modal Sandbox worker message stream ended without a terminal result.",
776
+ retryable: true,
777
+ });
778
+ }
779
+ }
780
+ catch {
781
+ if (controller.signal.aborted)
782
+ return;
783
+ await this.#reporter.fail(handle, {
784
+ code: "MODAL_SANDBOX_MESSAGE_STREAM_FAILED",
785
+ message: "Modal Sandbox worker message delivery failed.",
786
+ retryable: true,
787
+ });
788
+ }
789
+ finally {
790
+ this.#observers.delete(handle.id);
791
+ }
792
+ }
793
+ }
326
794
  export class ModalExecutionEngine extends RemoteExecutionEngine {
327
795
  constructor(gateway, controlPlane, options = {}) {
328
796
  super(new ModalComputeLauncher(gateway, options, supportsReporting(controlPlane) ? controlPlane : undefined), controlPlane);
329
797
  }
330
798
  }
799
+ export class ModalSandboxExecutionEngine extends RemoteExecutionEngine {
800
+ constructor(gateway, controlPlane, options) {
801
+ super(new ModalSandboxComputeLauncher(gateway, options, supportsReporting(controlPlane) ? controlPlane : undefined), controlPlane);
802
+ }
803
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/worker.js ADDED
@@ -0,0 +1,99 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from "node:child_process";
3
+ import { AesGcmWorkerInvocationCodec } from "@clearideas/agent-runtime-execution";
4
+ import { DEFAULT_MODAL_WORKER_AUDIENCE, decodeModalWorkerInvocation, } from "./index.js";
5
+ const ACTIVE_KEY_ID_ENV = "AGENT_RUNTIME_MODAL_INVOCATION_ACTIVE_KEY_ID";
6
+ const KEYRING_ENV = "AGENT_RUNTIME_MODAL_INVOCATION_KEYS";
7
+ const AUDIENCE_ENV = "AGENT_RUNTIME_MODAL_INVOCATION_AUDIENCE";
8
+ const EXECUTION_ID_ENV = "AGENT_RUNTIME_MODAL_EXECUTION_ID";
9
+ const RUN_ID_ENV = "AGENT_RUNTIME_MODAL_RUN_ID";
10
+ const COMMAND_ENV = "AGENT_RUNTIME_MODAL_WORKER_COMMAND";
11
+ const ARGS_ENV = "AGENT_RUNTIME_MODAL_WORKER_ARGS";
12
+ const ALLOW_PLAINTEXT_ENV = "AGENT_RUNTIME_MODAL_ALLOW_PLAINTEXT_FOR_DEVELOPMENT";
13
+ const MAXIMUM_INPUT_BYTES = 16 * 1024 * 1024;
14
+ const requiredEnvironment = (name) => {
15
+ const value = process.env[name];
16
+ if (!value?.trim())
17
+ throw new Error(`Missing required environment ${name}.`);
18
+ return value;
19
+ };
20
+ const readInput = async () => {
21
+ process.stdin.setEncoding("utf8");
22
+ let input = "";
23
+ for await (const chunk of process.stdin) {
24
+ input += chunk;
25
+ if (Buffer.byteLength(input, "utf8") > MAXIMUM_INPUT_BYTES) {
26
+ throw new Error("Modal Sandbox invocation exceeds the input limit.");
27
+ }
28
+ }
29
+ if (!input.trim())
30
+ throw new Error("Modal Sandbox invocation is empty.");
31
+ return input;
32
+ };
33
+ const parseStringArray = (value) => {
34
+ if (!value?.trim())
35
+ return ["worker"];
36
+ const parsed = JSON.parse(value);
37
+ if (!Array.isArray(parsed) ||
38
+ parsed.some((item) => typeof item !== "string")) {
39
+ throw new Error(`${ARGS_ENV} must be a JSON string array.`);
40
+ }
41
+ return parsed;
42
+ };
43
+ const run = async () => {
44
+ const request = JSON.parse(await readInput());
45
+ const allowPlaintext = process.env[ALLOW_PLAINTEXT_ENV]?.toLowerCase() === "true";
46
+ const codec = allowPlaintext
47
+ ? undefined
48
+ : new AesGcmWorkerInvocationCodec({
49
+ activeKeyId: requiredEnvironment(ACTIVE_KEY_ID_ENV),
50
+ keys: JSON.parse(requiredEnvironment(KEYRING_ENV)),
51
+ });
52
+ const invocation = decodeModalWorkerInvocation(request, codec, {
53
+ executionId: requiredEnvironment(EXECUTION_ID_ENV),
54
+ runId: requiredEnvironment(RUN_ID_ENV),
55
+ audience: process.env[AUDIENCE_ENV]?.trim() || DEFAULT_MODAL_WORKER_AUDIENCE,
56
+ allowPlaintextInvocationForDevelopment: allowPlaintext,
57
+ });
58
+ const childEnvironment = { ...process.env };
59
+ delete childEnvironment[ACTIVE_KEY_ID_ENV];
60
+ delete childEnvironment[KEYRING_ENV];
61
+ delete childEnvironment[ALLOW_PLAINTEXT_ENV];
62
+ const child = spawn(process.env[COMMAND_ENV]?.trim() || "agent-runtime", parseStringArray(process.env[ARGS_ENV]), {
63
+ env: childEnvironment,
64
+ stdio: ["pipe", "pipe", "pipe"],
65
+ });
66
+ child.stdout.pipe(process.stdout);
67
+ child.stderr.pipe(process.stderr);
68
+ child.stdin.end(`${JSON.stringify(invocation)}\n`);
69
+ const forwardSignal = (signal) => {
70
+ if (!child.killed)
71
+ child.kill(signal);
72
+ };
73
+ process.once("SIGTERM", forwardSignal);
74
+ process.once("SIGINT", forwardSignal);
75
+ try {
76
+ return await new Promise((resolve, reject) => {
77
+ child.once("error", reject);
78
+ child.once("exit", (code, signal) => {
79
+ if (signal)
80
+ reject(new Error(`Worker terminated by ${signal}.`));
81
+ else
82
+ resolve(code ?? 1);
83
+ });
84
+ });
85
+ }
86
+ finally {
87
+ process.removeListener("SIGTERM", forwardSignal);
88
+ process.removeListener("SIGINT", forwardSignal);
89
+ }
90
+ };
91
+ void run().then((code) => {
92
+ process.exitCode = code;
93
+ }, () => {
94
+ // Do not serialize raw errors: envelope, provider, or child failures may
95
+ // contain secret-bearing details. The host observes a sanitized stream
96
+ // failure and Modal retains stderr for trusted operational diagnostics.
97
+ process.stderr.write("Modal Sandbox worker bootstrap failed.\n");
98
+ process.exitCode = 1;
99
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clearideas/agent-runtime-execution-modal",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Modal compute adapter for Agent Runtime execution engines.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Clear Ideas Incorporated",
@@ -22,6 +22,9 @@
22
22
  "type": "module",
23
23
  "main": "dist/index.js",
24
24
  "types": "dist/index.d.ts",
25
+ "bin": {
26
+ "agent-runtime-modal-worker": "dist/worker.js"
27
+ },
25
28
  "exports": {
26
29
  ".": {
27
30
  "types": "./dist/index.d.ts",
@@ -36,12 +39,12 @@
36
39
  "postpack": "node ../../scripts/cleanup-package-license.mjs"
37
40
  },
38
41
  "dependencies": {
39
- "@clearideas/agent-runtime-contracts": "0.1.0",
40
- "@clearideas/agent-runtime-execution": "0.1.0"
42
+ "@clearideas/agent-runtime-contracts": "0.2.0",
43
+ "@clearideas/agent-runtime-execution": "0.2.0"
41
44
  },
42
45
  "devDependencies": {
43
- "@types/node": "^25.6.0",
44
- "typescript": "^6.0.3",
46
+ "@types/node": "^26.1.2",
47
+ "typescript": "^7.0.2",
45
48
  "vitest": "^4.0.18"
46
49
  },
47
50
  "engines": {