@opengeni/runtime 4.6.0 → 4.7.0-canary.37111190284001

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.
Files changed (75) hide show
  1. package/dist/agent-instructions/modules/media.d.ts +3 -0
  2. package/dist/anthropic-messages.d.ts +13 -3
  3. package/dist/anthropic-request-error.d.ts +10 -0
  4. package/dist/assets/codemode-client.json +1 -1
  5. package/dist/{chunk-D5DPVA2C.js → chunk-3QG5IL64.js} +2436 -1355
  6. package/dist/chunk-3QG5IL64.js.map +1 -0
  7. package/dist/{chunk-A22BKN4P.js → chunk-LJNCGUMB.js} +3 -3
  8. package/dist/chunk-LJNCGUMB.js.map +1 -0
  9. package/dist/{chunk-GTWKWJ67.js → chunk-YLRVEUJ7.js} +527 -103
  10. package/dist/chunk-YLRVEUJ7.js.map +1 -0
  11. package/dist/claude-subscription-usage.d.ts +14 -4
  12. package/dist/context-compaction.d.ts +7 -7
  13. package/dist/index.d.ts +2 -0
  14. package/dist/index.js +17 -3
  15. package/dist/interaction-tools.d.ts +1 -1
  16. package/dist/mcp-network.js +1 -1
  17. package/dist/runtime-skills.d.ts +1 -0
  18. package/dist/sandbox/channel-a.d.ts +3 -0
  19. package/dist/sandbox/index.d.ts +4 -1
  20. package/dist/sandbox/index.js +11 -1
  21. package/dist/sandbox/provider-command-session.d.ts +21 -0
  22. package/dist/sandbox/providers/modal-command-argv.d.ts +4 -0
  23. package/dist/sandbox/providers/modal-command-control.d.ts +17 -5
  24. package/dist/sandbox/providers/modal-command-observation-errors.d.ts +3 -0
  25. package/dist/sandbox/providers/modal-command-raw-page.d.ts +100 -0
  26. package/dist/sandbox/providers/modal-command-router-wire.d.ts +40 -0
  27. package/dist/sandbox/providers/modal-native-create-preparation.d.ts +208 -0
  28. package/dist/sandbox/routing/routing-session.d.ts +10 -0
  29. package/dist/sandbox/turn-tool-cancellation.d.ts +4 -0
  30. package/dist/workspace-tool-gateway.js +3 -3
  31. package/package.json +12 -12
  32. package/src/agent-instructions/PROMPT_CHANGELOG.md +23 -1
  33. package/src/agent-instructions/compose.ts +2 -0
  34. package/src/agent-instructions/modules/media.ts +20 -0
  35. package/src/agent-instructions/runtime-mechanics.ts +8 -0
  36. package/src/anthropic-messages.ts +223 -31
  37. package/src/anthropic-request-error.ts +45 -0
  38. package/src/bundled_default_skills/opengeni-client/SKILL.md +14 -9
  39. package/src/bundled_default_skills/opengeni-client/references/agent-recipes.md +17 -1
  40. package/src/bundled_default_skills/opengeni-client/references/api-workflows.md +61 -0
  41. package/src/bundled_default_skills/opengeni-client/references/compatibility-and-troubleshooting.md +86 -0
  42. package/src/bundled_default_skills/opengeni-client/references/configure-the-agent.md +19 -0
  43. package/src/bundled_default_skills/opengeni-client/references/data-tools-and-credentials.md +82 -0
  44. package/src/bundled_default_skills/opengeni-client/references/discovery-and-autonomy.md +32 -25
  45. package/src/bundled_default_skills/opengeni-client/references/external-users-and-connect.md +17 -0
  46. package/src/bundled_default_skills/opengeni-client/references/product-shapes-and-ui.md +157 -1
  47. package/src/bundled_schedule_skills/opengeni-schedules/SKILL.md +56 -0
  48. package/src/claude-subscription-usage.ts +55 -9
  49. package/src/context-compaction.ts +16 -9
  50. package/src/index.ts +120 -21
  51. package/src/interaction-tools.ts +113 -3
  52. package/src/lazy-tool-transport.ts +26 -10
  53. package/src/mcp-network.ts +4 -2
  54. package/src/model-provider-client.ts +11 -3
  55. package/src/model-provider-routing.ts +4 -0
  56. package/src/runtime-skills.ts +8 -0
  57. package/src/sandbox/channel-a.ts +3 -0
  58. package/src/sandbox/index.ts +19 -1
  59. package/src/sandbox/provider-command-session.ts +58 -0
  60. package/src/sandbox/provider-errors.ts +43 -9
  61. package/src/sandbox/providers/modal-command-argv.ts +20 -0
  62. package/src/sandbox/providers/modal-command-control.ts +422 -116
  63. package/src/sandbox/providers/modal-command-observation-errors.ts +65 -0
  64. package/src/sandbox/providers/modal-command-raw-page.ts +147 -0
  65. package/src/sandbox/providers/modal-command-router-wire.ts +202 -12
  66. package/src/sandbox/providers/modal-command-session.ts +26 -4
  67. package/src/sandbox/providers/modal-legacy-command-control.ts +2 -9
  68. package/src/sandbox/providers/modal-materialization-verification.ts +70 -6
  69. package/src/sandbox/providers/modal-native-create-preparation.ts +338 -0
  70. package/src/sandbox/routing/routing-session.ts +140 -41
  71. package/src/sandbox/run-credentials.ts +62 -19
  72. package/src/sandbox/turn-tool-cancellation.ts +159 -42
  73. package/dist/chunk-A22BKN4P.js.map +0 -1
  74. package/dist/chunk-D5DPVA2C.js.map +0 -1
  75. package/dist/chunk-GTWKWJ67.js.map +0 -1
@@ -55,6 +55,7 @@ import {
55
55
  assertShellEnvironmentName,
56
56
  deserializeHostPathGrantRedactionMetadata,
57
57
  deserializeManifest,
58
+ external_exports,
58
59
  getRecordedExposedPortEndpoint,
59
60
  getRunStateSessionTrustedConfig,
60
61
  isDir,
@@ -113,6 +114,50 @@ var ProviderCommandStartOutcomeUnknownError = class extends Error {
113
114
  this.name = "ProviderCommandStartOutcomeUnknownError";
114
115
  }
115
116
  };
117
+ var ProviderCommandInputOutcomeUnknownError = class extends Error {
118
+ constructor(command, byteOffset, byteLength2, cause) {
119
+ super(
120
+ "Provider command stdin outcome is unknown; the input was not resent. Do not resend stdin; inspect the original command with empty input.",
121
+ { cause }
122
+ );
123
+ this.command = command;
124
+ this.byteOffset = byteOffset;
125
+ this.byteLength = byteLength2;
126
+ this.name = "ProviderCommandInputOutcomeUnknownError";
127
+ }
128
+ };
129
+ var ProviderCommandObservationUnavailableError = class extends Error {
130
+ constructor(command, cause, readRetryAllowed = true) {
131
+ super("Provider command observation unavailable; do not replay the invocation", { cause });
132
+ this.command = command;
133
+ this.readRetryAllowed = readRetryAllowed;
134
+ this.name = "ProviderCommandObservationUnavailableError";
135
+ }
136
+ };
137
+ function isProviderCommandObservationUnavailableError(error) {
138
+ const pending = [error];
139
+ const seen = /* @__PURE__ */ new Set();
140
+ for (let count = 0; pending.length && count < 32; count++) {
141
+ const current = pending.pop();
142
+ if (!current || typeof current !== "object" || seen.has(current)) continue;
143
+ seen.add(current);
144
+ if (current instanceof ProviderCommandObservationUnavailableError) return true;
145
+ try {
146
+ for (const key of ["cause", "error"]) {
147
+ const property = Object.getOwnPropertyDescriptor(current, key);
148
+ if (property && "value" in property) pending.push(property.value);
149
+ }
150
+ const errors = Object.getOwnPropertyDescriptor(current, "errors");
151
+ if (errors && "value" in errors && Array.isArray(errors.value) && errors.value.length <= 16)
152
+ for (let index = 0; index < errors.value.length; index++) {
153
+ const item = Object.getOwnPropertyDescriptor(errors.value, String(index));
154
+ if (item && "value" in item) pending.push(item.value);
155
+ }
156
+ } catch {
157
+ }
158
+ }
159
+ return false;
160
+ }
116
161
  var admission = new AsyncLocalStorage();
117
162
  var pendingSupervision = new AsyncLocalStorage();
118
163
  function withPendingCommandSupervision(state, fn) {
@@ -152,8 +197,931 @@ function admittedProviderCommandHandle() {
152
197
  // src/sandbox/index.ts
153
198
  import { collectSandboxEnvironment, parseExposedPorts } from "@opengeni/config";
154
199
 
200
+ // src/sandbox/providers/modal-command-raw-page.ts
201
+ import { isDeepStrictEqual } from "util";
202
+ import { ModalRouterProviderCommand as ModalRouterProviderCommand2 } from "@opengeni/contracts";
203
+
204
+ // src/sandbox/providers/modal-legacy-command-control.ts
205
+ import { posix } from "path";
206
+ import { ModalClient } from "modal";
207
+
208
+ // src/sandbox/providers/modal-command-start-errors.ts
209
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
210
+ import { ModalRouterProviderCommand } from "@opengeni/contracts";
211
+ var boundaryBrand = Symbol.for("opengeni.modal.command-start.boundary.v1");
212
+ var invocationBrand = Symbol.for("opengeni.modal.command-start.invocation.v1");
213
+ var contextBrand = Symbol.for("opengeni.modal.command-start.context.v1");
214
+ var startSignal = new AsyncLocalStorage2();
215
+ function withModalCommandStartSignal(signal, operation) {
216
+ signal.throwIfAborted();
217
+ return startSignal.run(signal, operation);
218
+ }
219
+ function installModalCommandStartContext(modal) {
220
+ if (Object.getOwnPropertyDescriptor(modal, contextBrand)) return;
221
+ Object.defineProperty(modal, contextBrand, { value: () => startSignal.getStore() });
222
+ }
223
+ function modalCommandStartOwnData(value, key) {
224
+ const property = Object.getOwnPropertyDescriptor(value, key);
225
+ return property && "value" in property ? property.value : void 0;
226
+ }
227
+ function modalCommandStartHasOwnAccessor(value, key) {
228
+ const property = Object.getOwnPropertyDescriptor(value, key);
229
+ return !!property && !("value" in property);
230
+ }
231
+ function getModalCommandStartInvocation(error) {
232
+ const pending = [{ value: error, depth: 0 }];
233
+ const seen = /* @__PURE__ */ new WeakSet();
234
+ let result = null;
235
+ let inspected = 0;
236
+ while (pending.length) {
237
+ if (++inspected > 64) return null;
238
+ const { value, depth } = pending.shift();
239
+ if (!value || typeof value !== "object" || seen.has(value)) continue;
240
+ if (depth > 8) return null;
241
+ seen.add(value);
242
+ try {
243
+ if (["cause", "error", "errors"].some((key) => modalCommandStartHasOwnAccessor(value, key)))
244
+ return null;
245
+ if (hasModalCommandStartBoundary(value, "outcome-unknown")) {
246
+ const descriptor = modalCommandStartOwnData(value, invocationBrand);
247
+ if (!descriptor || typeof descriptor !== "object" || !Object.isFrozen(descriptor))
248
+ return null;
249
+ const sandboxId = modalCommandStartOwnData(descriptor, "sandboxId");
250
+ const taskId = modalCommandStartOwnData(descriptor, "taskId");
251
+ const execId = modalCommandStartOwnData(descriptor, "execId");
252
+ const observe = modalCommandStartOwnData(descriptor, "observe");
253
+ const ptyProperty = Object.getOwnPropertyDescriptor(descriptor, "pty");
254
+ if (ptyProperty && (!("value" in ptyProperty) || typeof ptyProperty.value !== "boolean"))
255
+ return null;
256
+ if (typeof sandboxId !== "string" || !sandboxId || typeof taskId !== "string" || !taskId || typeof execId !== "string" || !execId || typeof observe !== "function")
257
+ return null;
258
+ if (result && result !== descriptor) return null;
259
+ result = descriptor;
260
+ }
261
+ const nested = [
262
+ modalCommandStartOwnData(value, "cause"),
263
+ modalCommandStartOwnData(value, "error")
264
+ ].filter((child) => child !== void 0);
265
+ const errors = modalCommandStartOwnData(value, "errors");
266
+ if (errors !== void 0) {
267
+ if (!Array.isArray(errors)) return null;
268
+ const length = modalCommandStartOwnData(errors, "length");
269
+ if (typeof length !== "number" || !Number.isSafeInteger(length) || length < 1 || length > 32)
270
+ return null;
271
+ for (let index = 0; index < length; index++) {
272
+ const property = Object.getOwnPropertyDescriptor(errors, String(index));
273
+ if (!property || !("value" in property) || !property.value || typeof property.value !== "object")
274
+ return null;
275
+ nested.push(property.value);
276
+ }
277
+ }
278
+ if (depth === 8 && nested.length) return null;
279
+ for (const child of nested) pending.push({ value: child, depth: depth + 1 });
280
+ } catch {
281
+ return null;
282
+ }
283
+ }
284
+ return result;
285
+ }
286
+ function modalCommandStartRetainedError(error) {
287
+ if (error instanceof ProviderCommandStartOutcomeUnknownError) return error;
288
+ const invocation = getModalCommandStartInvocation(error);
289
+ if (!invocation) return error;
290
+ const cursor = () => ({ byteOffset: 0, utf8Remainder: "", eof: false, exitCode: null });
291
+ const command = ModalRouterProviderCommand.safeParse({
292
+ kind: "modal-router-v1",
293
+ sandboxId: invocation.sandboxId,
294
+ taskId: invocation.taskId,
295
+ execId: invocation.execId,
296
+ ...invocation.pty === void 0 ? {} : { pty: invocation.pty },
297
+ streams: { stdout: cursor(), stderr: cursor() }
298
+ });
299
+ return command.success ? new ProviderCommandStartOutcomeUnknownError(command.data, error) : error;
300
+ }
301
+ function hasModalCommandStartOutcomeUnknownBoundary(error) {
302
+ const pending = [{ value: error, depth: 0 }];
303
+ const seen = /* @__PURE__ */ new WeakSet();
304
+ for (let inspected = 0; pending.length && inspected < 64; inspected++) {
305
+ const { value, depth } = pending.shift();
306
+ if (!value || typeof value !== "object" || seen.has(value)) continue;
307
+ seen.add(value);
308
+ if (hasModalCommandStartBoundary(value, "outcome-unknown")) return true;
309
+ if (depth >= 8) continue;
310
+ try {
311
+ for (const key of ["cause", "error"]) {
312
+ const nested = modalCommandStartOwnData(value, key);
313
+ if (nested !== void 0) pending.push({ value: nested, depth: depth + 1 });
314
+ }
315
+ const errors = modalCommandStartOwnData(value, "errors");
316
+ if (Array.isArray(errors))
317
+ for (let index = 0; index < Math.min(errors.length, 32); index++)
318
+ pending.push({
319
+ value: modalCommandStartOwnData(errors, String(index)),
320
+ depth: depth + 1
321
+ });
322
+ } catch {
323
+ }
324
+ }
325
+ return false;
326
+ }
327
+ function modalCommandStartCleanupIsSafe(error) {
328
+ const pending = [{ value: error, depth: 0 }];
329
+ const seen = /* @__PURE__ */ new WeakSet();
330
+ let inspected = 0;
331
+ while (pending.length) {
332
+ if (++inspected > 64) return false;
333
+ const { value, depth } = pending.shift();
334
+ if (!value || typeof value !== "object" && typeof value !== "function") continue;
335
+ if (seen.has(value)) continue;
336
+ if (depth > 8) return false;
337
+ seen.add(value);
338
+ try {
339
+ if (value instanceof ProviderCommandStartOutcomeUnknownError || hasModalCommandStartBoundary(value, "outcome-unknown") || [boundaryBrand, "cause", "error", "errors"].some(
340
+ (key) => modalCommandStartHasOwnAccessor(value, key)
341
+ ))
342
+ return false;
343
+ const nested = [
344
+ modalCommandStartOwnData(value, "cause"),
345
+ modalCommandStartOwnData(value, "error")
346
+ ].filter((child) => child !== void 0 && child !== null);
347
+ const errors = modalCommandStartOwnData(value, "errors");
348
+ if (errors !== void 0) {
349
+ if (!Array.isArray(errors)) return false;
350
+ const length = modalCommandStartOwnData(errors, "length");
351
+ if (typeof length !== "number" || !Number.isSafeInteger(length) || length > 32)
352
+ return false;
353
+ for (let index = 0; index < length; index++) {
354
+ const property = Object.getOwnPropertyDescriptor(errors, String(index));
355
+ if (!property || !("value" in property) || !property.value || typeof property.value !== "object" && typeof property.value !== "function")
356
+ return false;
357
+ nested.push(property.value);
358
+ }
359
+ }
360
+ if (depth === 8 && nested.length) return false;
361
+ for (const child of nested) pending.push({ value: child, depth: depth + 1 });
362
+ } catch {
363
+ return false;
364
+ }
365
+ }
366
+ return true;
367
+ }
368
+ function installModalCommandStartRetention(session) {
369
+ for (const name of [
370
+ "execCommand",
371
+ "applyManifest",
372
+ "materializeEntry",
373
+ "hydrateWorkspace",
374
+ "persistWorkspace",
375
+ "runDirectCommand",
376
+ "runAsCommandRunner"
377
+ ]) {
378
+ const operation = Reflect.get(session, name);
379
+ if (typeof operation !== "function") continue;
380
+ Reflect.set(session, name, async function(...args) {
381
+ try {
382
+ return await operation.apply(session, args);
383
+ } catch (error) {
384
+ throw modalCommandStartRetainedError(error);
385
+ }
386
+ });
387
+ }
388
+ }
389
+ function hasModalCommandStartBoundary(error, kind) {
390
+ if (!error || typeof error !== "object") return false;
391
+ try {
392
+ const property = Object.getOwnPropertyDescriptor(error, boundaryBrand);
393
+ return property?.value === kind && property.writable === false && property.configurable === false;
394
+ } catch {
395
+ return false;
396
+ }
397
+ }
398
+ var ModalCommandStartOutcomeUnknownError = class extends Error {
399
+ constructor(taskId, execId, cause) {
400
+ super("Modal command Start outcome unknown; do not replay this invocation", { cause });
401
+ this.taskId = taskId;
402
+ this.execId = execId;
403
+ this.name = "CommandStartOutcomeUnknownError";
404
+ Object.defineProperty(this, boundaryBrand, { value: "outcome-unknown" });
405
+ }
406
+ };
407
+
408
+ // src/sandbox/providers/modal-legacy-command-control.ts
409
+ import { status as status2 } from "@grpc/grpc-js";
410
+
411
+ // src/sandbox/providers/modal-command-router-wire.ts
412
+ import { Client, Metadata, credentials, status } from "@grpc/grpc-js";
413
+ import { createHash } from "crypto";
414
+ import protobuf from "protobufjs";
415
+ var modalRouterWire = protobuf.parse(`syntax = "proto3";
416
+ message Identity { string task_id = 1; string exec_id = 2; }
417
+ message Pty {
418
+ bool enabled = 1; uint32 winsz_rows = 2; uint32 winsz_cols = 3;
419
+ string env_term = 4; string env_colorterm = 5; string env_term_program = 6;
420
+ int32 pty_type = 7; bool no_terminate_on_idle_stdin = 8;
421
+ }
422
+ message Start {
423
+ string task_id = 1; string exec_id = 2; repeated string command_args = 3;
424
+ int32 stdout_config = 4; int32 stderr_config = 5;
425
+ optional uint32 timeout_secs = 6; optional string workdir = 7;
426
+ repeated string secret_ids = 8; optional Pty pty_info = 9;
427
+ bool runtime_debug = 10; string container_id = 11; map<string,string> env = 12;
428
+ }
429
+ message Read {
430
+ string task_id = 1; string exec_id = 2; uint64 offset = 3; int32 file_descriptor = 4;
431
+ }
432
+ message Data { bytes data = 1; }
433
+ message Poll { optional int32 code = 1; optional int32 signal = 2; }
434
+ message Write {
435
+ string task_id = 1; string exec_id = 2; uint64 offset = 3; bytes data = 4; bool eof = 5;
436
+ }
437
+ message Empty {}
438
+ `).root;
439
+ var prefix = "/modal.task_command_router.TaskCommandRouter/";
440
+ var startEncoderVersion = "protobufjs@7.6.5";
441
+ var startEncoderFingerprint = `sha256:${createHash("sha256").update(
442
+ JSON.stringify({
443
+ encoderVersion: startEncoderVersion,
444
+ schema: modalRouterWire.toJSON(),
445
+ encoding: "Start.encode(Start.fromObject(value)).finish()"
446
+ })
447
+ ).digest("hex")}`;
448
+ var MODAL_ROUTER_READ_PAGE_BYTES = 1024 * 1024;
449
+ var maxWireBytes = 4 * 1024 * 1024;
450
+ var ModalCommandStartRejectedError = class extends ProviderCommandStartRejectedError {
451
+ constructor(code, cause) {
452
+ super(cause);
453
+ this.code = code;
454
+ this.name = "ModalCommandStartRejectedError";
455
+ }
456
+ };
457
+ var ModalCommandStartPreDispatchUnavailableError = class _ModalCommandStartPreDispatchUnavailableError extends Error {
458
+ constructor(cause) {
459
+ super("Modal command router was not ready before Start dispatch", { cause });
460
+ this.name = "ModalCommandStartPreDispatchUnavailableError";
461
+ }
462
+ /** The supplied operation must contain only read-only preparation, never
463
+ * Start itself. Its transport failure therefore proves non-dispatch. */
464
+ static async beforeDispatch(operation, signal) {
465
+ signal?.throwIfAborted();
466
+ try {
467
+ return await operation();
468
+ } catch (error) {
469
+ signal?.throwIfAborted();
470
+ const code = error?.code;
471
+ if (error instanceof Error && (code === status.UNAVAILABLE || code === status.DEADLINE_EXCEEDED))
472
+ throw new _ModalCommandStartPreDispatchUnavailableError(error);
473
+ throw error;
474
+ }
475
+ }
476
+ static async ensureReady(client, signal) {
477
+ signal?.throwIfAborted();
478
+ await new Promise((resolve7, reject) => {
479
+ let settled = false;
480
+ const finish = (error) => {
481
+ if (settled) return;
482
+ settled = true;
483
+ signal?.removeEventListener("abort", abort);
484
+ if (signal?.aborted) reject(signal.reason);
485
+ else if (error) reject(new _ModalCommandStartPreDispatchUnavailableError(error));
486
+ else resolve7();
487
+ };
488
+ const abort = () => finish();
489
+ signal?.addEventListener("abort", abort, { once: true });
490
+ client.waitForReady(Date.now() + 5e3, finish);
491
+ if (signal?.aborted) abort();
492
+ });
493
+ }
494
+ };
495
+ var ModalCommandStartNotDispatchedError = class extends Error {
496
+ constructor(cause) {
497
+ super(cause instanceof Error ? cause.message : "Modal command Start was never dispatched", {
498
+ cause
499
+ });
500
+ this.name = "ModalCommandStartNotDispatchedError";
501
+ }
502
+ };
503
+ function isReadinessRequest(request, snapshot) {
504
+ if (snapshot.commandArgs.length !== 1 || snapshot.commandArgs[0] !== "/bin/true" || snapshot.workdir !== "/tmp" || Reflect.ownKeys(snapshot.env).length !== 0 || snapshot.ptyInfo)
505
+ return false;
506
+ try {
507
+ return Reflect.ownKeys(request).every(
508
+ (key) => ["taskId", "execId", "commandArgs", "workdir", "env"].includes(key)
509
+ );
510
+ } catch {
511
+ return false;
512
+ }
513
+ }
514
+ function prepareStartRequest(request) {
515
+ const { taskId, execId, commandArgs, workdir, env, ptyInfo } = request;
516
+ if (!taskId || !execId || !Array.isArray(commandArgs) || !commandArgs.length || typeof workdir !== "string" || !env || typeof env !== "object" || Array.isArray(env))
517
+ throw new Error("Invalid Modal command Start request");
518
+ const snapshot = {
519
+ taskId,
520
+ execId,
521
+ commandArgs: [...commandArgs],
522
+ workdir,
523
+ env: { ...env },
524
+ ...ptyInfo ? {
525
+ ptyInfo: {
526
+ enabled: ptyInfo.enabled,
527
+ winszRows: ptyInfo.winszRows,
528
+ winszCols: ptyInfo.winszCols,
529
+ envTerm: ptyInfo.envTerm,
530
+ ptyType: ptyInfo.ptyType,
531
+ noTerminateOnIdleStdin: ptyInfo.noTerminateOnIdleStdin
532
+ }
533
+ } : {},
534
+ stdoutConfig: 1,
535
+ stderrConfig: 1
536
+ };
537
+ if (modalRouterWire.lookupType("Start").verify(snapshot))
538
+ throw new Error("Invalid Modal command Start request");
539
+ const preflight = encode("Start", snapshot);
540
+ if (preflight.length > maxWireBytes)
541
+ throw new Error("Modal command Start request exceeds the wire limit");
542
+ Object.freeze(snapshot.commandArgs);
543
+ Object.freeze(snapshot.env);
544
+ if (snapshot.ptyInfo) Object.freeze(snapshot.ptyInfo);
545
+ Object.freeze(snapshot);
546
+ const descriptor = isReadinessRequest(
547
+ request,
548
+ snapshot
549
+ ) ? Object.freeze({
550
+ taskId: snapshot.taskId,
551
+ execId: snapshot.execId,
552
+ descriptorProtocol: "modal-prepared-start-descriptor",
553
+ descriptorVersion: 1,
554
+ readinessRecipe: "modal-exec-readiness-bin-true-v1",
555
+ readinessRecipeVersion: 1,
556
+ startMessage: "Start",
557
+ rpcMethod: "/modal.task_command_router.TaskCommandRouter/TaskExecStart",
558
+ encoderVersion: startEncoderVersion,
559
+ preflight: Object.freeze({
560
+ encoding: "modal-start-protobuf-preflight-v1",
561
+ sha256: createHash("sha256").update(preflight).digest("hex"),
562
+ byteLength: preflight.length,
563
+ encoderFingerprint: startEncoderFingerprint
564
+ })
565
+ }) : void 0;
566
+ return { request: snapshot, descriptor };
567
+ }
568
+ function encode(type, value) {
569
+ const codec = modalRouterWire.lookupType(type);
570
+ return Buffer.from(codec.encode(codec.fromObject(value)).finish());
571
+ }
572
+ var ModalCommandRouterWire = class {
573
+ client;
574
+ metadata;
575
+ #preparedStarts = /* @__PURE__ */ new WeakMap();
576
+ closed = false;
577
+ constructor(access, trustedRoots) {
578
+ const url = new URL(access.url);
579
+ if (url.protocol !== "https:" || url.username || url.password || !access.jwt)
580
+ throw new Error("Modal command router requires authenticated TLS");
581
+ this.client = new Client(
582
+ `${url.hostname}:${url.port || "443"}`,
583
+ credentials.createSsl(trustedRoots),
584
+ {
585
+ "grpc.max_receive_message_length": maxWireBytes,
586
+ "grpc.max_send_message_length": maxWireBytes,
587
+ "grpc.enable_retries": 0,
588
+ // The HTTP/2 default 64 KiB window caps one read at 64 KiB per round
589
+ // trip. Two pages lets stdout and stderr each fill a page in one trip
590
+ // while bounding bytes discarded when a full read cancels its stream.
591
+ "grpc-node.flow_control_window": 2 * MODAL_ROUTER_READ_PAGE_BYTES
592
+ }
593
+ );
594
+ this.metadata = new Metadata();
595
+ this.metadata.set("authorization", `Bearer ${access.jwt}`);
596
+ }
597
+ close() {
598
+ this.closed = true;
599
+ this.client.close();
600
+ }
601
+ async unary(method, requestType, responseType, request, signal) {
602
+ signal?.throwIfAborted();
603
+ if (this.closed) throw new Error("Modal command router is closed");
604
+ return await new Promise((resolve7, reject) => {
605
+ const call = this.client.makeUnaryRequest(
606
+ prefix + method,
607
+ (value) => encode(requestType, value),
608
+ (bytes) => modalRouterWire.lookupType(responseType).decode(bytes),
609
+ request,
610
+ this.metadata,
611
+ { deadline: Date.now() + 3e4 },
612
+ (error, result) => {
613
+ signal?.removeEventListener("abort", abort);
614
+ if (signal?.aborted) reject(signal.reason);
615
+ else if (error) reject(error);
616
+ else if (result) resolve7(result);
617
+ else reject(new Error("Modal command router returned no response"));
618
+ }
619
+ );
620
+ const abort = () => call.cancel();
621
+ signal?.addEventListener("abort", abort, { once: true });
622
+ if (signal?.aborted) abort();
623
+ });
624
+ }
625
+ /** Read-only transport preparation. It sends neither Start nor stdin and
626
+ * does not invoke a caller's dispatch/admission callback. Prevalidation is not
627
+ * wire proof: gRPC still serializes at RPC invocation after dispatch begins. */
628
+ async prepareStart(request, signal) {
629
+ try {
630
+ signal?.throwIfAborted();
631
+ if (this.closed) throw new Error("Modal command router is closed");
632
+ const { request: snapshot, descriptor } = prepareStartRequest(request);
633
+ await ModalCommandStartPreDispatchUnavailableError.ensureReady(this.client, signal);
634
+ signal?.throwIfAborted();
635
+ if (this.closed) throw new Error("Modal command router is closed");
636
+ const prepared2 = Object.freeze({
637
+ taskId: snapshot.taskId,
638
+ execId: snapshot.execId
639
+ });
640
+ this.#preparedStarts.set(prepared2, { request: snapshot, descriptor, spent: false });
641
+ return prepared2;
642
+ } catch (error) {
643
+ if (this.closed)
644
+ throw new ModalCommandStartNotDispatchedError(
645
+ new Error("Modal command router is closed", { cause: error })
646
+ );
647
+ if (error instanceof ModalCommandStartPreDispatchUnavailableError) throw error;
648
+ throw new ModalCommandStartNotDispatchedError(error);
649
+ }
650
+ }
651
+ /** Passive, synchronous read on the same open issuing transport. Neither
652
+ * consumes the handle nor performs readiness/encoding/RPC/callback work.
653
+ * Every refusal is generic: no genuine non-dispatch or recovery proof. */
654
+ describePreparedStart(prepared2) {
655
+ const entry = this.#preparedStarts.get(prepared2);
656
+ if (this.closed || !entry || entry.spent || !entry.descriptor)
657
+ throw new Error("Invalid, unsupported or unavailable Modal prepared Start descriptor");
658
+ return entry.descriptor;
659
+ }
660
+ /** No readiness, route lookup or retry here. Consume the authentic local
661
+ * handle synchronously before RPC, including when cancellation/closure wins.
662
+ * Once spent it never resets, even if no acknowledgement was received. */
663
+ async dispatchPreparedStart(prepared2, signal) {
664
+ const entry = this.#preparedStarts.get(prepared2);
665
+ if (!entry || entry.spent)
666
+ throw new Error("Invalid or consumed Modal prepared Start handle");
667
+ entry.spent = true;
668
+ try {
669
+ signal?.throwIfAborted();
670
+ if (this.closed) throw new Error("Modal command router is closed");
671
+ } catch (error) {
672
+ throw new ModalCommandStartNotDispatchedError(error);
673
+ }
674
+ const request = entry.request;
675
+ try {
676
+ await this.unary("TaskExecStart", "Start", "Empty", request, signal);
677
+ } catch (error) {
678
+ const code = error?.code;
679
+ if (typeof code === "number" && [
680
+ status.INVALID_ARGUMENT,
681
+ status.NOT_FOUND,
682
+ status.PERMISSION_DENIED,
683
+ status.UNAUTHENTICATED,
684
+ status.UNIMPLEMENTED
685
+ ].includes(code))
686
+ throw new ModalCommandStartRejectedError(code, error);
687
+ throw new ModalCommandStartOutcomeUnknownError(request.taskId, request.execId, error);
688
+ }
689
+ }
690
+ async start(request, signal) {
691
+ const prepared2 = await this.prepareStart(request, signal);
692
+ await this.dispatchPreparedStart(prepared2, signal);
693
+ }
694
+ async write(identity, offset, data, signal) {
695
+ if (!Number.isSafeInteger(offset) || offset < 0)
696
+ throw new Error("Invalid Modal stdin byte offset");
697
+ await this.unary(
698
+ "TaskExecStdinWrite",
699
+ "Write",
700
+ "Empty",
701
+ { ...identity, offset, data, eof: false },
702
+ signal
703
+ );
704
+ }
705
+ async poll(identity, signal) {
706
+ const value = await this.unary("TaskExecPoll", "Identity", "Poll", identity, signal);
707
+ const decoded = modalRouterWire.lookupType("Poll").toObject(value);
708
+ if (decoded.code !== void 0) return decoded.code;
709
+ if (decoded.signal !== void 0) return 128 + decoded.signal;
710
+ return null;
711
+ }
712
+ async read(identity, stream, offset, waitMs, signal) {
713
+ signal?.throwIfAborted();
714
+ if (this.closed) throw new Error("Modal command router is closed");
715
+ if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isFinite(waitMs) || waitMs < 0 || waitMs > 5e4)
716
+ throw new Error("Invalid Modal output read bounds");
717
+ const chunks = [];
718
+ let length = 0;
719
+ let limited = false;
720
+ return await new Promise((resolve7, reject) => {
721
+ const call = this.client.makeServerStreamRequest(
722
+ prefix + "TaskExecStdioRead",
723
+ (value) => encode("Read", value),
724
+ (bytes) => modalRouterWire.lookupType("Data").decode(bytes),
725
+ { ...identity, offset, fileDescriptor: stream === "stdout" ? 0 : 1 },
726
+ this.metadata,
727
+ { deadline: Date.now() + Math.max(1, waitMs) }
728
+ );
729
+ const abort = () => call.cancel();
730
+ const finish = (eof, error) => {
731
+ signal?.removeEventListener("abort", abort);
732
+ if (signal?.aborted) reject(signal.reason);
733
+ else if (error) reject(error);
734
+ else resolve7({ bytes: Buffer.concat(chunks, length), eof });
735
+ };
736
+ call.on("data", (value) => {
737
+ if (limited) return;
738
+ const part = Buffer.from(value.data).subarray(0, MODAL_ROUTER_READ_PAGE_BYTES - length);
739
+ if (part.length) {
740
+ chunks.push(part);
741
+ length += part.length;
742
+ }
743
+ if (length === MODAL_ROUTER_READ_PAGE_BYTES) {
744
+ limited = true;
745
+ call.cancel();
746
+ }
747
+ });
748
+ call.once("error", (error) => {
749
+ if (limited && error.code === status.CANCELLED || error.code === status.DEADLINE_EXCEEDED)
750
+ finish(false);
751
+ else finish(false, error);
752
+ });
753
+ call.once("end", () => finish(!limited));
754
+ signal?.addEventListener("abort", abort, { once: true });
755
+ if (signal?.aborted) abort();
756
+ });
757
+ }
758
+ };
759
+
760
+ // src/sandbox/providers/modal-legacy-command-control.ts
761
+ import { ModalLegacyProviderCommand } from "@opengeni/contracts";
762
+
763
+ // src/sandbox/providers/modal-command-argv.ts
764
+ function modalCommandArgv(args) {
765
+ const command = [
766
+ args.shell ?? "/bin/sh",
767
+ args.shell && (args.login ?? true) ? "-lc" : "-c",
768
+ args.cmd
769
+ ];
770
+ if (!args.runAs) return command;
771
+ return [
772
+ "/bin/sh",
773
+ "-c",
774
+ `user=$1; shift; if [ "$(id -u)" = "$user" ] || [ "$(id -un 2>/dev/null)" = "$user" ]; then exec "$@"; elif [ "$(id -u)" = 0 ]; then exec su -s /bin/sh -c 'exec "$@"' -- "$user" sh "$@"; else exec sudo -n -u "$user" -- "$@"; fi`,
775
+ "opengeni-run-as",
776
+ args.runAs,
777
+ ...command
778
+ ];
779
+ }
780
+
781
+ // src/sandbox/providers/modal-legacy-command-control.ts
782
+ var modalCommandAbortMiddleware = async function* (call, options) {
783
+ options.signal?.throwIfAborted();
784
+ return yield* call.next(call.request, options);
785
+ };
786
+ var ModalClientBase = ModalClient;
787
+ var ModalCommandClient = class extends ModalClientBase {
788
+ retryMiddleware() {
789
+ return modalCommandAbortMiddleware;
790
+ }
791
+ };
792
+ var controlClients = /* @__PURE__ */ new WeakMap();
793
+ function commandControlPlane(client) {
794
+ if (!client.profile) return client.cpClient;
795
+ if (typeof Reflect.get(ModalClient.prototype, "retryMiddleware") !== "function")
796
+ throw new Error("Verified Modal command cancellation contract is unavailable");
797
+ let controlled = controlClients.get(client);
798
+ if (!controlled) {
799
+ const profile = client.profile;
800
+ if (!profile.tokenId || !profile.tokenSecret)
801
+ throw new Error("Modal command control requires its original authenticated profile");
802
+ controlled = new ModalCommandClient({
803
+ tokenId: profile.tokenId,
804
+ tokenSecret: profile.tokenSecret,
805
+ endpoint: profile.serverUrl,
806
+ environment: profile.environment ?? "",
807
+ ...profile.maxThrottleWaitSecs !== void 0 ? { maxThrottleWaitSecs: profile.maxThrottleWaitSecs } : {},
808
+ ...client.logger ? { logger: client.logger } : {}
809
+ });
810
+ controlClients.set(client, controlled);
811
+ }
812
+ return controlled.cpClient;
813
+ }
814
+ function decodePage(prior, input, terminal) {
815
+ const bytes = Buffer.concat([Buffer.from(prior, "base64"), ...input]);
816
+ let boundary = bytes.length;
817
+ if (!terminal) {
818
+ for (let start = Math.max(0, bytes.length - 3); start < bytes.length; start++) {
819
+ const first = bytes[start];
820
+ const width = first >= 194 && first <= 223 ? 2 : first >= 224 && first <= 239 ? 3 : first >= 240 && first <= 244 ? 4 : 0;
821
+ if (!width || bytes.length - start >= width) continue;
822
+ const suffix = bytes.subarray(start + 1);
823
+ if (!suffix.every((byte) => byte >= 128 && byte <= 191)) continue;
824
+ const second = suffix[0];
825
+ if (second !== void 0 && (first === 224 && second < 160 || first === 237 && second > 159 || first === 240 && second < 144 || first === 244 && second > 143))
826
+ continue;
827
+ boundary = start;
828
+ break;
829
+ }
830
+ }
831
+ return {
832
+ text: bytes.subarray(0, boundary).toString("utf8"),
833
+ remainder: bytes.subarray(boundary).toString("base64")
834
+ };
835
+ }
836
+ var ModalCommandControl = class _ModalCommandControl {
837
+ constructor(client, sandboxIdentity, root, environment = {}) {
838
+ this.client = client;
839
+ this.sandboxIdentity = sandboxIdentity;
840
+ this.root = root;
841
+ this.environment = environment;
842
+ }
843
+ static forSandbox(client, sandboxId, root, environment = {}) {
844
+ if (client.version() !== "0.9.0")
845
+ throw new Error("Modal command control requires the verified 0.9.0 SDK contract");
846
+ return new _ModalCommandControl(commandControlPlane(client), sandboxId, root, environment);
847
+ }
848
+ get sandboxId() {
849
+ return typeof this.sandboxIdentity === "function" ? this.sandboxIdentity() : this.sandboxIdentity;
850
+ }
851
+ async start(args, signal) {
852
+ signal?.throwIfAborted();
853
+ const workdir = posix.resolve(this.root, args.workdir ?? this.root);
854
+ if (workdir !== this.root && !workdir.startsWith(`${this.root.replace(/\/$/u, "")}/`))
855
+ throw new Error("Command workdir is outside the sandbox workspace");
856
+ const sandboxId = this.sandboxId;
857
+ const task = await ModalCommandStartPreDispatchUnavailableError.beforeDispatch(
858
+ () => this.client.sandboxGetTaskId({ sandboxId }, signal ? { signal } : void 0),
859
+ signal
860
+ );
861
+ if (!task.taskId || task.taskResult) throw new Error("Modal command task is unavailable");
862
+ if (sandboxId !== this.sandboxId)
863
+ throw new Error("Modal sandbox changed during command preparation");
864
+ let command = modalCommandArgv(args);
865
+ const environment = typeof this.environment === "function" ? this.environment() : this.environment;
866
+ if (Object.keys(environment).length) {
867
+ command = [
868
+ "/usr/bin/env",
869
+ "--",
870
+ ...Object.entries(environment).map(([key, value]) => `${key}=${value}`),
871
+ ...command
872
+ ];
873
+ }
874
+ const result = await this.client.containerExec(
875
+ {
876
+ taskId: task.taskId,
877
+ command,
878
+ terminateContainerOnExit: false,
879
+ runtimeDebug: false,
880
+ stdoutOutput: 2,
881
+ stderrOutput: 2,
882
+ timeoutSecs: 0,
883
+ workdir,
884
+ secretIds: [],
885
+ ...args.tty ? {
886
+ ptyInfo: {
887
+ enabled: true,
888
+ winszRows: 24,
889
+ winszCols: 80,
890
+ envTerm: "xterm",
891
+ envColorterm: "",
892
+ envTermProgram: "",
893
+ ptyType: 1,
894
+ noTerminateOnIdleStdin: true
895
+ }
896
+ } : {}
897
+ },
898
+ { retries: 0, ...signal ? { signal } : {} }
899
+ ).catch((error) => {
900
+ const code = error?.code;
901
+ if (typeof code === "number" && [
902
+ status2.INVALID_ARGUMENT,
903
+ status2.NOT_FOUND,
904
+ status2.PERMISSION_DENIED,
905
+ status2.UNAUTHENTICATED,
906
+ status2.UNIMPLEMENTED
907
+ ].includes(code))
908
+ throw new ProviderCommandStartRejectedError(error);
909
+ throw new ModalCommandStartOutcomeUnknownError(task.taskId, "", error);
910
+ });
911
+ if (!result.execId)
912
+ throw new ModalCommandStartOutcomeUnknownError(
913
+ task.taskId,
914
+ "",
915
+ new Error("Modal command start returned no execution identity")
916
+ );
917
+ return {
918
+ kind: "modal-control-v1",
919
+ sandboxId,
920
+ taskId: task.taskId,
921
+ execId: result.execId,
922
+ ...args.tty ? { pty: true } : {},
923
+ streams: {
924
+ stdout: { batchIndex: 0, utf8Remainder: "", exitCode: null },
925
+ stderr: { batchIndex: 0, utf8Remainder: "", exitCode: null }
926
+ }
927
+ };
928
+ }
929
+ async read(command, yieldTimeMs, signal) {
930
+ return this.readOutput(command, yieldTimeMs, signal);
931
+ }
932
+ /** Fixed internal probes own their cancellation controller and must drain
933
+ * both reads before relinquishing the surrounding provider-operation gate.
934
+ * Retained-command readers keep their existing signal/receipt contract.
935
+ */
936
+ async readProbe(command, yieldTimeMs, cancellation) {
937
+ return this.readOutput(
938
+ command,
939
+ yieldTimeMs,
940
+ cancellation.signal,
941
+ (error) => cancellation.abort(error)
942
+ );
943
+ }
944
+ async readOutput(command, yieldTimeMs, signal, cancelSiblings) {
945
+ signal?.throwIfAborted();
946
+ this.assertIdentity(command);
947
+ const next = structuredClone(command);
948
+ let failure;
949
+ const reads = ["stdout", "stderr"].map(async (stream) => {
950
+ const cursor = command.streams[stream];
951
+ if (cursor.exitCode !== null) return null;
952
+ const descriptor = stream === "stdout" ? 1 : 2;
953
+ for await (const batch of this.client.containerExecGetOutput(
954
+ {
955
+ execId: command.execId,
956
+ timeout: Math.max(0, yieldTimeMs) / 1e3,
957
+ lastBatchIndex: cursor.batchIndex,
958
+ fileDescriptor: descriptor,
959
+ getRawBytes: true
960
+ },
961
+ signal ? { signal } : void 0
962
+ )) {
963
+ if (batch.batchIndex <= cursor.batchIndex) continue;
964
+ if (!Number.isSafeInteger(batch.batchIndex))
965
+ throw new Error("Invalid Modal output cursor");
966
+ const terminal = batch.exitCode !== void 0;
967
+ if (terminal && !Number.isSafeInteger(batch.exitCode))
968
+ throw new Error("Invalid Modal exit status");
969
+ const decoded = decodePage(
970
+ cursor.utf8Remainder,
971
+ batch.items.filter((item) => item.fileDescriptor === descriptor).map((item) => item.messageBytes),
972
+ terminal
973
+ );
974
+ next.streams[stream] = {
975
+ batchIndex: batch.batchIndex,
976
+ utf8Remainder: decoded.remainder,
977
+ exitCode: terminal ? batch.exitCode : null
978
+ };
979
+ return {
980
+ stream,
981
+ chunkId: `modal:${command.execId}:${stream}:${cursor.batchIndex}:${batch.batchIndex}`,
982
+ text: decoded.text
983
+ };
984
+ }
985
+ return null;
986
+ }).map(
987
+ (read) => !cancelSiblings ? read : read.catch((error) => {
988
+ failure ??= { error };
989
+ cancelSiblings(error);
990
+ throw error;
991
+ })
992
+ );
993
+ const pages = cancelSiblings ? await Promise.allSettled(reads).then((results) => {
994
+ if (failure) throw failure.error;
995
+ return results.map((result) => {
996
+ if (result.status === "rejected") throw result.reason;
997
+ return result.value;
998
+ });
999
+ }) : await Promise.all(reads);
1000
+ const stdoutExit = next.streams.stdout.exitCode;
1001
+ const stderrExit = next.streams.stderr.exitCode;
1002
+ if (stdoutExit !== null && stderrExit !== null && stdoutExit !== stderrExit)
1003
+ throw new Error("Modal output streams disagree about command exit status");
1004
+ return {
1005
+ command: next,
1006
+ streamFidelity: command.pty ? "merged" : "separate",
1007
+ chunks: pages.filter((page) => page !== null),
1008
+ exitCode: stdoutExit !== null && stderrExit !== null ? stdoutExit : null
1009
+ };
1010
+ }
1011
+ async write(command, chars, messageIndex) {
1012
+ this.assertIdentity(command);
1013
+ if (!chars) return;
1014
+ if (!Number.isSafeInteger(messageIndex) || messageIndex < 1)
1015
+ throw new Error("Modal stdin requires a protected monotonic message index");
1016
+ await this.client.containerExecPutInput(
1017
+ {
1018
+ execId: command.execId,
1019
+ input: { message: Buffer.from(chars), messageIndex, eof: false }
1020
+ },
1021
+ { retries: 0 }
1022
+ );
1023
+ }
1024
+ assertIdentity(command) {
1025
+ ModalLegacyProviderCommand.parse(command);
1026
+ if (command.kind !== "modal-control-v1" || command.sandboxId !== this.sandboxId || !command.taskId || !command.execId)
1027
+ throw new Error("Modal command locator does not match the original sandbox");
1028
+ }
1029
+ };
1030
+
1031
+ // src/sandbox/providers/modal-command-raw-page.ts
1032
+ var RawStream = external_exports.object({
1033
+ bytes: external_exports.instanceof(Uint8Array).transform((bytes) => bytes).refine(
1034
+ (bytes) => bytes.byteLength <= MODAL_ROUTER_READ_PAGE_BYTES,
1035
+ "Raw page exceeded its bound"
1036
+ ),
1037
+ eof: external_exports.boolean()
1038
+ }).strict();
1039
+ var RawExit = external_exports.discriminatedUnion("source", [
1040
+ external_exports.object({ source: external_exports.literal("router_poll"), code: external_exports.number().int().nullable() }).strict(),
1041
+ external_exports.object({ source: external_exports.literal("retained_terminal"), code: external_exports.number().int() }).strict()
1042
+ ]);
1043
+ var RawPage = external_exports.object({
1044
+ protocol: external_exports.literal("modal-router-raw-page-v1"),
1045
+ expected: ModalRouterProviderCommand2,
1046
+ command: ModalRouterProviderCommand2,
1047
+ streams: external_exports.object({ stdout: RawStream, stderr: RawStream }).strict(),
1048
+ exit: RawExit
1049
+ }).strict();
1050
+ function project(expected, streams, exit) {
1051
+ const command = structuredClone(expected);
1052
+ const chunks = [];
1053
+ for (const stream of ["stdout", "stderr"]) {
1054
+ const old = expected.streams[stream];
1055
+ const page = streams[stream];
1056
+ const decoded = decodePage(old.utf8Remainder, [page.bytes], page.eof);
1057
+ const byteOffset = old.byteOffset + page.bytes.byteLength;
1058
+ if (!Number.isSafeInteger(byteOffset)) throw new Error("Modal output offset exhausted");
1059
+ command.streams[stream] = {
1060
+ byteOffset,
1061
+ utf8Remainder: decoded.remainder,
1062
+ eof: page.eof,
1063
+ exitCode: page.eof ? exit.code : null
1064
+ };
1065
+ if (decoded.text)
1066
+ chunks.push({
1067
+ stream,
1068
+ chunkId: `modal-router:${expected.execId}:${stream}:${old.byteOffset}:${byteOffset}:${page.eof ? 1 : 0}`,
1069
+ text: decoded.text
1070
+ });
1071
+ }
1072
+ return {
1073
+ command,
1074
+ expected: structuredClone(expected),
1075
+ chunks,
1076
+ exitCode: command.streams.stdout.eof && command.streams.stderr.eof ? exit.code : null,
1077
+ providerExited: exit.code !== null,
1078
+ streamFidelity: expected.pty ? "merged" : "separate"
1079
+ };
1080
+ }
1081
+ function collectModalRawOutputPage(command, streams, exit) {
1082
+ const expected = structuredClone(command);
1083
+ const captured = {
1084
+ stdout: { bytes: Buffer.from(streams.stdout.bytes), eof: streams.stdout.eof },
1085
+ stderr: { bytes: Buffer.from(streams.stderr.bytes), eof: streams.stderr.eof }
1086
+ };
1087
+ const output = project(expected, captured, exit);
1088
+ return {
1089
+ raw: {
1090
+ protocol: "modal-router-raw-page-v1",
1091
+ expected,
1092
+ command: structuredClone(output.command),
1093
+ streams: captured,
1094
+ exit: { ...exit }
1095
+ },
1096
+ output
1097
+ };
1098
+ }
1099
+ function reduceModalRawOutputPage(input, current) {
1100
+ const page = RawPage.parse(input);
1101
+ const expected = ModalRouterProviderCommand2.parse(current);
1102
+ if (!isDeepStrictEqual(page.expected, expected))
1103
+ throw new Error("Raw page does not match the current native cursor");
1104
+ for (const stream of ["stdout", "stderr"]) {
1105
+ const old = expected.streams[stream];
1106
+ const raw = page.streams[stream];
1107
+ const remainder = Buffer.from(old.utf8Remainder, "base64");
1108
+ if (remainder.toString("base64") !== old.utf8Remainder || remainder.length > 3 || remainder.length > old.byteOffset || old.eof && remainder.length !== 0)
1109
+ throw new Error("Raw page has an invalid saved UTF-8 remainder");
1110
+ if (old.eof && (!raw.eof || raw.bytes.byteLength !== 0))
1111
+ throw new Error("Raw page reopened or advanced a completed stream");
1112
+ if (old.exitCode !== null && page.exit.code !== old.exitCode)
1113
+ throw new Error("Raw page rewrote captured terminal evidence");
1114
+ }
1115
+ if (page.exit.source === "retained_terminal" && (!expected.streams.stdout.eof || !expected.streams.stderr.eof || expected.streams.stdout.exitCode !== page.exit.code || expected.streams.stderr.exitCode !== page.exit.code))
1116
+ throw new Error("Raw page has no matching retained terminal evidence");
1117
+ const output = project(expected, page.streams, page.exit);
1118
+ if (!isDeepStrictEqual(page.command, output.command))
1119
+ throw new Error("Raw page cursor delta or remainder does not match its bytes");
1120
+ return output;
1121
+ }
1122
+
155
1123
  // src/sandbox/host-archive-spool.ts
156
- import { createHash as createHash2 } from "crypto";
1124
+ import { createHash as createHash3 } from "crypto";
157
1125
  import { constants as constants2 } from "fs";
158
1126
  import {
159
1127
  lstat as lstat2,
@@ -170,7 +1138,7 @@ import { tmpdir } from "os";
170
1138
  import { isAbsolute as isAbsolute2, join as join2, relative, resolve, sep } from "path";
171
1139
 
172
1140
  // src/sandbox/workspace-archive.ts
173
- import { createHash } from "crypto";
1141
+ import { createHash as createHash2 } from "crypto";
174
1142
  import { constants } from "fs";
175
1143
  import { lstat, open, readdir } from "fs/promises";
176
1144
  import { isAbsolute, join } from "path";
@@ -318,7 +1286,7 @@ var WorkspaceArchiveIntegrityError = class extends Error {
318
1286
  retryable;
319
1287
  };
320
1288
  function sha256(bytes) {
321
- return createHash("sha256").update(bytes).digest("hex");
1289
+ return createHash2("sha256").update(bytes).digest("hex");
322
1290
  }
323
1291
  function decodeBase64Strict(value) {
324
1292
  if (value.length === 0 || value.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(value)) {
@@ -506,7 +1474,7 @@ function fingerprintSdkLocalProjection(directoryInput, fileInput) {
506
1474
  (left, right) => stableLogicalPathCompare(left.path, right.path)
507
1475
  );
508
1476
  const paths = /* @__PURE__ */ new Set();
509
- const hash = createHash("sha256");
1477
+ const hash = createHash2("sha256");
510
1478
  appendFingerprintFrame(hash, "projection", SDK_LOCAL_ARCHIVE_PROJECTION);
511
1479
  for (const directory of directories) {
512
1480
  if (paths.has(directory)) {
@@ -1027,7 +1995,7 @@ function frame(hash, label, value) {
1027
1995
  hash.update(label).update("\0").update(String(Buffer.byteLength(value))).update("\0").update(value).update("\0");
1028
1996
  }
1029
1997
  function projection(directories) {
1030
- const hash = createHash2("sha256");
1998
+ const hash = createHash3("sha256");
1031
1999
  frame(hash, "projection", PROJECTION);
1032
2000
  for (const path of [...directories].sort(compare)) frame(hash, "dir", path);
1033
2001
  return hash;
@@ -1115,7 +2083,7 @@ var ArchiveWriter = class {
1115
2083
  constructor(handle) {
1116
2084
  this.handle = handle;
1117
2085
  }
1118
- hash = createHash2("sha256");
2086
+ hash = createHash3("sha256");
1119
2087
  byteSize = 0;
1120
2088
  async write(input) {
1121
2089
  const bytes = typeof input === "string" ? Buffer.from(input) : input;
@@ -1151,12 +2119,12 @@ var Base64Encoder = class {
1151
2119
  if (this.carry) await this.encode(this.carry);
1152
2120
  }
1153
2121
  };
1154
- function ownedSpool(directory, path, byteSize, sha2563) {
2122
+ function ownedSpool(directory, path, byteSize, sha2564) {
1155
2123
  let disposal;
1156
2124
  return {
1157
2125
  path,
1158
2126
  byteSize,
1159
- sha256: sha2563,
2127
+ sha256: sha2564,
1160
2128
  async *open() {
1161
2129
  if (disposal) throw new Error("archive spool has been disposed");
1162
2130
  const handle = await open2(path, READ);
@@ -3827,7 +4795,7 @@ function decodeNativeSnapshotRef3(data) {
3827
4795
  }
3828
4796
 
3829
4797
  // ../../node_modules/.bun/@openai+agents-extensions@0.14.3+ec9838bc68a64a7b/node_modules/@openai/agents-extensions/dist/sandbox/blaxel/mounts.mjs
3830
- import { createHash as createHash3 } from "crypto";
4798
+ import { createHash as createHash4 } from "crypto";
3831
4799
 
3832
4800
  // ../../node_modules/.bun/@openai+agents-extensions@0.14.3+ec9838bc68a64a7b/node_modules/@openai/agents-extensions/dist/sandbox/shared/inContainerMounts.mjs
3833
4801
  var DEFAULT_PACKAGE_MANAGERS = ["apt"];
@@ -4370,7 +5338,7 @@ function rcloneArchiveArch(machine) {
4370
5338
  }
4371
5339
  function rcloneInstallCommand(arch) {
4372
5340
  const archive = `rclone-v${RCLONE_VERSION}-linux-${arch}.zip`;
4373
- const sha2563 = RCLONE_SHA256_BY_ARCH[arch];
5341
+ const sha2564 = RCLONE_SHA256_BY_ARCH[arch];
4374
5342
  const url = `https://downloads.rclone.org/v${RCLONE_VERSION}/${archive}`;
4375
5343
  return [
4376
5344
  "set -eu",
@@ -4383,7 +5351,7 @@ function rcloneInstallCommand(arch) {
4383
5351
  "trap cleanup EXIT",
4384
5352
  "trap 'exit 1' HUP INT TERM",
4385
5353
  `archive=${shellQuote(archive)}`,
4386
- `expected_sha256=${shellQuote(sha2563)}`,
5354
+ `expected_sha256=${shellQuote(sha2564)}`,
4387
5355
  `url=${shellQuote(url)}`,
4388
5356
  `curl --fail --location --silent --show-error --proto '=https' --tlsv1.2 --output "$tmp_dir/$archive" "$url"`,
4389
5357
  `if ! printf '%s %s\\n' "$expected_sha256" "$tmp_dir/$archive" | sha256sum --check --strict -; then`,
@@ -4996,7 +5964,7 @@ function mountStrategyType2(entry) {
4996
5964
  return entry.mountStrategy?.type;
4997
5965
  }
4998
5966
  function safeId(value) {
4999
- return createHash3("sha256").update(value).digest("hex");
5967
+ return createHash4("sha256").update(value).digest("hex");
5000
5968
  }
5001
5969
 
5002
5970
  // ../../node_modules/.bun/@openai+agents-extensions@0.14.3+ec9838bc68a64a7b/node_modules/@openai/agents-extensions/dist/sandbox/blaxel/sandbox.mjs
@@ -8455,7 +9423,7 @@ import { dirname, join as join3, resolve as resolve2 } from "path";
8455
9423
 
8456
9424
  // ../../node_modules/.bun/@openai+agents-core@0.14.3+933c5e7db4cd33c2/node_modules/@openai/agents-core/dist/sandbox/sandboxes/docker.mjs
8457
9425
  import { chmod as chmod2, mkdir as mkdir5, mkdtemp as mkdtemp5, realpath as realpath4, rm as rm5, stat as stat4 } from "fs/promises";
8458
- import { createHash as createHash5, randomUUID as randomUUID4 } from "crypto";
9426
+ import { createHash as createHash6, randomUUID as randomUUID4 } from "crypto";
8459
9427
  import { spawn as spawn3 } from "child_process";
8460
9428
  import { isAbsolute as isAbsolute5, join as join7, resolve as resolve5 } from "path";
8461
9429
  import { tmpdir as tmpdir5 } from "os";
@@ -9133,12 +10101,12 @@ function normalizeGitRepository2(entry) {
9133
10101
  // ../../node_modules/.bun/@openai+agents-core@0.14.3+933c5e7db4cd33c2/node_modules/@openai/agents-core/dist/sandbox/sandboxes/shared/localSnapshots.mjs
9134
10102
  import { lstat as lstat4, mkdir as mkdir3, mkdtemp as mkdtemp3, open as open4, readdir as readdir4, realpath as realpath3, rm as rm3, stat as stat2 } from "fs/promises";
9135
10103
  import { constants as constants4 } from "fs";
9136
- import { createHash as createHash4, randomUUID as randomUUID3 } from "crypto";
10104
+ import { createHash as createHash5, randomUUID as randomUUID3 } from "crypto";
9137
10105
  import { dirname as dirname3, join as join5, relative as relative3, sep as sep3 } from "path";
9138
10106
 
9139
10107
  // ../../node_modules/.bun/@openai+agents-core@0.14.3+933c5e7db4cd33c2/node_modules/@openai/agents-core/dist/sandbox/sandboxes/shared/localSnapshotPaths.mjs
9140
10108
  import { homedir, tmpdir as tmpdir3 } from "os";
9141
- import { posix, win32 } from "path";
10109
+ import { posix as posix2, win32 } from "path";
9142
10110
  function isAbsoluteWindowsPath(value) {
9143
10111
  const root = win32.parse(value).root;
9144
10112
  return win32.isAbsolute(value) && root.length > 1;
@@ -9150,14 +10118,14 @@ function defaultLocalSnapshotBaseDir() {
9150
10118
  }
9151
10119
  const home = homedir();
9152
10120
  if (process.platform === "darwin" && home) {
9153
- return posix.join(home, "Library", "Application Support", "openai-agents-js", "sandbox-snapshots");
10121
+ return posix2.join(home, "Library", "Application Support", "openai-agents-js", "sandbox-snapshots");
9154
10122
  }
9155
10123
  if (process.platform === "win32") {
9156
10124
  const localAppData = process.env.LOCALAPPDATA?.trim();
9157
10125
  return win32.join(localAppData && isAbsoluteWindowsPath(localAppData) ? localAppData : home ? win32.join(home, "AppData", "Local") : tmpdir3(), "openai-agents-js", "sandbox-snapshots");
9158
10126
  }
9159
10127
  const stateHome = process.env.XDG_STATE_HOME?.trim();
9160
- return posix.join(stateHome && posix.isAbsolute(stateHome) ? stateHome : home ? posix.join(home, ".local", "state") : tmpdir3(), "openai-agents-js", "sandbox-snapshots");
10128
+ return posix2.join(stateHome && posix2.isAbsolute(stateHome) ? stateHome : home ? posix2.join(home, ".local", "state") : tmpdir3(), "openai-agents-js", "sandbox-snapshots");
9161
10129
  }
9162
10130
 
9163
10131
  // ../../node_modules/.bun/@openai+agents-core@0.14.3+933c5e7db4cd33c2/node_modules/@openai/agents-core/dist/sandbox/sandboxes/shared/localSnapshots.mjs
@@ -9299,7 +10267,7 @@ async function restoreLocalSnapshotToWorkspace(state, workspaceRootPath, options
9299
10267
  return state;
9300
10268
  }
9301
10269
  async function computeLocalSnapshotFingerprint(state) {
9302
- const hash = createHash4("sha256");
10270
+ const hash = createHash5("sha256");
9303
10271
  appendHashFrame(hash, "version", LOCAL_SNAPSHOT_FINGERPRINT_VERSION);
9304
10272
  appendHashFrame(hash, "manifest", stableJsonStringify(serializeManifest(state.manifest), {
9305
10273
  encodeBytes: (value) => ({
@@ -11642,7 +12610,7 @@ async function resolveDockerManifestBindMounts(manifest) {
11642
12610
  function dockerMountAuthorityFingerprint(sessionIdentity2, workspaceMount, pathGrantMounts, manifestBindMounts, manifest) {
11643
12611
  const mountedGrants = [...pathGrantMounts].sort((left, right) => left.target < right.target ? -1 : left.target > right.target ? 1 : 0);
11644
12612
  const mountedManifestBinds = [...manifestBindMounts].sort((left, right) => left.target < right.target ? -1 : left.target > right.target ? 1 : 0);
11645
- return createHash5("sha256").update(stableJsonStringify({
12613
+ return createHash6("sha256").update(stableJsonStringify({
11646
12614
  sessionIdentity: sessionIdentity2,
11647
12615
  workspaceMount,
11648
12616
  mountedGrants,
@@ -11653,7 +12621,7 @@ function dockerMountAuthorityFingerprint(sessionIdentity2, workspaceMount, pathG
11653
12621
  })).digest("hex");
11654
12622
  }
11655
12623
  function dockerMaterializedEntriesFingerprint(manifest) {
11656
- return createHash5("sha256").update(stableJsonStringify({
12624
+ return createHash6("sha256").update(stableJsonStringify({
11657
12625
  entries: dockerNonMountManifestEntries(manifest)
11658
12626
  })).digest("hex");
11659
12627
  }
@@ -12853,7 +13821,7 @@ function sanitizeDockerMountName(value) {
12853
13821
  return value.replace(/[^A-Za-z0-9_-]/gu, "_");
12854
13822
  }
12855
13823
  function dockerPathHash(path) {
12856
- return createHash5("sha256").update(path).digest("hex").slice(0, 12);
13824
+ return createHash6("sha256").update(path).digest("hex").slice(0, 12);
12857
13825
  }
12858
13826
  function dockerPosixDirname(path) {
12859
13827
  const index = path.lastIndexOf("/");
@@ -12901,7 +13869,7 @@ function dockerMountCsvField(field) {
12901
13869
  return `"${field.replace(/"/gu, '""')}"`;
12902
13870
  }
12903
13871
  function dockerVolumeName(containerName, mountPath) {
12904
- const pathHash = createHash5("sha256").update(mountPath).digest("hex").slice(0, 12);
13872
+ const pathHash = createHash6("sha256").update(mountPath).digest("hex").slice(0, 12);
12905
13873
  const safePath = mountPath.replace(/[^A-Za-z0-9_.-]+/gu, "_").replace(/^_+|_+$/gu, "") || "workspace";
12906
13874
  return `${containerName}-${pathHash}-${safePath.slice(0, 80)}`;
12907
13875
  }
@@ -15452,7 +16420,19 @@ function createActiveProcess(process2) {
15452
16420
  droppedStderrChars: 0,
15453
16421
  done: false,
15454
16422
  exitCode: null,
15455
- donePromise: Promise.resolve()
16423
+ donePromise: Promise.resolve(),
16424
+ failed: false
16425
+ };
16426
+ let notifyFailure;
16427
+ activeProcess.failurePromise = new Promise((resolve7) => {
16428
+ notifyFailure = resolve7;
16429
+ });
16430
+ const errors = [];
16431
+ const recordFailure = (error) => {
16432
+ errors.push(error);
16433
+ activeProcess.failed = true;
16434
+ activeProcess.waitError = errors.length === 1 ? error : new AggregateError([...errors], "Modal process observation failed.");
16435
+ notifyFailure();
15456
16436
  };
15457
16437
  const stdoutPump = startTextStreamPump(process2.stdout, (chunk) => {
15458
16438
  appendActiveProcessOutput2(activeProcess, chunk, "stdout");
@@ -15460,19 +16440,19 @@ function createActiveProcess(process2) {
15460
16440
  const stderrPump = startTextStreamPump(process2.stderr, (chunk) => {
15461
16441
  appendActiveProcessOutput2(activeProcess, chunk, "stderr");
15462
16442
  });
16443
+ const stdoutDone = stdoutPump.promise.catch(recordFailure);
16444
+ const stderrDone = stderrPump.promise.catch(recordFailure);
15463
16445
  activeProcess.stopOutputPumps = async () => {
15464
16446
  await Promise.allSettled([stdoutPump.cancel(), stderrPump.cancel()]);
15465
16447
  };
15466
16448
  activeProcess.donePromise = (async () => {
15467
16449
  try {
15468
16450
  activeProcess.exitCode = await process2.wait();
15469
- await Promise.allSettled([stdoutPump.promise, stderrPump.promise]);
15470
16451
  } catch (error) {
15471
- activeProcess.waitError = error;
15472
- await Promise.allSettled([stdoutPump.promise, stderrPump.promise]);
15473
- } finally {
15474
- activeProcess.done = true;
16452
+ recordFailure(error);
15475
16453
  }
16454
+ await Promise.all([stdoutDone, stderrDone]);
16455
+ activeProcess.done = true;
15476
16456
  })();
15477
16457
  return activeProcess;
15478
16458
  }
@@ -15528,6 +16508,7 @@ async function waitForProcessOrTimeout2(activeProcess, timeoutMs) {
15528
16508
  try {
15529
16509
  await Promise.race([
15530
16510
  activeProcess.donePromise,
16511
+ activeProcess.failurePromise,
15531
16512
  new Promise((resolve7) => {
15532
16513
  timeout = setTimeout(resolve7, timeoutMs);
15533
16514
  unrefTimer(timeout);
@@ -15538,13 +16519,13 @@ async function waitForProcessOrTimeout2(activeProcess, timeoutMs) {
15538
16519
  clearTimeout(timeout);
15539
16520
  }
15540
16521
  }
15541
- if (activeProcess.waitError) {
16522
+ if (activeProcess.failed) {
15542
16523
  await activeProcess.stopOutputPumps?.();
15543
- throw new SandboxProviderError("ModalSandboxClient failed to wait for process completion.", {
16524
+ throw Object.assign(new SandboxProviderError("ModalSandboxClient failed to wait for process completion.", {
15544
16525
  provider: "modal",
15545
16526
  operation: "wait process",
15546
16527
  cause: modalErrorMessage(activeProcess.waitError)
15547
- });
16528
+ }), { cause: activeProcess.waitError });
15548
16529
  }
15549
16530
  }
15550
16531
  function modalErrorMessage(error) {
@@ -15658,7 +16639,7 @@ import {
15658
16639
  } from "@opengeni/contracts";
15659
16640
 
15660
16641
  // src/sandbox/channel-a.ts
15661
- import { createHash as createHash6 } from "crypto";
16642
+ import { createHash as createHash7 } from "crypto";
15662
16643
 
15663
16644
  // src/sandbox/confined-file-read.ts
15664
16645
  function confinedFileReadScript(root, path, maxBytes) {
@@ -15889,661 +16870,213 @@ function writeFilesPrelude(input) {
15889
16870
  input.sha256Function,
15890
16871
  `og_fail() { printf '%s' "$1"; exit "$2"; }`,
15891
16872
  `root=$(opengeni_realpath_existing ${shellQuote3(input.root)}) || og_fail __OPENGENI_FS_NOT_FOUND__ 66`,
15892
- `og_confined() { case "$1" in "$root"|"\${root%/}/"*) return 0 ;; *) return 1 ;; esac; }`,
15893
- // A directory on the path is never a symbolic link and always resolves
15894
- // beneath the workspace root. A missing one returns 1 for the caller.
15895
- [
15896
- "og_dir() {",
15897
- `[ ! -L "$2" ] || og_fail "__OPENGENI_FS_SYMLINK__D$1__" 68`,
15898
- `[ -e "$2" ] || return 1`,
15899
- `[ -d "$2" ] || og_fail "__OPENGENI_FS_NOT_DIR__D$1__" 69`,
15900
- `og_t=$(opengeni_realpath_existing "$2") || og_fail "__OPENGENI_FS_NOT_FOUND__D$1__" 66`,
15901
- `og_confined "$og_t" || og_fail "__OPENGENI_FS_ESCAPE__D$1__" 67`,
15902
- "}"
15903
- ].join("\n"),
15904
- // 0: the exact bytes already exist. 1: missing. Anything else fails.
15905
- [
15906
- "og_file() {",
15907
- `if [ -L "$2" ]; then og_fail "__OPENGENI_FS_CONFLICT__F$1__" 65; fi`,
15908
- `[ -e "$2" ] || return 1`,
15909
- `[ -f "$2" ] || og_fail "__OPENGENI_FS_CONFLICT__F$1__" 65`,
15910
- `og_n=$(wc -c < "$2") || og_fail "__OPENGENI_FS_CONFLICT__F$1__" 65`,
15911
- `[ "$((og_n))" = "$3" ] || og_fail "__OPENGENI_FS_CONFLICT__F$1__" 65`,
15912
- `og_h=$(opengeni_sha256_file "$2") || og_fail "__OPENGENI_FS_UNVERIFIED__F$1__" 65`,
15913
- `[ "$og_h" = "$4" ] || og_fail "__OPENGENI_FS_CONFLICT__F$1__" 65`,
15914
- "}"
15915
- ].join("\n"),
15916
- [
15917
- "og_mk() {",
15918
- `mkdir -- "$2" 2>/dev/null || og_fail "__OPENGENI_FS_WRITE_FAILED__D$1__" 70`,
15919
- `printf '__OGF_D__%s__' "$1"`,
15920
- `og_dir "$1" "$2" || og_fail "__OPENGENI_FS_NOT_FOUND__D$1__" 66`,
15921
- "}"
15922
- ].join("\n"),
15923
- // noclobber opens a missing path with O_EXCL, so a file that appeared
15924
- // since the check (including a dangling symlink) is never replaced. A
15925
- // failed open exits 1 and leaves the path alone. Once the open succeeded
15926
- // the file is this call's own, so a failed or short write (a full disk,
15927
- // for example) removes it; otherwise a repeat would find a truncated file
15928
- // and report a conflict instead of finishing the write.
15929
- [
15930
- "og_put() {",
15931
- `( set -C; { printf '%s' "$4" | base64 -d || exit 72; } > "$2" ) 2>/dev/null`,
15932
- "og_s=$?",
15933
- `[ "$og_s" != 72 ] || { rm -f -- "$2"; og_fail "__OPENGENI_FS_WRITE_FAILED__F$1__" 71; }`,
15934
- `[ "$og_s" = 0 ] || og_fail "__OPENGENI_FS_WRITE_FAILED__F$1__" 71`,
15935
- `og_n=$(wc -c < "$2") && [ "$((og_n))" = "$3" ] || { rm -f -- "$2"; og_fail "__OPENGENI_FS_WRITE_FAILED__F$1__" 71; }`,
15936
- `printf '__OGF_W__%s__' "$1"`,
15937
- "}"
15938
- ].join("\n")
15939
- ];
15940
- }
15941
- function directoryCheckFragment(directory) {
15942
- return `og_dir ${directory.index} ${shellQuote3(directory.providerPath)} || :`;
15943
- }
15944
- function fileCheckFragment(file, mode) {
15945
- const check = `og_file ${file.index} ${shellQuote3(file.providerPath)} ${file.sizeBytes} ${file.sha256}`;
15946
- const missing = mode === "check" ? `printf '__OGF_M__%s__' ${file.index}` : `og_m${file.index}=1`;
15947
- return `if ${check}; then printf '__OGF_S__%s__' ${file.index}; else ${missing}; fi`;
15948
- }
15949
- function directoryCreateFragment(directory) {
15950
- const path = shellQuote3(directory.providerPath);
15951
- return `og_dir ${directory.index} ${path} || og_mk ${directory.index} ${path}`;
15952
- }
15953
- function filePutFragment(file) {
15954
- if (file.base64 === void 0) throw new Error("write mode requires file content");
15955
- return `[ -z "\${og_m${file.index}:-}" ] || og_put ${file.index} ${shellQuote3(file.providerPath)} ${file.sizeBytes} ${shellQuote3(file.base64)}`;
15956
- }
15957
- function writeFilesScript(input) {
15958
- const lines = [...input.prelude];
15959
- for (const directory of input.directories) lines.push(directoryCheckFragment(directory));
15960
- for (const file of input.files) lines.push(fileCheckFragment(file, input.mode));
15961
- if (input.mode === "write") {
15962
- for (const directory of input.directories) lines.push(directoryCreateFragment(directory));
15963
- for (const file of input.files) lines.push(filePutFragment(file));
15964
- }
15965
- lines.push(`printf '%s' ${BATCH_OK}`);
15966
- return lines.join("\n");
15967
- }
15968
- function parseWriteFilesOutput(stdout) {
15969
- const output = {
15970
- complete: stdout.includes(BATCH_OK),
15971
- same: [],
15972
- missing: [],
15973
- written: [],
15974
- createdDirectories: [],
15975
- failure: null
15976
- };
15977
- for (const match of stdout.matchAll(/__OGF_([SMWD])__(\d+)__/g)) {
15978
- const index = Number(match[2]);
15979
- if (match[1] === "S") output.same.push(index);
15980
- else if (match[1] === "M") output.missing.push(index);
15981
- else if (match[1] === "W") output.written.push(index);
15982
- else output.createdDirectories.push(index);
15983
- }
15984
- const failure = /__OPENGENI_FS_(CONFLICT|UNVERIFIED|SYMLINK|NOT_DIR|NOT_FOUND|ESCAPE|WRITE_FAILED)__(?:([DF])(\d+)__)?/.exec(
15985
- stdout
15986
- );
15987
- if (failure) {
15988
- output.failure = {
15989
- code: failure[1],
15990
- target: failure[2] ? { kind: failure[2] === "D" ? "directory" : "file", index: Number(failure[3]) } : null
15991
- };
15992
- }
15993
- return output;
15994
- }
15995
-
15996
- // src/sandbox/exec-banner.ts
15997
- var typedHandleLossSessions = /* @__PURE__ */ new WeakSet();
15998
- function markTypedExecHandleLoss(session) {
15999
- typedHandleLossSessions.add(session);
16000
- }
16001
- function hasTypedExecHandleLoss(session, providerSessionId) {
16002
- if (!session) return false;
16003
- if (typedHandleLossSessions.has(session)) return true;
16004
- const routed = session;
16005
- return providerSessionId !== void 0 && routed.retainedProcessHasTypedHandleLoss?.(providerSessionId) === true;
16006
- }
16007
- var EXEC_BANNER_HEADER_MAX_CHARS = 16 * 1024;
16008
- var OUTPUT_DELIMITER = /\r?\nOutput:\r?\n/u;
16009
- var SDK_METADATA_LINE = /^(?:Chunk ID:|Wall time:|Original token count:|Output:|Process (?:running with session ID|exited with code))/mu;
16010
- var RUNNING_LINE = /^Process running with session ID (\d+)$/u;
16011
- var EXITED_LINE = /^Process exited with code (-?\d+)$/u;
16012
- var PROCESS_STATUS_PREFIX = /^Process (?:running with session ID|exited with code)/u;
16013
- function parseExecResponseBanner(raw) {
16014
- const delimiter = OUTPUT_DELIMITER.exec(raw);
16015
- if (!delimiter) {
16016
- return SDK_METADATA_LINE.test(raw) ? { kind: "invalid" } : { kind: "absent" };
16017
- }
16018
- if (delimiter.index > EXEC_BANNER_HEADER_MAX_CHARS) return { kind: "invalid" };
16019
- const header = raw.slice(0, delimiter.index);
16020
- const status4 = [];
16021
- for (const line of header.split(/\r?\n/u)) {
16022
- const running = RUNNING_LINE.exec(line);
16023
- if (running) {
16024
- status4.push({ kind: "running", value: running[1] });
16025
- continue;
16026
- }
16027
- const exited = EXITED_LINE.exec(line);
16028
- if (exited) {
16029
- status4.push({ kind: "exited", value: exited[1] });
16030
- continue;
16031
- }
16032
- if (PROCESS_STATUS_PREFIX.test(line)) return { kind: "invalid" };
16033
- }
16034
- if (status4.length !== 1) return { kind: "invalid" };
16035
- const terminal = status4[0];
16036
- const value = Number(terminal.value);
16037
- if (!Number.isSafeInteger(value)) return { kind: "invalid" };
16038
- if (terminal.kind === "running") {
16039
- return value >= 0 ? { kind: "running", sessionId: value } : { kind: "invalid" };
16040
- }
16041
- return { kind: "exited", exitCode: value };
16042
- }
16043
- function parseExecBannerSessionId(raw) {
16044
- const banner = parseExecResponseBanner(raw);
16045
- return banner.kind === "running" ? banner.sessionId : null;
16046
- }
16047
- function parseExecBannerExitCode(raw) {
16048
- const banner = parseExecResponseBanner(raw);
16049
- return banner.kind === "exited" ? banner.exitCode : null;
16050
- }
16051
- function isExecSessionLostBanner(out, execSessionId, source) {
16052
- if (source && typedHandleLossSessions.has(source)) return false;
16053
- if (!out || !Number.isSafeInteger(execSessionId) || execSessionId < 0) return false;
16054
- const delimiter = OUTPUT_DELIMITER.exec(out);
16055
- if (delimiter && delimiter.index > EXEC_BANNER_HEADER_MAX_CHARS) return false;
16056
- if (delimiter && parseExecResponseBanner(out).kind !== "exited") return false;
16057
- const candidate = delimiter ? out.slice(delimiter.index + delimiter[0].length) : out;
16058
- const match = candidate.match(/^(?:write_stdin failed: )?session not found: (\d+)$/);
16059
- if (!match || match[0] !== candidate) return false;
16060
- return match[1] === String(execSessionId);
16061
- }
16062
-
16063
- // src/sandbox/op-correlation.ts
16064
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
16065
- var storage = new AsyncLocalStorage2();
16066
- function sanitizeOpIdToken(raw) {
16067
- return raw.replace(/[^A-Za-z0-9_-]/g, (c) => `_${c.charCodeAt(0).toString(16)}_`);
16068
- }
16069
- function runWithToolCallCorrelation(callId, fn, options = {}) {
16070
- return storage.run(
16071
- {
16072
- callId: sanitizeOpIdToken(callId),
16073
- ordinal: 0,
16074
- ...options.onDurableOpOwnershipTransferStarted ? { onDurableOpOwnershipTransferStarted: options.onDurableOpOwnershipTransferStarted } : {},
16075
- ...options.onDurableOpOwnershipTransferred ? { onDurableOpOwnershipTransferred: options.onDurableOpOwnershipTransferred } : {}
16076
- },
16077
- fn
16078
- );
16079
- }
16080
- function nextDurableOpId() {
16081
- const context = storage.getStore();
16082
- if (!context) {
16083
- return null;
16084
- }
16085
- const ordinal = context.ordinal;
16086
- context.ordinal += 1;
16087
- return `${context.callId}:${ordinal}`;
16088
- }
16089
- function notifyDurableOpOwnershipTransferStarted(opId) {
16090
- storage.getStore()?.onDurableOpOwnershipTransferStarted?.(opId);
16091
- }
16092
- function notifyDurableOpOwnershipTransferred(opId) {
16093
- storage.getStore()?.onDurableOpOwnershipTransferred?.(opId);
16094
- }
16095
-
16096
- // src/sandbox/routing/routing-session.ts
16097
- import { SandboxFilesystemNotFoundError } from "modal";
16098
-
16099
- // src/sandbox/providers/modal-command-router-wire.ts
16100
- import { Client, Metadata, credentials, status } from "@grpc/grpc-js";
16101
- import protobuf from "protobufjs";
16102
-
16103
- // src/sandbox/providers/modal-command-start-errors.ts
16104
- import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
16105
- import { ModalRouterProviderCommand } from "@opengeni/contracts";
16106
- var boundaryBrand = Symbol.for("opengeni.modal.command-start.boundary.v1");
16107
- var invocationBrand = Symbol.for("opengeni.modal.command-start.invocation.v1");
16108
- var contextBrand = Symbol.for("opengeni.modal.command-start.context.v1");
16109
- var startSignal = new AsyncLocalStorage3();
16110
- function withModalCommandStartSignal(signal, operation) {
16111
- signal.throwIfAborted();
16112
- return startSignal.run(signal, operation);
16113
- }
16114
- function installModalCommandStartContext(modal) {
16115
- if (Object.getOwnPropertyDescriptor(modal, contextBrand)) return;
16116
- Object.defineProperty(modal, contextBrand, { value: () => startSignal.getStore() });
16117
- }
16118
- function modalCommandStartOwnData(value, key) {
16119
- const property = Object.getOwnPropertyDescriptor(value, key);
16120
- return property && "value" in property ? property.value : void 0;
16121
- }
16122
- function modalCommandStartHasOwnAccessor(value, key) {
16123
- const property = Object.getOwnPropertyDescriptor(value, key);
16124
- return !!property && !("value" in property);
16125
- }
16126
- function getModalCommandStartInvocation(error) {
16127
- const pending = [{ value: error, depth: 0 }];
16128
- const seen = /* @__PURE__ */ new WeakSet();
16129
- let result = null;
16130
- let inspected = 0;
16131
- while (pending.length) {
16132
- if (++inspected > 64) return null;
16133
- const { value, depth } = pending.shift();
16134
- if (!value || typeof value !== "object" || seen.has(value)) continue;
16135
- if (depth > 8) return null;
16136
- seen.add(value);
16137
- try {
16138
- if (["cause", "error", "errors"].some((key) => modalCommandStartHasOwnAccessor(value, key)))
16139
- return null;
16140
- if (hasModalCommandStartBoundary(value, "outcome-unknown")) {
16141
- const descriptor = modalCommandStartOwnData(value, invocationBrand);
16142
- if (!descriptor || typeof descriptor !== "object" || !Object.isFrozen(descriptor))
16143
- return null;
16144
- const sandboxId = modalCommandStartOwnData(descriptor, "sandboxId");
16145
- const taskId = modalCommandStartOwnData(descriptor, "taskId");
16146
- const execId = modalCommandStartOwnData(descriptor, "execId");
16147
- const observe = modalCommandStartOwnData(descriptor, "observe");
16148
- const ptyProperty = Object.getOwnPropertyDescriptor(descriptor, "pty");
16149
- if (ptyProperty && (!("value" in ptyProperty) || typeof ptyProperty.value !== "boolean"))
16150
- return null;
16151
- if (typeof sandboxId !== "string" || !sandboxId || typeof taskId !== "string" || !taskId || typeof execId !== "string" || !execId || typeof observe !== "function")
16152
- return null;
16153
- if (result && result !== descriptor) return null;
16154
- result = descriptor;
16155
- }
16156
- const nested = [
16157
- modalCommandStartOwnData(value, "cause"),
16158
- modalCommandStartOwnData(value, "error")
16159
- ].filter((child) => child !== void 0);
16160
- const errors = modalCommandStartOwnData(value, "errors");
16161
- if (errors !== void 0) {
16162
- if (!Array.isArray(errors)) return null;
16163
- const length = modalCommandStartOwnData(errors, "length");
16164
- if (typeof length !== "number" || !Number.isSafeInteger(length) || length < 1 || length > 32)
16165
- return null;
16166
- for (let index = 0; index < length; index++) {
16167
- const property = Object.getOwnPropertyDescriptor(errors, String(index));
16168
- if (!property || !("value" in property) || !property.value || typeof property.value !== "object")
16169
- return null;
16170
- nested.push(property.value);
16171
- }
16172
- }
16173
- if (depth === 8 && nested.length) return null;
16174
- for (const child of nested) pending.push({ value: child, depth: depth + 1 });
16175
- } catch {
16176
- return null;
16177
- }
16178
- }
16179
- return result;
16180
- }
16181
- function modalCommandStartRetainedError(error) {
16182
- if (error instanceof ProviderCommandStartOutcomeUnknownError) return error;
16183
- const invocation = getModalCommandStartInvocation(error);
16184
- if (!invocation) return error;
16185
- const cursor = () => ({ byteOffset: 0, utf8Remainder: "", eof: false, exitCode: null });
16186
- const command = ModalRouterProviderCommand.safeParse({
16187
- kind: "modal-router-v1",
16188
- sandboxId: invocation.sandboxId,
16189
- taskId: invocation.taskId,
16190
- execId: invocation.execId,
16191
- ...invocation.pty === void 0 ? {} : { pty: invocation.pty },
16192
- streams: { stdout: cursor(), stderr: cursor() }
16193
- });
16194
- return command.success ? new ProviderCommandStartOutcomeUnknownError(command.data, error) : error;
16195
- }
16196
- function hasModalCommandStartOutcomeUnknownBoundary(error) {
16197
- const pending = [{ value: error, depth: 0 }];
16198
- const seen = /* @__PURE__ */ new WeakSet();
16199
- for (let inspected = 0; pending.length && inspected < 64; inspected++) {
16200
- const { value, depth } = pending.shift();
16201
- if (!value || typeof value !== "object" || seen.has(value)) continue;
16202
- seen.add(value);
16203
- if (hasModalCommandStartBoundary(value, "outcome-unknown")) return true;
16204
- if (depth >= 8) continue;
16205
- try {
16206
- for (const key of ["cause", "error"]) {
16207
- const nested = modalCommandStartOwnData(value, key);
16208
- if (nested !== void 0) pending.push({ value: nested, depth: depth + 1 });
16209
- }
16210
- const errors = modalCommandStartOwnData(value, "errors");
16211
- if (Array.isArray(errors))
16212
- for (let index = 0; index < Math.min(errors.length, 32); index++)
16213
- pending.push({
16214
- value: modalCommandStartOwnData(errors, String(index)),
16215
- depth: depth + 1
16216
- });
16217
- } catch {
16218
- }
16219
- }
16220
- return false;
16221
- }
16222
- function modalCommandStartCleanupIsSafe(error) {
16223
- const pending = [{ value: error, depth: 0 }];
16224
- const seen = /* @__PURE__ */ new WeakSet();
16225
- let inspected = 0;
16226
- while (pending.length) {
16227
- if (++inspected > 64) return false;
16228
- const { value, depth } = pending.shift();
16229
- if (!value || typeof value !== "object" && typeof value !== "function") continue;
16230
- if (seen.has(value)) continue;
16231
- if (depth > 8) return false;
16232
- seen.add(value);
16233
- try {
16234
- if (value instanceof ProviderCommandStartOutcomeUnknownError || hasModalCommandStartBoundary(value, "outcome-unknown") || [boundaryBrand, "cause", "error", "errors"].some(
16235
- (key) => modalCommandStartHasOwnAccessor(value, key)
16236
- ))
16237
- return false;
16238
- const nested = [
16239
- modalCommandStartOwnData(value, "cause"),
16240
- modalCommandStartOwnData(value, "error")
16241
- ].filter((child) => child !== void 0 && child !== null);
16242
- const errors = modalCommandStartOwnData(value, "errors");
16243
- if (errors !== void 0) {
16244
- if (!Array.isArray(errors)) return false;
16245
- const length = modalCommandStartOwnData(errors, "length");
16246
- if (typeof length !== "number" || !Number.isSafeInteger(length) || length > 32)
16247
- return false;
16248
- for (let index = 0; index < length; index++) {
16249
- const property = Object.getOwnPropertyDescriptor(errors, String(index));
16250
- if (!property || !("value" in property) || !property.value || typeof property.value !== "object" && typeof property.value !== "function")
16251
- return false;
16252
- nested.push(property.value);
16253
- }
16254
- }
16255
- if (depth === 8 && nested.length) return false;
16256
- for (const child of nested) pending.push({ value: child, depth: depth + 1 });
16257
- } catch {
16258
- return false;
16259
- }
16260
- }
16261
- return true;
16262
- }
16263
- function installModalCommandStartRetention(session) {
16264
- for (const name of [
16265
- "execCommand",
16266
- "applyManifest",
16267
- "materializeEntry",
16268
- "hydrateWorkspace",
16269
- "persistWorkspace",
16270
- "runDirectCommand",
16271
- "runAsCommandRunner"
16272
- ]) {
16273
- const operation = Reflect.get(session, name);
16274
- if (typeof operation !== "function") continue;
16275
- Reflect.set(session, name, async function(...args) {
16276
- try {
16277
- return await operation.apply(session, args);
16278
- } catch (error) {
16279
- throw modalCommandStartRetainedError(error);
16280
- }
16281
- });
16282
- }
16283
- }
16284
- function hasModalCommandStartBoundary(error, kind) {
16285
- if (!error || typeof error !== "object") return false;
16286
- try {
16287
- const property = Object.getOwnPropertyDescriptor(error, boundaryBrand);
16288
- return property?.value === kind && property.writable === false && property.configurable === false;
16289
- } catch {
16290
- return false;
16291
- }
16873
+ `og_confined() { case "$1" in "$root"|"\${root%/}/"*) return 0 ;; *) return 1 ;; esac; }`,
16874
+ // A directory on the path is never a symbolic link and always resolves
16875
+ // beneath the workspace root. A missing one returns 1 for the caller.
16876
+ [
16877
+ "og_dir() {",
16878
+ `[ ! -L "$2" ] || og_fail "__OPENGENI_FS_SYMLINK__D$1__" 68`,
16879
+ `[ -e "$2" ] || return 1`,
16880
+ `[ -d "$2" ] || og_fail "__OPENGENI_FS_NOT_DIR__D$1__" 69`,
16881
+ `og_t=$(opengeni_realpath_existing "$2") || og_fail "__OPENGENI_FS_NOT_FOUND__D$1__" 66`,
16882
+ `og_confined "$og_t" || og_fail "__OPENGENI_FS_ESCAPE__D$1__" 67`,
16883
+ "}"
16884
+ ].join("\n"),
16885
+ // 0: the exact bytes already exist. 1: missing. Anything else fails.
16886
+ [
16887
+ "og_file() {",
16888
+ `if [ -L "$2" ]; then og_fail "__OPENGENI_FS_CONFLICT__F$1__" 65; fi`,
16889
+ `[ -e "$2" ] || return 1`,
16890
+ `[ -f "$2" ] || og_fail "__OPENGENI_FS_CONFLICT__F$1__" 65`,
16891
+ `og_n=$(wc -c < "$2") || og_fail "__OPENGENI_FS_CONFLICT__F$1__" 65`,
16892
+ `[ "$((og_n))" = "$3" ] || og_fail "__OPENGENI_FS_CONFLICT__F$1__" 65`,
16893
+ `og_h=$(opengeni_sha256_file "$2") || og_fail "__OPENGENI_FS_UNVERIFIED__F$1__" 65`,
16894
+ `[ "$og_h" = "$4" ] || og_fail "__OPENGENI_FS_CONFLICT__F$1__" 65`,
16895
+ "}"
16896
+ ].join("\n"),
16897
+ [
16898
+ "og_mk() {",
16899
+ `mkdir -- "$2" 2>/dev/null || og_fail "__OPENGENI_FS_WRITE_FAILED__D$1__" 70`,
16900
+ `printf '__OGF_D__%s__' "$1"`,
16901
+ `og_dir "$1" "$2" || og_fail "__OPENGENI_FS_NOT_FOUND__D$1__" 66`,
16902
+ "}"
16903
+ ].join("\n"),
16904
+ // noclobber opens a missing path with O_EXCL, so a file that appeared
16905
+ // since the check (including a dangling symlink) is never replaced. A
16906
+ // failed open exits 1 and leaves the path alone. Once the open succeeded
16907
+ // the file is this call's own, so a failed or short write (a full disk,
16908
+ // for example) removes it; otherwise a repeat would find a truncated file
16909
+ // and report a conflict instead of finishing the write.
16910
+ [
16911
+ "og_put() {",
16912
+ `( set -C; { printf '%s' "$4" | base64 -d || exit 72; } > "$2" ) 2>/dev/null`,
16913
+ "og_s=$?",
16914
+ `[ "$og_s" != 72 ] || { rm -f -- "$2"; og_fail "__OPENGENI_FS_WRITE_FAILED__F$1__" 71; }`,
16915
+ `[ "$og_s" = 0 ] || og_fail "__OPENGENI_FS_WRITE_FAILED__F$1__" 71`,
16916
+ `og_n=$(wc -c < "$2") && [ "$((og_n))" = "$3" ] || { rm -f -- "$2"; og_fail "__OPENGENI_FS_WRITE_FAILED__F$1__" 71; }`,
16917
+ `printf '__OGF_W__%s__' "$1"`,
16918
+ "}"
16919
+ ].join("\n")
16920
+ ];
16292
16921
  }
16293
- var ModalCommandStartOutcomeUnknownError = class extends Error {
16294
- constructor(taskId, execId, cause) {
16295
- super("Modal command Start outcome unknown; do not replay this invocation", { cause });
16296
- this.taskId = taskId;
16297
- this.execId = execId;
16298
- this.name = "CommandStartOutcomeUnknownError";
16299
- Object.defineProperty(this, boundaryBrand, { value: "outcome-unknown" });
16300
- }
16301
- };
16302
-
16303
- // src/sandbox/providers/modal-command-router-wire.ts
16304
- var modalRouterWire = protobuf.parse(`syntax = "proto3";
16305
- message Identity { string task_id = 1; string exec_id = 2; }
16306
- message Pty {
16307
- bool enabled = 1; uint32 winsz_rows = 2; uint32 winsz_cols = 3;
16308
- string env_term = 4; string env_colorterm = 5; string env_term_program = 6;
16309
- int32 pty_type = 7; bool no_terminate_on_idle_stdin = 8;
16922
+ function directoryCheckFragment(directory) {
16923
+ return `og_dir ${directory.index} ${shellQuote3(directory.providerPath)} || :`;
16310
16924
  }
16311
- message Start {
16312
- string task_id = 1; string exec_id = 2; repeated string command_args = 3;
16313
- int32 stdout_config = 4; int32 stderr_config = 5;
16314
- optional uint32 timeout_secs = 6; optional string workdir = 7;
16315
- repeated string secret_ids = 8; optional Pty pty_info = 9;
16316
- bool runtime_debug = 10; string container_id = 11; map<string,string> env = 12;
16925
+ function fileCheckFragment(file, mode) {
16926
+ const check = `og_file ${file.index} ${shellQuote3(file.providerPath)} ${file.sizeBytes} ${file.sha256}`;
16927
+ const missing = mode === "check" ? `printf '__OGF_M__%s__' ${file.index}` : `og_m${file.index}=1`;
16928
+ return `if ${check}; then printf '__OGF_S__%s__' ${file.index}; else ${missing}; fi`;
16317
16929
  }
16318
- message Read {
16319
- string task_id = 1; string exec_id = 2; uint64 offset = 3; int32 file_descriptor = 4;
16930
+ function directoryCreateFragment(directory) {
16931
+ const path = shellQuote3(directory.providerPath);
16932
+ return `og_dir ${directory.index} ${path} || og_mk ${directory.index} ${path}`;
16320
16933
  }
16321
- message Data { bytes data = 1; }
16322
- message Poll { optional int32 code = 1; optional int32 signal = 2; }
16323
- message Write {
16324
- string task_id = 1; string exec_id = 2; uint64 offset = 3; bytes data = 4; bool eof = 5;
16934
+ function filePutFragment(file) {
16935
+ if (file.base64 === void 0) throw new Error("write mode requires file content");
16936
+ return `[ -z "\${og_m${file.index}:-}" ] || og_put ${file.index} ${shellQuote3(file.providerPath)} ${file.sizeBytes} ${shellQuote3(file.base64)}`;
16325
16937
  }
16326
- message Empty {}
16327
- `).root;
16328
- var prefix = "/modal.task_command_router.TaskCommandRouter/";
16329
- var MODAL_ROUTER_READ_PAGE_BYTES = 1024 * 1024;
16330
- var maxWireBytes = 4 * 1024 * 1024;
16331
- var ModalCommandStartRejectedError = class extends ProviderCommandStartRejectedError {
16332
- constructor(code, cause) {
16333
- super(cause);
16334
- this.code = code;
16335
- this.name = "ModalCommandStartRejectedError";
16336
- }
16337
- };
16338
- var ModalCommandStartPreDispatchUnavailableError = class _ModalCommandStartPreDispatchUnavailableError extends Error {
16339
- constructor(cause) {
16340
- super("Modal command router was not ready before Start dispatch", { cause });
16341
- this.name = "ModalCommandStartPreDispatchUnavailableError";
16342
- }
16343
- /** The supplied operation must contain only read-only preparation, never
16344
- * Start itself. Its transport failure therefore proves non-dispatch. */
16345
- static async beforeDispatch(operation, signal) {
16346
- signal?.throwIfAborted();
16347
- try {
16348
- return await operation();
16349
- } catch (error) {
16350
- signal?.throwIfAborted();
16351
- const code = error?.code;
16352
- if (error instanceof Error && (code === status.UNAVAILABLE || code === status.DEADLINE_EXCEEDED))
16353
- throw new _ModalCommandStartPreDispatchUnavailableError(error);
16354
- throw error;
16355
- }
16356
- }
16357
- static async ensureReady(client, signal) {
16358
- signal?.throwIfAborted();
16359
- await new Promise((resolve7, reject) => {
16360
- let settled = false;
16361
- const finish = (error) => {
16362
- if (settled) return;
16363
- settled = true;
16364
- signal?.removeEventListener("abort", abort);
16365
- if (signal?.aborted) reject(signal.reason);
16366
- else if (error) reject(new _ModalCommandStartPreDispatchUnavailableError(error));
16367
- else resolve7();
16368
- };
16369
- const abort = () => finish();
16370
- signal?.addEventListener("abort", abort, { once: true });
16371
- client.waitForReady(Date.now() + 5e3, finish);
16372
- if (signal?.aborted) abort();
16373
- });
16374
- }
16375
- };
16376
- var ModalCommandStartNotDispatchedError = class extends Error {
16377
- constructor(cause) {
16378
- super(cause instanceof Error ? cause.message : "Modal command Start was never dispatched", {
16379
- cause
16380
- });
16381
- this.name = "ModalCommandStartNotDispatchedError";
16938
+ function writeFilesScript(input) {
16939
+ const lines = [...input.prelude];
16940
+ for (const directory of input.directories) lines.push(directoryCheckFragment(directory));
16941
+ for (const file of input.files) lines.push(fileCheckFragment(file, input.mode));
16942
+ if (input.mode === "write") {
16943
+ for (const directory of input.directories) lines.push(directoryCreateFragment(directory));
16944
+ for (const file of input.files) lines.push(filePutFragment(file));
16382
16945
  }
16383
- };
16384
- function encode(type, value) {
16385
- const codec = modalRouterWire.lookupType(type);
16386
- return Buffer.from(codec.encode(codec.fromObject(value)).finish());
16946
+ lines.push(`printf '%s' ${BATCH_OK}`);
16947
+ return lines.join("\n");
16387
16948
  }
16388
- var ModalCommandRouterWire = class {
16389
- client;
16390
- metadata;
16391
- closed = false;
16392
- constructor(access, trustedRoots) {
16393
- const url = new URL(access.url);
16394
- if (url.protocol !== "https:" || url.username || url.password || !access.jwt)
16395
- throw new Error("Modal command router requires authenticated TLS");
16396
- this.client = new Client(
16397
- `${url.hostname}:${url.port || "443"}`,
16398
- credentials.createSsl(trustedRoots),
16399
- {
16400
- "grpc.max_receive_message_length": maxWireBytes,
16401
- "grpc.max_send_message_length": maxWireBytes,
16402
- "grpc.enable_retries": 0,
16403
- // The HTTP/2 default 64 KiB window caps one read at 64 KiB per round
16404
- // trip. Two pages lets stdout and stderr each fill a page in one trip
16405
- // while bounding bytes discarded when a full read cancels its stream.
16406
- "grpc-node.flow_control_window": 2 * MODAL_ROUTER_READ_PAGE_BYTES
16407
- }
16408
- );
16409
- this.metadata = new Metadata();
16410
- this.metadata.set("authorization", `Bearer ${access.jwt}`);
16949
+ function parseWriteFilesOutput(stdout) {
16950
+ const output = {
16951
+ complete: stdout.includes(BATCH_OK),
16952
+ same: [],
16953
+ missing: [],
16954
+ written: [],
16955
+ createdDirectories: [],
16956
+ failure: null
16957
+ };
16958
+ for (const match of stdout.matchAll(/__OGF_([SMWD])__(\d+)__/g)) {
16959
+ const index = Number(match[2]);
16960
+ if (match[1] === "S") output.same.push(index);
16961
+ else if (match[1] === "M") output.missing.push(index);
16962
+ else if (match[1] === "W") output.written.push(index);
16963
+ else output.createdDirectories.push(index);
16411
16964
  }
16412
- close() {
16413
- this.closed = true;
16414
- this.client.close();
16965
+ const failure = /__OPENGENI_FS_(CONFLICT|UNVERIFIED|SYMLINK|NOT_DIR|NOT_FOUND|ESCAPE|WRITE_FAILED)__(?:([DF])(\d+)__)?/.exec(
16966
+ stdout
16967
+ );
16968
+ if (failure) {
16969
+ output.failure = {
16970
+ code: failure[1],
16971
+ target: failure[2] ? { kind: failure[2] === "D" ? "directory" : "file", index: Number(failure[3]) } : null
16972
+ };
16415
16973
  }
16416
- async unary(method, requestType, responseType, request, signal) {
16417
- signal?.throwIfAborted();
16418
- if (this.closed) throw new Error("Modal command router is closed");
16419
- return await new Promise((resolve7, reject) => {
16420
- const call = this.client.makeUnaryRequest(
16421
- prefix + method,
16422
- (value) => encode(requestType, value),
16423
- (bytes) => modalRouterWire.lookupType(responseType).decode(bytes),
16424
- request,
16425
- this.metadata,
16426
- { deadline: Date.now() + 3e4 },
16427
- (error, result) => {
16428
- signal?.removeEventListener("abort", abort);
16429
- if (signal?.aborted) reject(signal.reason);
16430
- else if (error) reject(error);
16431
- else if (result) resolve7(result);
16432
- else reject(new Error("Modal command router returned no response"));
16433
- }
16434
- );
16435
- const abort = () => call.cancel();
16436
- signal?.addEventListener("abort", abort, { once: true });
16437
- if (signal?.aborted) abort();
16438
- });
16974
+ return output;
16975
+ }
16976
+
16977
+ // src/sandbox/exec-banner.ts
16978
+ var typedHandleLossSessions = /* @__PURE__ */ new WeakSet();
16979
+ function markTypedExecHandleLoss(session) {
16980
+ typedHandleLossSessions.add(session);
16981
+ }
16982
+ function hasTypedExecHandleLoss(session, providerSessionId) {
16983
+ if (!session) return false;
16984
+ if (typedHandleLossSessions.has(session)) return true;
16985
+ const routed = session;
16986
+ return providerSessionId !== void 0 && routed.retainedProcessHasTypedHandleLoss?.(providerSessionId) === true;
16987
+ }
16988
+ var EXEC_BANNER_HEADER_MAX_CHARS = 16 * 1024;
16989
+ var OUTPUT_DELIMITER = /\r?\nOutput:\r?\n/u;
16990
+ var SDK_METADATA_LINE = /^(?:Chunk ID:|Wall time:|Original token count:|Output:|Process (?:running with session ID|exited with code))/mu;
16991
+ var RUNNING_LINE = /^Process running with session ID (\d+)$/u;
16992
+ var EXITED_LINE = /^Process exited with code (-?\d+)$/u;
16993
+ var PROCESS_STATUS_PREFIX = /^Process (?:running with session ID|exited with code)/u;
16994
+ function parseExecResponseBanner(raw) {
16995
+ const delimiter = OUTPUT_DELIMITER.exec(raw);
16996
+ if (!delimiter) {
16997
+ return SDK_METADATA_LINE.test(raw) ? { kind: "invalid" } : { kind: "absent" };
16439
16998
  }
16440
- async start(request, signal) {
16441
- try {
16442
- if (this.closed) throw new Error("Modal command router is closed");
16443
- await ModalCommandStartPreDispatchUnavailableError.ensureReady(this.client, signal);
16444
- signal?.throwIfAborted();
16445
- if (this.closed) throw new Error("Modal command router is closed");
16446
- } catch (error) {
16447
- if (this.closed)
16448
- throw new ModalCommandStartNotDispatchedError(
16449
- new Error("Modal command router is closed", { cause: error })
16450
- );
16451
- if (error instanceof ModalCommandStartPreDispatchUnavailableError) throw error;
16452
- throw new ModalCommandStartNotDispatchedError(error);
16999
+ if (delimiter.index > EXEC_BANNER_HEADER_MAX_CHARS) return { kind: "invalid" };
17000
+ const header = raw.slice(0, delimiter.index);
17001
+ const status4 = [];
17002
+ for (const line of header.split(/\r?\n/u)) {
17003
+ const running = RUNNING_LINE.exec(line);
17004
+ if (running) {
17005
+ status4.push({ kind: "running", value: running[1] });
17006
+ continue;
16453
17007
  }
16454
- try {
16455
- await this.unary(
16456
- "TaskExecStart",
16457
- "Start",
16458
- "Empty",
16459
- {
16460
- ...request,
16461
- stdoutConfig: 1,
16462
- stderrConfig: 1
16463
- },
16464
- signal
16465
- );
16466
- } catch (error) {
16467
- const code = error?.code;
16468
- if (typeof code === "number" && [
16469
- status.INVALID_ARGUMENT,
16470
- status.NOT_FOUND,
16471
- status.PERMISSION_DENIED,
16472
- status.UNAUTHENTICATED,
16473
- status.UNIMPLEMENTED
16474
- ].includes(code))
16475
- throw new ModalCommandStartRejectedError(code, error);
16476
- throw new ModalCommandStartOutcomeUnknownError(request.taskId, request.execId, error);
17008
+ const exited = EXITED_LINE.exec(line);
17009
+ if (exited) {
17010
+ status4.push({ kind: "exited", value: exited[1] });
17011
+ continue;
16477
17012
  }
17013
+ if (PROCESS_STATUS_PREFIX.test(line)) return { kind: "invalid" };
16478
17014
  }
16479
- async write(identity, offset, data, signal) {
16480
- if (!Number.isSafeInteger(offset) || offset < 0)
16481
- throw new Error("Invalid Modal stdin byte offset");
16482
- await this.unary(
16483
- "TaskExecStdinWrite",
16484
- "Write",
16485
- "Empty",
16486
- { ...identity, offset, data, eof: false },
16487
- signal
16488
- );
17015
+ if (status4.length !== 1) return { kind: "invalid" };
17016
+ const terminal = status4[0];
17017
+ const value = Number(terminal.value);
17018
+ if (!Number.isSafeInteger(value)) return { kind: "invalid" };
17019
+ if (terminal.kind === "running") {
17020
+ return value >= 0 ? { kind: "running", sessionId: value } : { kind: "invalid" };
16489
17021
  }
16490
- async poll(identity, signal) {
16491
- const value = await this.unary("TaskExecPoll", "Identity", "Poll", identity, signal);
16492
- const decoded = modalRouterWire.lookupType("Poll").toObject(value);
16493
- if (decoded.code !== void 0) return decoded.code;
16494
- if (decoded.signal !== void 0) return 128 + decoded.signal;
17022
+ return { kind: "exited", exitCode: value };
17023
+ }
17024
+ function parseExecBannerSessionId(raw) {
17025
+ const banner = parseExecResponseBanner(raw);
17026
+ return banner.kind === "running" ? banner.sessionId : null;
17027
+ }
17028
+ function parseExecBannerExitCode(raw) {
17029
+ const banner = parseExecResponseBanner(raw);
17030
+ return banner.kind === "exited" ? banner.exitCode : null;
17031
+ }
17032
+ function isExecSessionLostBanner(out, execSessionId, source) {
17033
+ if (source && typedHandleLossSessions.has(source)) return false;
17034
+ if (!out || !Number.isSafeInteger(execSessionId) || execSessionId < 0) return false;
17035
+ const delimiter = OUTPUT_DELIMITER.exec(out);
17036
+ if (delimiter && delimiter.index > EXEC_BANNER_HEADER_MAX_CHARS) return false;
17037
+ if (delimiter && parseExecResponseBanner(out).kind !== "exited") return false;
17038
+ const candidate = delimiter ? out.slice(delimiter.index + delimiter[0].length) : out;
17039
+ const match = candidate.match(/^(?:write_stdin failed: )?session not found: (\d+)$/);
17040
+ if (!match || match[0] !== candidate) return false;
17041
+ return match[1] === String(execSessionId);
17042
+ }
17043
+
17044
+ // src/sandbox/op-correlation.ts
17045
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
17046
+ var storage = new AsyncLocalStorage3();
17047
+ function sanitizeOpIdToken(raw) {
17048
+ return raw.replace(/[^A-Za-z0-9_-]/g, (c) => `_${c.charCodeAt(0).toString(16)}_`);
17049
+ }
17050
+ function runWithToolCallCorrelation(callId, fn, options = {}) {
17051
+ return storage.run(
17052
+ {
17053
+ callId: sanitizeOpIdToken(callId),
17054
+ ordinal: 0,
17055
+ ...options.onDurableOpOwnershipTransferStarted ? { onDurableOpOwnershipTransferStarted: options.onDurableOpOwnershipTransferStarted } : {},
17056
+ ...options.onDurableOpOwnershipTransferred ? { onDurableOpOwnershipTransferred: options.onDurableOpOwnershipTransferred } : {}
17057
+ },
17058
+ fn
17059
+ );
17060
+ }
17061
+ function nextDurableOpId() {
17062
+ const context = storage.getStore();
17063
+ if (!context) {
16495
17064
  return null;
16496
17065
  }
16497
- async read(identity, stream, offset, waitMs, signal) {
16498
- signal?.throwIfAborted();
16499
- if (this.closed) throw new Error("Modal command router is closed");
16500
- if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isFinite(waitMs) || waitMs < 0 || waitMs > 5e4)
16501
- throw new Error("Invalid Modal output read bounds");
16502
- const chunks = [];
16503
- let length = 0;
16504
- let limited = false;
16505
- return await new Promise((resolve7, reject) => {
16506
- const call = this.client.makeServerStreamRequest(
16507
- prefix + "TaskExecStdioRead",
16508
- (value) => encode("Read", value),
16509
- (bytes) => modalRouterWire.lookupType("Data").decode(bytes),
16510
- { ...identity, offset, fileDescriptor: stream === "stdout" ? 0 : 1 },
16511
- this.metadata,
16512
- { deadline: Date.now() + Math.max(1, waitMs) }
16513
- );
16514
- const abort = () => call.cancel();
16515
- const finish = (eof, error) => {
16516
- signal?.removeEventListener("abort", abort);
16517
- if (signal?.aborted) reject(signal.reason);
16518
- else if (error) reject(error);
16519
- else resolve7({ bytes: Buffer.concat(chunks, length), eof });
16520
- };
16521
- call.on("data", (value) => {
16522
- if (limited) return;
16523
- const part = Buffer.from(value.data).subarray(0, MODAL_ROUTER_READ_PAGE_BYTES - length);
16524
- if (part.length) {
16525
- chunks.push(part);
16526
- length += part.length;
16527
- }
16528
- if (length === MODAL_ROUTER_READ_PAGE_BYTES) {
16529
- limited = true;
16530
- call.cancel();
16531
- }
16532
- });
16533
- call.once("error", (error) => {
16534
- if (limited && error.code === status.CANCELLED || error.code === status.DEADLINE_EXCEEDED)
16535
- finish(false);
16536
- else finish(false, error);
16537
- });
16538
- call.once("end", () => finish(!limited));
16539
- signal?.addEventListener("abort", abort, { once: true });
16540
- if (signal?.aborted) abort();
16541
- });
16542
- }
16543
- };
17066
+ const ordinal = context.ordinal;
17067
+ context.ordinal += 1;
17068
+ return `${context.callId}:${ordinal}`;
17069
+ }
17070
+ function notifyDurableOpOwnershipTransferStarted(opId) {
17071
+ storage.getStore()?.onDurableOpOwnershipTransferStarted?.(opId);
17072
+ }
17073
+ function notifyDurableOpOwnershipTransferred(opId) {
17074
+ storage.getStore()?.onDurableOpOwnershipTransferred?.(opId);
17075
+ }
16544
17076
 
16545
17077
  // src/sandbox/routing/routing-session.ts
16546
- import { isDeepStrictEqual } from "util";
17078
+ import { SandboxFilesystemNotFoundError } from "modal";
17079
+ import { isDeepStrictEqual as isDeepStrictEqual2 } from "util";
16547
17080
 
16548
17081
  // src/sandbox/materialization-verification-error.ts
16549
17082
  var EXPLANATIONS = {
@@ -17615,6 +18148,11 @@ var RoutingSandboxSession = class {
17615
18148
  () => write.call(record.backend.session, args)
17616
18149
  );
17617
18150
  } catch (error) {
18151
+ let inputUnknown = false;
18152
+ try {
18153
+ inputUnknown = error instanceof ProviderCommandInputOutcomeUnknownError;
18154
+ } catch {
18155
+ }
17618
18156
  if (this.deps.afterProcessMutation) {
17619
18157
  const pending = {
17620
18158
  op,
@@ -17629,11 +18167,21 @@ var RoutingSandboxSession = class {
17629
18167
  record.pendingMutationSettlement = pending;
17630
18168
  throw new RoutingMutationOutcomeUnknownError(
17631
18169
  op,
17632
- `Retained-process stdin rejected at the provider but lost durable settlement; it was not replayed`,
17633
- { cause: settlementError }
18170
+ inputUnknown ? "Retained-process stdin acknowledgement and durable settlement unavailable; input may have been accepted. Do not resend stdin." : "Retained-process stdin rejected at the provider but lost durable settlement; it was not replayed",
18171
+ inputUnknown ? {
18172
+ cause: new AggregateError([error, settlementError]),
18173
+ retainedProcess: record.process
18174
+ } : { cause: settlementError }
17634
18175
  );
17635
18176
  }
17636
18177
  }
18178
+ if (inputUnknown) {
18179
+ throw new RoutingMutationOutcomeUnknownError(
18180
+ op,
18181
+ "Provider stdin acknowledgement unavailable; input may have been accepted and was not resent. Do not resend stdin.",
18182
+ { cause: error, retainedProcess: record.process }
18183
+ );
18184
+ }
17637
18185
  throw error;
17638
18186
  }
17639
18187
  if (this.deps.afterProcessMutation) {
@@ -17993,7 +18541,7 @@ var RoutingSandboxSession = class {
17993
18541
  { retainedProcess: process2 }
17994
18542
  );
17995
18543
  const persisted = await this.deps.providerCommandPersistence(process2).load();
17996
- if (!persisted || !isDeepStrictEqual(persisted, command))
18544
+ if (!persisted || !isDeepStrictEqual2(persisted, command))
17997
18545
  throw new Error(
17998
18546
  "Supervised launch reservation did not retain the exact invocation"
17999
18547
  );
@@ -18362,7 +18910,13 @@ var RoutingSandboxSession = class {
18362
18910
  async writeStdin(args) {
18363
18911
  const providerSessionId = providerSessionIdFromArgs(args);
18364
18912
  if (providerSessionId !== null && this.retainedProcesses.has(providerSessionId)) {
18365
- return await this.dispatchProcessMutation(args);
18913
+ try {
18914
+ return await this.dispatchProcessMutation(args);
18915
+ } catch (error) {
18916
+ if (isRoutingMutationOutcomeUnknownError(error))
18917
+ return renderRoutingMutationOutcomeUnknownToolResult(error);
18918
+ throw error;
18919
+ }
18366
18920
  }
18367
18921
  return this.dispatch("writeStdin", true, async (s) => {
18368
18922
  if (!s.writeStdin) {
@@ -18383,6 +18937,18 @@ var RoutingSandboxSession = class {
18383
18937
  hasRetainedProcess(providerSessionId) {
18384
18938
  return positiveProviderSessionId(providerSessionId) !== null && this.retainedProcesses.has(providerSessionId);
18385
18939
  }
18940
+ /** A reaper may have settled the command while a local capture/control receipt
18941
+ * remained pending. Cleanup may consume that same durable proof without
18942
+ * replaying a provider operation or accepting pending output into the model. */
18943
+ async reconcileRetainedProcess(providerSessionId) {
18944
+ const record = this.retainedProcesses.get(providerSessionId);
18945
+ if (!record || !this.deps.isProcessSettled) return false;
18946
+ if (!await this.deps.isProcessSettled({ backend: record.backend, process: record.process }))
18947
+ return false;
18948
+ if (this.retainedProcesses.get(providerSessionId) !== record) return false;
18949
+ this.retainedProcesses.delete(providerSessionId);
18950
+ return true;
18951
+ }
18386
18952
  /** Local, Docker, and OpenSandbox process ids address an in-memory table on one worker
18387
18953
  * session object. They are not valid durable locators for the independently
18388
18954
  * scheduled reaper, so their yielded handles stay turn-owned until terminal
@@ -18583,40 +19149,15 @@ var RoutingSandboxSession = class {
18583
19149
  async writePlacementPrivate(args) {
18584
19150
  const input = placementPrivateWrite(args);
18585
19151
  return this.dispatch("writePlacementPrivate", false, async (session, backend) => {
18586
- if (session.writePlacementPrivate) return await session.writePlacementPrivate(input);
18587
- if (session.writeFile) return await session.writeFile(input);
18588
- return await streamPlacementPrivateFile(session, input, backend.kind);
19152
+ return await writePlacementPrivateOnBackend(session, input, backend.kind);
18589
19153
  });
18590
19154
  }
18591
19155
  /** Delete only an OpenGeni placement-private staging file. This narrow
18592
19156
  * control operation cannot be repurposed into a generic mutation bypass. */
18593
19157
  async deletePlacementPrivate(path, runAs) {
18594
19158
  const privatePath = placementPrivatePath(path);
18595
- await this.dispatch("deletePlacementPrivate", false, async (session) => {
18596
- if (session.deletePlacementPrivate) {
18597
- await session.deletePlacementPrivate(privatePath, runAs);
18598
- return;
18599
- }
18600
- const args = {
18601
- cmd: `rm -f ${shellSingleQuote(privatePath)}`,
18602
- ...runAs ? { runAs } : {}
18603
- };
18604
- if (session.exec) {
18605
- const result = await session.exec(args);
18606
- if (result && typeof result === "object" && typeof result.exitCode === "number" && result.exitCode !== 0) {
18607
- throw new Error("placement-private cleanup failed");
18608
- }
18609
- return;
18610
- }
18611
- if (session.execCommand) {
18612
- const result = await session.execCommand(args);
18613
- const exitCode = parseExecBannerExitCode(result);
18614
- if (exitCode !== null && exitCode !== 0) {
18615
- throw new Error("placement-private cleanup failed");
18616
- }
18617
- return;
18618
- }
18619
- throw new RoutingUnsupportedError("deletePlacementPrivate", this.cached?.kind ?? "unknown");
19159
+ await this.dispatch("deletePlacementPrivate", false, async (session, backend) => {
19160
+ await deletePlacementPrivateOnBackend(session, privatePath, runAs, backend.kind);
18620
19161
  });
18621
19162
  }
18622
19163
  /** Keep private download authority and its consuming import on one exact
@@ -18625,7 +19166,7 @@ var RoutingSandboxSession = class {
18625
19166
  async importWorkspaceFileOnResolvedBackend(input) {
18626
19167
  return await this.dispatch("importWorkspaceFile", true, async (session, backend) => {
18627
19168
  const channel = new SandboxChannelAService({
18628
- session,
19169
+ session: withPlacementPrivateControl(session, backend.kind),
18629
19170
  workspaceRoot: input.workspaceRoot,
18630
19171
  ...backend.kind === "selfhosted" ? { providerPathMode: "workspace-relative" } : {},
18631
19172
  revision: input.revision,
@@ -18641,7 +19182,7 @@ var RoutingSandboxSession = class {
18641
19182
  async importWorkspaceFilesOnResolvedBackend(input) {
18642
19183
  return await this.dispatch("importWorkspaceFiles", true, async (session, backend) => {
18643
19184
  const channel = new SandboxChannelAService({
18644
- session,
19185
+ session: withPlacementPrivateControl(session, backend.kind),
18645
19186
  workspaceRoot: input.workspaceRoot,
18646
19187
  ...backend.kind === "selfhosted" ? { providerPathMode: "workspace-relative" } : {},
18647
19188
  revision: input.revision,
@@ -18875,8 +19416,59 @@ function placementPrivateWrite(value) {
18875
19416
  ...typeof input.runAs === "string" ? { runAs: input.runAs } : {}
18876
19417
  };
18877
19418
  }
19419
+ function withPlacementPrivateControl(session, backendKind) {
19420
+ return new Proxy(session, {
19421
+ get(target, property) {
19422
+ if (property === "writePlacementPrivate") {
19423
+ return async (args) => await writePlacementPrivateOnBackend(target, placementPrivateWrite(args), backendKind);
19424
+ }
19425
+ if (property === "deletePlacementPrivate") {
19426
+ return async (path, runAs) => await deletePlacementPrivateOnBackend(
19427
+ target,
19428
+ placementPrivatePath(path),
19429
+ runAs,
19430
+ backendKind
19431
+ );
19432
+ }
19433
+ const value = Reflect.get(target, property, target);
19434
+ return typeof value === "function" ? value.bind(target) : value;
19435
+ }
19436
+ });
19437
+ }
19438
+ async function writePlacementPrivateOnBackend(session, input, backendKind) {
19439
+ if (session.writePlacementPrivate) return await session.writePlacementPrivate(input);
19440
+ if (session.writeFile) return await session.writeFile(input);
19441
+ return await streamPlacementPrivateFile(session, input, backendKind);
19442
+ }
19443
+ async function deletePlacementPrivateOnBackend(session, privatePath, runAs, backendKind) {
19444
+ if (session.deletePlacementPrivate) {
19445
+ await session.deletePlacementPrivate(privatePath, runAs);
19446
+ return;
19447
+ }
19448
+ const args = {
19449
+ cmd: `rm -f ${shellSingleQuote(privatePath)}`,
19450
+ ...runAs ? { runAs } : {}
19451
+ };
19452
+ if (session.exec) {
19453
+ const result = await session.exec(args);
19454
+ if (result && typeof result === "object" && typeof result.exitCode === "number" && result.exitCode !== 0) {
19455
+ throw new Error("placement-private cleanup failed");
19456
+ }
19457
+ return;
19458
+ }
19459
+ if (session.execCommand) {
19460
+ const result = await session.execCommand(args);
19461
+ const exitCode = parseExecBannerExitCode(result);
19462
+ if (exitCode !== null && exitCode !== 0) {
19463
+ throw new Error("placement-private cleanup failed");
19464
+ }
19465
+ return;
19466
+ }
19467
+ throw new RoutingUnsupportedError("deletePlacementPrivate", backendKind);
19468
+ }
18878
19469
  async function streamPlacementPrivateFile(session, input, backendKind) {
18879
- if (!session.exec || !session.writeStdin) {
19470
+ const exec = session.exec?.bind(session) ?? session.execCommand?.bind(session);
19471
+ if (!exec || !session.writeStdin) {
18880
19472
  throw new RoutingUnsupportedError("writePlacementPrivate", backendKind);
18881
19473
  }
18882
19474
  const bytes = typeof input.content === "string" ? Buffer.from(input.content) : input.content;
@@ -18887,7 +19479,7 @@ async function streamPlacementPrivateFile(session, input, backendKind) {
18887
19479
  ...input.createParents ? [`install -d -m 0700 -- ${shellSingleQuote(parent)}`] : []
18888
19480
  ];
18889
19481
  if (bytes.byteLength === 0) {
18890
- const result = await session.exec({
19482
+ const result = await exec({
18891
19483
  cmd: [
18892
19484
  ...prelude,
18893
19485
  `: > ${shellSingleQuote(input.path)}`,
@@ -18914,7 +19506,7 @@ async function streamPlacementPrivateFile(session, input, backendKind) {
18914
19506
  `chmod 0600 -- ${shellSingleQuote(input.path)}`,
18915
19507
  `printf %s ${shellSingleQuote(marker)}`
18916
19508
  ].join("; ");
18917
- const started = await session.exec({
19509
+ const started = await exec({
18918
19510
  cmd: command,
18919
19511
  ...input.runAs ? { runAs: input.runAs } : {},
18920
19512
  yieldTimeMs: 250,
@@ -19179,8 +19771,14 @@ function cancellableShellCommand(command, markerPath) {
19179
19771
  'case "$__opengeni_outer_pid:$__opengeni_outer_pgid" in *[!0-9:]*|*:|:*) exit 125 ;; esac',
19180
19772
  'if [ "$__opengeni_outer_pid" != "$__opengeni_outer_pgid" ]; then',
19181
19773
  ' __opengeni_setsid="$(command -v setsid 2>/dev/null)"',
19182
- ' [ -n "$__opengeni_setsid" ] || exit 125',
19183
- ` exec "$__opengeni_setsid" /bin/sh -c ${singleQuote(groupLeaderCommand)}`,
19774
+ ' if [ -n "$__opengeni_setsid" ]; then',
19775
+ ` exec "$__opengeni_setsid" /bin/sh -c ${singleQuote(groupLeaderCommand)}`,
19776
+ " fi",
19777
+ // macOS has setsid(2), but no setsid executable. The parent is proven
19778
+ // not to be a group leader, so the same process can safely start a session.
19779
+ ' __opengeni_python="$(command -v python3 2>/dev/null)"',
19780
+ ' [ -n "$__opengeni_python" ] || exit 125',
19781
+ ` exec "$__opengeni_python" -c ${singleQuote('import os,sys; os.setsid(); os.execv("/bin/sh", ["/bin/sh", "-c", sys.argv[1]])')} ${singleQuote(groupLeaderCommand)}`,
19184
19782
  "fi",
19185
19783
  groupLeaderCommand
19186
19784
  ].join("\n");
@@ -19282,6 +19880,12 @@ function retainedProcessSession(session, providerSessionId) {
19282
19880
  return session?.hasRetainedProcess?.(providerSessionId) === true ? session : null;
19283
19881
  }
19284
19882
  function renderDirectToolFault(error, retainedProcessSessionId) {
19883
+ if (error instanceof ProviderCommandInputOutcomeUnknownError) {
19884
+ return `Command input acknowledgement unavailable${retainedProcessSessionId === void 0 ? "" : ` for session ID ${retainedProcessSessionId}`}. The input may have been accepted; its outcome is unknown and it was not resent. Do not resend stdin. Inspect the existing command with write_stdin using empty chars.`;
19885
+ }
19886
+ if (isProviderCommandObservationUnavailableError(error)) {
19887
+ return `Command observation unavailable${retainedProcessSessionId === void 0 ? "" : ` for session ID ${retainedProcessSessionId}`}. Outcome unknown; the original invocation remains retained. Do not replay the command or resend stdin; observe the existing command.`;
19888
+ }
19285
19889
  try {
19286
19890
  const terminal = error;
19287
19891
  if (retainedProcessSessionId !== void 0 && Number.isSafeInteger(retainedProcessSessionId) && terminal.name === "SandboxRetainedProcessTerminalError" && terminal.code === "process_fenced") {
@@ -19353,6 +19957,7 @@ function wrapComputer(computer, track) {
19353
19957
  }
19354
19958
  var TurnToolCancellationControllerImpl = class {
19355
19959
  cancelled = false;
19960
+ observationCancellation = new AbortController();
19356
19961
  reason;
19357
19962
  inFlight = /* @__PURE__ */ new Set();
19358
19963
  shellSessions = /* @__PURE__ */ new Map();
@@ -19375,6 +19980,7 @@ var TurnToolCancellationControllerImpl = class {
19375
19980
  if (!this.cancelled) {
19376
19981
  this.cancelled = true;
19377
19982
  this.reason = reason;
19983
+ this.observationCancellation.abort(cancellationError(reason));
19378
19984
  this.signal?.removeEventListener("abort", this.onAbort);
19379
19985
  }
19380
19986
  void this.ensureDrain().catch(() => void 0);
@@ -19422,6 +20028,7 @@ var TurnToolCancellationControllerImpl = class {
19422
20028
  }
19423
20029
  const directArgs = {
19424
20030
  sessionId: parsed.session_id,
20031
+ signal: this.observationCancellation.signal,
19425
20032
  ...typeof parsed.chars === "string" ? { chars: parsed.chars } : {},
19426
20033
  ...typeof parsed.yield_time_ms === "number" ? { yieldTimeMs: parsed.yield_time_ms } : {},
19427
20034
  ...typeof parsed.max_output_tokens === "number" ? { maxOutputTokens: parsed.max_output_tokens } : {}
@@ -19808,6 +20415,7 @@ var TurnToolCancellationControllerImpl = class {
19808
20415
  const directProcessSession = sessionId === null ? null : retainedProcessSession(cancellationSession, sessionId);
19809
20416
  const typedHandleLoss = sessionId !== null && (hasTypedExecHandleLoss(cancellationSession, sessionId) || this.shellSessions.get(sessionId)?.typedHandleLoss === true);
19810
20417
  let output;
20418
+ let initialObservationFailure;
19811
20419
  if (sessionId !== null && directProcessSession?.writeStdinForProcessMutation) {
19812
20420
  try {
19813
20421
  output = await directProcessSession.writeStdinForProcessMutation({
@@ -19817,7 +20425,10 @@ var TurnToolCancellationControllerImpl = class {
19817
20425
  ...typeof parsed?.max_output_tokens === "number" ? { maxOutputTokens: parsed.max_output_tokens } : {}
19818
20426
  });
19819
20427
  } catch (error) {
19820
- return renderDirectToolFault(error, sessionId);
20428
+ if (!(error instanceof ProviderCommandObservationUnavailableError))
20429
+ return renderDirectToolFault(error, sessionId);
20430
+ initialObservationFailure = error;
20431
+ output = "";
19821
20432
  }
19822
20433
  } else {
19823
20434
  output = await tool.invoke(runContext, cappedInput, details);
@@ -19863,6 +20474,7 @@ var TurnToolCancellationControllerImpl = class {
19863
20474
  return state && typeof output === "string" ? await this.awaitModelFacingShellResult({
19864
20475
  state,
19865
20476
  initialOutput: output,
20477
+ ...initialObservationFailure ? { initialObservationFailure } : {},
19866
20478
  startedAt,
19867
20479
  waitMs: modelWaitMs(parsed?.yield_time_ms),
19868
20480
  maxOutputTokens: typeof parsed?.max_output_tokens === "number" ? parsed.max_output_tokens : 2e4
@@ -19887,11 +20499,13 @@ var TurnToolCancellationControllerImpl = class {
19887
20499
  this.shellSessions.delete(state.sessionId);
19888
20500
  return input.initialOutput;
19889
20501
  }
19890
- if (parseExecBannerSessionId(input.initialOutput) !== state.sessionId) {
20502
+ if (!input.initialObservationFailure && parseExecBannerSessionId(input.initialOutput) !== state.sessionId) {
19891
20503
  return input.initialOutput;
19892
20504
  }
19893
20505
  let output = appendBoundedOutput3("", execOutput(input.initialOutput), maxOutputTokens);
20506
+ let observationFailure = input.initialObservationFailure ?? null;
19894
20507
  for (; ; ) {
20508
+ if (observationFailure?.readRetryAllowed === false) break;
19895
20509
  if (performance.now() - startedAt >= waitMs) break;
19896
20510
  if (this.cancelled) throw cancellationError(this.reason);
19897
20511
  if (!state.writeInvoke && !state.processSession?.writeStdinForProcessRead && !state.processSession?.writeStdinForProcessControl) {
@@ -19903,21 +20517,33 @@ var TurnToolCancellationControllerImpl = class {
19903
20517
  if (remainingMs <= 0) break;
19904
20518
  const yieldTimeMs = Math.min(TURN_PROVIDER_YIELD_SLICE_MS, Math.ceil(remainingMs));
19905
20519
  const read = state.processSession?.writeStdinForProcessRead ?? state.processSession?.writeStdinForProcessControl;
19906
- const next = read ? await read.call(state.processSession, {
19907
- sessionId: state.sessionId,
19908
- chars: "",
19909
- yieldTimeMs,
19910
- maxOutputTokens
19911
- }) : await state.writeInvoke(
19912
- state.runContext,
19913
- JSON.stringify({
19914
- session_id: state.sessionId,
20520
+ let next;
20521
+ try {
20522
+ next = read ? await read.call(state.processSession, {
20523
+ sessionId: state.sessionId,
19915
20524
  chars: "",
19916
- yield_time_ms: yieldTimeMs,
19917
- max_output_tokens: maxOutputTokens
19918
- }),
19919
- void 0
19920
- );
20525
+ yieldTimeMs,
20526
+ maxOutputTokens,
20527
+ signal: this.observationCancellation.signal
20528
+ }) : await state.writeInvoke(
20529
+ state.runContext,
20530
+ JSON.stringify({
20531
+ session_id: state.sessionId,
20532
+ chars: "",
20533
+ yield_time_ms: yieldTimeMs,
20534
+ max_output_tokens: maxOutputTokens
20535
+ }),
20536
+ void 0
20537
+ );
20538
+ } catch (error) {
20539
+ if (this.cancelled) throw cancellationError(this.reason);
20540
+ if (!(error instanceof ProviderCommandObservationUnavailableError)) throw error;
20541
+ observationFailure = error;
20542
+ if (!error.readRetryAllowed) break;
20543
+ await delay(Math.min(SHELL_POLL_MS, Math.max(0, waitMs - (performance.now() - startedAt))));
20544
+ continue;
20545
+ }
20546
+ observationFailure = null;
19921
20547
  if (this.cancelled) throw cancellationError(this.reason);
19922
20548
  if (typeof next !== "string")
19923
20549
  throw new Error("Retained command read returned no provider status");
@@ -19937,6 +20563,13 @@ var TurnToolCancellationControllerImpl = class {
19937
20563
  }
19938
20564
  await delay(Math.min(SHELL_POLL_MS, Math.max(0, remainingMs)));
19939
20565
  }
20566
+ if (observationFailure) {
20567
+ const commandId = state.processSession?.retainedProcessIdentity?.(state.sessionId)?.id;
20568
+ return `${renderDirectToolFault(observationFailure, state.sessionId)}${commandId ? `
20569
+ Command ID: ${commandId}` : ""}
20570
+ Output:
20571
+ ${output}`;
20572
+ }
19940
20573
  if (!canAdoptInBackground) {
19941
20574
  return `${runningCommandBanner(state.sessionId, output)}
19942
20575
  This process is turn-scoped; it will stop when this turn ends or is interrupted.
@@ -20017,7 +20650,13 @@ This process is turn-scoped; it will stop when this turn ends or is interrupted.
20017
20650
  return promise;
20018
20651
  }
20019
20652
  ensureDrain() {
20020
- this.drainPromise ??= this.drain();
20653
+ if (!this.drainPromise) {
20654
+ const drain = this.drain();
20655
+ this.drainPromise = drain;
20656
+ void drain.catch(() => {
20657
+ if (this.drainPromise === drain) this.drainPromise = null;
20658
+ });
20659
+ }
20021
20660
  return this.drainPromise;
20022
20661
  }
20023
20662
  async drain() {
@@ -20160,8 +20799,43 @@ This process is turn-scoped; it will stop when this turn ends or is interrupted.
20160
20799
  });
20161
20800
  return state.cancellation;
20162
20801
  }
20802
+ async reconcileSettledShellSession(state) {
20803
+ try {
20804
+ if (await state.processSession?.reconcileRetainedProcess?.(state.sessionId)) {
20805
+ this.shellSessions.delete(state.sessionId);
20806
+ return true;
20807
+ }
20808
+ } catch {
20809
+ }
20810
+ return false;
20811
+ }
20812
+ async awaitShellControl(state, operation) {
20813
+ if (!state.processSession?.reconcileRetainedProcess)
20814
+ return { reconciled: false, value: await operation };
20815
+ const observed = operation.then(
20816
+ (value) => ({ kind: "resolved", value }),
20817
+ (error) => ({ kind: "rejected", error })
20818
+ );
20819
+ while (true) {
20820
+ const result = await Promise.race([
20821
+ observed,
20822
+ delay(SHELL_POLL_MS).then(() => ({ kind: "pending" }))
20823
+ ]);
20824
+ if (result.kind === "resolved") return { reconciled: false, value: result.value };
20825
+ if (result.kind === "rejected") throw result.error;
20826
+ if (await this.reconcileSettledShellSession(state)) return { reconciled: true };
20827
+ }
20828
+ }
20163
20829
  async cancelShellSessionOnce(state) {
20164
- if (await state.processSession?.cancelSupervisedCommand?.(state.sessionId, "explicit_stop")) {
20830
+ if (await this.reconcileSettledShellSession(state)) return;
20831
+ const nativeCancellation = await this.awaitShellControl(
20832
+ state,
20833
+ Promise.resolve(
20834
+ state.processSession?.cancelSupervisedCommand?.(state.sessionId, "explicit_stop")
20835
+ )
20836
+ );
20837
+ if (nativeCancellation.reconciled) return;
20838
+ if (nativeCancellation.value) {
20165
20839
  while (state.processSession?.hasRetainedProcess?.(state.sessionId) === true) {
20166
20840
  if (await this.rawWrite(state, "", SHELL_POLL_MS)) {
20167
20841
  await this.forgetShellSessionAfterExactSettlement(state);
@@ -20183,12 +20857,17 @@ This process is turn-scoped; it will stop when this turn ends or is interrupted.
20183
20857
  }
20184
20858
  if (state.token && state.processSession?.execCommandForProcessControl && state.processSession.writeStdinForProcessControl) {
20185
20859
  while (state.processSession.hasRetainedProcess?.(state.sessionId) === true) {
20860
+ if (await this.reconcileSettledShellSession(state)) return;
20186
20861
  try {
20187
- const output = await state.processSession.execCommandForProcessControl(
20188
- state.sessionId,
20189
- shellHelperArgs(retainedShellCancellationCommand(state))
20862
+ const control = await this.awaitShellControl(
20863
+ state,
20864
+ state.processSession.execCommandForProcessControl(
20865
+ state.sessionId,
20866
+ shellHelperArgs(retainedShellCancellationCommand(state))
20867
+ )
20190
20868
  );
20191
- const exitCode = parseExecBannerExitCode(output);
20869
+ if (control.reconciled) return;
20870
+ const exitCode = parseExecBannerExitCode(control.value);
20192
20871
  if (exitCode === 0 || exitCode === RETAINED_SHELL_MARKER_PENDING_EXIT_CODE) {
20193
20872
  await this.forgetShellSessionAfterExactSettlement(state);
20194
20873
  return;
@@ -20251,23 +20930,29 @@ This process is turn-scoped; it will stop when this turn ends or is interrupted.
20251
20930
  this.shellSessions.delete(state.sessionId);
20252
20931
  }
20253
20932
  async rawWrite(state, chars, yieldTimeMs) {
20933
+ if (await this.reconcileSettledShellSession(state)) return true;
20254
20934
  if (!state.writeInvoke && !state.processSession?.writeStdinForProcessControl) return false;
20255
20935
  try {
20256
- const output = state.processSession?.writeStdinForProcessControl ? await state.processSession.writeStdinForProcessControl({
20257
- sessionId: state.sessionId,
20258
- chars,
20259
- yieldTimeMs,
20260
- maxOutputTokens: 128
20261
- }) : await state.writeInvoke(
20262
- state.runContext,
20263
- JSON.stringify({
20264
- session_id: state.sessionId,
20936
+ const control = await this.awaitShellControl(
20937
+ state,
20938
+ state.processSession?.writeStdinForProcessControl ? state.processSession.writeStdinForProcessControl({
20939
+ sessionId: state.sessionId,
20265
20940
  chars,
20266
- yield_time_ms: yieldTimeMs,
20267
- max_output_tokens: 128
20268
- }),
20269
- void 0
20941
+ yieldTimeMs,
20942
+ maxOutputTokens: 128
20943
+ }) : state.writeInvoke(
20944
+ state.runContext,
20945
+ JSON.stringify({
20946
+ session_id: state.sessionId,
20947
+ chars,
20948
+ yield_time_ms: yieldTimeMs,
20949
+ max_output_tokens: 128
20950
+ }),
20951
+ void 0
20952
+ )
20270
20953
  );
20954
+ if (control.reconciled) return true;
20955
+ const output = control.value;
20271
20956
  if (typeof output !== "string") return false;
20272
20957
  if (!state.typedHandleLoss && isExecSessionLostBanner(output, state.sessionId)) return true;
20273
20958
  if (parseExecBannerSessionId(output) === state.sessionId) return false;
@@ -21184,7 +21869,7 @@ var SandboxChannelAService = class {
21184
21869
  ancestors.push(directorySegments.slice(0, depth).join("/"));
21185
21870
  }
21186
21871
  const filePaths = /* @__PURE__ */ new Set();
21187
- const prepared = req.files.map((file) => {
21872
+ const prepared2 = req.files.map((file) => {
21188
21873
  const requestPath = strictWorkspaceRelativePath(file.path, "file");
21189
21874
  const workspacePath2 = `${directory}/${requestPath}`;
21190
21875
  if (filePaths.has(workspacePath2)) {
@@ -21200,7 +21885,7 @@ var SandboxChannelAService = class {
21200
21885
  return { requestPath, workspacePath: workspacePath2, bytes, parents };
21201
21886
  });
21202
21887
  const allDirectories = new Set(ancestors);
21203
- for (const file of prepared) for (const parent of file.parents) allDirectories.add(parent);
21888
+ for (const file of prepared2) for (const parent of file.parents) allDirectories.add(parent);
21204
21889
  for (const path of allDirectories) {
21205
21890
  if (filePaths.has(path)) {
21206
21891
  throw new ChannelAValidationError(`path is both a file and a directory: ${path}`);
@@ -21213,13 +21898,13 @@ var SandboxChannelAService = class {
21213
21898
  directoryPaths.set(workspacePath2, index);
21214
21899
  return { index, workspacePath: workspacePath2, providerPath: this.joinRoot(workspacePath2) };
21215
21900
  });
21216
- const files = prepared.map((file, index) => ({
21901
+ const files = prepared2.map((file, index) => ({
21217
21902
  index,
21218
21903
  requestPath: file.requestPath,
21219
21904
  workspacePath: file.workspacePath,
21220
21905
  providerPath: this.joinRoot(file.workspacePath),
21221
21906
  sizeBytes: file.bytes.byteLength,
21222
- sha256: createHash6("sha256").update(file.bytes).digest("hex"),
21907
+ sha256: createHash7("sha256").update(file.bytes).digest("hex"),
21223
21908
  base64: file.bytes.toString("base64"),
21224
21909
  chain: file.parents.map((parent) => directoryPaths.get(parent))
21225
21910
  }));
@@ -23471,9 +24156,180 @@ function parseUnifiedPatch(patch) {
23471
24156
 
23472
24157
  // src/sandbox/providers/modal-command-session.ts
23473
24158
  import { randomUUID as randomUUID5 } from "crypto";
23474
- import { isDeepStrictEqual as isDeepStrictEqual2 } from "util";
24159
+ import { isDeepStrictEqual as isDeepStrictEqual4 } from "util";
24160
+
24161
+ // src/sandbox/provider-errors.ts
24162
+ var GRPC_TRANSIENT = /* @__PURE__ */ new Set([1, 2, 4, 13, 14]);
24163
+ var TRANSIENT_CODES = /* @__PURE__ */ new Set([
24164
+ "1",
24165
+ "2",
24166
+ "4",
24167
+ "13",
24168
+ "14",
24169
+ "CANCELLED",
24170
+ "UNKNOWN",
24171
+ "DEADLINE_EXCEEDED",
24172
+ "INTERNAL",
24173
+ "UNAVAILABLE",
24174
+ "ECONNRESET",
24175
+ "ECONNREFUSED",
24176
+ "ETIMEDOUT",
24177
+ "EAI_AGAIN",
24178
+ "ENOTFOUND"
24179
+ ]);
24180
+ var NOT_FOUND_CODES = /* @__PURE__ */ new Set(["404", "NOT_FOUND", "RESOURCE_NOT_FOUND", "SANDBOX_NOT_FOUND"]);
24181
+ var SAFE_CODE = /^[A-Z0-9._:-]{1,64}$/;
24182
+ var UNREADABLE_ERROR_SIGNAL = Symbol("unreadable-error-signal");
24183
+ function safeRead(record, key) {
24184
+ try {
24185
+ const descriptor = Object.getOwnPropertyDescriptor(record, key);
24186
+ return descriptor ? "value" in descriptor ? descriptor.value : UNREADABLE_ERROR_SIGNAL : void 0;
24187
+ } catch {
24188
+ return UNREADABLE_ERROR_SIGNAL;
24189
+ }
24190
+ }
24191
+ function collectSignals(value) {
24192
+ const out = { numbers: [], codes: [], messages: [], incomplete: false };
24193
+ const seen = /* @__PURE__ */ new Set();
24194
+ const read = (record, key) => {
24195
+ const signal = safeRead(record, key);
24196
+ if (signal !== UNREADABLE_ERROR_SIGNAL) return signal;
24197
+ out.incomplete = true;
24198
+ return void 0;
24199
+ };
24200
+ const visit = (current, depth) => {
24201
+ if (current === null || current === void 0) return;
24202
+ if (depth > 6 || seen.size >= 64) {
24203
+ out.incomplete = true;
24204
+ return;
24205
+ }
24206
+ if (typeof current === "string") {
24207
+ if (current.length <= 512) out.messages.push(current);
24208
+ return;
24209
+ }
24210
+ if (typeof current !== "object" || seen.has(current)) return;
24211
+ seen.add(current);
24212
+ for (const key of [
24213
+ "status",
24214
+ "statusCode",
24215
+ "httpStatus",
24216
+ "httpStatusCode",
24217
+ "responseStatus",
24218
+ "errorCode",
24219
+ "code"
24220
+ ]) {
24221
+ const signal = read(current, key);
24222
+ if (typeof signal === "number" && Number.isFinite(signal)) out.numbers.push(signal);
24223
+ if (typeof signal === "string") {
24224
+ const code = signal.trim().toUpperCase();
24225
+ if (SAFE_CODE.test(code)) out.codes.push(code);
24226
+ }
24227
+ }
24228
+ for (const key of ["name", "message", "details", "cause"]) {
24229
+ const signal = read(current, key);
24230
+ if (typeof signal === "string" && signal.length <= 512) out.messages.push(signal);
24231
+ else visit(signal, depth + 1);
24232
+ }
24233
+ visit(read(current, "response"), depth + 1);
24234
+ visit(read(current, "error"), depth + 1);
24235
+ const errors = read(current, "errors");
24236
+ if (errors !== void 0) {
24237
+ if (!Array.isArray(errors) || !errors.length || errors.length > 16) out.incomplete = true;
24238
+ else
24239
+ for (let index = 0; index < errors.length; index++) {
24240
+ const nested = read(errors, String(index));
24241
+ if (!nested || typeof nested !== "object") out.incomplete = true;
24242
+ visit(nested, depth + 1);
24243
+ }
24244
+ }
24245
+ };
24246
+ visit(value, 0);
24247
+ return out;
24248
+ }
24249
+ function safeDiagnostic(signals) {
24250
+ const code = signals.codes.find(Boolean);
24251
+ const numeric = signals.numbers.find((value) => Number.isFinite(value));
24252
+ return [code ? `code=${code}` : "", numeric !== void 0 ? `status=${numeric}` : ""].filter(Boolean).join(" ");
24253
+ }
24254
+ function hasTransientSignal(signals) {
24255
+ return signals.codes.some((code) => TRANSIENT_CODES.has(code)) || signals.numbers.some((status4) => GRPC_TRANSIENT.has(status4));
24256
+ }
24257
+ function hasModalTerminalSandboxMessage(signals) {
24258
+ return signals.messages.some(
24259
+ (message) => /^Modal sandbox [A-Za-z0-9_-]+ is no longer running\.$/.test(message) || /^Modal sandbox [A-Za-z0-9_-]+ not found \(has been terminated\)$/.test(message)
24260
+ );
24261
+ }
24262
+ function hasUnixLocalTerminalWorkspaceMessage(signals) {
24263
+ return signals.messages.includes(
24264
+ "UnixLocal sandbox workspace is unavailable and no local snapshot could be restored."
24265
+ );
24266
+ }
24267
+ function hasDockerTerminalWorkspaceMessage(signals) {
24268
+ return signals.messages.includes(
24269
+ "Docker sandbox resources are unavailable and no local snapshot could be restored."
24270
+ );
24271
+ }
24272
+ function hasCloudflareTerminalSandboxMessage(signals) {
24273
+ return signals.messages.some(
24274
+ (message) => /^Cloudflare sandbox [A-Za-z0-9._:-]+ is no longer running\.$/.test(message)
24275
+ );
24276
+ }
24277
+ function classifyProviderSandboxFailure(backendId, error) {
24278
+ if (backendId === "selfhosted" || !error) {
24279
+ return { kind: "other", diagnostic: "selfhosted-or-empty" };
24280
+ }
24281
+ const signals = collectSignals(error);
24282
+ const diagnostic = safeDiagnostic(signals) || "unclassified_provider_failure";
24283
+ if (hasTransientSignal(signals)) {
24284
+ return { kind: "transient_transport", diagnostic };
24285
+ }
24286
+ if (signals.incomplete) return { kind: "other", diagnostic };
24287
+ if (signals.numbers.some((status4) => status4 === 404) || signals.codes.some((code) => NOT_FOUND_CODES.has(code))) {
24288
+ return { kind: "not_found", diagnostic };
24289
+ }
24290
+ if (backendId === "modal" && hasModalTerminalSandboxMessage(signals)) {
24291
+ return {
24292
+ kind: "not_found",
24293
+ diagnostic: diagnostic === "unclassified_provider_failure" ? "modal_terminal_message" : `${diagnostic} modal_terminal_message`
24294
+ };
24295
+ }
24296
+ if (backendId === "cloudflare" && hasCloudflareTerminalSandboxMessage(signals)) {
24297
+ return {
24298
+ kind: "not_found",
24299
+ diagnostic: diagnostic === "unclassified_provider_failure" ? "cloudflare_terminal_message" : `${diagnostic} cloudflare_terminal_message`
24300
+ };
24301
+ }
24302
+ if ((backendId === "local" || backendId === "unix_local") && hasUnixLocalTerminalWorkspaceMessage(signals)) {
24303
+ return {
24304
+ kind: "not_found",
24305
+ diagnostic: diagnostic === "unclassified_provider_failure" ? "unix_local_workspace_missing" : `${diagnostic} unix_local_workspace_missing`
24306
+ };
24307
+ }
24308
+ if (backendId === "docker" && hasDockerTerminalWorkspaceMessage(signals)) {
24309
+ return {
24310
+ kind: "not_found",
24311
+ diagnostic: diagnostic === "unclassified_provider_failure" ? "docker_resources_missing" : `${diagnostic} docker_resources_missing`
24312
+ };
24313
+ }
24314
+ return { kind: "other", diagnostic };
24315
+ }
24316
+ function isProviderSandboxNotFoundError2(backendId, error) {
24317
+ return classifyProviderSandboxFailure(backendId, error).kind === "not_found";
24318
+ }
24319
+ function isProviderSandboxGoneDuringRoutedOperation(backendId, error) {
24320
+ if (backendId === "selfhosted" || !error) return false;
24321
+ const signals = collectSignals(error);
24322
+ if (hasTransientSignal(signals) || signals.incomplete) return false;
24323
+ if (signals.codes.includes("SANDBOX_NOT_FOUND")) return true;
24324
+ return backendId === "modal" && hasModalTerminalSandboxMessage(signals);
24325
+ }
24326
+ function isProviderSandboxTransientError(backendId, error) {
24327
+ return classifyProviderSandboxFailure(backendId, error).kind === "transient_transport";
24328
+ }
23475
24329
 
23476
24330
  // src/sandbox/providers/modal-materialization-verification.ts
24331
+ import { isDeepStrictEqual as isDeepStrictEqual3 } from "util";
24332
+ import { setTimeout as delay2 } from "timers/promises";
23477
24333
  var MARKER = "__OPENGENI_MATERIALIZED_PATH_VISIBLE__";
23478
24334
  var OUTPUT_LIMIT = 16 * 1024;
23479
24335
  async function verifyModalMaterializedPath(control, path, workdir, pending, observationTimeoutMs = 3e4) {
@@ -23482,6 +24338,7 @@ async function verifyModalMaterializedPath(control, path, workdir, pending, obse
23482
24338
  const cancellation = new AbortController();
23483
24339
  const deadlineReason = new Error("Materialization visibility observation deadline exceeded");
23484
24340
  let providerCommand;
24341
+ let startUnknown;
23485
24342
  let stdout = "";
23486
24343
  let stderr = "";
23487
24344
  const diagnostic = (reason, exitCode = null) => ({
@@ -23506,13 +24363,46 @@ async function verifyModalMaterializedPath(control, path, workdir, pending, obse
23506
24363
  timer.unref();
23507
24364
  pending.add(cancellation);
23508
24365
  try {
23509
- providerCommand = await control.start(
23510
- { cmd: command, workdir, shell: "sh", login: false, tty: false },
23511
- cancellation.signal
23512
- );
24366
+ try {
24367
+ providerCommand = await control.start(
24368
+ { cmd: command, workdir, shell: "sh", login: false, tty: false },
24369
+ cancellation.signal
24370
+ );
24371
+ } catch (error) {
24372
+ if (!(error instanceof ProviderCommandStartOutcomeUnknownError)) throw error;
24373
+ providerCommand = structuredClone(error.command);
24374
+ startUnknown = error;
24375
+ }
23513
24376
  for (; ; ) {
23514
24377
  cancellation.signal.throwIfAborted();
23515
- const page = await control.readProbe(providerCommand, 1e3, cancellation);
24378
+ let page;
24379
+ try {
24380
+ page = await control.readProbe(providerCommand, 1e3, cancellation);
24381
+ } catch (error) {
24382
+ cancellation.signal.throwIfAborted();
24383
+ if (!(error instanceof ProviderCommandObservationUnavailableError) || !error.readRetryAllowed) {
24384
+ if (!startUnknown) throw error;
24385
+ throw new ProviderCommandObservationUnavailableError(
24386
+ structuredClone(providerCommand),
24387
+ new AggregateError(
24388
+ [startUnknown, error],
24389
+ "Original visibility Start and observation remain uncertain"
24390
+ ),
24391
+ false
24392
+ );
24393
+ }
24394
+ if (!isDeepStrictEqual3(error.command, providerCommand))
24395
+ throw new SandboxMaterializationVerificationError(diagnostic("invalid_response"), {
24396
+ cause: error
24397
+ });
24398
+ try {
24399
+ await delay2(100, void 0, { signal: cancellation.signal });
24400
+ } catch (interrupted) {
24401
+ cancellation.signal.throwIfAborted();
24402
+ throw interrupted;
24403
+ }
24404
+ continue;
24405
+ }
23516
24406
  cancellation.signal.throwIfAborted();
23517
24407
  if (page.command.sandboxId !== providerCommand.sandboxId || page.command.taskId !== providerCommand.taskId || page.command.execId !== providerCommand.execId) {
23518
24408
  throw new SandboxMaterializationVerificationError(diagnostic("invalid_response"));
@@ -23544,7 +24434,15 @@ async function verifyModalMaterializedPath(control, path, workdir, pending, obse
23544
24434
  ...diagnostic("command_pending"),
23545
24435
  causeMessage: "Observation deadline exceeded; provider process completion is unconfirmed"
23546
24436
  },
23547
- { cause: error }
24437
+ {
24438
+ cause: providerCommand ? new ProviderCommandObservationUnavailableError(
24439
+ providerCommand,
24440
+ startUnknown ? new AggregateError(
24441
+ [startUnknown, error],
24442
+ "Original visibility Start and observation deadline remain uncertain"
24443
+ ) : error
24444
+ ) : error
24445
+ }
23548
24446
  );
23549
24447
  }
23550
24448
  if (!(error instanceof SandboxMaterializationVerificationError)) {
@@ -23563,7 +24461,7 @@ async function verifyModalMaterializedPath(control, path, workdir, pending, obse
23563
24461
 
23564
24462
  // src/sandbox/providers/modal-command-session.ts
23565
24463
  function sameExecution(a, b) {
23566
- return a.kind === b.kind && a.sandboxId === b.sandboxId && a.taskId === b.taskId && a.execId === b.execId && isDeepStrictEqual2(
24464
+ return a.kind === b.kind && a.sandboxId === b.sandboxId && a.taskId === b.taskId && a.execId === b.execId && isDeepStrictEqual4(
23567
24465
  "supervision" in a ? a.supervision : void 0,
23568
24466
  "supervision" in b ? b.supervision : void 0
23569
24467
  ) && Boolean(a.pty) === Boolean(b.pty);
@@ -23782,7 +24680,7 @@ function installModalCommandSession(session, control) {
23782
24680
  session.captureCommandOutput = async (result) => {
23783
24681
  const receipt = receipts.get(result);
23784
24682
  if (!receipt || receipt.page.command.kind !== "modal-router-v1") return false;
23785
- if (receipt.page.command.supervision && !receipt.page.expected && receipt.page.exitCode === null && receipt.page.chunks.length === 0) {
24683
+ if (!receipt.page.expected && receipt.page.exitCode === null && receipt.page.chunks.length === 0) {
23786
24684
  receipts.delete(result);
23787
24685
  return true;
23788
24686
  }
@@ -23840,9 +24738,23 @@ function installModalCommandSession(session, control) {
23840
24738
  if (!retained || !sameExecution(entry.command, retained))
23841
24739
  throw new Error("Original Modal command identity is unavailable");
23842
24740
  const index = await entry.persistence.reserveInput(Buffer.byteLength(args.chars));
23843
- await control.write(retained, args.chars, index);
24741
+ try {
24742
+ await control.write(retained, args.chars, index);
24743
+ } catch (error) {
24744
+ if (retained.kind === "modal-router-v1" && // Contain supported transport graphs, including mixed failures. This
24745
+ // grants no read/write retry permission; the locator and byte range
24746
+ // come only from the retained command and its one input reservation.
24747
+ classifyProviderSandboxFailure("modal", error).kind === "transient_transport")
24748
+ throw new ProviderCommandInputOutcomeUnknownError(
24749
+ retained,
24750
+ index,
24751
+ Buffer.byteLength(args.chars),
24752
+ error
24753
+ );
24754
+ throw error;
24755
+ }
23844
24756
  }
23845
- return read(args.sessionId, entry, args.yieldTimeMs ?? 250, args.maxOutputTokens);
24757
+ return read(args.sessionId, entry, args.yieldTimeMs ?? 250, args.maxOutputTokens, args.signal);
23846
24758
  };
23847
24759
  }
23848
24760
 
@@ -23850,274 +24762,88 @@ function installModalCommandSession(session, control) {
23850
24762
  import { randomUUID as randomUUID6, randomBytes } from "crypto";
23851
24763
  import { posix as posix3 } from "path";
23852
24764
  import { status as status3 } from "@grpc/grpc-js";
23853
- import { setTimeout as delay2 } from "timers/promises";
24765
+ import { setTimeout as delay3 } from "timers/promises";
23854
24766
  import {
23855
24767
  SandboxProviderCommand,
23856
- CommandSupervisionReceipt
24768
+ CommandSupervisionReceipt,
24769
+ ModalRouterProviderCommand as ModalRouterProviderCommand3
23857
24770
  } from "@opengeni/contracts";
23858
24771
 
23859
- // src/sandbox/providers/modal-legacy-command-control.ts
23860
- import { posix as posix2 } from "path";
23861
- import { ModalClient } from "modal";
23862
- import { status as status2 } from "@grpc/grpc-js";
23863
- import { ModalLegacyProviderCommand } from "@opengeni/contracts";
23864
- var modalCommandAbortMiddleware = async function* (call, options) {
23865
- options.signal?.throwIfAborted();
23866
- return yield* call.next(call.request, options);
23867
- };
23868
- var ModalClientBase = ModalClient;
23869
- var ModalCommandClient = class extends ModalClientBase {
23870
- retryMiddleware() {
23871
- return modalCommandAbortMiddleware;
23872
- }
23873
- };
23874
- var controlClients = /* @__PURE__ */ new WeakMap();
23875
- function commandControlPlane(client) {
23876
- if (!client.profile) return client.cpClient;
23877
- if (typeof Reflect.get(ModalClient.prototype, "retryMiddleware") !== "function")
23878
- throw new Error("Verified Modal command cancellation contract is unavailable");
23879
- let controlled = controlClients.get(client);
23880
- if (!controlled) {
23881
- const profile = client.profile;
23882
- if (!profile.tokenId || !profile.tokenSecret)
23883
- throw new Error("Modal command control requires its original authenticated profile");
23884
- controlled = new ModalCommandClient({
23885
- tokenId: profile.tokenId,
23886
- tokenSecret: profile.tokenSecret,
23887
- endpoint: profile.serverUrl,
23888
- environment: profile.environment ?? "",
23889
- ...profile.maxThrottleWaitSecs !== void 0 ? { maxThrottleWaitSecs: profile.maxThrottleWaitSecs } : {},
23890
- ...client.logger ? { logger: client.logger } : {}
23891
- });
23892
- controlClients.set(client, controlled);
23893
- }
23894
- return controlled.cpClient;
23895
- }
23896
- function decodePage(prior, input, terminal) {
23897
- const bytes = Buffer.concat([Buffer.from(prior, "base64"), ...input]);
23898
- let boundary = bytes.length;
23899
- if (!terminal) {
23900
- for (let start = Math.max(0, bytes.length - 3); start < bytes.length; start++) {
23901
- const first = bytes[start];
23902
- const width = first >= 194 && first <= 223 ? 2 : first >= 224 && first <= 239 ? 3 : first >= 240 && first <= 244 ? 4 : 0;
23903
- if (!width || bytes.length - start >= width) continue;
23904
- const suffix = bytes.subarray(start + 1);
23905
- if (!suffix.every((byte) => byte >= 128 && byte <= 191)) continue;
23906
- const second = suffix[0];
23907
- if (second !== void 0 && (first === 224 && second < 160 || first === 237 && second > 159 || first === 240 && second < 144 || first === 244 && second > 143))
23908
- continue;
23909
- boundary = start;
23910
- break;
23911
- }
23912
- }
23913
- return {
23914
- text: bytes.subarray(0, boundary).toString("utf8"),
23915
- remainder: bytes.subarray(boundary).toString("base64")
24772
+ // src/sandbox/providers/modal-command-observation-errors.ts
24773
+ function isModalCommandObservationTransportError(error) {
24774
+ const seen = /* @__PURE__ */ new Map();
24775
+ let nodes = 0;
24776
+ const own = (value, key) => {
24777
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
24778
+ if (descriptor && !("value" in descriptor)) throw new Error("Unreadable provider error graph");
24779
+ return descriptor && "value" in descriptor ? descriptor.value : void 0;
23916
24780
  };
23917
- }
23918
- var ModalCommandControl = class _ModalCommandControl {
23919
- constructor(client, sandboxIdentity, root, environment = {}) {
23920
- this.client = client;
23921
- this.sandboxIdentity = sandboxIdentity;
23922
- this.root = root;
23923
- this.environment = environment;
23924
- }
23925
- static forSandbox(client, sandboxId, root, environment = {}) {
23926
- if (client.version() !== "0.9.0")
23927
- throw new Error("Modal command control requires the verified 0.9.0 SDK contract");
23928
- return new _ModalCommandControl(commandControlPlane(client), sandboxId, root, environment);
23929
- }
23930
- get sandboxId() {
23931
- return typeof this.sandboxIdentity === "function" ? this.sandboxIdentity() : this.sandboxIdentity;
23932
- }
23933
- async start(args, signal) {
23934
- signal?.throwIfAborted();
23935
- const workdir = posix2.resolve(this.root, args.workdir ?? this.root);
23936
- if (workdir !== this.root && !workdir.startsWith(`${this.root.replace(/\/$/u, "")}/`))
23937
- throw new Error("Command workdir is outside the sandbox workspace");
23938
- const sandboxId = this.sandboxId;
23939
- const task = await ModalCommandStartPreDispatchUnavailableError.beforeDispatch(
23940
- () => this.client.sandboxGetTaskId({ sandboxId }, signal ? { signal } : void 0),
23941
- signal
23942
- );
23943
- if (!task.taskId || task.taskResult) throw new Error("Modal command task is unavailable");
23944
- if (sandboxId !== this.sandboxId)
23945
- throw new Error("Modal sandbox changed during command preparation");
23946
- const login = args.shell ? args.login ?? true : false;
23947
- let command = [args.shell ?? "/bin/sh", login ? "-lc" : "-c", args.cmd];
23948
- if (args.runAs) {
23949
- const user = shellQuote(args.runAs);
23950
- const invocation = command.map(shellQuote).join(" ");
23951
- const script = `if [ "$(id -u)" = ${user} ] || [ "$(id -un 2>/dev/null)" = ${user} ]; then exec ${invocation}; elif [ "$(id -u)" = 0 ]; then exec su -s /bin/sh ${user} -c ${shellQuote(`exec ${invocation}`)}; else exec sudo -n -u ${user} -- ${invocation}; fi`;
23952
- command = ["/bin/sh", "-c", script];
23953
- }
23954
- const environment = typeof this.environment === "function" ? this.environment() : this.environment;
23955
- if (Object.keys(environment).length) {
23956
- command = [
23957
- "/usr/bin/env",
23958
- "--",
23959
- ...Object.entries(environment).map(([key, value]) => `${key}=${value}`),
23960
- ...command
23961
- ];
23962
- }
23963
- const result = await this.client.containerExec(
23964
- {
23965
- taskId: task.taskId,
23966
- command,
23967
- terminateContainerOnExit: false,
23968
- runtimeDebug: false,
23969
- stdoutOutput: 2,
23970
- stderrOutput: 2,
23971
- timeoutSecs: 0,
23972
- workdir,
23973
- secretIds: [],
23974
- ...args.tty ? {
23975
- ptyInfo: {
23976
- enabled: true,
23977
- winszRows: 24,
23978
- winszCols: 80,
23979
- envTerm: "xterm",
23980
- envColorterm: "",
23981
- envTermProgram: "",
23982
- ptyType: 1,
23983
- noTerminateOnIdleStdin: true
23984
- }
23985
- } : {}
23986
- },
23987
- { retries: 0, ...signal ? { signal } : {} }
23988
- ).catch((error) => {
23989
- const code = error?.code;
23990
- if (typeof code === "number" && [
23991
- status2.INVALID_ARGUMENT,
23992
- status2.NOT_FOUND,
23993
- status2.PERMISSION_DENIED,
23994
- status2.UNAUTHENTICATED,
23995
- status2.UNIMPLEMENTED
23996
- ].includes(code))
23997
- throw new ProviderCommandStartRejectedError(error);
23998
- throw new ModalCommandStartOutcomeUnknownError(task.taskId, "", error);
23999
- });
24000
- if (!result.execId)
24001
- throw new ModalCommandStartOutcomeUnknownError(
24002
- task.taskId,
24003
- "",
24004
- new Error("Modal command start returned no execution identity")
24781
+ const visit = (value, depth) => {
24782
+ if (!value || typeof value !== "object" || depth > 6 || ++nodes > 32) return false;
24783
+ if (seen.has(value)) return seen.get(value);
24784
+ seen.set(value, false);
24785
+ try {
24786
+ const code = own(value, "code");
24787
+ const nested = [own(value, "cause"), own(value, "error")].filter(
24788
+ (item) => item !== void 0
24005
24789
  );
24006
- return {
24007
- kind: "modal-control-v1",
24008
- sandboxId,
24009
- taskId: task.taskId,
24010
- execId: result.execId,
24011
- ...args.tty ? { pty: true } : {},
24012
- streams: {
24013
- stdout: { batchIndex: 0, utf8Remainder: "", exitCode: null },
24014
- stderr: { batchIndex: 0, utf8Remainder: "", exitCode: null }
24790
+ const errors = own(value, "errors");
24791
+ if (errors !== void 0) {
24792
+ if (!Array.isArray(errors) || !errors.length || errors.length > 16) return false;
24793
+ for (let index = 0; index < errors.length; index++) nested.push(own(errors, String(index)));
24015
24794
  }
24016
- };
24017
- }
24018
- async read(command, yieldTimeMs, signal) {
24019
- return this.readOutput(command, yieldTimeMs, signal);
24020
- }
24021
- /** Fixed internal probes own their cancellation controller and must drain
24022
- * both reads before relinquishing the surrounding provider-operation gate.
24023
- * Retained-command readers keep their existing signal/receipt contract.
24024
- */
24025
- async readProbe(command, yieldTimeMs, cancellation) {
24026
- return this.readOutput(
24027
- command,
24028
- yieldTimeMs,
24029
- cancellation.signal,
24030
- (error) => cancellation.abort(error)
24031
- );
24032
- }
24033
- async readOutput(command, yieldTimeMs, signal, cancelSiblings) {
24034
- signal?.throwIfAborted();
24035
- this.assertIdentity(command);
24036
- const next = structuredClone(command);
24037
- let failure;
24038
- const reads = ["stdout", "stderr"].map(async (stream) => {
24039
- const cursor = command.streams[stream];
24040
- if (cursor.exitCode !== null) return null;
24041
- const descriptor = stream === "stdout" ? 1 : 2;
24042
- for await (const batch of this.client.containerExecGetOutput(
24043
- {
24044
- execId: command.execId,
24045
- timeout: Math.max(0, yieldTimeMs) / 1e3,
24046
- lastBatchIndex: cursor.batchIndex,
24047
- fileDescriptor: descriptor,
24048
- getRawBytes: true
24049
- },
24050
- signal ? { signal } : void 0
24051
- )) {
24052
- if (batch.batchIndex <= cursor.batchIndex) continue;
24053
- if (!Number.isSafeInteger(batch.batchIndex))
24054
- throw new Error("Invalid Modal output cursor");
24055
- const terminal = batch.exitCode !== void 0;
24056
- if (terminal && !Number.isSafeInteger(batch.exitCode))
24057
- throw new Error("Invalid Modal exit status");
24058
- const decoded = decodePage(
24059
- cursor.utf8Remainder,
24060
- batch.items.filter((item) => item.fileDescriptor === descriptor).map((item) => item.messageBytes),
24061
- terminal
24062
- );
24063
- next.streams[stream] = {
24064
- batchIndex: batch.batchIndex,
24065
- utf8Remainder: decoded.remainder,
24066
- exitCode: terminal ? batch.exitCode : null
24067
- };
24068
- return {
24069
- stream,
24070
- chunkId: `modal:${command.execId}:${stream}:${cursor.batchIndex}:${batch.batchIndex}`,
24071
- text: decoded.text
24072
- };
24795
+ if (code !== void 0) {
24796
+ const normalized = typeof code === "string" ? code.trim().toUpperCase() : code;
24797
+ if (![
24798
+ 1,
24799
+ 2,
24800
+ 4,
24801
+ 13,
24802
+ 14,
24803
+ "1",
24804
+ "2",
24805
+ "4",
24806
+ "13",
24807
+ "14",
24808
+ "CANCELLED",
24809
+ "UNKNOWN",
24810
+ "DEADLINE_EXCEEDED",
24811
+ "INTERNAL",
24812
+ "UNAVAILABLE",
24813
+ "ECONNRESET",
24814
+ "ECONNREFUSED",
24815
+ "ETIMEDOUT",
24816
+ "EAI_AGAIN",
24817
+ "ENOTFOUND"
24818
+ ].includes(normalized))
24819
+ return false;
24820
+ const result2 = nested.length === 0 || nested.every((item) => visit(item, depth + 1));
24821
+ seen.set(value, result2);
24822
+ return result2;
24073
24823
  }
24074
- return null;
24075
- }).map(
24076
- (read) => !cancelSiblings ? read : read.catch((error) => {
24077
- failure ??= { error };
24078
- cancelSiblings(error);
24079
- throw error;
24080
- })
24081
- );
24082
- const pages = cancelSiblings ? await Promise.allSettled(reads).then((results) => {
24083
- if (failure) throw failure.error;
24084
- return results.map((result) => {
24085
- if (result.status === "rejected") throw result.reason;
24086
- return result.value;
24087
- });
24088
- }) : await Promise.all(reads);
24089
- const stdoutExit = next.streams.stdout.exitCode;
24090
- const stderrExit = next.streams.stderr.exitCode;
24091
- if (stdoutExit !== null && stderrExit !== null && stdoutExit !== stderrExit)
24092
- throw new Error("Modal output streams disagree about command exit status");
24093
- return {
24094
- command: next,
24095
- streamFidelity: command.pty ? "merged" : "separate",
24096
- chunks: pages.filter((page) => page !== null),
24097
- exitCode: stdoutExit !== null && stderrExit !== null ? stdoutExit : null
24098
- };
24099
- }
24100
- async write(command, chars, messageIndex) {
24101
- this.assertIdentity(command);
24102
- if (!chars) return;
24103
- if (!Number.isSafeInteger(messageIndex) || messageIndex < 1)
24104
- throw new Error("Modal stdin requires a protected monotonic message index");
24105
- await this.client.containerExecPutInput(
24106
- {
24107
- execId: command.execId,
24108
- input: { message: Buffer.from(chars), messageIndex, eof: false }
24109
- },
24110
- { retries: 0 }
24111
- );
24112
- }
24113
- assertIdentity(command) {
24114
- ModalLegacyProviderCommand.parse(command);
24115
- if (command.kind !== "modal-control-v1" || command.sandboxId !== this.sandboxId || !command.taskId || !command.execId)
24116
- throw new Error("Modal command locator does not match the original sandbox");
24117
- }
24118
- };
24824
+ const result = nested.length > 0 && nested.every((item) => visit(item, depth + 1));
24825
+ seen.set(value, result);
24826
+ return result;
24827
+ } catch {
24828
+ return false;
24829
+ }
24830
+ };
24831
+ return visit(error, 0);
24832
+ }
24119
24833
 
24120
24834
  // src/sandbox/providers/modal-command-control.ts
24835
+ function awaitRouterAccess(pending, signal) {
24836
+ if (!signal) return pending;
24837
+ signal.throwIfAborted();
24838
+ return new Promise((resolve7, reject) => {
24839
+ const abort = () => {
24840
+ signal.removeEventListener("abort", abort);
24841
+ reject(signal.reason);
24842
+ };
24843
+ signal.addEventListener("abort", abort, { once: true });
24844
+ void pending.then(resolve7, reject).finally(() => signal.removeEventListener("abort", abort));
24845
+ });
24846
+ }
24121
24847
  var ModalCommandControl2 = class _ModalCommandControl {
24122
24848
  constructor(client, sandboxIdentity, root, environment) {
24123
24849
  this.sandboxIdentity = sandboxIdentity;
@@ -24127,6 +24853,8 @@ var ModalCommandControl2 = class _ModalCommandControl {
24127
24853
  this.legacy = ModalCommandControl.forSandbox(client, sandboxIdentity, root, environment);
24128
24854
  }
24129
24855
  routers = /* @__PURE__ */ new Map();
24856
+ routerLookups = /* @__PURE__ */ new Map();
24857
+ controlHelpers = /* @__PURE__ */ new Map();
24130
24858
  client;
24131
24859
  legacy;
24132
24860
  closed = false;
@@ -24144,10 +24872,15 @@ var ModalCommandControl2 = class _ModalCommandControl {
24144
24872
  let pending = this.routers.get(taskId);
24145
24873
  const reused = Boolean(pending);
24146
24874
  if (!pending) {
24875
+ const lookup2 = {
24876
+ controller: new AbortController(),
24877
+ waiters: 0,
24878
+ settled: false
24879
+ };
24147
24880
  pending = (async () => {
24148
- const access = await this.client.taskGetCommandRouterAccess(
24149
- { taskId },
24150
- signal ? { signal } : void 0
24881
+ const access = await awaitRouterAccess(
24882
+ this.client.taskGetCommandRouterAccess({ taskId }, { signal: lookup2.controller.signal }),
24883
+ lookup2.controller.signal
24151
24884
  );
24152
24885
  let refreshAt = Date.now() + 6e4;
24153
24886
  try {
@@ -24161,15 +24894,33 @@ var ModalCommandControl2 = class _ModalCommandControl {
24161
24894
  return { router: new ModalCommandRouterWire(access), users: 0, refreshAt };
24162
24895
  })();
24163
24896
  this.routers.set(taskId, pending);
24164
- void pending.catch(() => {
24897
+ this.routerLookups.set(pending, lookup2);
24898
+ const settled = () => {
24899
+ lookup2.settled = true;
24900
+ this.routerLookups.delete(pending);
24901
+ };
24902
+ void pending.then(settled, () => {
24903
+ settled();
24165
24904
  if (this.routers.get(taskId) === pending) this.routers.delete(taskId);
24166
24905
  });
24167
24906
  }
24168
- const entry = await pending;
24907
+ const lookup = this.routerLookups.get(pending);
24908
+ if (lookup) lookup.waiters++;
24909
+ let entry;
24910
+ try {
24911
+ entry = await awaitRouterAccess(pending, signal);
24912
+ } finally {
24913
+ if (lookup && --lookup.waiters === 0 && !lookup.settled) {
24914
+ if (this.routers.get(taskId) === pending) this.routers.delete(taskId);
24915
+ lookup.controller.abort(new Error("Modal router access has no remaining waiters"));
24916
+ }
24917
+ }
24169
24918
  if (reused && !entry.users && Date.now() > entry.refreshAt) {
24170
- clearTimeout(entry.idle);
24171
- entry.router.close();
24172
- this.routers.delete(taskId);
24919
+ if (this.routers.get(taskId) === pending) {
24920
+ this.routers.delete(taskId);
24921
+ clearTimeout(entry.idle);
24922
+ entry.router.close();
24923
+ }
24173
24924
  return await this.withRouter(taskId, signal, run2);
24174
24925
  }
24175
24926
  clearTimeout(entry.idle);
@@ -24192,6 +24943,8 @@ var ModalCommandControl2 = class _ModalCommandControl {
24192
24943
  }
24193
24944
  async close() {
24194
24945
  this.closed = true;
24946
+ for (const lookup of this.routerLookups.values())
24947
+ lookup.controller.abort(new Error("Modal command control is closed"));
24195
24948
  const entries = await Promise.allSettled(this.routers.values());
24196
24949
  this.routers.clear();
24197
24950
  for (const entry of entries)
@@ -24240,19 +24993,7 @@ var ModalCommandControl2 = class _ModalCommandControl {
24240
24993
  nonce: randomBytes(32).toString("hex"),
24241
24994
  controlPath: `/tmp/opengeni-supervision/${invocationId}.sock`
24242
24995
  } : void 0;
24243
- let commandArgs = [
24244
- args.shell ?? "/bin/sh",
24245
- args.shell && (args.login ?? true) ? "-lc" : "-c",
24246
- args.cmd
24247
- ];
24248
- if (args.runAs) {
24249
- const user = shellQuote(args.runAs), invocation = commandArgs.map(shellQuote).join(" ");
24250
- commandArgs = [
24251
- "/bin/sh",
24252
- "-c",
24253
- `if [ "$(id -u)" = ${user} ] || [ "$(id -un 2>/dev/null)" = ${user} ]; then exec ${invocation}; elif [ "$(id -u)" = 0 ]; then exec su -s /bin/sh ${user} -c ${shellQuote(`exec ${invocation}`)}; else exec sudo -n -u ${user} -- ${invocation}; fi`
24254
- ];
24255
- }
24996
+ let commandArgs = modalCommandArgv(args);
24256
24997
  const env = typeof this.environment === "function" ? this.environment() : this.environment;
24257
24998
  if (supervision)
24258
24999
  commandArgs = [
@@ -24325,28 +25066,50 @@ var ModalCommandControl2 = class _ModalCommandControl {
24325
25066
  if (!task.taskId || task.taskResult) throw new Error("Modal command task is unavailable");
24326
25067
  await this.withStartRouter(task.taskId, signal, async (router) => {
24327
25068
  const identity = { taskId: task.taskId, execId: randomUUID6() };
24328
- await router.start(
24329
- {
25069
+ const observation = {
25070
+ command: {
25071
+ kind: "modal-router-v1",
25072
+ sandboxId,
24330
25073
  ...identity,
24331
- commandArgs: ["/usr/local/bin/opengeni-command-supervisor", "capabilities"],
24332
- workdir: "/tmp",
24333
- env: {}
25074
+ streams: {
25075
+ stdout: { byteOffset: 0, utf8Remainder: "", eof: false, exitCode: null },
25076
+ stderr: { byteOffset: 0, utf8Remainder: "", eof: false, exitCode: null }
25077
+ }
24334
25078
  },
24335
- signal
24336
- );
24337
- let offset = 0;
24338
- let output = "";
24339
- let eof = false;
24340
- let exit = null;
24341
- while (!eof || exit === null) {
24342
- signal.throwIfAborted();
24343
- const page = await router.read(identity, "stdout", offset, 250, signal);
24344
- offset += page.bytes.length;
24345
- if (offset > 128) throw new Error("Modal supervision capability response exceeds bound");
24346
- output += page.bytes.toString("utf8");
24347
- eof = page.eof;
24348
- exit = await router.poll(identity, signal);
25079
+ output: ""
25080
+ };
25081
+ let startUnknown;
25082
+ try {
25083
+ await router.start(
25084
+ {
25085
+ ...identity,
25086
+ commandArgs: ["/usr/local/bin/opengeni-command-supervisor", "capabilities"],
25087
+ workdir: "/tmp",
25088
+ env: {}
25089
+ },
25090
+ signal
25091
+ );
25092
+ } catch (error) {
25093
+ if (!(error instanceof ModalCommandStartOutcomeUnknownError)) throw error;
25094
+ if (error.taskId !== identity.taskId || error.execId !== identity.execId) throw error;
25095
+ startUnknown = error;
25096
+ }
25097
+ let result;
25098
+ try {
25099
+ result = await this.readControlOutput(identity, 128, signal, observation);
25100
+ } catch (error) {
25101
+ if (!startUnknown) throw error;
25102
+ throw new ProviderCommandObservationUnavailableError(
25103
+ structuredClone(observation.command),
25104
+ new AggregateError(
25105
+ [startUnknown, error],
25106
+ "Original capability Start and observation remain uncertain"
25107
+ ),
25108
+ error instanceof ProviderCommandObservationUnavailableError && error.readRetryAllowed
25109
+ );
24349
25110
  }
25111
+ signal.throwIfAborted();
25112
+ const { output, exit } = result;
24350
25113
  if (exit !== 0 || output !== "native-subreaper-v1")
24351
25114
  throw new Error(
24352
25115
  "Exact Modal instance lacks compatible native supervision; command not admitted"
@@ -24373,7 +25136,7 @@ var ModalCommandControl2 = class _ModalCommandControl {
24373
25136
  const transientObservation = (error) => [status3.UNAVAILABLE, status3.DEADLINE_EXCEEDED].includes(
24374
25137
  error?.code ?? -1
24375
25138
  );
24376
- const pause = () => delay2(100, void 0, { signal });
25139
+ const pause = () => delay3(100, void 0, { signal });
24377
25140
  return await this.withStartRouter(task.taskId, signal, async (router) => {
24378
25141
  for (; ; ) {
24379
25142
  signal.throwIfAborted();
@@ -24426,45 +25189,92 @@ var ModalCommandControl2 = class _ModalCommandControl {
24426
25189
  const descriptor = command.supervision;
24427
25190
  if (!descriptor || command.sandboxId !== this.sandboxId)
24428
25191
  throw new Error("Supervised command identity is unavailable");
24429
- const identity = { taskId: command.taskId, execId: randomUUID6() };
24430
- const signal = AbortSignal.timeout(5e3);
24431
- return await this.withStartRouter(command.taskId, signal, async (router) => {
24432
- await router.start(
24433
- {
24434
- ...identity,
24435
- commandArgs: [
24436
- "/usr/local/bin/opengeni-command-supervisor",
24437
- "control",
24438
- "--invocation",
24439
- descriptor.invocationId,
24440
- "--nonce",
24441
- descriptor.nonce,
24442
- "--socket",
24443
- descriptor.controlPath,
24444
- "--action",
24445
- action,
24446
- ...receiptId ? ["--receipt", receiptId] : []
24447
- ],
24448
- workdir: "/tmp",
24449
- env: {}
24450
- },
24451
- signal
24452
- );
24453
- const buffers = [];
24454
- let offset = 0;
24455
- let eof = false;
24456
- let exit = null;
24457
- while (!eof || exit === null) {
24458
- signal.throwIfAborted();
24459
- const page = await router.read(identity, "stdout", offset, 250, signal);
24460
- offset += page.bytes.length;
24461
- if (offset > 4096) throw new Error("Supervisor control response exceeds its bound");
24462
- buffers.push(page.bytes);
24463
- eof = page.eof;
24464
- exit = await router.poll(identity, signal);
25192
+ const key = JSON.stringify([
25193
+ command.sandboxId,
25194
+ command.taskId,
25195
+ command.execId,
25196
+ descriptor.invocationId,
25197
+ descriptor.nonce,
25198
+ descriptor.controlPath,
25199
+ action,
25200
+ receiptId ?? null
25201
+ ]);
25202
+ let helper = this.controlHelpers.get(key);
25203
+ if (!helper) {
25204
+ helper = {
25205
+ startPending: true,
25206
+ output: "",
25207
+ command: {
25208
+ kind: "modal-router-v1",
25209
+ sandboxId: command.sandboxId,
25210
+ taskId: command.taskId,
25211
+ execId: randomUUID6(),
25212
+ streams: {
25213
+ stdout: { byteOffset: 0, utf8Remainder: "", eof: false, exitCode: null },
25214
+ stderr: { byteOffset: 0, utf8Remainder: "", eof: false, exitCode: null }
25215
+ }
25216
+ }
25217
+ };
25218
+ this.controlHelpers.set(key, helper);
25219
+ }
25220
+ const observation = helper;
25221
+ const run2 = async () => {
25222
+ const signal = AbortSignal.timeout(5e3);
25223
+ if (observation.startPending) {
25224
+ try {
25225
+ await this.withStartRouter(command.taskId, signal, async (router) => {
25226
+ observation.startPending = false;
25227
+ await router.start(
25228
+ {
25229
+ taskId: observation.command.taskId,
25230
+ execId: observation.command.execId,
25231
+ commandArgs: [
25232
+ "/usr/local/bin/opengeni-command-supervisor",
25233
+ "control",
25234
+ "--invocation",
25235
+ descriptor.invocationId,
25236
+ "--nonce",
25237
+ descriptor.nonce,
25238
+ "--socket",
25239
+ descriptor.controlPath,
25240
+ "--action",
25241
+ action,
25242
+ ...receiptId ? ["--receipt", receiptId] : []
25243
+ ],
25244
+ workdir: "/tmp",
25245
+ env: {}
25246
+ },
25247
+ signal
25248
+ );
25249
+ });
25250
+ } catch (error) {
25251
+ if (observation.startPending || error instanceof ModalCommandStartNotDispatchedError || error instanceof ModalCommandStartRejectedError || error instanceof ModalCommandStartPreDispatchUnavailableError) {
25252
+ this.controlHelpers.delete(key);
25253
+ throw error;
25254
+ }
25255
+ observation.startUnknown = error;
25256
+ throw error;
25257
+ }
24465
25258
  }
25259
+ let response;
25260
+ try {
25261
+ response = await this.readControlOutput(observation.command, 4096, signal, observation);
25262
+ } catch (error) {
25263
+ if (observation.startUnknown !== void 0 && error instanceof ProviderCommandObservationUnavailableError)
25264
+ throw new ProviderCommandObservationUnavailableError(
25265
+ error.command,
25266
+ new AggregateError(
25267
+ [observation.startUnknown, error],
25268
+ "Original helper Start and observation remain uncertain"
25269
+ ),
25270
+ error.readRetryAllowed
25271
+ );
25272
+ throw error;
25273
+ }
25274
+ const { output, exit } = response;
25275
+ this.controlHelpers.delete(key);
24466
25276
  if (exit !== 0) throw new Error("Supervisor control is unavailable");
24467
- const result = JSON.parse(Buffer.concat(buffers).toString("utf8"));
25277
+ const result = JSON.parse(output);
24468
25278
  if (!result || !["idle", "running", "quiescent"].includes(result.state))
24469
25279
  throw new Error("Invalid supervisor control response");
24470
25280
  if (result.receipt !== void 0) {
@@ -24475,27 +25285,169 @@ var ModalCommandControl2 = class _ModalCommandControl {
24475
25285
  if (result.state === "quiescent" !== Boolean(result.receipt))
24476
25286
  throw new Error("Supervisor quiescence response lacks its receipt");
24477
25287
  return result;
24478
- });
25288
+ };
25289
+ observation.inFlight ??= run2().finally(() => {
25290
+ delete observation.inFlight;
25291
+ });
25292
+ return await observation.inFlight;
25293
+ }
25294
+ /** These fixed helpers already started once. Observe only their original
25295
+ * invocation within the caller's existing five-second budget. */
25296
+ async readControlOutput(identity, limit, signal, observation) {
25297
+ const state = observation ?? {
25298
+ command: {
25299
+ kind: "modal-router-v1",
25300
+ sandboxId: this.sandboxId,
25301
+ ...identity,
25302
+ streams: {
25303
+ stdout: { byteOffset: 0, utf8Remainder: "", eof: false, exitCode: null },
25304
+ stderr: { byteOffset: 0, utf8Remainder: "", eof: false, exitCode: null }
25305
+ }
25306
+ },
25307
+ output: ""
25308
+ };
25309
+ for (; ; ) {
25310
+ try {
25311
+ signal.throwIfAborted();
25312
+ const page = await this.read(state.command, 250, signal);
25313
+ state.command = page.command;
25314
+ if (state.command.streams.stdout.byteOffset + state.command.streams.stderr.byteOffset > limit)
25315
+ throw new Error("Supervisor control response exceeds its bound");
25316
+ state.output += page.chunks.filter((chunk) => chunk.stream === "stdout").map((chunk) => chunk.text).join("");
25317
+ if (page.exitCode !== null) return { output: state.output, exit: page.exitCode };
25318
+ } catch (error) {
25319
+ if (signal.aborted)
25320
+ throw new ProviderCommandObservationUnavailableError(
25321
+ structuredClone(state.command),
25322
+ error
25323
+ );
25324
+ if (!(error instanceof ProviderCommandObservationUnavailableError) || !error.readRetryAllowed)
25325
+ throw error;
25326
+ }
25327
+ try {
25328
+ await delay3(100, void 0, { signal });
25329
+ } catch (error) {
25330
+ throw new ProviderCommandObservationUnavailableError(structuredClone(state.command), error);
25331
+ }
25332
+ }
24479
25333
  }
24480
25334
  async read(command, waitMs, signal) {
24481
25335
  SandboxProviderCommand.parse(command);
24482
25336
  if (command.sandboxId !== this.sandboxId)
24483
25337
  throw new Error("Modal command does not belong to this sandbox");
24484
25338
  if (command.kind === "modal-control-v1") return await this.legacy.read(command, waitMs, signal);
24485
- const next = structuredClone(command);
25339
+ return (await this.readNative(command, waitMs, signal)).output;
25340
+ }
25341
+ /** Native capture plumbing only. Raw bytes are acquired by the same joined
25342
+ * read/poll path as read(); no legacy locator or new command is admitted. */
25343
+ async readRaw(command, waitMs, signal) {
25344
+ return (await this.readNative(command, waitMs, signal)).raw;
25345
+ }
25346
+ async readNative(input, waitMs, signal) {
25347
+ const command = structuredClone(ModalRouterProviderCommand3.parse(input));
25348
+ if (command.sandboxId !== this.sandboxId)
25349
+ throw new Error("Modal command does not belong to this sandbox");
25350
+ if (!Number.isFinite(waitMs) || waitMs < 0 || waitMs > 5e4)
25351
+ throw new Error("Invalid Modal output read bounds");
25352
+ signal?.throwIfAborted();
25353
+ const stdout = command.streams.stdout;
25354
+ const stderr = command.streams.stderr;
25355
+ if (stdout.eof && stderr.eof && stdout.utf8Remainder === "" && stderr.utf8Remainder === "" && stdout.exitCode !== null && stdout.exitCode === stderr.exitCode) {
25356
+ return collectModalRawOutputPage(
25357
+ command,
25358
+ {
25359
+ stdout: { bytes: Buffer.alloc(0), eof: true },
25360
+ stderr: { bytes: Buffer.alloc(0), eof: true }
25361
+ },
25362
+ { source: "retained_terminal", code: stdout.exitCode }
25363
+ );
25364
+ }
25365
+ const budget = new AbortController();
25366
+ const abort = () => budget.abort(signal?.reason);
25367
+ signal?.addEventListener("abort", abort, { once: true });
25368
+ if (signal?.aborted) abort();
25369
+ const deadline = performance.now() + Math.max(1, waitMs);
25370
+ const timeout = setTimeout(
25371
+ () => budget.abort(new Error("Modal command read budget exhausted")),
25372
+ Math.max(1, waitMs) + 5e3
25373
+ );
25374
+ let lastError;
25375
+ try {
25376
+ for (let attempt = 0; attempt < 5; attempt++) {
25377
+ signal?.throwIfAborted();
25378
+ if (attempt > 0 && performance.now() >= deadline) break;
25379
+ try {
25380
+ return await this.readRouterPage(
25381
+ command,
25382
+ Math.min(Math.max(1, waitMs), Math.max(1, deadline - performance.now())),
25383
+ budget.signal,
25384
+ deadline
25385
+ );
25386
+ } catch (error) {
25387
+ signal?.throwIfAborted();
25388
+ if (!budget.signal.aborted && !isModalCommandObservationTransportError(error)) {
25389
+ if (classifyProviderSandboxFailure("modal", error).kind === "transient_transport")
25390
+ throw new ProviderCommandObservationUnavailableError(
25391
+ structuredClone(command),
25392
+ error,
25393
+ false
25394
+ );
25395
+ throw error;
25396
+ }
25397
+ lastError = error;
25398
+ if (budget.signal.aborted || performance.now() >= deadline || attempt === 4) break;
25399
+ try {
25400
+ await delay3(Math.min(100, Math.max(1, deadline - performance.now())), void 0, {
25401
+ signal: budget.signal
25402
+ });
25403
+ } catch {
25404
+ signal?.throwIfAborted();
25405
+ break;
25406
+ }
25407
+ }
25408
+ }
25409
+ throw new ProviderCommandObservationUnavailableError(structuredClone(command), lastError);
25410
+ } finally {
25411
+ clearTimeout(timeout);
25412
+ signal?.removeEventListener("abort", abort);
25413
+ }
25414
+ }
25415
+ async readRouterPage(command, waitMs, signal, deadline) {
24486
25416
  const cancellation = new AbortController();
24487
- const abort = () => cancellation.abort(signal?.reason);
25417
+ const lookupCancellation = new AbortController();
25418
+ const abort = () => {
25419
+ cancellation.abort(signal.reason);
25420
+ lookupCancellation.abort(signal.reason);
25421
+ };
24488
25422
  signal?.addEventListener("abort", abort, { once: true });
24489
25423
  if (signal?.aborted) abort();
25424
+ const lookupTimeout = setTimeout(
25425
+ () => lookupCancellation.abort(
25426
+ new ProviderCommandObservationUnavailableError(
25427
+ structuredClone(command),
25428
+ new Error("Modal command read access budget exhausted")
25429
+ )
25430
+ ),
25431
+ Math.max(1, deadline - performance.now())
25432
+ );
24490
25433
  try {
24491
- return await this.withRouter(command.taskId, cancellation.signal, async (router) => {
25434
+ return await this.withRouter(command.taskId, lookupCancellation.signal, async (router) => {
25435
+ clearTimeout(lookupTimeout);
25436
+ lookupCancellation.signal.throwIfAborted();
25437
+ signal.throwIfAborted();
25438
+ if (performance.now() >= deadline)
25439
+ throw new ProviderCommandObservationUnavailableError(
25440
+ structuredClone(command),
25441
+ new Error("Modal command read budget exhausted")
25442
+ );
25443
+ const remainingWait = Math.max(1, Math.min(waitMs, deadline - performance.now()));
24492
25444
  const operations = [
24493
25445
  ...["stdout", "stderr"].map(
24494
25446
  async (stream) => command.streams[stream].eof ? { bytes: Buffer.alloc(0), eof: true } : await router.read(
24495
25447
  command,
24496
25448
  stream,
24497
25449
  command.streams[stream].byteOffset,
24498
- waitMs,
25450
+ remainingWait,
24499
25451
  cancellation.signal
24500
25452
  )
24501
25453
  ),
@@ -24510,42 +25462,18 @@ var ModalCommandControl2 = class _ModalCommandControl {
24510
25462
  )
24511
25463
  );
24512
25464
  const failed = results.find((result) => result.status === "rejected");
24513
- if (failed?.status === "rejected") throw failed.reason;
25465
+ if (failed?.status === "rejected") throw cancellation.signal.reason ?? failed.reason;
24514
25466
  const stdout = results[0].value;
24515
25467
  const stderr = results[1].value;
24516
25468
  const exit = results[2].value;
24517
- const chunks = [];
24518
- for (const [stream, page] of [
24519
- ["stdout", stdout],
24520
- ["stderr", stderr]
24521
- ]) {
24522
- const old = command.streams[stream];
24523
- const decoded = decodePage(old.utf8Remainder, [page.bytes], page.eof);
24524
- const byteOffset = old.byteOffset + page.bytes.length;
24525
- if (!Number.isSafeInteger(byteOffset)) throw new Error("Modal output offset exhausted");
24526
- next.streams[stream] = {
24527
- byteOffset,
24528
- utf8Remainder: decoded.remainder,
24529
- eof: page.eof,
24530
- exitCode: page.eof ? exit : null
24531
- };
24532
- if (decoded.text)
24533
- chunks.push({
24534
- stream,
24535
- chunkId: `modal-router:${command.execId}:${stream}:${old.byteOffset}:${byteOffset}:${page.eof ? 1 : 0}`,
24536
- text: decoded.text
24537
- });
24538
- }
24539
- return {
24540
- command: next,
24541
- expected: structuredClone(command),
24542
- chunks,
24543
- exitCode: next.streams.stdout.eof && next.streams.stderr.eof ? exit : null,
24544
- providerExited: exit !== null,
24545
- streamFidelity: command.pty ? "merged" : "separate"
24546
- };
25469
+ return collectModalRawOutputPage(
25470
+ command,
25471
+ { stdout, stderr },
25472
+ { source: "router_poll", code: exit }
25473
+ );
24547
25474
  });
24548
25475
  } finally {
25476
+ clearTimeout(lookupTimeout);
24549
25477
  signal?.removeEventListener("abort", abort);
24550
25478
  }
24551
25479
  }
@@ -24569,7 +25497,7 @@ var ModalCommandControl2 = class _ModalCommandControl {
24569
25497
  import { ModalClient as ModalClient2, Sandbox } from "modal";
24570
25498
 
24571
25499
  // src/sandbox/providers/modal-create-boundary.ts
24572
- import { createHash as createHash7 } from "crypto";
25500
+ import { createHash as createHash8 } from "crypto";
24573
25501
  var CREATE_PATH = "/modal.client.ModalClient/SandboxCreate";
24574
25502
  var OPERATION_TAG = "opengeni_provider_create_operation_id";
24575
25503
  function modalCreateOperationName(operationId) {
@@ -24607,7 +25535,7 @@ function createModalProviderCreateBoundary(input) {
24607
25535
  name,
24608
25536
  appId: request.appId,
24609
25537
  imageId: request.definition.imageId,
24610
- requestSha256: createHash7("sha256").update(JSON.stringify(wireRequest)).digest("hex")
25538
+ requestSha256: createHash8("sha256").update(JSON.stringify(wireRequest)).digest("hex")
24611
25539
  };
24612
25540
  attempted = true;
24613
25541
  await input.beforeDispatch(intent);
@@ -25373,14 +26301,14 @@ var modalProvider = {
25373
26301
  if (!imageId) {
25374
26302
  throw new Error("Modal provider image snapshot returned no immutable image id");
25375
26303
  }
25376
- const binding = await resolveModalCheckpointProviderBindingForSession(settings, session);
26304
+ const binding2 = await resolveModalCheckpointProviderBindingForSession(settings, session);
25377
26305
  return {
25378
26306
  provider: "modal",
25379
26307
  backend: "modal",
25380
26308
  imageId,
25381
26309
  imageDigest: null,
25382
- providerBindingKey: binding.key,
25383
- providerBinding: binding.binding
26310
+ providerBindingKey: binding2.key,
26311
+ providerBinding: binding2.binding
25384
26312
  };
25385
26313
  } finally {
25386
26314
  snapshotHandle.detach?.();
@@ -25558,7 +26486,7 @@ async function resolveModalCheckpointProviderBindingForSession(settings, session
25558
26486
  throw new Error("Pinned Modal session no longer exposes its authenticated checkpoint identity");
25559
26487
  }
25560
26488
  const pending = modalCheckpointProviderBindingForClient(settings, modal).then(
25561
- (binding) => canonicalModalCheckpointProviderBinding(binding)
26489
+ (binding2) => canonicalModalCheckpointProviderBinding(binding2)
25562
26490
  );
25563
26491
  modalSessionCheckpointBindings.set(session, pending);
25564
26492
  try {
@@ -25575,8 +26503,8 @@ async function modalSessionMatchesCheckpointProviderBinding(settings, session, e
25575
26503
  async function resolveModalCheckpointProviderBinding(settings, createClient = createModalClient) {
25576
26504
  const modal = await createClient(settings);
25577
26505
  try {
25578
- const binding = await modalCheckpointProviderBindingForClient(settings, modal);
25579
- return canonicalModalCheckpointProviderBinding(binding);
26506
+ const binding2 = await modalCheckpointProviderBindingForClient(settings, modal);
26507
+ return canonicalModalCheckpointProviderBinding(binding2);
25580
26508
  } finally {
25581
26509
  modal.close();
25582
26510
  }
@@ -25586,10 +26514,10 @@ async function findModalProviderCreateReceipt(settings, attempt, createClient =
25586
26514
  throw new Error("Modal create recovery requires exact persisted provider identity");
25587
26515
  const modal = await createClient(settings);
25588
26516
  try {
25589
- const binding = canonicalModalCheckpointProviderBinding(
26517
+ const binding2 = canonicalModalCheckpointProviderBinding(
25590
26518
  await modalCheckpointProviderBindingForClient(settings, modal)
25591
26519
  );
25592
- if (binding?.key !== attempt.providerBindingKey)
26520
+ if (binding2?.key !== attempt.providerBindingKey)
25593
26521
  throw new Error("Modal create recovery refused a different authenticated namespace");
25594
26522
  let beforeTimestamp;
25595
26523
  const found = /* @__PURE__ */ new Set();
@@ -25624,13 +26552,13 @@ async function resolveModalCheckpointProviderBindingForLiveSandbox(settings, san
25624
26552
  if (!sandboxId) throw new Error("Modal live-sandbox identity requires a sandbox id");
25625
26553
  const modal = await createClient(settings);
25626
26554
  try {
25627
- const binding = await modalCheckpointProviderBindingForClient(settings, modal);
26555
+ const binding2 = await modalCheckpointProviderBindingForClient(settings, modal);
25628
26556
  const sandbox = await modal.sandboxes.fromId(sandboxId);
25629
26557
  const exitCode = await sandbox.poll();
25630
26558
  if (exitCode !== null) {
25631
26559
  throw new Error(`Modal sandbox ${sandboxId} is no longer running`);
25632
26560
  }
25633
- return canonicalModalCheckpointProviderBinding(binding);
26561
+ return canonicalModalCheckpointProviderBinding(binding2);
25634
26562
  } finally {
25635
26563
  modal.close();
25636
26564
  }
@@ -25639,10 +26567,10 @@ async function inspectModalSandboxLifecycle(settings, sandboxId, expectedBinding
25639
26567
  if (!sandboxId) throw new Error("Modal lifecycle inspection requires a sandbox id");
25640
26568
  const modal = await createClient(settings);
25641
26569
  try {
25642
- const binding = canonicalModalCheckpointProviderBinding(
26570
+ const binding2 = canonicalModalCheckpointProviderBinding(
25643
26571
  await modalCheckpointProviderBindingForClient(settings, modal)
25644
26572
  );
25645
- if (expectedBindingKey && binding.key !== expectedBindingKey) {
26573
+ if (expectedBindingKey && binding2.key !== expectedBindingKey) {
25646
26574
  throw new Error(
25647
26575
  "Modal lifecycle inspection refused because the configured credential workspace changed"
25648
26576
  );
@@ -25652,20 +26580,20 @@ async function inspectModalSandboxLifecycle(settings, sandboxId, expectedBinding
25652
26580
  const exitCode = await sandbox.poll();
25653
26581
  return exitCode === null ? {
25654
26582
  status: "running",
25655
- providerBindingKey: binding.key,
25656
- providerBinding: binding.binding
26583
+ providerBindingKey: binding2.key,
26584
+ providerBinding: binding2.binding
25657
26585
  } : {
25658
26586
  status: "terminated",
25659
26587
  exitCode,
25660
- providerBindingKey: binding.key,
25661
- providerBinding: binding.binding
26588
+ providerBindingKey: binding2.key,
26589
+ providerBinding: binding2.binding
25662
26590
  };
25663
26591
  } catch (error) {
25664
26592
  if (isModalNotFoundError(error)) {
25665
26593
  return {
25666
26594
  status: "not_found",
25667
- providerBindingKey: binding.key,
25668
- providerBinding: binding.binding
26595
+ providerBindingKey: binding2.key,
26596
+ providerBinding: binding2.binding
25669
26597
  };
25670
26598
  }
25671
26599
  throw error;
@@ -25678,8 +26606,8 @@ async function deleteModalCheckpointSnapshot(settings, expectedBindingKey, snaps
25678
26606
  if (!snapshotId) throw new Error("Modal checkpoint deletion requires a snapshot id");
25679
26607
  const modal = await createClient(settings);
25680
26608
  try {
25681
- const binding = await modalCheckpointProviderBindingForClient(settings, modal);
25682
- const identity = canonicalModalCheckpointProviderBinding(binding);
26609
+ const binding2 = await modalCheckpointProviderBindingForClient(settings, modal);
26610
+ const identity = canonicalModalCheckpointProviderBinding(binding2);
25683
26611
  if (expectedBindingKey !== identity.key) {
25684
26612
  throw new Error(
25685
26613
  "Modal checkpoint deletion refused because the configured credential workspace changed"
@@ -25716,10 +26644,10 @@ async function terminateModalSandboxById(settings, sandboxId, createClient = cre
25716
26644
  const modal = await createClient(settings);
25717
26645
  try {
25718
26646
  if (expectedProviderBindingKey) {
25719
- const binding = canonicalModalCheckpointProviderBinding(
26647
+ const binding2 = canonicalModalCheckpointProviderBinding(
25720
26648
  await modalCheckpointProviderBindingForClient(settings, modal)
25721
26649
  );
25722
- if (binding?.key !== expectedProviderBindingKey)
26650
+ if (binding2?.key !== expectedProviderBindingKey)
25723
26651
  throw new Error("Modal create cleanup refused a different authenticated namespace");
25724
26652
  }
25725
26653
  const sandbox = await modal.sandboxes.fromId(sandboxId);
@@ -25895,7 +26823,7 @@ import {
25895
26823
  SandboxApiException,
25896
26824
  createDefaultAdapterFactory
25897
26825
  } from "@alibaba-group/opensandbox";
25898
- import { createHash as createHash8, randomUUID as randomUUID7 } from "crypto";
26826
+ import { createHash as createHash9, randomUUID as randomUUID7 } from "crypto";
25899
26827
  import { lstat as lstat6, readFile as readLocalFile, readdir as readdir6 } from "fs/promises";
25900
26828
  import { posix as posix4 } from "path";
25901
26829
 
@@ -26104,7 +27032,7 @@ function canonicalBaseUrl(value) {
26104
27032
  return url.toString().replace(/\/$/u, "");
26105
27033
  }
26106
27034
  function providerBindingHash(baseUrl) {
26107
- return createHash8("sha256").update(canonicalBaseUrl(baseUrl)).digest("hex");
27035
+ return createHash9("sha256").update(canonicalBaseUrl(baseUrl)).digest("hex");
26108
27036
  }
26109
27037
  function connectionOptions(input) {
26110
27038
  return {
@@ -26241,7 +27169,7 @@ function commandForArgs(args) {
26241
27169
  if (!requestedShell) return args.cmd;
26242
27170
  return `${shellQuote(requestedShell)}${args.login === false ? "" : " -l"} -c ${shellQuote(args.cmd)}`;
26243
27171
  }
26244
- function delay3(ms) {
27172
+ function delay4(ms) {
26245
27173
  return new Promise((resolve7) => setTimeout(resolve7, Math.max(0, ms)));
26246
27174
  }
26247
27175
  function consumeProcessOutput(process2) {
@@ -26600,7 +27528,7 @@ var OpenSandboxSession = class {
26600
27528
  }
26601
27529
  } catch {
26602
27530
  }
26603
- await delay3(DEFAULT_WRITE_STDIN_YIELD_TIME_MS3);
27531
+ await delay4(DEFAULT_WRITE_STDIN_YIELD_TIME_MS3);
26604
27532
  }
26605
27533
  }
26606
27534
  async execToCompletion(args) {
@@ -26641,7 +27569,7 @@ var OpenSandboxSession = class {
26641
27569
  const yieldTimeMs = requestedYieldMs >= DEFAULT_EXEC_YIELD_TIME_MS3 ? requestedYieldMs + COMMAND_API_SETTLE_GRACE_MS : requestedYieldMs;
26642
27570
  const outcome = await Promise.race([
26643
27571
  process2.completed.then((value) => ({ done: true, value })),
26644
- delay3(yieldTimeMs).then(() => ({ done: false }))
27572
+ delay4(yieldTimeMs).then(() => ({ done: false }))
26645
27573
  ]);
26646
27574
  const consumed = consumeProcessOutput(process2);
26647
27575
  const output = truncateOutput(consumed.output, args.maxOutputTokens);
@@ -26753,7 +27681,7 @@ var OpenSandboxSession = class {
26753
27681
  }
26754
27682
  const outcome = await Promise.race([
26755
27683
  process2.completed.then((value) => ({ done: true, value })),
26756
- delay3(args.yieldTimeMs ?? DEFAULT_WRITE_STDIN_YIELD_TIME_MS3).then(() => ({
27684
+ delay4(args.yieldTimeMs ?? DEFAULT_WRITE_STDIN_YIELD_TIME_MS3).then(() => ({
26757
27685
  done: false
26758
27686
  }))
26759
27687
  ]);
@@ -33536,147 +34464,6 @@ function negotiateCapabilities(ctx) {
33536
34464
  };
33537
34465
  }
33538
34466
 
33539
- // src/sandbox/provider-errors.ts
33540
- var GRPC_TRANSIENT = /* @__PURE__ */ new Set([1, 2, 4, 13, 14]);
33541
- var TRANSIENT_CODES = /* @__PURE__ */ new Set([
33542
- "CANCELLED",
33543
- "UNKNOWN",
33544
- "DEADLINE_EXCEEDED",
33545
- "INTERNAL",
33546
- "UNAVAILABLE",
33547
- "ECONNRESET",
33548
- "ECONNREFUSED",
33549
- "ETIMEDOUT",
33550
- "EAI_AGAIN",
33551
- "ENOTFOUND"
33552
- ]);
33553
- var NOT_FOUND_CODES = /* @__PURE__ */ new Set(["404", "NOT_FOUND", "RESOURCE_NOT_FOUND", "SANDBOX_NOT_FOUND"]);
33554
- var SAFE_CODE = /^[A-Z0-9._:-]{1,64}$/;
33555
- function safeRead(record, key) {
33556
- try {
33557
- return Reflect.get(record, key);
33558
- } catch {
33559
- return void 0;
33560
- }
33561
- }
33562
- function collectSignals(value) {
33563
- const out = { numbers: [], codes: [], messages: [] };
33564
- const seen = /* @__PURE__ */ new Set();
33565
- const visit = (current, depth) => {
33566
- if (depth > 3 || current === null || current === void 0) return;
33567
- if (typeof current === "string") {
33568
- if (current.length <= 512) out.messages.push(current);
33569
- return;
33570
- }
33571
- if (typeof current !== "object" || seen.has(current)) return;
33572
- seen.add(current);
33573
- for (const key of [
33574
- "status",
33575
- "statusCode",
33576
- "httpStatus",
33577
- "httpStatusCode",
33578
- "responseStatus",
33579
- "errorCode",
33580
- "code"
33581
- ]) {
33582
- const signal = safeRead(current, key);
33583
- if (typeof signal === "number" && Number.isFinite(signal)) out.numbers.push(signal);
33584
- if (typeof signal === "string") {
33585
- const code = signal.trim().toUpperCase();
33586
- if (SAFE_CODE.test(code)) out.codes.push(code);
33587
- }
33588
- }
33589
- for (const key of ["name", "message", "details", "cause"]) {
33590
- const signal = safeRead(current, key);
33591
- if (typeof signal === "string" && signal.length <= 512) out.messages.push(signal);
33592
- else visit(signal, depth + 1);
33593
- }
33594
- visit(safeRead(current, "response"), depth + 1);
33595
- visit(safeRead(current, "error"), depth + 1);
33596
- };
33597
- visit(value, 0);
33598
- return out;
33599
- }
33600
- function safeDiagnostic(signals) {
33601
- const code = signals.codes.find(Boolean);
33602
- const numeric = signals.numbers.find((value) => Number.isFinite(value));
33603
- return [code ? `code=${code}` : "", numeric !== void 0 ? `status=${numeric}` : ""].filter(Boolean).join(" ");
33604
- }
33605
- function hasTransientSignal(signals) {
33606
- return signals.codes.some((code) => TRANSIENT_CODES.has(code)) || signals.numbers.some((status4) => GRPC_TRANSIENT.has(status4));
33607
- }
33608
- function hasModalTerminalSandboxMessage(signals) {
33609
- return signals.messages.some(
33610
- (message) => /^Modal sandbox [A-Za-z0-9_-]+ is no longer running\.$/.test(message) || /^Modal sandbox [A-Za-z0-9_-]+ not found \(has been terminated\)$/.test(message)
33611
- );
33612
- }
33613
- function hasUnixLocalTerminalWorkspaceMessage(signals) {
33614
- return signals.messages.includes(
33615
- "UnixLocal sandbox workspace is unavailable and no local snapshot could be restored."
33616
- );
33617
- }
33618
- function hasDockerTerminalWorkspaceMessage(signals) {
33619
- return signals.messages.includes(
33620
- "Docker sandbox resources are unavailable and no local snapshot could be restored."
33621
- );
33622
- }
33623
- function hasCloudflareTerminalSandboxMessage(signals) {
33624
- return signals.messages.some(
33625
- (message) => /^Cloudflare sandbox [A-Za-z0-9._:-]+ is no longer running\.$/.test(message)
33626
- );
33627
- }
33628
- function classifyProviderSandboxFailure(backendId, error) {
33629
- if (backendId === "selfhosted" || !error) {
33630
- return { kind: "other", diagnostic: "selfhosted-or-empty" };
33631
- }
33632
- const signals = collectSignals(error);
33633
- const diagnostic = safeDiagnostic(signals) || "unclassified_provider_failure";
33634
- if (hasTransientSignal(signals)) {
33635
- return { kind: "transient_transport", diagnostic };
33636
- }
33637
- if (signals.numbers.some((status4) => status4 === 404) || signals.codes.some((code) => NOT_FOUND_CODES.has(code))) {
33638
- return { kind: "not_found", diagnostic };
33639
- }
33640
- if (backendId === "modal" && hasModalTerminalSandboxMessage(signals)) {
33641
- return {
33642
- kind: "not_found",
33643
- diagnostic: diagnostic === "unclassified_provider_failure" ? "modal_terminal_message" : `${diagnostic} modal_terminal_message`
33644
- };
33645
- }
33646
- if (backendId === "cloudflare" && hasCloudflareTerminalSandboxMessage(signals)) {
33647
- return {
33648
- kind: "not_found",
33649
- diagnostic: diagnostic === "unclassified_provider_failure" ? "cloudflare_terminal_message" : `${diagnostic} cloudflare_terminal_message`
33650
- };
33651
- }
33652
- if ((backendId === "local" || backendId === "unix_local") && hasUnixLocalTerminalWorkspaceMessage(signals)) {
33653
- return {
33654
- kind: "not_found",
33655
- diagnostic: diagnostic === "unclassified_provider_failure" ? "unix_local_workspace_missing" : `${diagnostic} unix_local_workspace_missing`
33656
- };
33657
- }
33658
- if (backendId === "docker" && hasDockerTerminalWorkspaceMessage(signals)) {
33659
- return {
33660
- kind: "not_found",
33661
- diagnostic: diagnostic === "unclassified_provider_failure" ? "docker_resources_missing" : `${diagnostic} docker_resources_missing`
33662
- };
33663
- }
33664
- return { kind: "other", diagnostic };
33665
- }
33666
- function isProviderSandboxNotFoundError2(backendId, error) {
33667
- return classifyProviderSandboxFailure(backendId, error).kind === "not_found";
33668
- }
33669
- function isProviderSandboxGoneDuringRoutedOperation(backendId, error) {
33670
- if (backendId === "selfhosted" || !error) return false;
33671
- const signals = collectSignals(error);
33672
- if (hasTransientSignal(signals)) return false;
33673
- if (signals.codes.includes("SANDBOX_NOT_FOUND")) return true;
33674
- return backendId === "modal" && hasModalTerminalSandboxMessage(signals);
33675
- }
33676
- function isProviderSandboxTransientError(backendId, error) {
33677
- return classifyProviderSandboxFailure(backendId, error).kind === "transient_transport";
33678
- }
33679
-
33680
34467
  // src/protocol-json.ts
33681
34468
  var MAX_PROTOCOL_JSON_DEPTH = 512;
33682
34469
  var UnsupportedProtocolJsonValueError = class extends TypeError {
@@ -33920,6 +34707,262 @@ function repairSerializedRunStateExposedPorts(serializedRunState) {
33920
34707
  // src/sandbox/index.ts
33921
34708
  import { collectSandboxEnvironment as collectSandboxEnvironment2, parseExposedPorts as parseExposedPorts2 } from "@opengeni/config";
33922
34709
 
34710
+ // src/sandbox/providers/modal-native-create-preparation.ts
34711
+ import { createHash as createHash10 } from "crypto";
34712
+ import { types } from "util";
34713
+ import { canonicalModalCheckpointProviderBinding as canonicalModalCheckpointProviderBinding2 } from "@opengeni/contracts";
34714
+ var uuid = external_exports.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/u);
34715
+ var empty = external_exports.object({}).strict();
34716
+ var binding = external_exports.object({
34717
+ version: external_exports.literal(1),
34718
+ serverUrl: external_exports.string().max(2048),
34719
+ workspaceName: external_exports.string().min(1).max(200),
34720
+ environment: external_exports.string().max(200)
34721
+ }).strict();
34722
+ var blueprint = external_exports.object({
34723
+ version: external_exports.literal(1),
34724
+ adapterId: external_exports.literal("modal-native-fresh-creator-reservation-v1"),
34725
+ create: external_exports.object({
34726
+ operationId: uuid,
34727
+ appId: external_exports.string().regex(/^ap-[A-Za-z0-9_-]{1,200}$/u),
34728
+ imageId: external_exports.string().regex(/^im-[A-Za-z0-9_-]{1,200}$/u),
34729
+ cpu: external_exports.number().positive().max(128).refine((value) => {
34730
+ const milli = Math.trunc(1e3 * value);
34731
+ return Number.isSafeInteger(milli) && milli >= 1 && milli / 1e3 === value;
34732
+ }),
34733
+ memoryMiB: external_exports.number().int().safe().min(128).max(1048576),
34734
+ timeoutSeconds: external_exports.number().int().safe().min(1).max(86400),
34735
+ env: empty,
34736
+ mounts: external_exports.tuple([])
34737
+ }).strict(),
34738
+ restore: external_exports.null(),
34739
+ readiness: external_exports.object({
34740
+ operationId: uuid,
34741
+ execId: uuid,
34742
+ commandArgs: external_exports.tuple([external_exports.literal("/bin/true")]),
34743
+ workdir: external_exports.literal("/tmp"),
34744
+ env: empty
34745
+ }).strict(),
34746
+ publishOperationId: uuid,
34747
+ cleanup: external_exports.object({ operationId: uuid, requires: external_exports.literal("physical-terminal-proof") }).strict()
34748
+ }).strict();
34749
+ var specSchema = external_exports.object({
34750
+ version: external_exports.literal(1),
34751
+ recipeId: external_exports.literal("modal-native-fresh-v1"),
34752
+ recipeRevision: external_exports.literal(1),
34753
+ createWorkdir: external_exports.literal("/tmp"),
34754
+ entrypoint: external_exports.tuple([external_exports.literal("sleep"), external_exports.literal("infinity")]),
34755
+ origin: external_exports.object({
34756
+ version: external_exports.literal(1),
34757
+ planId: uuid,
34758
+ creatorId: uuid,
34759
+ accountId: uuid,
34760
+ workspaceId: uuid,
34761
+ sessionId: uuid,
34762
+ turnId: uuid,
34763
+ attemptId: uuid,
34764
+ executionGeneration: external_exports.number().int().positive().safe(),
34765
+ triggerEventId: uuid,
34766
+ sandboxGroupId: uuid,
34767
+ routeKind: external_exports.literal("home"),
34768
+ routeTargetId: external_exports.null(),
34769
+ routeEpoch: external_exports.number().int().nonnegative().safe(),
34770
+ providerBindingKey: external_exports.string().min(1).max(4096),
34771
+ providerBinding: binding
34772
+ }).strict(),
34773
+ blueprint
34774
+ }).strict();
34775
+ var normalization = {
34776
+ recipeId: "modal-native-fresh-v1",
34777
+ recipeRevision: 1,
34778
+ schema: "modal.client.ModalClient/SandboxCreate",
34779
+ encoding: "modal-create-json-v1",
34780
+ sdkVersion: "0.9.0",
34781
+ // Reviewed installed source; this is a pinned normalization fingerprint,
34782
+ // not a runtime file read or an attestation of transmitted protobuf bytes.
34783
+ sdkSourceSha256: "bb830ded1925e1d927d1fc221b2329d961f9a57eafdd9a85bf13fb7cfc982599",
34784
+ entrypoint: ["sleep", "infinity"],
34785
+ createWorkdir: "/tmp",
34786
+ env: {},
34787
+ mounts: [],
34788
+ restore: null,
34789
+ idleTimeout: "unset",
34790
+ gpu: "unset",
34791
+ gpuProto: { type: 0, count: 0, gpuType: "" },
34792
+ cpuLimit: "unset",
34793
+ memoryLimit: "unset",
34794
+ pty: "unset",
34795
+ regions: "unset",
34796
+ proxy: "unset",
34797
+ readinessProbe: "unset",
34798
+ environmentVariables: "unset",
34799
+ network: {
34800
+ access: "OPEN",
34801
+ outboundCidrs: [],
34802
+ outboundDomains: [],
34803
+ inboundCidrs: [],
34804
+ i6pn: false
34805
+ },
34806
+ volumes: [],
34807
+ cloudBucketMounts: [],
34808
+ secrets: [],
34809
+ ports: [],
34810
+ cloud: "",
34811
+ verbose: false,
34812
+ includeOidcIdentityToken: false,
34813
+ experimentalOptions: {},
34814
+ experimentalOptionsV2: {},
34815
+ customDomain: ""
34816
+ };
34817
+ var sha2562 = (value) => createHash10("sha256").update(value).digest("hex");
34818
+ var compilerFingerprint = sha2562(JSON.stringify(normalization));
34819
+ function freeze(value) {
34820
+ if (value !== null && typeof value === "object") {
34821
+ for (const child of Object.values(value)) freeze(child);
34822
+ Object.freeze(value);
34823
+ }
34824
+ return value;
34825
+ }
34826
+ freeze(normalization);
34827
+ function ownData(value, depth = 0) {
34828
+ if (depth > 12) throw new Error("Unsupported native fresh-create specification");
34829
+ if (value === null || typeof value === "string" || typeof value === "boolean") return;
34830
+ if (typeof value === "number") {
34831
+ if (Number.isFinite(value) && !Object.is(value, -0)) return;
34832
+ throw new Error("Unsupported native fresh-create specification");
34833
+ }
34834
+ if (typeof value !== "object" || types.isProxy(value))
34835
+ throw new Error("Unsupported native fresh-create specification");
34836
+ const array = Array.isArray(value);
34837
+ const prototype = Object.getPrototypeOf(value);
34838
+ if (array ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null)
34839
+ throw new Error("Unsupported native fresh-create specification");
34840
+ const descriptors = Object.getOwnPropertyDescriptors(value);
34841
+ const keys = Reflect.ownKeys(descriptors).filter((key) => !(array && key === "length"));
34842
+ if (array && keys.length !== value.length)
34843
+ throw new Error("Unsupported native fresh-create specification");
34844
+ for (const key of keys) {
34845
+ if (typeof key !== "string" || array && !/^(0|[1-9][0-9]*)$/u.test(key))
34846
+ throw new Error("Unsupported native fresh-create specification");
34847
+ const descriptor = descriptors[key];
34848
+ if (!descriptor.enumerable || !("value" in descriptor))
34849
+ throw new Error("Unsupported native fresh-create specification");
34850
+ ownData(descriptor.value, depth + 1);
34851
+ }
34852
+ }
34853
+ function normalizedRequest(spec) {
34854
+ const create = spec.blueprint.create;
34855
+ return {
34856
+ appId: create.appId,
34857
+ definition: {
34858
+ entrypointArgs: [...spec.entrypoint],
34859
+ mountIds: [],
34860
+ imageId: create.imageId,
34861
+ secretIds: [],
34862
+ resources: {
34863
+ memoryMb: create.memoryMiB,
34864
+ milliCpu: Math.trunc(1e3 * create.cpu),
34865
+ gpuConfig: { type: 0, count: 0, gpuType: "" },
34866
+ memoryMbMax: 0,
34867
+ ephemeralDiskMb: 0,
34868
+ milliCpuMax: 0,
34869
+ rdma: false
34870
+ },
34871
+ cloudProvider: 0,
34872
+ timeoutSecs: create.timeoutSeconds * 1e3 / 1e3,
34873
+ workdir: spec.createWorkdir,
34874
+ nfsMounts: [],
34875
+ runtimeDebug: false,
34876
+ blockNetwork: false,
34877
+ s3Mounts: [],
34878
+ cloudBucketMounts: [],
34879
+ volumeMounts: [],
34880
+ ptyInfo: void 0,
34881
+ schedulerPlacement: void 0,
34882
+ workerId: "",
34883
+ openPorts: { ports: [] },
34884
+ i6pnEnabled: false,
34885
+ networkAccess: { networkAccessType: 1, allowedCidrs: [], allowedDomains: [] },
34886
+ proxyId: void 0,
34887
+ enableSnapshot: false,
34888
+ snapshotVersion: void 0,
34889
+ cloudProviderStr: "",
34890
+ runscRuntimeVersion: void 0,
34891
+ runtime: void 0,
34892
+ verbose: false,
34893
+ name: `opengeni-create-${create.operationId}`,
34894
+ experimentalOptions: {},
34895
+ experimentalOptionsV2: {},
34896
+ preloadPathPrefixes: [],
34897
+ idleTimeoutSecs: void 0,
34898
+ directSandboxCommandsEnabled: false,
34899
+ RestoreInstanceType: "",
34900
+ customDomain: "",
34901
+ includeOidcIdentityToken: false,
34902
+ readinessProbe: void 0,
34903
+ inboundCidrAllowlist: [],
34904
+ environmentVariables: void 0
34905
+ },
34906
+ environmentName: "",
34907
+ tags: [{ tagName: "opengeni_provider_create_operation_id", tagValue: create.operationId }]
34908
+ };
34909
+ }
34910
+ var prepared = /* @__PURE__ */ new WeakMap();
34911
+ function compileNativeFreshCreate(input) {
34912
+ try {
34913
+ ownData(input);
34914
+ const copied = structuredClone(input);
34915
+ if (Buffer.byteLength(JSON.stringify(copied)) > 32768)
34916
+ throw new Error("Unsupported native fresh-create specification");
34917
+ const spec = specSchema.parse(copied);
34918
+ const { origin, blueprint: plan } = spec;
34919
+ const canonical = canonicalModalCheckpointProviderBinding2(origin.providerBinding);
34920
+ const serverUrl = new URL(origin.providerBinding.serverUrl);
34921
+ if (!canonical || canonical.key !== origin.providerBindingKey || ["serverUrl", "workspaceName", "environment"].some(
34922
+ (field) => canonical.binding[field] !== origin.providerBinding[field]
34923
+ ) || !["https:", "http:"].includes(serverUrl.protocol) || serverUrl.username || serverUrl.password || serverUrl.search || serverUrl.hash || origin.creatorId === origin.attemptId)
34924
+ throw new Error("Unsupported native fresh-create specification");
34925
+ const ids = [
34926
+ origin.planId,
34927
+ origin.creatorId,
34928
+ plan.create.operationId,
34929
+ plan.readiness.operationId,
34930
+ plan.readiness.execId,
34931
+ plan.publishOperationId,
34932
+ plan.cleanup.operationId
34933
+ ];
34934
+ if (new Set(ids).size !== 7) throw new Error("Unsupported native fresh-create specification");
34935
+ const request = normalizedRequest(spec);
34936
+ const requestJson = JSON.stringify(request);
34937
+ const compilation = freeze({
34938
+ version: 1,
34939
+ recipeId: "modal-native-fresh-v1",
34940
+ recipeRevision: 1,
34941
+ compilerFingerprint,
34942
+ normalization,
34943
+ spec,
34944
+ normalizedRequest: request,
34945
+ requestJson,
34946
+ request: {
34947
+ encoding: "modal-create-json-v1",
34948
+ sha256: sha2562(requestJson),
34949
+ byteLength: Buffer.byteLength(requestJson),
34950
+ encoderFingerprint: compilerFingerprint
34951
+ }
34952
+ });
34953
+ const handle = Object.freeze({});
34954
+ prepared.set(handle, compilation);
34955
+ return handle;
34956
+ } catch {
34957
+ throw new Error("Unsupported native fresh-create specification");
34958
+ }
34959
+ }
34960
+ function describeNativeFreshCreate(handle) {
34961
+ const compilation = prepared.get(handle);
34962
+ if (!compilation) throw new Error("Unknown native fresh-create preparation");
34963
+ return compilation;
34964
+ }
34965
+
33923
34966
  // src/sandbox/display-stack.ts
33924
34967
  import {
33925
34968
  DESKTOP_STREAM_PORT as DESKTOP_STREAM_PORT5,
@@ -34827,7 +35870,7 @@ function shellQuote6(value) {
34827
35870
  }
34828
35871
 
34829
35872
  // src/sandbox/browser-control-client.ts
34830
- import { createHash as createHash9, randomUUID as randomUUID8 } from "crypto";
35873
+ import { createHash as createHash11, randomUUID as randomUUID8 } from "crypto";
34831
35874
  import { posix as posixPath2 } from "path";
34832
35875
  import { parseBrowserFrameMetadata } from "@opengeni/sdk";
34833
35876
  import {
@@ -35099,13 +36142,13 @@ var BrowserControlClient = class {
35099
36142
  };
35100
36143
  }
35101
36144
  async endSession(reference, options) {
35102
- const binding = parseReference(reference);
36145
+ const binding2 = parseReference(reference);
35103
36146
  const data = await this.requestJson({
35104
36147
  method: "POST",
35105
- path: `/v1/browser-sessions/${binding.browserSessionId}/end`,
36148
+ path: `/v1/browser-sessions/${binding2.browserSessionId}/end`,
35106
36149
  token: this.adminToken,
35107
36150
  body: {
35108
- controllerGeneration: binding.controllerGeneration,
36151
+ controllerGeneration: binding2.controllerGeneration,
35109
36152
  removeState: options.removeState
35110
36153
  }
35111
36154
  });
@@ -35114,13 +36157,13 @@ var BrowserControlClient = class {
35114
36157
  }
35115
36158
  }
35116
36159
  async endComputerSession(reference, options) {
35117
- const binding = parseComputerReference(reference);
36160
+ const binding2 = parseComputerReference(reference);
35118
36161
  const data = await this.requestJson({
35119
36162
  method: "POST",
35120
- path: `/v1/computer-sessions/${binding.computerSessionId}/end`,
36163
+ path: `/v1/computer-sessions/${binding2.computerSessionId}/end`,
35121
36164
  token: this.adminToken,
35122
36165
  body: {
35123
- controllerGeneration: binding.controllerGeneration,
36166
+ controllerGeneration: binding2.controllerGeneration,
35124
36167
  removeState: options.removeState
35125
36168
  }
35126
36169
  });
@@ -35131,16 +36174,16 @@ var BrowserControlClient = class {
35131
36174
  }
35132
36175
  }
35133
36176
  async createViewGrant(reference, input) {
35134
- const binding = parseReference(reference);
36177
+ const binding2 = parseReference(reference);
35135
36178
  const grantId = requireUuid(input.grantId, "view grant id");
35136
36179
  const expiresAt = timestamp(input.expiresAt, "view grant expiry");
35137
36180
  const data = await this.requestJson({
35138
36181
  method: "POST",
35139
- path: `/v1/browser-sessions/${binding.browserSessionId}/view-grants`,
36182
+ path: `/v1/browser-sessions/${binding2.browserSessionId}/view-grants`,
35140
36183
  token: this.adminToken,
35141
36184
  body: {
35142
36185
  grantId,
35143
- controllerGeneration: binding.controllerGeneration,
36186
+ controllerGeneration: binding2.controllerGeneration,
35144
36187
  token: requireToken(input.token, "view grant token"),
35145
36188
  expiresAt
35146
36189
  }
@@ -35166,16 +36209,16 @@ var BrowserControlClient = class {
35166
36209
  };
35167
36210
  }
35168
36211
  async createComputerViewGrant(reference, input) {
35169
- const binding = parseComputerReference(reference);
36212
+ const binding2 = parseComputerReference(reference);
35170
36213
  const grantId = requireUuid(input.grantId, "computer view grant id");
35171
36214
  const expiresAt = timestamp(input.expiresAt, "computer view grant expiry");
35172
36215
  const data = await this.requestJson({
35173
36216
  method: "POST",
35174
- path: `/v1/computer-sessions/${binding.computerSessionId}/view-grants`,
36217
+ path: `/v1/computer-sessions/${binding2.computerSessionId}/view-grants`,
35175
36218
  token: this.adminToken,
35176
36219
  body: {
35177
36220
  grantId,
35178
- controllerGeneration: binding.controllerGeneration,
36221
+ controllerGeneration: binding2.controllerGeneration,
35179
36222
  token: requireToken(input.token, "computer view grant token"),
35180
36223
  expiresAt
35181
36224
  }
@@ -35227,7 +36270,7 @@ var BrowserControlClient = class {
35227
36270
  return new ComputerControlSessionClient(this, input);
35228
36271
  }
35229
36272
  async frameStreamUrl(reference, targetId, stream = {}) {
35230
- const binding = parseReference(reference);
36273
+ const binding2 = parseReference(reference);
35231
36274
  if (!this.session.resolveExposedPort) {
35232
36275
  throw new BrowserControlUnsupportedError(
35233
36276
  "browser placement cannot expose its live-frame port"
@@ -35236,12 +36279,12 @@ var BrowserControlClient = class {
35236
36279
  const endpoint = await this.session.resolveExposedPort(this.port);
35237
36280
  const path = joinControllerPath(
35238
36281
  endpoint.path,
35239
- `/v1/browser-sessions/${binding.browserSessionId}/targets/${encodeURIComponent(requireOpaqueId(targetId, "target id"))}/frames`
36282
+ `/v1/browser-sessions/${binding2.browserSessionId}/targets/${encodeURIComponent(requireOpaqueId(targetId, "target id"))}/frames`
35240
36283
  );
35241
36284
  return frameStreamUrlWithOptions(buildStreamUrl({ ...endpoint, path }), stream);
35242
36285
  }
35243
36286
  async computerFrameStreamUrl(reference, targetId, stream = {}) {
35244
- const binding = parseComputerReference(reference);
36287
+ const binding2 = parseComputerReference(reference);
35245
36288
  if (!this.session.resolveExposedPort) {
35246
36289
  throw new BrowserControlUnsupportedError(
35247
36290
  "computer placement cannot expose its live-frame port"
@@ -35250,12 +36293,12 @@ var BrowserControlClient = class {
35250
36293
  const endpoint = await this.session.resolveExposedPort(this.port);
35251
36294
  const path = joinControllerPath(
35252
36295
  endpoint.path,
35253
- `/v1/computer-sessions/${binding.computerSessionId}/targets/${encodeURIComponent(requireOpaqueId(targetId, "computer target id"))}/frames`
36296
+ `/v1/computer-sessions/${binding2.computerSessionId}/targets/${encodeURIComponent(requireOpaqueId(targetId, "computer target id"))}/frames`
35254
36297
  );
35255
36298
  return frameStreamUrlWithOptions(buildStreamUrl({ ...endpoint, path }), stream);
35256
36299
  }
35257
36300
  async computerRfbStreamUrl(reference, targetId) {
35258
- const binding = parseComputerReference(reference);
36301
+ const binding2 = parseComputerReference(reference);
35259
36302
  if (!this.session.resolveExposedPort) {
35260
36303
  throw new BrowserControlUnsupportedError(
35261
36304
  "computer placement cannot expose its live RFB port"
@@ -35264,7 +36307,7 @@ var BrowserControlClient = class {
35264
36307
  const endpoint = await this.session.resolveExposedPort(this.port);
35265
36308
  const path = joinControllerPath(
35266
36309
  endpoint.path,
35267
- `/v1/computer-sessions/${binding.computerSessionId}/targets/${encodeURIComponent(requireOpaqueId(targetId, "computer target id"))}/rfb`
36310
+ `/v1/computer-sessions/${binding2.computerSessionId}/targets/${encodeURIComponent(requireOpaqueId(targetId, "computer target id"))}/rfb`
35268
36311
  );
35269
36312
  return buildStreamUrl({ ...endpoint, path });
35270
36313
  }
@@ -36261,7 +37304,7 @@ function validateComputerControlFrameEvidence(frame2, expected) {
36261
37304
  if (metadata.mediaType !== frame2.mediaType) {
36262
37305
  throw new ComputerFrameEvidenceMismatchError("frame_media_mismatch");
36263
37306
  }
36264
- const digest = createHash9("sha256").update(frame2.data).digest("hex");
37307
+ const digest = createHash11("sha256").update(frame2.data).digest("hex");
36265
37308
  if (metadata.sha256 !== digest) {
36266
37309
  throw new ComputerFrameEvidenceMismatchError("frame_digest_mismatch");
36267
37310
  }
@@ -36596,8 +37639,8 @@ function parseStateCaptureReceipt(value) {
36596
37639
  controllerGeneration,
36597
37640
  objectKey: browserStateObjectKey(value.objectKey),
36598
37641
  format: BROWSER_PROFILE_ARTIFACT_FORMAT,
36599
- artifactDigest: sha2562(value.artifactDigest, "browser state artifact digest"),
36600
- contentDigest: sha2562(value.contentDigest, "browser state content digest"),
37642
+ artifactDigest: sha2563(value.artifactDigest, "browser state artifact digest"),
37643
+ contentDigest: sha2563(value.contentDigest, "browser state content digest"),
36601
37644
  sizeBytes: positiveSafeInteger(value.sizeBytes, "browser state artifact size"),
36602
37645
  fileCount: nonnegativeSafeInteger(value.fileCount, "browser state file count"),
36603
37646
  profileBytes: nonnegativeSafeInteger(value.profileBytes, "browser state profile size"),
@@ -36681,9 +37724,9 @@ function browserStateRestoreRequest(input) {
36681
37724
  wire: {
36682
37725
  objectKey: browserStateObjectKey(input.objectKey),
36683
37726
  format: BROWSER_PROFILE_ARTIFACT_FORMAT,
36684
- artifactDigest: sha2562(input.artifactDigest, "browser state artifact digest"),
36685
- contentDigest: sha2562(input.contentDigest, "browser state content digest"),
36686
- manifestDigest: sha2562(input.manifestDigest, "browser state manifest digest"),
37727
+ artifactDigest: sha2563(input.artifactDigest, "browser state artifact digest"),
37728
+ contentDigest: sha2563(input.contentDigest, "browser state content digest"),
37729
+ manifestDigest: sha2563(input.manifestDigest, "browser state manifest digest"),
36687
37730
  sizeBytes: positiveSafeInteger(input.sizeBytes, "browser state artifact size"),
36688
37731
  dataKeyBase64: dataKey.toString("base64"),
36689
37732
  aadBase64: aad.toString("base64"),
@@ -36708,7 +37751,7 @@ function boundedBytes(value, minimum, maximum, label) {
36708
37751
  }
36709
37752
  return value;
36710
37753
  }
36711
- function sha2562(value, label) {
37754
+ function sha2563(value, label) {
36712
37755
  if (typeof value !== "string" || !SHA256_PATTERN.test(value)) {
36713
37756
  throw new BrowserControlProtocolError(`${label} is invalid`);
36714
37757
  }
@@ -37172,7 +38215,7 @@ var MAX_CREDENTIAL_FILES = 64;
37172
38215
  var MAX_CREDENTIAL_FILE_BYTES = 1024 * 1024;
37173
38216
  var MAX_TOTAL_MATERIAL_BYTES = 4 * 1024 * 1024;
37174
38217
  var MAX_AUTH_NEEDED_NOTICES = 32;
37175
- var WRITE_CHUNK_BYTES = 24 * 1024;
38218
+ var WRITE_CHUNK_BYTES = 1536;
37176
38219
  var COMMAND_OK_MARKER = "__OPENGENI_RUN_CREDENTIAL_COMMAND_OK__";
37177
38220
  var AUTH_NEEDED_REASONS = /* @__PURE__ */ new Set([
37178
38221
  "missing_connection",
@@ -37536,23 +38579,43 @@ env -u BASH_ENV bash --noprofile --norc -c ${shellQuote8(marked)}`,
37536
38579
  throw new Error("run credential materialization command failed");
37537
38580
  }
37538
38581
  }
37539
- async function writeCredentialFile(session, path, content, commandRunner) {
37540
- await runCredentialCommand(session, `: > ${shellQuote8(path)}`, commandRunner);
38582
+ async function writeCredentialFile(session, directory, relativePath, content, commandRunner) {
38583
+ await runCredentialCommand(
38584
+ session,
38585
+ credentialFileCommand(directory, relativePath, ': > "$_opengeni_credential_path"'),
38586
+ commandRunner
38587
+ );
37541
38588
  const encoded = base64(content);
37542
38589
  for (let offset = 0; offset < encoded.length; offset += WRITE_CHUNK_BYTES) {
37543
38590
  const chunk = encoded.slice(offset, offset + WRITE_CHUNK_BYTES);
37544
38591
  await runCredentialCommand(
37545
38592
  session,
37546
- `printf %s ${shellQuote8(chunk)} | ${portableBase64DecodeCommand()} >> ${shellQuote8(path)}`,
38593
+ credentialFileCommand(
38594
+ directory,
38595
+ relativePath,
38596
+ `printf %s ${shellQuote8(chunk)} | ${portableBase64DecodeCommand()} >> "$_opengeni_credential_path"`
38597
+ ),
37547
38598
  commandRunner
37548
38599
  );
37549
38600
  }
37550
38601
  await runCredentialCommand(
37551
38602
  session,
37552
- `[ "$(wc -c < ${shellQuote8(path)} | tr -d '[:space:]')" = ${shellQuote8(String(byteLength(content)))} ]`,
38603
+ credentialFileCommand(
38604
+ directory,
38605
+ relativePath,
38606
+ `[ "$(wc -c < "$_opengeni_credential_path" | tr -d '[:space:]')" = ${shellQuote8(String(byteLength(content)))} ]`
38607
+ ),
37553
38608
  commandRunner
37554
38609
  );
37555
38610
  }
38611
+ function credentialFileCommand(directory, relativePath, command) {
38612
+ const escapedPath = [...Buffer.from(relativePath, "utf8")].map((byte) => `\\x${byte.toString(16).padStart(2, "0")}`).join("");
38613
+ return [
38614
+ `printf -v _opengeni_credential_path %b ${shellQuote8(escapedPath)}`,
38615
+ `_opengeni_credential_path=${shellQuote8(directory)}/"$_opengeni_credential_path"`,
38616
+ command
38617
+ ].join("\n");
38618
+ }
37556
38619
  async function materializeRunCredentials(session, material, options) {
37557
38620
  const root = runCredentialRoot(options.sessionId);
37558
38621
  const attemptId = assertPathIdentity(options.attemptId, "attemptId");
@@ -37591,7 +38654,8 @@ async function materializeRunCredentials(session, material, options) {
37591
38654
  ];
37592
38655
  await writeCredentialFile(
37593
38656
  session,
37594
- `${stage}/env`,
38657
+ stage,
38658
+ "env",
37595
38659
  environmentLines.length > 0 ? `${environmentLines.join("\n")}
37596
38660
  ` : "",
37597
38661
  options.commandRunner
@@ -37602,33 +38666,45 @@ async function materializeRunCredentials(session, material, options) {
37602
38666
  options.commandRunner
37603
38667
  );
37604
38668
  for (const file of material.files) {
37605
- const target = `${stage}/files/${file.path}`;
37606
- const parent = target.slice(0, target.lastIndexOf("/"));
37607
- await runCredentialCommand(session, `mkdir -p -- ${shellQuote8(parent)}`, options.commandRunner);
37608
- await writeCredentialFile(session, target, file.content, options.commandRunner);
38669
+ const directory = `${stage}/files`;
37609
38670
  await runCredentialCommand(
37610
38671
  session,
37611
- `chmod -- ${shellQuote8(file.mode ?? "0600")} ${shellQuote8(target)}`,
38672
+ credentialFileCommand(directory, file.path, 'mkdir -p -- "${_opengeni_credential_path%/*}"'),
38673
+ options.commandRunner
38674
+ );
38675
+ await writeCredentialFile(session, directory, file.path, file.content, options.commandRunner);
38676
+ await runCredentialCommand(
38677
+ session,
38678
+ credentialFileCommand(
38679
+ directory,
38680
+ file.path,
38681
+ `chmod -- ${shellQuote8(file.mode ?? "0600")} "$_opengeni_credential_path"`
38682
+ ),
37612
38683
  options.commandRunner
37613
38684
  );
37614
38685
  }
37615
38686
  await runCredentialCommand(
37616
38687
  session,
37617
38688
  [
38689
+ // Bind validated identifiers once rather than repeatedly expanding long
38690
+ // paths through cancellation and SDK run-as shell quoting.
38691
+ `_opengeni_credential_root=${shellQuote8(root)}`,
38692
+ `_opengeni_credential_version_name=${shellQuote8(versionName)}`,
38693
+ `_opengeni_credential_prefix=${shellQuote8(prefix2)}`,
37618
38694
  ...pointerLockAcquireCommands(root),
37619
- `previous=$(cat -- ${shellQuote8(`${root}/current`)} 2>/dev/null || :)`,
37620
- `mv -- ${shellQuote8(stage)} ${shellQuote8(version)}`,
37621
- `printf '%s\\n' ${shellQuote8(versionName)} > ${shellQuote8(`${root}/.next`)}`,
37622
- `mv -f -- ${shellQuote8(`${root}/.next`)} ${shellQuote8(`${root}/current`)}`,
38695
+ 'previous=$(cat -- "$_opengeni_credential_root/current" 2>/dev/null || :)',
38696
+ 'mv -- "$_opengeni_credential_root/versions/.stage-$_opengeni_credential_version_name" "$_opengeni_credential_root/versions/$_opengeni_credential_version_name"',
38697
+ `printf '%s\\n' "$_opengeni_credential_version_name" > "$_opengeni_credential_root/.next"`,
38698
+ 'mv -f -- "$_opengeni_credential_root/.next" "$_opengeni_credential_root/current"',
37623
38699
  ...options.prunePreviousGenerations ? [
37624
- `find ${shellQuote8(`${root}/versions`)} -mindepth 1 -maxdepth 1 ! -name ${shellQuote8(versionName)} -exec rm -rf -- {} +`
38700
+ 'find "$_opengeni_credential_root/versions" -mindepth 1 -maxdepth 1 ! -name "$_opengeni_credential_version_name" -exec rm -rf -- {} +'
37625
38701
  ] : options.pruneOtherAttempts ? [
37626
- `find ${shellQuote8(`${root}/versions`)} -mindepth 1 -maxdepth 1 ! -name ${shellQuote8(`${attemptId}-${options.executionGeneration}-*`)} -exec rm -rf -- {} +`
38702
+ 'find "$_opengeni_credential_root/versions" -mindepth 1 -maxdepth 1 ! -name "${_opengeni_credential_prefix}*" -exec rm -rf -- {} +'
37627
38703
  ] : options.pruneSupersededGenerations ? [
37628
- `for candidate in ${shellQuote8(`${root}/versions`)}/${prefix2}*; do`,
38704
+ 'for candidate in "$_opengeni_credential_root/versions/$_opengeni_credential_prefix"*; do',
37629
38705
  ` [ -e "$candidate" ] || continue`,
37630
38706
  ` name=\${candidate##*/}`,
37631
- ` [ "$name" = ${shellQuote8(versionName)} ] || [ "$name" = "$previous" ] || rm -rf -- "$candidate"`,
38707
+ ' [ "$name" = "$_opengeni_credential_version_name" ] || [ "$name" = "$previous" ] || rm -rf -- "$candidate"',
37632
38708
  "done"
37633
38709
  ] : [],
37634
38710
  ...pointerLockReleaseCommands()
@@ -37754,16 +38830,16 @@ function withRunCredentialsClient(client, sessionId, onSessionReady) {
37754
38830
  }
37755
38831
 
37756
38832
  // src/sandbox/codemode-token.ts
37757
- import { createHash as createHash11 } from "crypto";
38833
+ import { createHash as createHash13 } from "crypto";
37758
38834
  import { posix as posixPath3 } from "path";
37759
38835
 
37760
38836
  // src/sandbox/codemode-client.ts
37761
- import { createHash as createHash10, randomUUID as randomUUID9 } from "crypto";
38837
+ import { createHash as createHash12, randomUUID as randomUUID9 } from "crypto";
37762
38838
  import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
37763
38839
  import { dirname as dirname5, join as join8, posix as posix5, resolve as resolve6 } from "path";
37764
38840
  import { fileURLToPath } from "url";
37765
38841
  function managedCodemodeClientDigest(client) {
37766
- return createHash10("sha256").update(JSON.stringify(client)).digest("hex");
38842
+ return createHash12("sha256").update(JSON.stringify(client)).digest("hex");
37767
38843
  }
37768
38844
  function managedCodemodeClientDirectory(client, workspaceRoot = "/workspace") {
37769
38845
  if (!posix5.isAbsolute(workspaceRoot) || workspaceRoot.includes("\0")) {
@@ -37950,7 +39026,7 @@ function codemodeTokenFileForSession(manifestTokenFile, sessionId) {
37950
39026
  manifestTokenFile,
37951
39027
  "Codemode manifest token file"
37952
39028
  );
37953
- const digest = createHash11("sha256").update(assertCodemodeSessionId(sessionId)).digest("hex");
39029
+ const digest = createHash13("sha256").update(assertCodemodeSessionId(sessionId)).digest("hex");
37954
39030
  return posixPath3.join(posixPath3.dirname(normalizedManifestFile), "codemode-tokens", digest);
37955
39031
  }
37956
39032
  function codemodeTokenFileFromEnvironment(environment, sessionId) {
@@ -40379,6 +41455,8 @@ export {
40379
41455
  UnsupportedProtocolJsonValueError,
40380
41456
  normalizeProtocolJsonValue,
40381
41457
  ProviderCommandStartOutcomeUnknownError,
41458
+ ProviderCommandObservationUnavailableError,
41459
+ isProviderCommandObservationUnavailableError,
40382
41460
  withModalCommandStartSignal,
40383
41461
  getModalCommandStartInvocation,
40384
41462
  parseExecBannerSessionId,
@@ -40443,6 +41521,7 @@ export {
40443
41521
  renderRoutingMutationOutcomeUnknownToolResult,
40444
41522
  RoutingSandboxSession,
40445
41523
  ModalCloudBucketMountStrategy,
41524
+ reduceModalRawOutputPage,
40446
41525
  captureWorkspaceArchiveForStorage,
40447
41526
  disposeWorkspaceArchive,
40448
41527
  WorkspaceArchiveIntegrityError,
@@ -40460,6 +41539,10 @@ export {
40460
41539
  CAPABILITY_DESCRIPTORS,
40461
41540
  DESKTOP_STREAM_PORT,
40462
41541
  assertDescriptorRegistryInvariants,
41542
+ classifyProviderSandboxFailure,
41543
+ isProviderSandboxNotFoundError2 as isProviderSandboxNotFoundError,
41544
+ isProviderSandboxGoneDuringRoutedOperation,
41545
+ isProviderSandboxTransientError,
40463
41546
  modalSandboxAttributionEnvironment,
40464
41547
  modalSandboxAttributionTags,
40465
41548
  isModalTaskExecStartPreDispatchUnavailableError,
@@ -40533,10 +41616,6 @@ export {
40533
41616
  backendSupportsOs,
40534
41617
  desktopCapableBackend,
40535
41618
  negotiateCapabilities,
40536
- classifyProviderSandboxFailure,
40537
- isProviderSandboxNotFoundError2 as isProviderSandboxNotFoundError,
40538
- isProviderSandboxGoneDuringRoutedOperation,
40539
- isProviderSandboxTransientError,
40540
41619
  sandboxCommandExitCode,
40541
41620
  sandboxCommandOutput,
40542
41621
  sandboxCommandStdout,
@@ -40544,6 +41623,8 @@ export {
40544
41623
  runStateExposedPortsRecord,
40545
41624
  runStateCompatibilityProvider,
40546
41625
  repairSerializedRunStateExposedPorts,
41626
+ compileNativeFreshCreate,
41627
+ describeNativeFreshCreate,
40547
41628
  STREAM_PORT,
40548
41629
  DISPLAY_STACK_TIMEOUT_MS,
40549
41630
  DEFAULT_DESKTOP_GEOMETRY,
@@ -40647,4 +41728,4 @@ export {
40647
41728
  collectSandboxEnvironment2 as collectSandboxEnvironment,
40648
41729
  parseExposedPorts2 as parseExposedPorts
40649
41730
  };
40650
- //# sourceMappingURL=chunk-D5DPVA2C.js.map
41731
+ //# sourceMappingURL=chunk-3QG5IL64.js.map