@tangle-network/sandbox 0.13.0-develop.20260727091103.289ad8d → 0.13.0-develop.20260727130113.8ef847a

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.
@@ -1,6 +1,973 @@
1
- import { c as encodeTextForWire, d as normalizeRuntimeBackendConfig, i as SANDBOX_PROXY_REQUEST_MAX_BYTES, l as applyRequestedModel, o as combineAbortSignals, s as encodePromptForWire, u as assertCurrentBackendType } from "./runtime-api-CCvDLhAW.js";
2
- import { a as NotFoundError, c as SandboxError, d as TimeoutError, f as ValidationError, i as NetworkError, o as PartialFailureError, p as parseErrorResponse, t as AuthError } from "./errors-D9fFOWX9.js";
3
- import { g as exportTraceBundle, m as normalizeConnection, n as createSandboxInstanceFromResponse, r as normalizeStartupDiagnostics, y as parseSSEStream } from "./sandbox-CAiVH_Mg.js";
1
+ import { c as encodeTextForWire, d as normalizeRuntimeBackendConfig, f as backendTypeSchema, i as SANDBOX_PROXY_REQUEST_MAX_BYTES, l as applyRequestedModel, o as combineAbortSignals, s as encodePromptForWire, u as assertCurrentBackendType } from "./runtime-api-CCvDLhAW.js";
2
+ import { a as NotFoundError, c as SandboxError, d as TimeoutError, f as ValidationError, i as NetworkError, l as ServerError, o as PartialFailureError, p as parseErrorResponse, t as AuthError } from "./errors-D9fFOWX9.js";
3
+ import { g as exportTraceBundle, m as normalizeConnection, n as createSandboxInstanceFromResponse, r as normalizeStartupDiagnostics, y as parseSSEStream } from "./sandbox-Bvt_WexG.js";
4
+ import { agentProfileSchema } from "@tangle-network/agent-interface";
5
+ import { z } from "zod";
6
+ //#region ../../../packages/runtime-contracts/dist/git-policy.js
7
+ const MAX_GIT_AUTH_TOKEN_LENGTH = 4096;
8
+ const MAX_GIT_REPOSITORY_PATH_SEGMENT_LENGTH = 255;
9
+ const SAFE_GIT_REPOSITORY_PATH_SEGMENT = /^[A-Za-z0-9._~-]+$/u;
10
+ const ENCODED_PATH_SEPARATOR = /%(?:2f|5c)/iu;
11
+ /**
12
+ * Parse only the owner/repository portion of a Git URL.
13
+ * Protocol, credentials, host, port, query, and fragment remain the caller's
14
+ * responsibility because public and internal callers have different host rules.
15
+ */
16
+ function parseGitRepositoryPath(rawUrl) {
17
+ const match = /^[A-Za-z][A-Za-z0-9+.-]*:\/\/[^/?#]*(?<path>\/[^?#]*)?(?:[?#].*)?$/u.exec(rawUrl);
18
+ if (!match) return void 0;
19
+ const rawPath = match?.groups?.path ?? "/";
20
+ if (ENCODED_PATH_SEPARATOR.test(rawPath)) return void 0;
21
+ let decodedPath;
22
+ try {
23
+ decodedPath = decodeURIComponent(rawPath);
24
+ } catch {
25
+ return;
26
+ }
27
+ if (!decodedPath.startsWith("/") || decodedPath.includes("\\")) return;
28
+ const segments = decodedPath.slice(1).split("/");
29
+ if (segments.at(-1) === "") segments.pop();
30
+ if (segments.length < 2 || segments.some((segment) => segment.length === 0 || segment.length > MAX_GIT_REPOSITORY_PATH_SEGMENT_LENGTH || segment === "." || segment === ".." || !SAFE_GIT_REPOSITORY_PATH_SEGMENT.test(segment))) return;
31
+ const repositorySegment = segments.at(-1);
32
+ if (!repositorySegment) return void 0;
33
+ const repositoryName = repositorySegment.endsWith(".git") ? repositorySegment.slice(0, -4) : repositorySegment;
34
+ if (!repositoryName || repositoryName === "." || repositoryName === "..") return;
35
+ return {
36
+ canonicalPathname: `/${segments.join("/")}`,
37
+ ownerPath: segments.slice(0, -1),
38
+ repositoryName
39
+ };
40
+ }
41
+ //#endregion
42
+ //#region ../../../packages/runtime-contracts/dist/batch-request.js
43
+ const BATCH_MAX_TASKS = 1e3;
44
+ const BATCH_MAX_MESSAGE_LENGTH = 64 * 1024;
45
+ const BATCH_MAX_REQUEST_BYTES = 512 * 1024;
46
+ const BATCH_MAX_CONTEXT_BYTES = 64 * 1024;
47
+ const BATCH_MAX_PROFILE_BYTES = 128 * 1024;
48
+ const BATCH_MAX_TIMEOUT_MS = 864e5;
49
+ const BATCH_MAX_PROVISION_TIMEOUT_MS = 9e5;
50
+ const BATCH_MAX_PUBLIC_GRACE_MS = 3e5;
51
+ const BATCH_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
52
+ const BATCH_MAX_LIFECYCLE_TIMEOUT_MS = 2592e6;
53
+ const BATCH_MAX_GIT_DEPTH = 1e3;
54
+ const BATCH_MAX_THINKING_TOKENS = 1e6;
55
+ const batchIdSchema = z.string().regex(BATCH_ID_PATTERN, { message: "must start with a letter or number and contain only letters, numbers, dots, underscores, or hyphens" });
56
+ function opaqueBatchKeySchema(label, maxLength) {
57
+ return z.string().min(1).max(maxLength).regex(/^[\x21-\x7e]+$/, { message: `${label} must contain only visible ASCII characters` });
58
+ }
59
+ /** HTTP retry identity. It is transported in `Idempotency-Key`, never the body. */
60
+ const batchIdempotencyKeySchema = opaqueBatchKeySchema("Idempotency-Key", 128);
61
+ /** Caller-owned identity for persistent compute reused across batch requests. */
62
+ const batchReuseKeySchema = opaqueBatchKeySchema("reuseKey", 128);
63
+ function uniqueIds(kind) {
64
+ return (values, context) => {
65
+ const seen = /* @__PURE__ */ new Set();
66
+ for (let index = 0; index < values.length; index += 1) {
67
+ const id = values[index]?.id;
68
+ if (id !== void 0 && seen.has(id)) context.addIssue({
69
+ code: "custom",
70
+ message: `Duplicate ${kind} id: ${id}`,
71
+ path: [index, "id"]
72
+ });
73
+ if (id !== void 0) seen.add(id);
74
+ }
75
+ };
76
+ }
77
+ function serializedJsonBytes(value) {
78
+ try {
79
+ const serialized = JSON.stringify(value);
80
+ if (serialized === void 0) return void 0;
81
+ return new TextEncoder().encode(serialized).byteLength;
82
+ } catch {
83
+ return;
84
+ }
85
+ }
86
+ function exceedsJsonDepth(value, maxDepth) {
87
+ const pending = [{
88
+ value,
89
+ depth: 0
90
+ }];
91
+ while (pending.length > 0) {
92
+ const current = pending.pop();
93
+ if (!current || current.value === null || typeof current.value !== "object") continue;
94
+ const depth = current.depth + 1;
95
+ if (depth > maxDepth) return true;
96
+ const children = Array.isArray(current.value) ? current.value : Object.values(current.value);
97
+ for (const child of children) pending.push({
98
+ value: child,
99
+ depth
100
+ });
101
+ }
102
+ return false;
103
+ }
104
+ function addStructuredJsonLimits(value, context, options) {
105
+ const bytes = serializedJsonBytes(value);
106
+ if (bytes === void 0) {
107
+ context.addIssue({
108
+ code: "custom",
109
+ message: `${options.label} must be JSON serializable`
110
+ });
111
+ return;
112
+ }
113
+ if (bytes > options.maxBytes) context.addIssue({
114
+ code: "custom",
115
+ message: `${options.label} must be at most ${options.maxBytes} serialized bytes`
116
+ });
117
+ if (exceedsJsonDepth(value, 16)) context.addIssue({
118
+ code: "custom",
119
+ message: `${options.label} must be at most 16 JSON containers deep`
120
+ });
121
+ }
122
+ function addBatchRequestSizeLimit(value, context) {
123
+ const bytes = serializedJsonBytes(value);
124
+ if (bytes === void 0 || bytes > 524288) context.addIssue({
125
+ code: "custom",
126
+ message: `batch request must be at most ${BATCH_MAX_REQUEST_BYTES} serialized bytes`
127
+ });
128
+ }
129
+ const batchContextSchema = z.record(z.string(), z.unknown()).refine((value) => Object.keys(value).length <= 256, { message: "context must contain at most 256 entries" }).superRefine((value, context) => addStructuredJsonLimits(value, context, {
130
+ label: "context",
131
+ maxBytes: BATCH_MAX_CONTEXT_BYTES
132
+ }));
133
+ const batchProfileSchema = agentProfileSchema.safeExtend({ harness: agentProfileSchema.shape.harness.unwrap().and(backendTypeSchema).optional() }).superRefine((value, context) => addStructuredJsonLimits(value, context, {
134
+ label: "profile",
135
+ maxBytes: BATCH_MAX_PROFILE_BYTES
136
+ }));
137
+ const batchExecutionClassSchema = z.enum([
138
+ "project",
139
+ "simulation",
140
+ "background"
141
+ ]);
142
+ const batchTaskSchema = z.object({
143
+ id: batchIdSchema,
144
+ message: z.string().min(1).max(BATCH_MAX_MESSAGE_LENGTH),
145
+ context: batchContextSchema.optional(),
146
+ timeoutMs: z.number().int().positive().max(BATCH_MAX_TIMEOUT_MS).optional()
147
+ }).strict();
148
+ const batchTasksSchema = z.array(batchTaskSchema).min(1).max(BATCH_MAX_TASKS).superRefine(uniqueIds("task"));
149
+ const batchBackendSchema = z.object({
150
+ id: batchIdSchema,
151
+ type: backendTypeSchema,
152
+ model: z.object({
153
+ provider: z.string().min(1).max(128).optional(),
154
+ model: z.string().min(1).max(256).optional(),
155
+ apiKey: z.string().min(1).max(65536).optional(),
156
+ baseUrl: z.string().url().max(2048).optional(),
157
+ maxThinkingTokens: z.number().int().nonnegative().max(BATCH_MAX_THINKING_TOKENS).optional(),
158
+ mode: z.enum(["api", "cli"]).optional()
159
+ }).strict().optional(),
160
+ server: z.object({
161
+ hostname: z.string().min(1).max(256).optional(),
162
+ port: z.number().int().min(1).max(65535).optional()
163
+ }).strict().optional(),
164
+ profile: batchProfileSchema.optional()
165
+ }).strict();
166
+ const batchBackendsSchema = z.array(batchBackendSchema).min(1).max(20).superRefine(uniqueIds("backend"));
167
+ function parseRepositoryUrl(value) {
168
+ try {
169
+ const url = new URL(value);
170
+ const repositoryPath = parseGitRepositoryPath(value);
171
+ const hostname = url.hostname.toLowerCase();
172
+ const labels = hostname.split(".");
173
+ if (!repositoryPath || url.protocol !== "https:" || url.username.length > 0 || url.password.length > 0 || url.port.length > 0 || url.search.length > 0 || url.hash.length > 0 || hostname.endsWith(".") || hostname.includes(":") || labels.length < 2 || labels.every((label) => /^\d+$/.test(label)) || labels.some((label) => !/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(label) || label.length > 63) || [
174
+ "instance-data.ec2.internal",
175
+ "metadata.azure.com",
176
+ "metadata.goog",
177
+ "metadata.google.internal"
178
+ ].includes(hostname) || [
179
+ ".home.arpa",
180
+ ".internal",
181
+ ".local",
182
+ ".localhost"
183
+ ].some((suffix) => hostname.endsWith(suffix))) return;
184
+ url.pathname = repositoryPath.canonicalPathname;
185
+ return url;
186
+ } catch {
187
+ return;
188
+ }
189
+ }
190
+ const repositoryUrlSchema = z.string().min(1).max(2048).refine((value) => parseRepositoryUrl(value) !== void 0, { message: "must be a credential-free HTTPS URL on a public DNS host with no query, fragment, or custom port" });
191
+ const batchGitSchema = z.object({
192
+ url: repositoryUrlSchema,
193
+ ref: z.string().min(1).max(1024).optional(),
194
+ depth: z.number().int().positive().max(BATCH_MAX_GIT_DEPTH).optional(),
195
+ sparse: z.array(z.string().min(1).max(4096)).max(256).optional(),
196
+ auth: z.object({ token: z.string().min(1).max(MAX_GIT_AUTH_TOKEN_LENGTH).optional() }).strict().optional()
197
+ }).strict();
198
+ const batchLifecycleSchema = z.object({
199
+ idleTimeoutMs: z.number().int().positive().max(BATCH_MAX_LIFECYCLE_TIMEOUT_MS).default(3e5),
200
+ coldTimeoutMs: z.number().int().positive().max(BATCH_MAX_LIFECYCLE_TIMEOUT_MS).default(36e5)
201
+ }).strict();
202
+ const commonBatchRequestShape = {
203
+ tasks: batchTasksSchema,
204
+ backends: batchBackendsSchema,
205
+ timeoutMs: z.number().int().positive().max(BATCH_MAX_TIMEOUT_MS).default(3e5),
206
+ executionClass: batchExecutionClassSchema.default("simulation")
207
+ };
208
+ const batchPartnerShape = { partnerId: z.string().min(1).max(256).optional() };
209
+ const batchIdentityShape = {
210
+ userId: z.string().min(1).max(256),
211
+ ...batchPartnerShape
212
+ };
213
+ const trustedBatchControlShape = {
214
+ scalingMode: z.enum([
215
+ "fastest",
216
+ "balanced",
217
+ "cheapest"
218
+ ]).default("balanced"),
219
+ desiredCapacity: z.number().int().positive().max(500).optional(),
220
+ provisionTimeoutMs: z.number().int().positive().max(BATCH_MAX_PROVISION_TIMEOUT_MS).default(3e5),
221
+ mock: z.boolean().default(false)
222
+ };
223
+ const temporaryBatchRequestShape = {
224
+ persistent: z.literal(false).default(false),
225
+ graceMs: z.number().int().nonnegative().max(BATCH_MAX_PUBLIC_GRACE_MS).optional()
226
+ };
227
+ const persistentBatchRequestShape = {
228
+ persistent: z.literal(true),
229
+ reuseKey: batchReuseKeySchema,
230
+ lifecycle: batchLifecycleSchema.optional(),
231
+ git: batchGitSchema.optional()
232
+ };
233
+ const temporaryBatchRunRequestSchema = z.object({
234
+ ...commonBatchRequestShape,
235
+ ...batchIdentityShape,
236
+ ...trustedBatchControlShape,
237
+ ...temporaryBatchRequestShape
238
+ }).strict().superRefine(addBatchRequestSizeLimit);
239
+ const persistentBatchRunRequestSchema = z.object({
240
+ ...commonBatchRequestShape,
241
+ ...batchIdentityShape,
242
+ ...trustedBatchControlShape,
243
+ ...persistentBatchRequestShape
244
+ }).strict().superRefine(addBatchRequestSizeLimit);
245
+ z.union([temporaryBatchRunRequestSchema, persistentBatchRunRequestSchema]);
246
+ const trustedTemporaryBatchRunRequestBodySchema = z.object({
247
+ ...commonBatchRequestShape,
248
+ ...batchPartnerShape,
249
+ ...trustedBatchControlShape,
250
+ ...temporaryBatchRequestShape
251
+ }).strict().superRefine(addBatchRequestSizeLimit);
252
+ const trustedPersistentBatchRunRequestBodySchema = z.object({
253
+ ...commonBatchRequestShape,
254
+ ...batchPartnerShape,
255
+ ...trustedBatchControlShape,
256
+ ...persistentBatchRequestShape
257
+ }).strict().superRefine(addBatchRequestSizeLimit);
258
+ z.union([trustedTemporaryBatchRunRequestBodySchema, trustedPersistentBatchRunRequestBodySchema]);
259
+ const publicTemporaryBatchRunRequestSchema = z.object({
260
+ ...commonBatchRequestShape,
261
+ ...temporaryBatchRequestShape
262
+ }).strict().superRefine(addBatchRequestSizeLimit);
263
+ const publicPersistentBatchRunRequestSchema = z.object({
264
+ ...commonBatchRequestShape,
265
+ ...persistentBatchRequestShape
266
+ }).strict().superRefine(addBatchRequestSizeLimit);
267
+ /** Public callers control work only. Identity and capacity are server-owned. */
268
+ const publicBatchRunRequestSchema = z.union([publicTemporaryBatchRunRequestSchema, publicPersistentBatchRunRequestSchema]);
269
+ //#endregion
270
+ //#region ../../../packages/runtime-contracts/dist/batch-stream.js
271
+ /** A transport-independent batch event sequence failure. */
272
+ var BatchStreamError = class extends Error {
273
+ kind;
274
+ failure;
275
+ cleanup;
276
+ name = "BatchStreamError";
277
+ constructor(message, kind, failure, cleanup) {
278
+ super(message);
279
+ this.kind = kind;
280
+ this.failure = failure;
281
+ this.cleanup = cleanup;
282
+ }
283
+ };
284
+ function invalid(message) {
285
+ throw new BatchStreamError(message, "invalid");
286
+ }
287
+ function incomplete(message) {
288
+ throw new BatchStreamError(message, "incomplete");
289
+ }
290
+ function executionKey(taskId, backendId) {
291
+ return JSON.stringify([taskId, backendId]);
292
+ }
293
+ function expectedSuccessRate(success, total) {
294
+ return total === 0 ? 0 : success / total * 100;
295
+ }
296
+ function ratesMatch(left, right) {
297
+ return Math.abs(left - right) < 1e-9;
298
+ }
299
+ function setsMatch(left, right) {
300
+ return left.size === right.size && [...left].every((value) => right.has(value));
301
+ }
302
+ function backendStatsMatch(left, right) {
303
+ return left.backendId === right.backendId && left.backendType === right.backendType && left.backendLabel === right.backendLabel && left.backendModel === right.backendModel && left.success === right.success && left.failure === right.failure && left.retries === right.retries && ratesMatch(left.successRate, right.successRate);
304
+ }
305
+ function eventMetadata(event) {
306
+ return {
307
+ backendLabel: event.backendLabel,
308
+ backendModel: event.backendModel,
309
+ sidecarId: event.sidecarId,
310
+ projectRef: event.projectRef
311
+ };
312
+ }
313
+ function metadataMatches(left, right) {
314
+ return left.backendLabel === right.backendLabel && left.backendModel === right.backendModel && left.sidecarId === right.sidecarId && left.projectRef === right.projectRef;
315
+ }
316
+ function hasTrustedCapacityFields(request) {
317
+ return "userId" in request;
318
+ }
319
+ /**
320
+ * Validates one canonical batch event sequence and assembles its complete
321
+ * terminal result. It has no transport or SDK error dependencies.
322
+ */
323
+ var BatchStreamState = class {
324
+ request;
325
+ taskIndexes;
326
+ backendTypes;
327
+ executions = /* @__PURE__ */ new Map();
328
+ allocatedSidecarsByBackend = /* @__PURE__ */ new Map();
329
+ allocatedSidecarIds = /* @__PURE__ */ new Set();
330
+ completedBackends = /* @__PURE__ */ new Map();
331
+ releasingSidecars = /* @__PURE__ */ new Set();
332
+ releasedSidecars = /* @__PURE__ */ new Set();
333
+ pendingSidecars = /* @__PURE__ */ new Set();
334
+ eventIds = /* @__PURE__ */ new Set();
335
+ provisioning;
336
+ provisioned;
337
+ started;
338
+ sidecars;
339
+ completion;
340
+ failure;
341
+ cleanup;
342
+ constructor(request) {
343
+ this.request = request;
344
+ this.taskIndexes = new Map(request.tasks.map((task, index) => [task.id, index]));
345
+ this.backendTypes = new Map(request.backends.map((backend) => [backend.id, backend.type]));
346
+ for (const task of request.tasks) for (const backend of request.backends) this.executions.set(executionKey(task.id, backend.id), {
347
+ started: false,
348
+ retries: 0
349
+ });
350
+ }
351
+ get terminal() {
352
+ if (this.completion) return "completed";
353
+ if (this.failure) return "failed";
354
+ }
355
+ add(event) {
356
+ if (event.id !== void 0) {
357
+ if (this.eventIds.has(event.id)) invalid(`Batch stream repeated event id: ${event.id}`);
358
+ this.eventIds.add(event.id);
359
+ }
360
+ switch (event.type) {
361
+ case "batch.provisioning":
362
+ this.addProvisioning(event.data);
363
+ return;
364
+ case "batch.provisioned":
365
+ this.addProvisioned(event.data);
366
+ return;
367
+ case "batch.started":
368
+ this.addStarted(event.data);
369
+ return;
370
+ case "sidecars.allocated":
371
+ this.addSidecars(event.data);
372
+ return;
373
+ case "task.started":
374
+ this.addTaskStarted(event.data);
375
+ return;
376
+ case "task.message.delta":
377
+ case "task.reasoning":
378
+ case "task.tool.updated":
379
+ this.addTaskProgress(event.type, event.data);
380
+ return;
381
+ case "task.retry":
382
+ this.addTaskRetry(event.data);
383
+ return;
384
+ case "task.completed":
385
+ this.addTaskCompleted(event.data);
386
+ return;
387
+ case "task.failed":
388
+ this.addTaskFailed(event.data);
389
+ return;
390
+ case "backend.completed":
391
+ this.addBackendCompleted(event.data);
392
+ return;
393
+ case "batch.completed":
394
+ this.addBatchCompleted(event.data);
395
+ return;
396
+ case "batch.failed":
397
+ this.addBatchFailed(event.data);
398
+ return;
399
+ case "batch.persistent":
400
+ this.addPersistentCleanup(event.data);
401
+ return;
402
+ case "batch.grace_period":
403
+ this.addGraceCleanup(event.data);
404
+ return;
405
+ case "sidecar.releasing":
406
+ this.addSidecarReleasing(event.data);
407
+ return;
408
+ case "sidecar.released":
409
+ this.addSidecarReleased(event.data);
410
+ return;
411
+ case "sidecar.release_pending":
412
+ this.addSidecarReleasePending(event.data);
413
+ return;
414
+ }
415
+ }
416
+ finish() {
417
+ if (!this.completion && !this.failure) incomplete("Batch stream ended before batch.completed or batch.failed");
418
+ const cleanup = this.finishCleanup();
419
+ if (this.failure) throw new BatchStreamError(this.failure.error, "failed", this.failure, cleanup);
420
+ const completion = this.completion;
421
+ const started = this.started;
422
+ const sidecars = this.sidecars;
423
+ if (!completion || !started || !sidecars) incomplete("Batch stream ended without complete execution metadata");
424
+ const byBackend = this.request.backends.map((backend) => {
425
+ const result = this.completedBackends.get(backend.id);
426
+ if (!result) incomplete(`Batch stream ended before backend ${backend.id} completed`);
427
+ return result;
428
+ });
429
+ const results = this.request.tasks.flatMap((task) => this.request.backends.map((backend) => {
430
+ const result = this.executions.get(executionKey(task.id, backend.id))?.terminal;
431
+ if (!result) incomplete(`Batch stream ended before task ${task.id} and backend ${backend.id} completed`);
432
+ return result;
433
+ }));
434
+ return {
435
+ totalTasks: completion.taskCount,
436
+ totalBackends: completion.backendCount,
437
+ totalExecutions: completion.totalExecutions,
438
+ totalSuccess: completion.totalSuccess,
439
+ totalFailure: completion.totalFailure,
440
+ totalRetries: completion.totalRetries,
441
+ successRate: completion.successRate,
442
+ byBackend,
443
+ results,
444
+ execution: {
445
+ ...this.provisioning && this.provisioned ? { provisioning: {
446
+ requested: this.provisioning,
447
+ provisioned: this.provisioned
448
+ } } : {},
449
+ started,
450
+ sidecars,
451
+ completion,
452
+ cleanup
453
+ }
454
+ };
455
+ }
456
+ requireBeforeStart(eventType) {
457
+ if (this.started || this.terminal) invalid(`Batch stream emitted ${eventType} after batch.started`);
458
+ }
459
+ requireRunning(eventType) {
460
+ if (this.terminal) invalid(`Batch stream emitted ${eventType} after batch.${this.terminal}`);
461
+ if (!this.started) invalid(`Batch stream emitted ${eventType} before batch.started`);
462
+ }
463
+ requireAllocated(eventType) {
464
+ this.requireRunning(eventType);
465
+ if (!this.sidecars) invalid(`Batch stream emitted ${eventType} before sidecars.allocated`);
466
+ }
467
+ requireTerminal(eventType) {
468
+ if (!this.terminal) invalid(`Batch stream emitted ${eventType} before a batch terminal event`);
469
+ }
470
+ validateBackend(identity) {
471
+ const expectedType = this.backendTypes.get(identity.backendId);
472
+ if (!expectedType) invalid(`Batch stream referenced unknown backend id: ${identity.backendId}`);
473
+ if (identity.backendType !== expectedType) invalid(`Batch stream reported backend ${identity.backendId} as ${identity.backendType}; expected ${expectedType}`);
474
+ return expectedType;
475
+ }
476
+ execution(identity) {
477
+ if (!this.taskIndexes.has(identity.taskId)) invalid(`Batch stream referenced unknown task id: ${identity.taskId}`);
478
+ this.validateBackend(identity);
479
+ if (this.completedBackends.has(identity.backendId)) invalid(`Batch stream emitted a task event after backend.completed for backend ${identity.backendId}`);
480
+ const state = this.executions.get(executionKey(identity.taskId, identity.backendId));
481
+ if (!state) invalid("Batch stream referenced an unknown task-backend execution");
482
+ if (state.terminal) invalid(`Batch stream emitted an execution event after the terminal event for task ${identity.taskId} and backend ${identity.backendId}`);
483
+ return state;
484
+ }
485
+ validateMetadata(identity, data, state) {
486
+ const sidecars = this.allocatedSidecarsByBackend.get(identity.backendId);
487
+ if (data.sidecarId !== void 0 && !sidecars?.has(data.sidecarId)) invalid(`Batch stream reported unallocated sidecar ${data.sidecarId} for backend ${identity.backendId}`);
488
+ if (this.request.persistent) {
489
+ if (data.sidecarId !== void 0 && data.projectRef === void 0) invalid(`Batch stream omitted projectRef for persistent task ${identity.taskId}`);
490
+ } else if (data.projectRef !== void 0) invalid(`Batch stream reported projectRef for non-persistent task ${identity.taskId}`);
491
+ if (!state.metadata) {
492
+ state.metadata = data;
493
+ return;
494
+ }
495
+ if (!metadataMatches(state.metadata, data)) invalid(`Batch stream changed execution metadata for task ${identity.taskId} and backend ${identity.backendId}`);
496
+ }
497
+ addProvisioning(data) {
498
+ this.requireBeforeStart("batch.provisioning");
499
+ if (this.provisioning || this.provisioned) invalid("Batch stream emitted batch.provisioning out of order or more than once");
500
+ if (data.currentCapacity >= data.desiredCapacity) invalid("Batch provisioning metadata does not describe a capacity shortfall");
501
+ if (hasTrustedCapacityFields(this.request) && (this.request.desiredCapacity !== void 0 && data.desiredCapacity !== this.request.desiredCapacity || data.provisionTimeoutMs !== this.request.provisionTimeoutMs)) invalid("Batch provisioning metadata does not match the request");
502
+ this.provisioning = data;
503
+ }
504
+ addProvisioned(data) {
505
+ this.requireBeforeStart("batch.provisioned");
506
+ if (!this.provisioning || this.provisioned) invalid("Batch stream emitted batch.provisioned out of order or more than once");
507
+ if (data.capacity < this.provisioning.desiredCapacity) invalid("Batch provisioned capacity does not satisfy the request");
508
+ this.provisioned = data;
509
+ }
510
+ addStarted(data) {
511
+ if (this.started || this.terminal) invalid("Batch stream emitted batch.started more than once");
512
+ if (this.provisioning && !this.provisioned) invalid("Batch stream emitted batch.started before batch.provisioned");
513
+ const reportedIds = new Set(data.backendIds);
514
+ const identitiesMatch = data.backendIds.every((backendId, index) => this.backendTypes.get(backendId) === data.backendTypes[index]);
515
+ const expectedExecutions = this.taskIndexes.size * this.backendTypes.size;
516
+ if (data.taskCount !== this.taskIndexes.size || data.backendCount !== this.backendTypes.size || data.totalExecutions !== expectedExecutions || data.backendIds.length !== this.backendTypes.size || data.backendTypes.length !== this.backendTypes.size || reportedIds.size !== this.backendTypes.size || [...this.backendTypes.keys()].some((id) => !reportedIds.has(id)) || !identitiesMatch || data.backendGroups < 1 || data.backendGroups > this.backendTypes.size || data.executionClass !== this.request.executionClass || data.maxConcurrentPerSidecar < 1 || data.maxSidecarsTotal < 1 || data.driverCapacity < 1) invalid("Batch start metadata does not match the request");
517
+ this.started = data;
518
+ }
519
+ addSidecars(data) {
520
+ this.requireRunning("sidecars.allocated");
521
+ if (this.sidecars) invalid("Batch stream emitted sidecars.allocated more than once");
522
+ const started = this.started;
523
+ if (!started) invalid("Batch stream is missing batch start metadata");
524
+ const coveredBackends = /* @__PURE__ */ new Set();
525
+ const backendGroups = /* @__PURE__ */ new Map();
526
+ const groupSignatures = /* @__PURE__ */ new Set();
527
+ for (const group of data.groups) {
528
+ if (group.variants !== group.backendIds.length || new Set(group.backendIds).size !== group.backendIds.length) invalid(`Sidecar ${group.sidecarId} reported inconsistent backend variants`);
529
+ if (this.allocatedSidecarIds.has(group.sidecarId)) invalid(`Batch sidecar allocation repeated sidecar id: ${group.sidecarId}`);
530
+ this.allocatedSidecarIds.add(group.sidecarId);
531
+ const signature = JSON.stringify([group.backendType, [...group.backendIds].sort()]);
532
+ groupSignatures.add(signature);
533
+ for (const backendId of group.backendIds) {
534
+ this.validateBackend({
535
+ backendId,
536
+ backendType: group.backendType
537
+ });
538
+ const previousGroup = backendGroups.get(backendId);
539
+ if (previousGroup !== void 0 && previousGroup !== signature) invalid(`Batch sidecar allocation assigned backend ${backendId} to inconsistent groups`);
540
+ backendGroups.set(backendId, signature);
541
+ coveredBackends.add(backendId);
542
+ const sidecars = this.allocatedSidecarsByBackend.get(backendId) ?? /* @__PURE__ */ new Set();
543
+ sidecars.add(group.sidecarId);
544
+ this.allocatedSidecarsByBackend.set(backendId, sidecars);
545
+ }
546
+ }
547
+ if (data.count !== data.groups.length || data.count < 1 || data.count > started.maxSidecarsTotal || data.count > started.driverCapacity || coveredBackends.size !== this.backendTypes.size || [...this.backendTypes.keys()].some((id) => !coveredBackends.has(id)) || groupSignatures.size !== started.backendGroups || data.executionClass !== started.executionClass || data.maxConcurrentPerSidecar !== started.maxConcurrentPerSidecar || data.maxSidecarsTotal !== started.maxSidecarsTotal || data.driverCapacity !== started.driverCapacity || data.policyMaxConcurrentPerSidecar !== started.policyMaxConcurrentPerSidecar) invalid("Batch sidecar allocation metadata does not match batch.started");
548
+ this.sidecars = data;
549
+ }
550
+ addTaskStarted(data) {
551
+ this.requireAllocated("task.started");
552
+ const state = this.execution(data);
553
+ if (state.started) invalid(`Batch stream emitted task.started more than once for task ${data.taskId} and backend ${data.backendId}`);
554
+ if (data.index !== this.taskIndexes.get(data.taskId) || data.total !== this.taskIndexes.size || data.attempt !== 1 || data.retries !== 0) invalid(`Batch task start metadata does not match task ${data.taskId}`);
555
+ this.validateMetadata(data, eventMetadata(data), state);
556
+ state.started = true;
557
+ }
558
+ addTaskProgress(type, data) {
559
+ this.requireAllocated(type);
560
+ const state = this.execution(data);
561
+ if (!state.started) invalid(`Batch stream emitted ${type} before task.started for task ${data.taskId} and backend ${data.backendId}`);
562
+ this.validateMetadata(data, eventMetadata(data), state);
563
+ }
564
+ addTaskRetry(data) {
565
+ this.requireAllocated("task.retry");
566
+ const state = this.execution(data);
567
+ if (!state.started) invalid(`Batch stream emitted task.retry before task.started for task ${data.taskId} and backend ${data.backendId}`);
568
+ const expectedAttempt = state.retries + 1;
569
+ if (data.attempt !== expectedAttempt || data.maxRetries < data.attempt || data.executionClass !== this.request.executionClass || state.maxRetries !== void 0 && state.maxRetries !== data.maxRetries) invalid(`Batch retry metadata is inconsistent for task ${data.taskId} and backend ${data.backendId}`);
570
+ this.validateMetadata(data, eventMetadata(data), state);
571
+ state.retries += 1;
572
+ state.maxRetries = data.maxRetries;
573
+ }
574
+ validateTerminalAttempt(data, state) {
575
+ if (data.retries !== state.retries || data.attempt !== state.retries + 1) invalid(`Batch terminal attempt metadata is inconsistent for task ${data.taskId} and backend ${data.backendId}`);
576
+ }
577
+ addTaskCompleted(data) {
578
+ this.requireAllocated("task.completed");
579
+ const state = this.execution(data);
580
+ if (!state.started) invalid(`Batch stream emitted task.completed before task.started for task ${data.taskId} and backend ${data.backendId}`);
581
+ this.validateTerminalAttempt(data, state);
582
+ this.validateMetadata(data, eventMetadata(data), state);
583
+ state.terminal = {
584
+ ...data,
585
+ success: true
586
+ };
587
+ }
588
+ addTaskFailed(data) {
589
+ this.requireAllocated("task.failed");
590
+ const state = this.execution(data);
591
+ if (!state.started && (data.attempt !== 1 || data.retries !== 0)) invalid(`Batch stream emitted retried task.failed before task.started for task ${data.taskId} and backend ${data.backendId}`);
592
+ this.validateTerminalAttempt(data, state);
593
+ this.validateMetadata(data, eventMetadata(data), state);
594
+ state.terminal = {
595
+ ...data,
596
+ success: false
597
+ };
598
+ }
599
+ resultsForBackend(backendId) {
600
+ return this.request.tasks.flatMap((task) => {
601
+ const result = this.executions.get(executionKey(task.id, backendId))?.terminal;
602
+ return result ? [result] : [];
603
+ });
604
+ }
605
+ addBackendCompleted(data) {
606
+ this.requireAllocated("backend.completed");
607
+ this.validateBackend(data);
608
+ if (this.completedBackends.has(data.backendId)) invalid(`Batch stream emitted backend.completed more than once for backend ${data.backendId}`);
609
+ const observed = this.resultsForBackend(data.backendId);
610
+ if (observed.length !== this.taskIndexes.size) invalid(`Batch stream emitted backend.completed for ${data.backendId} after ${observed.length} of ${this.taskIndexes.size} task terminals`);
611
+ const success = observed.filter((result) => result.success).length;
612
+ const failure = observed.length - success;
613
+ const retries = observed.reduce((sum, result) => sum + result.retries, 0);
614
+ if (data.success !== success || data.failure !== failure || data.retries !== retries || !ratesMatch(data.successRate, expectedSuccessRate(success, observed.length))) invalid(`Batch backend summary for ${data.backendId} does not match its task results`);
615
+ if (observed.some((result) => result.backendLabel !== data.backendLabel || result.backendModel !== data.backendModel)) invalid(`Batch backend metadata for ${data.backendId} does not match its task results`);
616
+ const expectedSidecars = this.allocatedSidecarsByBackend.get(data.backendId) ?? /* @__PURE__ */ new Set();
617
+ const reportedSidecars = new Set(data.sidecarIds ?? []);
618
+ if (data.sidecarIds === void 0 || data.sidecarIds.length !== reportedSidecars.size || !setsMatch(expectedSidecars, reportedSidecars)) invalid(`Batch backend ${data.backendId} reported incomplete or mismatched sidecar metadata`);
619
+ this.completedBackends.set(data.backendId, {
620
+ ...data,
621
+ sidecarIds: [...data.sidecarIds]
622
+ });
623
+ }
624
+ addBatchCompleted(data) {
625
+ this.requireAllocated("batch.completed");
626
+ const observedResults = [...this.executions.values()].flatMap((state) => state.terminal ? [state.terminal] : []);
627
+ const expectedExecutions = this.executions.size;
628
+ const totalSuccess = observedResults.filter((result) => result.success).length;
629
+ const totalFailure = observedResults.length - totalSuccess;
630
+ const totalRetries = observedResults.reduce((sum, result) => sum + result.retries, 0);
631
+ if (observedResults.length !== expectedExecutions) invalid(`Batch stream emitted batch.completed after ${observedResults.length} of ${expectedExecutions} task terminals`);
632
+ if (this.completedBackends.size !== this.backendTypes.size) invalid(`Batch stream emitted batch.completed after ${this.completedBackends.size} of ${this.backendTypes.size} backend terminals`);
633
+ const summaries = new Map(data.byBackend.map((summary) => [summary.backendId, summary]));
634
+ const summariesMatch = [...this.completedBackends].every(([backendId, backend]) => {
635
+ const summary = summaries.get(backendId);
636
+ return summary !== void 0 && backendStatsMatch(backend, summary);
637
+ });
638
+ if (data.taskCount !== this.taskIndexes.size || data.backendCount !== this.backendTypes.size || data.totalExecutions !== expectedExecutions || data.totalSuccess !== totalSuccess || data.totalFailure !== totalFailure || data.totalRetries !== totalRetries || !ratesMatch(data.successRate, expectedSuccessRate(totalSuccess, expectedExecutions)) || data.byBackend.length !== this.backendTypes.size || summaries.size !== this.backendTypes.size || !summariesMatch) invalid("Batch completion summary does not match observed task results");
639
+ this.completion = data;
640
+ }
641
+ addBatchFailed(data) {
642
+ if (this.terminal) invalid("Batch stream emitted more than one terminal event");
643
+ const reported = new Set(data.backendIds);
644
+ if (data.backendIds.length !== this.backendTypes.size || reported.size !== this.backendTypes.size || [...this.backendTypes.keys()].some((id) => !reported.has(id))) invalid("Batch failure metadata does not match the requested backends");
645
+ this.failure = data;
646
+ }
647
+ addPersistentCleanup(data) {
648
+ this.requireTerminal("batch.persistent");
649
+ if (!this.completion || !this.request.persistent || this.cleanup) invalid("Batch stream emitted invalid or duplicate batch.persistent cleanup metadata");
650
+ if (data.sidecarCount !== this.allocatedSidecarIds.size) invalid("Batch persistent sidecar count does not match allocation");
651
+ this.cleanup = {
652
+ mode: "persistent",
653
+ ...data
654
+ };
655
+ }
656
+ addGraceCleanup(data) {
657
+ this.requireTerminal("batch.grace_period");
658
+ if (!this.completion || this.request.persistent || this.cleanup || this.request.graceMs === 0) invalid("Batch stream emitted invalid or duplicate batch.grace_period cleanup metadata");
659
+ const reported = new Set(data.sidecarIds);
660
+ if (data.sidecarCount !== this.allocatedSidecarIds.size || data.sidecarIds.length !== reported.size || !setsMatch(this.allocatedSidecarIds, reported) || this.request.graceMs !== void 0 && data.graceMs !== this.request.graceMs) invalid("Batch grace-period metadata does not match allocation");
661
+ this.cleanup = {
662
+ mode: "grace",
663
+ ...data
664
+ };
665
+ }
666
+ addSidecarReleasing(data) {
667
+ this.requireTerminal("sidecar.releasing");
668
+ const graceMs = "graceMs" in this.request ? this.request.graceMs : void 0;
669
+ if (this.request.persistent && this.terminal === "completed" || this.cleanup?.mode === "persistent" || this.cleanup?.mode === "grace" || this.terminal === "completed" && graceMs !== void 0 && graceMs > 0) invalid("Batch stream emitted sidecar.releasing for retained compute");
670
+ if (this.terminal === "completed" && !this.allocatedSidecarIds.has(data.sidecarId)) invalid(`Batch stream released unknown sidecar: ${data.sidecarId}`);
671
+ if (this.releasingSidecars.has(data.sidecarId) || this.releasedSidecars.has(data.sidecarId) || this.pendingSidecars.has(data.sidecarId)) invalid(`Batch stream started sidecar release more than once: ${data.sidecarId}`);
672
+ this.releasingSidecars.add(data.sidecarId);
673
+ }
674
+ addSidecarReleased(data) {
675
+ this.requireTerminal("sidecar.released");
676
+ if (!this.releasingSidecars.delete(data.sidecarId)) invalid(`Batch stream confirmed release before sidecar.releasing: ${data.sidecarId}`);
677
+ this.releasedSidecars.add(data.sidecarId);
678
+ }
679
+ addSidecarReleasePending(data) {
680
+ this.requireTerminal("sidecar.release_pending");
681
+ if (!this.releasingSidecars.delete(data.sidecarId)) invalid(`Batch stream reported pending release before sidecar.releasing: ${data.sidecarId}`);
682
+ if (data.attempt < 1 || data.retryInMs < 1) invalid("Batch stream reported invalid pending release retry metadata");
683
+ this.pendingSidecars.add(data.sidecarId);
684
+ }
685
+ finishCleanup() {
686
+ const graceMs = "graceMs" in this.request ? this.request.graceMs : void 0;
687
+ if (this.request.persistent && this.terminal === "completed") {
688
+ if (this.cleanup?.mode !== "persistent") incomplete("Batch stream ended before batch.persistent cleanup metadata");
689
+ return this.cleanup;
690
+ }
691
+ if (this.cleanup?.mode === "grace" && this.terminal === "completed") return this.cleanup;
692
+ if (this.terminal === "completed" && graceMs !== void 0 && graceMs > 0) incomplete("Batch stream ended before batch.grace_period cleanup metadata");
693
+ if (this.releasingSidecars.size > 0) incomplete(`Batch stream ended while releasing ${this.releasingSidecars.size} sidecars`);
694
+ const terminalCleanupSidecars = new Set([...this.releasedSidecars, ...this.pendingSidecars]);
695
+ if (this.terminal === "completed" && !setsMatch(terminalCleanupSidecars, this.allocatedSidecarIds)) incomplete(`Batch stream ended after resolving cleanup for ${terminalCleanupSidecars.size} of ${this.allocatedSidecarIds.size} sidecars`);
696
+ if (this.failure && [...this.allocatedSidecarIds].some((sidecarId) => !terminalCleanupSidecars.has(sidecarId))) incomplete(`Failed batch stream ended after resolving cleanup for ${terminalCleanupSidecars.size} of ${this.allocatedSidecarIds.size} sidecars`);
697
+ return {
698
+ mode: "release",
699
+ releasedSidecarIds: [...this.releasedSidecars],
700
+ pendingSidecarIds: [...this.pendingSidecars],
701
+ isComplete: this.pendingSidecars.size === 0
702
+ };
703
+ }
704
+ };
705
+ //#endregion
706
+ //#region src/batch.ts
707
+ const BATCH_RUN_PATH = "/v1/sandboxes/batch/run";
708
+ function formatIssuePath(path) {
709
+ return path.map((part, index) => {
710
+ if (typeof part === "number") return `[${part}]`;
711
+ const value = String(part);
712
+ return index === 0 ? value : `.${value}`;
713
+ }).join("");
714
+ }
715
+ function requestValidationIssue(issue, persistent) {
716
+ if (issue.code !== "invalid_union" || !issue.errors) return issue;
717
+ const nested = (issue.errors[persistent ? 1 : 0] ?? issue.errors[0])?.[0];
718
+ return nested ? requestValidationIssue(nested, persistent) : issue;
719
+ }
720
+ /** Validate and normalize one public batch request. */
721
+ function validateBatchRunRequest(request) {
722
+ const parsed = publicBatchRunRequestSchema.safeParse(request);
723
+ if (parsed.success) return parsed.data;
724
+ const rootIssue = parsed.error.issues[0];
725
+ const issue = rootIssue ? requestValidationIssue(rootIssue, request.persistent === true) : void 0;
726
+ if (!issue) throw new ValidationError("Invalid batch request");
727
+ const path = formatIssuePath(issue.path.length === 0 && issue.code === "unrecognized_keys" ? [issue.keys?.[0] ?? "request"] : issue.path);
728
+ throw new ValidationError(path ? `${path}: ${issue.message}` : issue.message, path ? { [path]: issue.message } : void 0);
729
+ }
730
+ function mapBatchStreamError(error) {
731
+ if (!(error instanceof BatchStreamError)) throw error;
732
+ if (error.kind === "failed") throw new ServerError(error.message, 500, {
733
+ endpoint: BATCH_RUN_PATH,
734
+ origin: "sandbox-api"
735
+ });
736
+ throw new NetworkError(error.message, {
737
+ endpoint: BATCH_RUN_PATH,
738
+ origin: "sandbox-api"
739
+ });
740
+ }
741
+ /**
742
+ * Create a result accumulator that preserves Sandbox SDK error types while
743
+ * delegating all event semantics to runtime-contracts.
744
+ */
745
+ function createBatchResultAccumulator(request) {
746
+ return createNormalizedBatchResultAccumulator(validateBatchRunRequest(request));
747
+ }
748
+ /** Internal adapter for requests that have already passed public validation. */
749
+ function createNormalizedBatchResultAccumulator(request) {
750
+ const state = new BatchStreamState(request);
751
+ return {
752
+ add(event) {
753
+ try {
754
+ state.add(event);
755
+ } catch (error) {
756
+ mapBatchStreamError(error);
757
+ }
758
+ },
759
+ finish() {
760
+ try {
761
+ return state.finish();
762
+ } catch (error) {
763
+ mapBatchStreamError(error);
764
+ }
765
+ }
766
+ };
767
+ }
768
+ //#endregion
769
+ //#region ../../../packages/runtime-contracts/dist/batch-events.js
770
+ const countSchema = z.number().int().nonnegative();
771
+ const durationSchema = z.number().nonnegative();
772
+ const successRateSchema = z.number().min(0).max(100);
773
+ const backendIdentityShape = {
774
+ backendId: z.string().min(1),
775
+ backendType: backendTypeSchema,
776
+ backendLabel: z.string().optional(),
777
+ backendModel: z.string().optional()
778
+ };
779
+ const taskIdentityShape = {
780
+ taskId: z.string().min(1),
781
+ ...backendIdentityShape
782
+ };
783
+ /** Token and tool usage emitted when one batch task completes. */
784
+ const batchTaskUsageSchema = z.object({
785
+ inputTokens: countSchema,
786
+ outputTokens: countSchema,
787
+ cacheReadTokens: countSchema.optional(),
788
+ cacheWriteTokens: countSchema.optional(),
789
+ toolCallCount: countSchema.optional(),
790
+ reasoningTokens: countSchema.optional(),
791
+ cost: z.number().nonnegative().optional()
792
+ }).strict();
793
+ /** Per-backend aggregate emitted by `batch.completed`. */
794
+ const batchBackendStatsSchema = z.object({
795
+ ...backendIdentityShape,
796
+ success: countSchema,
797
+ failure: countSchema,
798
+ retries: countSchema,
799
+ successRate: successRateSchema
800
+ }).strict();
801
+ /** One sidecar allocated to a backend group. */
802
+ const batchSidecarGroupSchema = z.object({
803
+ backendType: backendTypeSchema,
804
+ backendIds: z.array(z.string().min(1)).min(1),
805
+ sidecarId: z.string().min(1),
806
+ variants: countSchema
807
+ }).strict();
808
+ /** Whether a streamed text value appends to or replaces prior text. */
809
+ const batchTextValueModeSchema = z.enum(["delta", "snapshot"]);
810
+ const batchEventDataSchemas = {
811
+ "batch.provisioning": z.object({
812
+ desiredCapacity: countSchema,
813
+ currentCapacity: countSchema,
814
+ provisionTimeoutMs: durationSchema
815
+ }).strict(),
816
+ "batch.provisioned": z.object({ capacity: countSchema }).strict(),
817
+ "batch.started": z.object({
818
+ taskCount: countSchema,
819
+ backendCount: countSchema,
820
+ totalExecutions: countSchema,
821
+ backendIds: z.array(z.string().min(1)).min(1),
822
+ backendTypes: z.array(backendTypeSchema).min(1),
823
+ backendGroups: countSchema,
824
+ executionClass: batchExecutionClassSchema,
825
+ maxConcurrentPerSidecar: countSchema,
826
+ maxSidecarsTotal: countSchema,
827
+ driverCapacity: countSchema,
828
+ policyMaxConcurrentPerSidecar: countSchema.nullable()
829
+ }).strict(),
830
+ "sidecars.allocated": z.object({
831
+ count: countSchema,
832
+ groups: z.array(batchSidecarGroupSchema),
833
+ executionClass: batchExecutionClassSchema,
834
+ maxConcurrentPerSidecar: countSchema,
835
+ maxSidecarsTotal: countSchema,
836
+ driverCapacity: countSchema,
837
+ policyMaxConcurrentPerSidecar: countSchema.nullable()
838
+ }).strict(),
839
+ "batch.completed": z.object({
840
+ taskCount: countSchema,
841
+ backendCount: countSchema,
842
+ totalExecutions: countSchema,
843
+ totalSuccess: countSchema,
844
+ totalFailure: countSchema,
845
+ totalRetries: countSchema,
846
+ successRate: successRateSchema,
847
+ byBackend: z.array(batchBackendStatsSchema).min(1)
848
+ }).strict(),
849
+ "batch.failed": z.object({
850
+ error: z.string().min(1),
851
+ backendIds: z.array(z.string().min(1)).min(1)
852
+ }).strict(),
853
+ "batch.persistent": z.object({
854
+ message: z.string(),
855
+ sidecarCount: countSchema
856
+ }).strict(),
857
+ "batch.grace_period": z.object({
858
+ message: z.string(),
859
+ sidecarCount: countSchema,
860
+ graceMs: durationSchema,
861
+ sidecarIds: z.array(z.string().min(1))
862
+ }).strict(),
863
+ "task.started": z.object({
864
+ ...taskIdentityShape,
865
+ index: countSchema,
866
+ total: countSchema,
867
+ attempt: countSchema,
868
+ retries: countSchema,
869
+ sidecarId: z.string().min(1),
870
+ projectRef: z.string().optional()
871
+ }).strict(),
872
+ "task.message.delta": z.object({
873
+ ...taskIdentityShape,
874
+ sidecarId: z.string().min(1),
875
+ projectRef: z.string().optional(),
876
+ value: z.string(),
877
+ valueMode: batchTextValueModeSchema,
878
+ part: z.record(z.string(), z.unknown())
879
+ }).strict(),
880
+ "task.reasoning": z.object({
881
+ ...taskIdentityShape,
882
+ sidecarId: z.string().min(1),
883
+ projectRef: z.string().optional(),
884
+ value: z.string(),
885
+ valueMode: batchTextValueModeSchema,
886
+ part: z.record(z.string(), z.unknown())
887
+ }).strict(),
888
+ "task.tool.updated": z.object({
889
+ ...taskIdentityShape,
890
+ sidecarId: z.string().min(1),
891
+ projectRef: z.string().optional(),
892
+ part: z.record(z.string(), z.unknown())
893
+ }).strict(),
894
+ "task.completed": z.object({
895
+ ...taskIdentityShape,
896
+ durationMs: durationSchema,
897
+ attempt: countSchema,
898
+ retries: countSchema,
899
+ sidecarId: z.string().min(1),
900
+ projectRef: z.string().optional(),
901
+ resultSummary: z.string().optional(),
902
+ sessionId: z.string().optional(),
903
+ usage: batchTaskUsageSchema
904
+ }).strict(),
905
+ "task.failed": z.object({
906
+ ...taskIdentityShape,
907
+ durationMs: durationSchema,
908
+ attempt: countSchema,
909
+ retries: countSchema,
910
+ error: z.string().min(1),
911
+ sidecarId: z.string().min(1).optional(),
912
+ projectRef: z.string().optional(),
913
+ usage: batchTaskUsageSchema.optional()
914
+ }).strict(),
915
+ "task.retry": z.object({
916
+ ...taskIdentityShape,
917
+ attempt: countSchema,
918
+ maxRetries: countSchema,
919
+ error: z.string().min(1),
920
+ delayMs: durationSchema,
921
+ executionClass: batchExecutionClassSchema,
922
+ sidecarId: z.string().min(1),
923
+ projectRef: z.string().optional()
924
+ }).strict(),
925
+ "backend.completed": z.object({
926
+ ...backendIdentityShape,
927
+ sidecarIds: z.array(z.string().min(1)).optional(),
928
+ success: countSchema,
929
+ failure: countSchema,
930
+ retries: countSchema,
931
+ successRate: successRateSchema
932
+ }).strict(),
933
+ "sidecar.releasing": z.object({ sidecarId: z.string().min(1) }).strict(),
934
+ "sidecar.released": z.object({ sidecarId: z.string().min(1) }).strict(),
935
+ "sidecar.release_pending": z.object({
936
+ sidecarId: z.string().min(1),
937
+ attempt: countSchema,
938
+ retryInMs: durationSchema
939
+ }).strict()
940
+ };
941
+ function eventSchema(type, data) {
942
+ return z.object({
943
+ type: z.literal(type),
944
+ data,
945
+ id: z.string().optional()
946
+ }).strict();
947
+ }
948
+ /** Runtime parser and discriminated type for one batch SSE event. */
949
+ const batchEventSchema = z.discriminatedUnion("type", [
950
+ eventSchema("batch.provisioning", batchEventDataSchemas["batch.provisioning"]),
951
+ eventSchema("batch.provisioned", batchEventDataSchemas["batch.provisioned"]),
952
+ eventSchema("batch.started", batchEventDataSchemas["batch.started"]),
953
+ eventSchema("sidecars.allocated", batchEventDataSchemas["sidecars.allocated"]),
954
+ eventSchema("batch.completed", batchEventDataSchemas["batch.completed"]),
955
+ eventSchema("batch.failed", batchEventDataSchemas["batch.failed"]),
956
+ eventSchema("batch.persistent", batchEventDataSchemas["batch.persistent"]),
957
+ eventSchema("batch.grace_period", batchEventDataSchemas["batch.grace_period"]),
958
+ eventSchema("task.started", batchEventDataSchemas["task.started"]),
959
+ eventSchema("task.message.delta", batchEventDataSchemas["task.message.delta"]),
960
+ eventSchema("task.reasoning", batchEventDataSchemas["task.reasoning"]),
961
+ eventSchema("task.tool.updated", batchEventDataSchemas["task.tool.updated"]),
962
+ eventSchema("task.completed", batchEventDataSchemas["task.completed"]),
963
+ eventSchema("task.failed", batchEventDataSchemas["task.failed"]),
964
+ eventSchema("task.retry", batchEventDataSchemas["task.retry"]),
965
+ eventSchema("backend.completed", batchEventDataSchemas["backend.completed"]),
966
+ eventSchema("sidecar.releasing", batchEventDataSchemas["sidecar.releasing"]),
967
+ eventSchema("sidecar.released", batchEventDataSchemas["sidecar.released"]),
968
+ eventSchema("sidecar.release_pending", batchEventDataSchemas["sidecar.release_pending"])
969
+ ]);
970
+ //#endregion
4
971
  //#region src/fleet.ts
5
972
  const FLEET_ID_META = "tangle.fleet.id";
6
973
  const MACHINE_ID_META = "tangle.fleet.machine_id";
@@ -1347,24 +2314,6 @@ async function waitForCreateRetry(delayMs, signal) {
1347
2314
  signal.addEventListener("abort", onAbort, { once: true });
1348
2315
  });
1349
2316
  }
1350
- /**
1351
- * Extra grace the SDK's client-side batch deadline gets on top of
1352
- * the server-side `timeoutMs`. The server's clock starts when the
1353
- * HTTP request lands on the server; the SDK's `AbortSignal.timeout`
1354
- * clock starts before the TCP handshake. Without a grace buffer,
1355
- * the two deadlines line up almost exactly — and a batch that legitimately
1356
- * runs to the full `timeoutMs` on the server will race the SDK
1357
- * deadline firing as the final `batch.completed` SSE event is still
1358
- * in transit, making the caller throw `AbortError` and drop the
1359
- * result.
1360
- *
1361
- * The client deadline is purely a safety valve against hung
1362
- * connections, not a batch correctness timer — the server enforces
1363
- * the real `timeoutMs`. 30s is enough to cover TCP/TLS setup, the
1364
- * server-side batch bookkeeping, and SSE teardown, while still
1365
- * shutting down quickly on a truly hung stream.
1366
- */
1367
- const CLIENT_DEADLINE_GRACE_MS = 3e4;
1368
2317
  function isLocalSandboxEndpoint(baseUrl) {
1369
2318
  try {
1370
2319
  const { hostname } = new URL(baseUrl);
@@ -1393,11 +2342,11 @@ function withRequestContextHeaders(response, path, method) {
1393
2342
  });
1394
2343
  }
1395
2344
  async function resolveLocalCliAuthFiles(backendType) {
1396
- const { discoverLocalCliAuthFiles } = await import("./local-cli-auth-DHBoF3wi.js");
2345
+ const { discoverLocalCliAuthFiles } = await import("./local-cli-auth-D4u7fsnH.js");
1397
2346
  return discoverLocalCliAuthFiles(backendType);
1398
2347
  }
1399
2348
  async function describeLocalCliAuthExpectation(backendType) {
1400
- const { describeLocalCliAuthExpectation: describe } = await import("./local-cli-auth-DHBoF3wi.js");
2349
+ const { describeLocalCliAuthExpectation: describe } = await import("./local-cli-auth-D4u7fsnH.js");
1401
2350
  return describe(backendType);
1402
2351
  }
1403
2352
  async function hydrateLocalCliBackendAuth(backend, baseUrl, trustLocalCliAuth) {
@@ -1957,15 +2906,10 @@ var Sandbox = class {
1957
2906
  * @param options - Batch execution options
1958
2907
  * @returns Aggregated batch results
1959
2908
  *
1960
- * @throws {@link TimeoutError} if the server hasn't begun responding
1961
- * before the deadline (pre-stream timeout).
1962
2909
  * @throws {@link ValidationError} / {@link QuotaError} / other typed
1963
2910
  * SDK errors if the server rejects the request before streaming.
1964
2911
  * @throws `DOMException` with `name === "AbortError"` if
1965
- * `options.signal` fires OR the safety-valve deadline fires
1966
- * AFTER streaming has begun — parseSSEStream can't distinguish
1967
- * the source mid-stream. Callers that need to tell cancel from
1968
- * timeout should check `options.signal?.aborted` in their catch.
2912
+ * `options.signal` fires.
1969
2913
  * @throws `Error` with the server message if the stream emits a
1970
2914
  * `batch.failed` event.
1971
2915
  *
@@ -1976,61 +2920,17 @@ var Sandbox = class {
1976
2920
  * { id: "task-1", message: "Analyze this file" },
1977
2921
  * { id: "task-2", message: "Generate a summary" },
1978
2922
  * ],
2923
+ * backends: [{ id: "primary", type: "opencode" }],
1979
2924
  * });
1980
2925
  * console.log(`Success rate: ${result.successRate}%`);
1981
2926
  * ```
1982
2927
  */
1983
2928
  async runBatch(request, options) {
1984
- const results = [];
1985
- let totalRetries = 0;
1986
- for await (const event of this.streamBatch(request, options)) {
1987
- if (event.type === "task.completed") {
1988
- const data = event.data;
1989
- results.push({
1990
- taskId: data.taskId,
1991
- success: true,
1992
- resultSummary: data.resultSummary,
1993
- durationMs: data.durationMs,
1994
- retries: data.retries,
1995
- usage: data.usage,
1996
- backend: data.backend,
1997
- backendLabel: data.backendLabel,
1998
- backendModel: data.backendModel,
1999
- sessionId: data.sessionId,
2000
- sandboxId: data.sidecarId
2001
- });
2002
- totalRetries += data.retries;
2003
- }
2004
- if (event.type === "task.failed") {
2005
- const data = event.data;
2006
- results.push({
2007
- taskId: data.taskId,
2008
- success: false,
2009
- error: data.error,
2010
- durationMs: data.durationMs,
2011
- retries: data.retries,
2012
- backend: data.backend,
2013
- backendLabel: data.backendLabel,
2014
- backendModel: data.backendModel,
2015
- sandboxId: data.sidecarId
2016
- });
2017
- totalRetries += data.retries;
2018
- }
2019
- if (event.type === "batch.failed") {
2020
- const data = event.data;
2021
- throw new Error(data.error ?? "Batch failed");
2022
- }
2929
+ const stream = this.streamBatch(request, options);
2930
+ while (true) {
2931
+ const next = await stream.next();
2932
+ if (next.done) return next.value;
2023
2933
  }
2024
- const succeeded = results.filter((r) => r.success).length;
2025
- const failed = results.filter((r) => !r.success).length;
2026
- return {
2027
- totalTasks: request.tasks.length,
2028
- succeeded,
2029
- failed,
2030
- totalRetries,
2031
- successRate: results.length > 0 ? succeeded / results.length * 100 : 0,
2032
- results
2033
- };
2034
2934
  }
2035
2935
  /**
2036
2936
  * Stream events from a batch execution.
@@ -2039,18 +2939,17 @@ var Sandbox = class {
2039
2939
  * @param request - Complete batch request
2040
2940
  * @param options - Per-call controls
2041
2941
  *
2042
- * @throws {@link TimeoutError} if the server hasn't begun responding
2043
- * before the deadline (pre-stream timeout).
2044
2942
  * @throws {@link ValidationError} / {@link QuotaError} / other typed
2045
2943
  * SDK errors if the server rejects the request before streaming.
2046
- * @throws `DOMException` with `name === "AbortError"` if
2047
- * `options.signal` fires OR the safety-valve deadline fires
2048
- * AFTER streaming has begun. Distinguish via
2049
- * `options.signal?.aborted` in the consumer's catch.
2944
+ * @throws `DOMException` with `name === "AbortError"` when
2945
+ * `options.signal` fires.
2050
2946
  *
2051
2947
  * @example
2052
2948
  * ```typescript
2053
- * for await (const event of client.streamBatch({ tasks })) {
2949
+ * for await (const event of client.streamBatch({
2950
+ * tasks,
2951
+ * backends: [{ id: "primary", type: "opencode" }],
2952
+ * })) {
2054
2953
  * if (event.type === "task.completed") {
2055
2954
  * console.log(`Task ${event.data.taskId} completed`);
2056
2955
  * }
@@ -2058,30 +2957,17 @@ var Sandbox = class {
2058
2957
  * ```
2059
2958
  */
2060
2959
  async *streamBatch(request, options) {
2061
- if (request.backend?.type !== void 0) assertCurrentBackendType(request.backend.type, "backend.type");
2062
- request.backends?.forEach((backend, index) => {
2063
- if (backend.type !== void 0) assertCurrentBackendType(backend.type, `backends[${index}].type`);
2064
- });
2960
+ const normalizedRequest = validateBatchRunRequest(request);
2961
+ const accumulator = createNormalizedBatchResultAccumulator(normalizedRequest);
2065
2962
  const userSignal = options?.signal;
2066
- const url = `${this.baseUrl}/batch/run`;
2067
- const resolvedTimeoutMs = request.timeoutMs ?? 3e5;
2068
- const requestBody = JSON.stringify({
2069
- ...request,
2070
- backend: request.backend ? {
2071
- ...request.backend,
2072
- type: request.backend.type ?? "opencode"
2073
- } : request.backends ? void 0 : { type: "opencode" },
2074
- backends: request.backends?.map((backend) => ({
2075
- ...backend,
2076
- type: backend.type ?? "opencode"
2077
- })),
2078
- timeoutMs: resolvedTimeoutMs,
2079
- scalingMode: request.scalingMode ?? "balanced",
2080
- persistent: request.persistent ?? false,
2081
- graceMs: request.graceMs ?? 0
2082
- });
2083
- const deadline = AbortSignal.timeout(resolvedTimeoutMs + CLIENT_DEADLINE_GRACE_MS);
2084
- const combinedSignal = userSignal ? combineAbortSignals([userSignal, deadline]) : deadline;
2963
+ const url = `${this.baseUrl}${BATCH_RUN_PATH}`;
2964
+ const requestBody = JSON.stringify(normalizedRequest);
2965
+ const rawIdempotencyKey = options?.idempotencyKey;
2966
+ const parsedIdempotencyKey = rawIdempotencyKey === void 0 ? void 0 : batchIdempotencyKeySchema.safeParse(rawIdempotencyKey);
2967
+ if (parsedIdempotencyKey && !parsedIdempotencyKey.success) {
2968
+ const issue = parsedIdempotencyKey.error.issues[0];
2969
+ throw new ValidationError(`idempotencyKey: ${issue?.message ?? "Invalid batch idempotency key"}`, { idempotencyKey: issue?.message ?? "Invalid value" });
2970
+ }
2085
2971
  let response;
2086
2972
  try {
2087
2973
  response = await globalThis.fetch(url, {
@@ -2089,16 +2975,16 @@ var Sandbox = class {
2089
2975
  headers: {
2090
2976
  Authorization: `Bearer ${this.apiKey}`,
2091
2977
  "Content-Type": "application/json",
2092
- Accept: "text/event-stream"
2978
+ Accept: "text/event-stream",
2979
+ ...parsedIdempotencyKey?.success ? { "Idempotency-Key": parsedIdempotencyKey.data } : {}
2093
2980
  },
2094
2981
  body: requestBody,
2095
- signal: combinedSignal
2982
+ signal: userSignal
2096
2983
  });
2097
2984
  } catch (err) {
2098
2985
  if (userSignal?.aborted) throw err instanceof Error && err.name === "AbortError" ? err : new DOMException("Batch aborted", "AbortError");
2099
- if (err instanceof Error && (err.name === "AbortError" || err.name === "TimeoutError")) throw new TimeoutError(resolvedTimeoutMs, "Batch request timed out before the first SSE event");
2100
2986
  throw new NetworkError(`Failed to connect to Sandbox API: ${err instanceof Error ? err.message : String(err)}`, err instanceof Error ? err : void 0, {
2101
- endpoint: "/batch/run",
2987
+ endpoint: BATCH_RUN_PATH,
2102
2988
  origin: "sandbox-api"
2103
2989
  });
2104
2990
  }
@@ -2106,7 +2992,27 @@ var Sandbox = class {
2106
2992
  const errBody = await response.text();
2107
2993
  throw parseErrorResponse(response.status, errBody, void 0, response.headers);
2108
2994
  }
2109
- for await (const event of parseSSEStream(response.body, { signal: combinedSignal })) yield event;
2995
+ const contentType = response.headers.get("content-type")?.toLowerCase();
2996
+ if (!contentType?.includes("text/event-stream")) {
2997
+ const responseBody = await response.text().catch(() => "");
2998
+ throw new NetworkError(`Batch endpoint returned ${contentType ?? "no content type"} instead of text/event-stream${responseBody ? `: ${responseBody.slice(0, 200)}` : ""}`, {
2999
+ endpoint: BATCH_RUN_PATH,
3000
+ origin: "sandbox-api"
3001
+ });
3002
+ }
3003
+ for await (const event of parseSSEStream(response.body, { signal: userSignal })) {
3004
+ const parsed = batchEventSchema.safeParse(event);
3005
+ if (!parsed.success) {
3006
+ const issue = parsed.error.issues[0];
3007
+ throw new NetworkError(`Batch stream emitted an invalid ${event.type} event: ${issue ? `${issue.path.join(".") || "event"}: ${issue.message}` : parsed.error.message}`, {
3008
+ endpoint: BATCH_RUN_PATH,
3009
+ origin: "sandbox-api"
3010
+ });
3011
+ }
3012
+ accumulator.add(parsed.data);
3013
+ yield parsed.data;
3014
+ }
3015
+ return accumulator.finish();
2110
3016
  }
2111
3017
  /**
2112
3018
  * Make an authenticated HTTP request to the API.
@@ -2711,4 +3617,4 @@ var TeamsClient = class {
2711
3617
  }
2712
3618
  };
2713
3619
  //#endregion
2714
- export { splitInlineProfileSkills as a, SandboxFleetClient as c, splitInlineProfileFileMounts as i, Sandbox as n, validateDeferredProfileFileMounts as o, materializeProfileFileMounts as r, SandboxFleet as s, IntelligenceClient as t };
3620
+ export { splitInlineProfileSkills as a, SandboxFleetClient as c, splitInlineProfileFileMounts as i, createBatchResultAccumulator as l, Sandbox as n, validateDeferredProfileFileMounts as o, materializeProfileFileMounts as r, SandboxFleet as s, IntelligenceClient as t, validateBatchRunRequest as u };