openpond 0.0.39 → 0.0.41

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 (27) hide show
  1. package/dist/chunks/{app-layer-LTBWNA2F.js → app-layer-UPNMLDO5.js} +7 -3
  2. package/dist/chunks/{app-server-runtime-VYYJ2AWX.js → app-server-runtime-SZ76TNNY.js} +4 -4
  3. package/dist/chunks/{apps-CZAJBGE3.js → apps-XLPSFCW4.js} +2 -2
  4. package/dist/chunks/{chunk-JJPAMKXZ.js → chunk-4SWPERMD.js} +1 -1
  5. package/dist/chunks/{chunk-L6XH4ZGZ.js → chunk-FTHWWUKZ.js} +1 -1
  6. package/dist/chunks/{chunk-6V7MJVRO.js → chunk-ISMG72XN.js} +2 -2
  7. package/dist/chunks/{chunk-JRROTGQT.js → chunk-KSOI7GFA.js} +1 -1
  8. package/dist/chunks/{chunk-4N6E3OVF.js → chunk-MCBAI5M5.js} +1 -1
  9. package/dist/chunks/{chunk-4HIWFIMN.js → chunk-OBQP6UAS.js} +3832 -165
  10. package/dist/chunks/{chunk-3CDPPVLE.js → chunk-QHUJ2XVJ.js} +31 -31
  11. package/dist/chunks/{chunk-BQQZNGI6.js → chunk-ZTE6A2VE.js} +3 -2
  12. package/dist/chunks/{cli-JS76LCW2.js → cli-SEPGE6SM.js} +3 -3
  13. package/dist/chunks/{core-commands-4MRJQZJV.js → core-commands-D66KZEHU.js} +3 -3
  14. package/dist/chunks/{desktop-test-RNMWLOVU.js → desktop-test-FDA6MV77.js} +2 -2
  15. package/dist/chunks/{help-LWNREJ7U.js → help-7QG4UITV.js} +1 -1
  16. package/dist/chunks/{opchat-2K2JIGK3.js → opchat-I2WGEFGU.js} +2 -2
  17. package/dist/chunks/{organizations-Z5HVD2E7.js → organizations-MADRLI2I.js} +2 -2
  18. package/dist/chunks/{profile-QNECVVGN.js → profile-B4A3GT3U.js} +2 -2
  19. package/dist/chunks/{project-agent-W3V75WBR.js → project-agent-PCO42FZJ.js} +2 -2
  20. package/dist/chunks/{sandbox-command-X3FO74NX.js → sandbox-command-LBKSIR7P.js} +2 -2
  21. package/dist/chunks/{sandbox-template-5B4T4BGU.js → sandbox-template-YJXGG4H3.js} +3 -3
  22. package/dist/chunks/{src-ESAILPUH.js → src-35JYS27L.js} +1 -1
  23. package/dist/chunks/{src-IC5RX4L6.js → src-44QFJZM5.js} +266 -3720
  24. package/dist/chunks/{teams-bot-NTQ6VFFL.js → teams-bot-L4SR2SWM.js} +2 -2
  25. package/dist/chunks/{workspaces-XC3QBD2Y.js → workspaces-C3DGNUX2.js} +2 -2
  26. package/dist/cli.js +13 -13
  27. package/package.json +1 -1
@@ -20,7 +20,7 @@ import {
20
20
  getBundledRuntimeVersion,
21
21
  loadOpenPondAccountContext,
22
22
  streamOpenPondHostedChatTurn
23
- } from "./chunk-BQQZNGI6.js";
23
+ } from "./chunk-ZTE6A2VE.js";
24
24
  import {
25
25
  assertSafeBranchName,
26
26
  isGeneratedWorkspacePath,
@@ -33,14 +33,14 @@ import {
33
33
  truncatePatch,
34
34
  uniqueSortedPaths,
35
35
  workspaceImageContentType
36
- } from "./chunk-L6XH4ZGZ.js";
36
+ } from "./chunk-FTHWWUKZ.js";
37
37
  import {
38
38
  HOSTED_CHAT_SYSTEM_PROMPT,
39
39
  VERSION,
40
40
  event,
41
41
  now,
42
42
  textFromUnknown
43
- } from "./chunk-JJPAMKXZ.js";
43
+ } from "./chunk-4SWPERMD.js";
44
44
  import {
45
45
  AppPreferencesSchema,
46
46
  ApplyCreateImproveRunActionRequestSchema,
@@ -160,6 +160,8 @@ import {
160
160
  ImprovementRouteDecisionSchema,
161
161
  OPENPOND_MANIFEST_FILE_NAME,
162
162
  RefinementTriggerDecisionSchema,
163
+ SANDBOX_TEMPLATE_PREVIEW_PORT_MAX,
164
+ SANDBOX_TEMPLATE_PREVIEW_PORT_MIN,
163
165
  WorkEvidenceReceiptSchema,
164
166
  WorkFeedbackReceiptSchema,
165
167
  WorkProcessTraceSchema,
@@ -16140,6 +16142,3658 @@ var MUTATING_WORKSPACE_TOOL_ACTIONS = [
16140
16142
  "work_agent_package_install"
16141
16143
  ];
16142
16144
 
16145
+ // ../../packages/sdk/dist/index.js
16146
+ function createSandboxRuntimeNamespace(client) {
16147
+ return {
16148
+ list: (input = {}) => client.listSandboxRuntimes(input),
16149
+ create: (input) => client.createSandboxRuntime(input),
16150
+ handle: (runtimeId, initial = null) => client.sandboxRuntime(runtimeId, initial),
16151
+ get: (runtimeId) => client.getSandboxRuntime(runtimeId),
16152
+ createSandbox: (runtimeId, input = {}, options = {}) => client.createSandboxRuntimeSandbox(runtimeId, input, options),
16153
+ updateStatus: (runtimeId, input) => client.updateSandboxRuntimeStatus(runtimeId, input),
16154
+ events: (runtimeId) => client.listSandboxRuntimeEvents(runtimeId),
16155
+ event: (runtimeId, input) => client.emitSandboxRuntimeEvent(runtimeId, input),
16156
+ checkpoint: (runtimeId, input = {}) => client.checkpointSandboxRuntime(runtimeId, input),
16157
+ promote: (runtimeId, input, options = {}) => client.promoteSandboxRuntime(runtimeId, input, options),
16158
+ preserveSource: (runtimeId, input = {}, options = {}) => client.preserveSandboxRuntimeSource(runtimeId, input, options)
16159
+ };
16160
+ }
16161
+ function createSandboxNamespace(client) {
16162
+ return {
16163
+ list: (input = {}) => client.list(input),
16164
+ create: (input) => client.create(input),
16165
+ get: (sandboxId) => client.get(sandboxId),
16166
+ pricing: () => client.pricing(),
16167
+ costs: (input = {}) => client.costs(input)
16168
+ };
16169
+ }
16170
+ function createSandboxProjectNamespace(client) {
16171
+ return {
16172
+ list: (input) => client.listProjects(input),
16173
+ upsert: (input) => client.upsertProject(input),
16174
+ upsertGitRemote: (input) => client.upsertProjectGitRemote(input),
16175
+ get: (projectId, input) => client.getProject(projectId, input),
16176
+ update: (projectId, input) => client.updateProject(projectId, input),
16177
+ sync: (projectId, input) => client.syncProject(projectId, input),
16178
+ ensureGitRemote: (projectId, input) => client.ensureProjectGitRemote(projectId, input),
16179
+ getGitRemote: (projectId, input) => client.ensureProjectGitRemote(projectId, input),
16180
+ git: (projectId, input) => client.ensureProjectGitRemote(projectId, input),
16181
+ uploadSource: (projectId, input) => client.uploadProjectSource(projectId, input),
16182
+ archive: (projectId, input) => client.archiveProject(projectId, input)
16183
+ };
16184
+ }
16185
+ function createSandboxProfileNamespace(client) {
16186
+ return {
16187
+ get: (input) => client.getHostedProfile(input),
16188
+ status: (input) => client.getHostedProfile(input),
16189
+ ensureHosted: (input) => client.ensureHostedProfile(input),
16190
+ push: (input) => client.pushHostedProfile(input)
16191
+ };
16192
+ }
16193
+ function createSandboxAgentNamespace(client) {
16194
+ return {
16195
+ list: (input) => client.listAgents(input),
16196
+ upsert: (input) => client.upsertAgent(input),
16197
+ get: (agentId, input) => client.getAgent(agentId, input),
16198
+ update: (agentId, input) => client.updateAgent(agentId, input),
16199
+ archive: (agentId, input) => client.archiveAgent(agentId, input),
16200
+ run: (agentId, input) => client.runAgent(agentId, input),
16201
+ sourceDeployPlan: (agentId, input) => client.getAgentSourceDeployPlan(agentId, input),
16202
+ manifestSnapshots: (agentId, input) => client.listAgentManifestSnapshots(agentId, input),
16203
+ requestSourceChecks: (agentId, input) => client.requestAgentSourceChecks(agentId, input),
16204
+ publishSource: (agentId, input) => client.publishAgentSource(agentId, input)
16205
+ };
16206
+ }
16207
+ function createSandboxRuntimeHandle(client, runtimeId, initial = null) {
16208
+ const currentSandbox = async (input = {}, options = {}) => {
16209
+ const runtime = await client.getSandboxRuntime(runtimeId);
16210
+ if (runtime.sandboxId) {
16211
+ return client.get(runtime.sandboxId);
16212
+ }
16213
+ return client.createSandboxRuntimeSandbox(runtimeId, input, options).then((payload) => payload.sandbox);
16214
+ };
16215
+ const resume = async (input = {}, options = {}) => {
16216
+ const runtime = await client.getSandboxRuntime(runtimeId);
16217
+ if (!runtime.sandboxId) {
16218
+ return client.createSandboxRuntimeSandbox(runtimeId, input, options).then((payload) => payload.sandbox);
16219
+ }
16220
+ const sandbox = await client.get(runtime.sandboxId);
16221
+ if (sandbox.state === "stopped") {
16222
+ return client.start(sandbox.id, options).then((payload) => payload.sandbox);
16223
+ }
16224
+ if (sandbox.state === "archived") {
16225
+ return client.restore(sandbox.id).then((payload) => payload.sandbox);
16226
+ }
16227
+ if (sandbox.state === "deleted" || sandbox.state === "error") {
16228
+ return client.createSandboxRuntimeSandbox(runtimeId, input, options).then((payload) => payload.sandbox);
16229
+ }
16230
+ return sandbox;
16231
+ };
16232
+ const checkpointHint = (input = {}) => client.emitSandboxRuntimeEvent(runtimeId, {
16233
+ type: "workflow.checkpoint_hint",
16234
+ summary: input.summary ?? input.reason ?? "Workflow checkpoint hint",
16235
+ payload: {
16236
+ ...input.payload,
16237
+ reason: input.reason ?? null
16238
+ },
16239
+ artifactRefs: input.artifactRefs,
16240
+ lifecycleHint: {
16241
+ kind: "checkpoint",
16242
+ reason: input.reason ?? null
16243
+ }
16244
+ });
16245
+ const waitForUser = async (input = {}) => {
16246
+ await client.emitSandboxRuntimeEvent(runtimeId, {
16247
+ type: "workflow.waiting_for_user",
16248
+ summary: input.summary ?? input.reason ?? "Waiting for user",
16249
+ payload: {
16250
+ ...input.payload,
16251
+ reason: input.reason ?? null
16252
+ },
16253
+ lifecycleHint: {
16254
+ kind: "waiting_for_user",
16255
+ reason: input.reason ?? null
16256
+ }
16257
+ });
16258
+ const current = await client.getSandboxRuntime(runtimeId);
16259
+ if (current.status === "waiting_for_user")
16260
+ return current;
16261
+ return client.updateSandboxRuntimeStatus(runtimeId, {
16262
+ status: "waiting_for_user",
16263
+ expectedVersion: current.version,
16264
+ summary: input.summary ?? input.reason,
16265
+ metadata: {
16266
+ workflowWaitForUserReason: input.reason ?? null
16267
+ }
16268
+ });
16269
+ };
16270
+ const keepAlive = (input = {}) => {
16271
+ const keepaliveUntil = runtimeKeepaliveUntilIso(input);
16272
+ return client.emitSandboxRuntimeEvent(runtimeId, {
16273
+ type: "workflow.keepalive",
16274
+ summary: input.summary ?? input.reason ?? "Workflow keepalive",
16275
+ payload: {
16276
+ ...input.payload,
16277
+ reason: input.reason ?? null,
16278
+ keepaliveUntil
16279
+ },
16280
+ lifecycleHint: {
16281
+ kind: "keepalive",
16282
+ reason: input.reason ?? null,
16283
+ keepaliveUntil
16284
+ }
16285
+ });
16286
+ };
16287
+ return {
16288
+ id: runtimeId,
16289
+ initial,
16290
+ get: () => client.getSandboxRuntime(runtimeId),
16291
+ sandbox: currentSandbox,
16292
+ resume,
16293
+ createSandbox: (input = {}, options = {}) => client.createSandboxRuntimeSandbox(runtimeId, input, options),
16294
+ status: async (input) => {
16295
+ if (typeof input !== "string") {
16296
+ return client.updateSandboxRuntimeStatus(runtimeId, input);
16297
+ }
16298
+ const current = await client.getSandboxRuntime(runtimeId);
16299
+ return client.updateSandboxRuntimeStatus(runtimeId, {
16300
+ status: input,
16301
+ expectedVersion: current.version
16302
+ });
16303
+ },
16304
+ events: () => client.listSandboxRuntimeEvents(runtimeId),
16305
+ event: (input) => client.emitSandboxRuntimeEvent(runtimeId, input),
16306
+ recordCommit: (commitSha, input = {}) => client.emitSandboxRuntimeEvent(runtimeId, {
16307
+ ...input,
16308
+ type: input.type ?? "git.commit",
16309
+ commitSha
16310
+ }),
16311
+ checkpointHint,
16312
+ waitForUser,
16313
+ keepAlive,
16314
+ checkpoint: (input) => client.checkpointSandboxRuntime(runtimeId, input),
16315
+ files: {
16316
+ write: async (path37, contents) => client.uploadFile((await resume()).id, path37, contents),
16317
+ read: async (path37) => client.downloadFile((await resume()).id, path37),
16318
+ readResponse: async (input) => client.downloadFileResponse((await resume()).id, input),
16319
+ list: async (input = {}) => client.listFiles((await resume()).id, input),
16320
+ delete: async (path37, input = {}) => client.deleteFile((await resume()).id, path37, input),
16321
+ search: async (input) => client.searchFiles((await resume()).id, input),
16322
+ stat: async (path37) => client.statFile((await resume()).id, path37),
16323
+ mkdir: async (input) => client.mkdir((await resume()).id, input),
16324
+ move: async (input) => client.moveFile((await resume()).id, input)
16325
+ },
16326
+ commands: {
16327
+ run: async (command) => client.exec((await resume()).id, typeof command === "string" ? { command } : command)
16328
+ },
16329
+ ports: {
16330
+ expose: async (port) => client.openPort((await resume()).id, typeof port === "number" ? { port } : port)
16331
+ },
16332
+ promote: (input, options = {}) => client.promoteSandboxRuntime(runtimeId, input, options),
16333
+ preserveSource: (input = {}, options = {}) => client.preserveSandboxRuntimeSource(runtimeId, input, options),
16334
+ archive: async (expectedVersion) => {
16335
+ const version = expectedVersion ?? (await client.getSandboxRuntime(runtimeId)).version;
16336
+ return client.updateSandboxRuntimeStatus(runtimeId, {
16337
+ status: "archived",
16338
+ expectedVersion: version
16339
+ });
16340
+ }
16341
+ };
16342
+ }
16343
+ function runtimeKeepaliveUntilIso(input) {
16344
+ if (input?.until instanceof Date) {
16345
+ return input.until.toISOString();
16346
+ }
16347
+ if (typeof input?.until === "string" && input.until.trim()) {
16348
+ return new Date(input.until).toISOString();
16349
+ }
16350
+ const seconds = typeof input?.seconds === "number" && Number.isFinite(input.seconds) ? Math.max(1, Math.trunc(input.seconds)) : 60;
16351
+ return new Date(Date.now() + seconds * 1e3).toISOString();
16352
+ }
16353
+ async function runSandboxSmoke(client, options = {}) {
16354
+ const runId = `openpond-code-smoke-${Date.now()}`;
16355
+ const expectedExec = `openpond-code-exec-ok:${runId}`;
16356
+ const expectedPreview = `openpond-code-preview-ok:${runId}`;
16357
+ const expectedFile = `openpond-code-file-ok:${runId}`;
16358
+ const previewPort = 4173;
16359
+ let sandboxId = null;
16360
+ let forkSandboxId = null;
16361
+ let deleted = false;
16362
+ let forkDeleted = false;
16363
+ try {
16364
+ const sandbox = await waitForCreateReady(client, await client.create({
16365
+ repo: options.repo ?? "https://github.com/octocat/Hello-World",
16366
+ resources: {
16367
+ cpu: options.cpu ?? 1,
16368
+ memoryGb: options.memoryGb ?? 1,
16369
+ diskGb: options.diskGb ?? 8
16370
+ },
16371
+ budget: { maxUsd: options.budgetUsd ?? "0.05" },
16372
+ quotas: {
16373
+ maxSpendUsd: options.budgetUsd ?? "0.05",
16374
+ maxDurationSeconds: 600,
16375
+ idleTimeoutSeconds: 600,
16376
+ maxOpenPorts: 2
16377
+ },
16378
+ metadata: {
16379
+ runId,
16380
+ source: "openpond-code-sandbox-smoke"
16381
+ }
16382
+ }, { async: true }));
16383
+ sandboxId = sandbox.id;
16384
+ const expectedMppMode = options.expectedMppMode;
16385
+ if (expectedMppMode && sandbox.reservation.mpp?.mode !== expectedMppMode) {
16386
+ throw new Error(`expected ${expectedMppMode} reservation, got ${sandbox.reservation.mpp?.mode ?? "none"}`);
16387
+ }
16388
+ if (!expectedMppMode && !sandbox.reservation.mpp?.mode) {
16389
+ throw new Error("expected sandbox reservation MPP metadata");
16390
+ }
16391
+ const exec = await client.exec(sandbox.id, {
16392
+ command: [
16393
+ `printf '${expectedExec}\\n'`,
16394
+ "test -f README && printf 'repo-clone-ok\\n'",
16395
+ "cat > server.cjs <<'EOF'",
16396
+ "const { createServer } = require('node:http');",
16397
+ `createServer((_request, response) => response.end('${expectedPreview}')).listen(${previewPort}, '0.0.0.0');`,
16398
+ "EOF",
16399
+ "nohup node server.cjs > server.log 2>&1 & sleep 1"
16400
+ ].join("\n"),
16401
+ timeoutSeconds: 120
16402
+ });
16403
+ if (exec.command.status !== "succeeded") {
16404
+ throw new Error(`expected command success, got ${exec.command.status}`);
16405
+ }
16406
+ if (!exec.command.output.includes(expectedExec)) {
16407
+ throw new Error("expected exec marker");
16408
+ }
16409
+ await client.uploadFile(sandbox.id, "openpond-code-smoke.txt", expectedFile);
16410
+ const downloaded = await client.downloadFile(sandbox.id, "openpond-code-smoke.txt");
16411
+ if (downloaded !== expectedFile) {
16412
+ throw new Error("expected file roundtrip marker");
16413
+ }
16414
+ let snapshotId = null;
16415
+ if (options.snapshot || options.fork) {
16416
+ const snapshotResponse = await client.createSnapshot(sandbox.id, {
16417
+ async: true,
16418
+ name: `openpond-code-smoke-${runId}`,
16419
+ replay: {
16420
+ entrypoints: [
16421
+ {
16422
+ command: "cat openpond-code-smoke.txt",
16423
+ name: "default"
16424
+ }
16425
+ ],
16426
+ retention: {
16427
+ class: "pinned"
16428
+ },
16429
+ safety: {
16430
+ cleanup: "delete",
16431
+ idleTimeoutSeconds: 600,
16432
+ internetEgress: "block",
16433
+ maxDurationSeconds: 600,
16434
+ maxSpendUsd: options.budgetUsd ?? "0.05",
16435
+ publicPreview: false
16436
+ },
16437
+ validation: {
16438
+ commands: [
16439
+ {
16440
+ command: "test -f openpond-code-smoke.txt"
16441
+ }
16442
+ ]
16443
+ }
16444
+ }
16445
+ });
16446
+ const snapshot = snapshotResponse.snapshot ?? (await waitForSnapshotReady(client, sandbox.id, snapshotResponse.snapshotJob?.snapshotId)).snapshot;
16447
+ snapshotId = snapshot.id;
16448
+ if (snapshot.state !== "ready") {
16449
+ throw new Error(`expected ready snapshot, got ${snapshot.state}`);
16450
+ }
16451
+ }
16452
+ if (options.fork) {
16453
+ if (!snapshotId) {
16454
+ throw new Error("expected snapshot id before fork");
16455
+ }
16456
+ const forked = await waitForCreateReady(client, (await client.forkSnapshot(snapshotId, {
16457
+ budget: { maxUsd: options.budgetUsd ?? "0.05" },
16458
+ metadata: {
16459
+ source: "openpond-code-sandbox-smoke-fork",
16460
+ templateSnapshotId: snapshotId
16461
+ }
16462
+ }, { async: true })).sandbox);
16463
+ forkSandboxId = forked.id;
16464
+ const forkExec = await client.exec(forked.id, {
16465
+ command: "cat openpond-code-smoke.txt",
16466
+ timeoutSeconds: 120
16467
+ });
16468
+ if (forkExec.command.status !== "succeeded") {
16469
+ throw new Error(`expected fork command success, got ${forkExec.command.status}`);
16470
+ }
16471
+ if (!forkExec.command.output.includes(expectedFile)) {
16472
+ throw new Error("expected fork snapshot marker");
16473
+ }
16474
+ if (!options.keep) {
16475
+ await deleteSandboxForSmoke(client, forked.id);
16476
+ forkDeleted = true;
16477
+ }
16478
+ }
16479
+ let previewStatus = null;
16480
+ if (options.preview !== false) {
16481
+ const opened = await client.openPort(sandbox.id, {
16482
+ label: "openpond-code-smoke",
16483
+ port: previewPort
16484
+ });
16485
+ const preview = await fetch(opened.preview.url);
16486
+ previewStatus = preview.status;
16487
+ const body = await preview.text();
16488
+ if (preview.status !== 200) {
16489
+ throw new Error(`expected preview HTTP 200, got ${preview.status}`);
16490
+ }
16491
+ if (!body.includes(expectedPreview)) {
16492
+ throw new Error("expected preview marker");
16493
+ }
16494
+ }
16495
+ const { sandbox: readback, receipts } = await stopSandboxForSmoke(client, sandbox.id);
16496
+ if (!options.keep) {
16497
+ await deleteSandboxForSmoke(client, sandbox.id);
16498
+ deleted = true;
16499
+ }
16500
+ return {
16501
+ deleted,
16502
+ execOutput: exec.command.output.trim(),
16503
+ fileRoundtrip: true,
16504
+ forkSandboxId,
16505
+ previewStatus,
16506
+ receiptRefs: receipts.map((receipt) => receipt.mpp.receiptRef ?? null),
16507
+ reservationRef: sandbox.reservation.mpp?.reservationRef ?? null,
16508
+ runId,
16509
+ sandboxId: sandbox.id,
16510
+ snapshotId,
16511
+ state: readback.state
16512
+ };
16513
+ } finally {
16514
+ if (forkSandboxId && !options.keep && !forkDeleted) {
16515
+ await cleanupSandboxBestEffort(client, forkSandboxId);
16516
+ }
16517
+ if (sandboxId && !options.keep && !deleted) {
16518
+ await cleanupSandboxBestEffort(client, sandboxId);
16519
+ }
16520
+ }
16521
+ }
16522
+ async function stopSandboxForSmoke(client, sandboxId) {
16523
+ try {
16524
+ await client.stop(sandboxId);
16525
+ } catch {
16526
+ await client.stop(sandboxId, { async: true });
16527
+ }
16528
+ const sandbox = await waitForSandboxState(client, sandboxId, /* @__PURE__ */ new Set(["stopped", "deleted"]), "stop");
16529
+ const receipts = await waitForReceipts(client, sandboxId);
16530
+ if (receipts.length === 0) {
16531
+ throw new Error("expected receipt readback");
16532
+ }
16533
+ return { sandbox, receipts };
16534
+ }
16535
+ async function deleteSandboxForSmoke(client, sandboxId) {
16536
+ try {
16537
+ const deleted = await client.delete(sandboxId);
16538
+ if (deleted.state === "deleted") {
16539
+ return deleted;
16540
+ }
16541
+ await client.delete(sandboxId, { async: true });
16542
+ } catch {
16543
+ await client.delete(sandboxId, { async: true });
16544
+ }
16545
+ return waitForSandboxState(client, sandboxId, /* @__PURE__ */ new Set(["deleted"]), "delete");
16546
+ }
16547
+ async function cleanupSandboxBestEffort(client, sandboxId) {
16548
+ try {
16549
+ await deleteSandboxForSmoke(client, sandboxId);
16550
+ } catch {
16551
+ await client.delete(sandboxId, { async: true }).catch(() => void 0);
16552
+ }
16553
+ }
16554
+ async function waitForSandboxState(client, sandboxId, targetStates, operation) {
16555
+ const timeoutMs = 5 * 6e4;
16556
+ const pollMs = 3e3;
16557
+ const deadline = Date.now() + timeoutMs;
16558
+ let latest = await client.get(sandboxId);
16559
+ while (Date.now() < deadline) {
16560
+ if (targetStates.has(latest.state)) {
16561
+ return latest;
16562
+ }
16563
+ if (latest.state === "error") {
16564
+ throw new Error(`sandbox ${operation} failed: ${sandboxId}`);
16565
+ }
16566
+ await sleep2(pollMs);
16567
+ latest = await client.get(sandboxId);
16568
+ }
16569
+ throw new Error(`sandbox ${operation} did not reach ${[...targetStates].join("/")} before timeout: ${sandboxId} (${latest.state})`);
16570
+ }
16571
+ async function waitForReceipts(client, sandboxId) {
16572
+ const timeoutMs = 2 * 6e4;
16573
+ const pollMs = 3e3;
16574
+ const deadline = Date.now() + timeoutMs;
16575
+ let receipts = await client.receipts(sandboxId);
16576
+ while (Date.now() < deadline) {
16577
+ if (receipts.length > 0) {
16578
+ return receipts;
16579
+ }
16580
+ await sleep2(pollMs);
16581
+ receipts = await client.receipts(sandboxId);
16582
+ }
16583
+ return receipts;
16584
+ }
16585
+ async function waitForCreateReady(client, sandbox) {
16586
+ if (sandbox.state === "running" || sandbox.state === "stopped") {
16587
+ return sandbox;
16588
+ }
16589
+ if (sandbox.state === "error") {
16590
+ throw new Error(`sandbox create failed: ${sandbox.id}
16591
+ ${sandbox.logs.join("\n")}`);
16592
+ }
16593
+ const timeoutMs = 12 * 6e4;
16594
+ const pollMs = 3e3;
16595
+ const deadline = Date.now() + timeoutMs;
16596
+ let latest = sandbox;
16597
+ while (Date.now() < deadline) {
16598
+ await sleep2(pollMs);
16599
+ latest = await client.get(sandbox.id);
16600
+ if (latest.state === "running" || latest.state === "stopped") {
16601
+ return latest;
16602
+ }
16603
+ if (latest.state === "error") {
16604
+ throw new Error(`sandbox create failed: ${latest.id}
16605
+ ${latest.logs.join("\n")}`);
16606
+ }
16607
+ }
16608
+ throw new Error(`sandbox create did not reach running state before timeout: ${latest.id} (${latest.state})`);
16609
+ }
16610
+ async function waitForSnapshotReady(client, sandboxId, snapshotId) {
16611
+ if (!snapshotId) {
16612
+ throw new Error("snapshot job did not return snapshot id");
16613
+ }
16614
+ const timeoutMs = 12 * 6e4;
16615
+ const pollMs = 3e3;
16616
+ const deadline = Date.now() + timeoutMs;
16617
+ let latest = await client.get(sandboxId);
16618
+ while (Date.now() < deadline) {
16619
+ const snapshot = latest.snapshots?.find((item) => item.id === snapshotId);
16620
+ if (snapshot?.state === "ready") {
16621
+ return { sandbox: latest, snapshot };
16622
+ }
16623
+ const job = latest.snapshotJobs?.find((item) => item.snapshotId === snapshotId);
16624
+ if (job?.status === "failed") {
16625
+ throw new Error(`snapshot job failed: ${job.error ?? snapshotId}`);
16626
+ }
16627
+ await sleep2(pollMs);
16628
+ latest = await client.get(sandboxId);
16629
+ }
16630
+ throw new Error(`snapshot did not reach ready state before timeout: ${snapshotId}`);
16631
+ }
16632
+ function sleep2(ms) {
16633
+ return new Promise((resolve) => setTimeout(resolve, ms));
16634
+ }
16635
+ function asyncRequestHeaders(options = {}) {
16636
+ return options.async || options.respondAsync ? { Prefer: "respond-async" } : void 0;
16637
+ }
16638
+ var VERCEL_PROTECTION_BYPASS_HEADER = "x-vercel-protection-bypass";
16639
+ function withVercelProtectionBypass2(requestUrl, inputHeaders, env = typeof process === "undefined" ? {} : process.env) {
16640
+ const headers = new Headers(inputHeaders);
16641
+ const secret = env.VERCEL_AUTOMATION_BYPASS_SECRET?.trim();
16642
+ if (!secret || !isOpenPondStagingUrl(requestUrl))
16643
+ return headers;
16644
+ headers.set(VERCEL_PROTECTION_BYPASS_HEADER, secret);
16645
+ return headers;
16646
+ }
16647
+ function isOpenPondStagingUrl(requestUrl) {
16648
+ try {
16649
+ const hostname = new URL(requestUrl).hostname.toLowerCase();
16650
+ return hostname === "staging.openpond.ai" || hostname === "staging-api.openpond.ai" || hostname.endsWith(".staging-api.openpond.ai");
16651
+ } catch {
16652
+ return false;
16653
+ }
16654
+ }
16655
+ var DEFAULT_API_TIMEOUT_MS = 3e4;
16656
+ var DEFAULT_API_RESPONSE_BYTES = 8 * 1024 * 1024;
16657
+ var LONG_STREAM_API_OPTIONS = { timeoutMs: 15 * 60 * 1e3, maxResponseBytes: 64 * 1024 * 1024 };
16658
+ var ApiTimeoutError = class extends Error {
16659
+ timeoutMs;
16660
+ requestUrl;
16661
+ code = "OPENPOND_API_TIMEOUT";
16662
+ constructor(timeoutMs, requestUrl) {
16663
+ super(`API request timed out after ${timeoutMs}ms: ${requestUrl}`);
16664
+ this.timeoutMs = timeoutMs;
16665
+ this.requestUrl = requestUrl;
16666
+ this.name = "ApiTimeoutError";
16667
+ }
16668
+ };
16669
+ var ApiResponseTooLargeError = class extends Error {
16670
+ maximumBytes;
16671
+ requestUrl;
16672
+ code = "OPENPOND_API_RESPONSE_TOO_LARGE";
16673
+ constructor(maximumBytes, requestUrl) {
16674
+ super(`API response exceeded ${maximumBytes} bytes: ${requestUrl}`);
16675
+ this.maximumBytes = maximumBytes;
16676
+ this.requestUrl = requestUrl;
16677
+ this.name = "ApiResponseTooLargeError";
16678
+ }
16679
+ };
16680
+ var OpenPondApiError = class extends Error {
16681
+ status;
16682
+ apiMessage;
16683
+ code;
16684
+ constructor(status, errorCode, label, apiMessage = null) {
16685
+ const detail = apiMessage || errorCode;
16686
+ super(`${label} failed: ${status}${detail ? ` ${detail}` : ""}`);
16687
+ this.status = status;
16688
+ this.apiMessage = apiMessage;
16689
+ this.name = "OpenPondApiError";
16690
+ this.code = errorCode || "OPENPOND_API_ERROR";
16691
+ }
16692
+ };
16693
+ async function apiFetch2(baseUrl, token, requestPath, options = {}) {
16694
+ const { timeoutMs = DEFAULT_API_TIMEOUT_MS, maxResponseBytes = DEFAULT_API_RESPONSE_BYTES, ...init } = options;
16695
+ const requestUrl = `${baseUrl}${requestPath}`;
16696
+ const headers = withVercelProtectionBypass2(requestUrl, init.headers);
16697
+ headers.set("Content-Type", "application/json");
16698
+ const apiKey = process.env.OPENPOND_API_KEY;
16699
+ const trimmedToken = token?.trim() || "";
16700
+ const tokenIsApiKey = trimmedToken.startsWith("opk_");
16701
+ const effectiveApiKey = apiKey || (tokenIsApiKey ? trimmedToken : null);
16702
+ if (effectiveApiKey && !headers.has("openpond-api-key"))
16703
+ headers.set("openpond-api-key", effectiveApiKey);
16704
+ if (token) {
16705
+ headers.set("Authorization", tokenIsApiKey ? `ApiKey ${trimmedToken}` : `Bearer ${token}`);
16706
+ } else if (apiKey && !headers.has("Authorization")) {
16707
+ headers.set("Authorization", `ApiKey ${apiKey}`);
16708
+ }
16709
+ const timeoutController = new AbortController();
16710
+ const timeoutError = new ApiTimeoutError(timeoutMs, requestUrl);
16711
+ const timer = timeoutMs > 0 ? setTimeout(() => timeoutController.abort(timeoutError), timeoutMs) : null;
16712
+ timer?.unref?.();
16713
+ const signal = composedSignal(init.signal, timeoutController.signal, timeoutMs);
16714
+ const cleanup = () => {
16715
+ if (timer)
16716
+ clearTimeout(timer);
16717
+ };
16718
+ try {
16719
+ const response = await fetch(requestUrl, { ...init, headers, signal });
16720
+ return boundedResponse(response, {
16721
+ cleanup,
16722
+ maximumBytes: maxResponseBytes,
16723
+ requestUrl,
16724
+ timeoutController,
16725
+ timeoutError
16726
+ });
16727
+ } catch (error) {
16728
+ cleanup();
16729
+ if (timeoutController.signal.aborted)
16730
+ throw timeoutError;
16731
+ throw error;
16732
+ }
16733
+ }
16734
+ async function readApiJson(response, label) {
16735
+ let payload;
16736
+ try {
16737
+ const text = await response.text();
16738
+ payload = text ? JSON.parse(text) : {};
16739
+ } catch (error) {
16740
+ if (error instanceof ApiTimeoutError || error instanceof ApiResponseTooLargeError)
16741
+ throw error;
16742
+ payload = {};
16743
+ }
16744
+ if (!response.ok) {
16745
+ const errorCode = typeof payload.error === "string" ? payload.error : null;
16746
+ const apiMessage = typeof payload.message === "string" ? payload.message : null;
16747
+ throw new OpenPondApiError(response.status, errorCode, label, apiMessage);
16748
+ }
16749
+ return payload;
16750
+ }
16751
+ function boundedResponse(response, input) {
16752
+ if (!response.body) {
16753
+ input.cleanup();
16754
+ return response;
16755
+ }
16756
+ const contentLength = Number(response.headers.get("content-length"));
16757
+ if (input.maximumBytes > 0 && Number.isFinite(contentLength) && contentLength > input.maximumBytes) {
16758
+ input.cleanup();
16759
+ void response.body.cancel();
16760
+ throw new ApiResponseTooLargeError(input.maximumBytes, input.requestUrl);
16761
+ }
16762
+ const reader = response.body.getReader();
16763
+ let receivedBytes = 0;
16764
+ const body = new ReadableStream({
16765
+ async pull(controller) {
16766
+ try {
16767
+ const result = await reader.read();
16768
+ if (result.done) {
16769
+ input.cleanup();
16770
+ controller.close();
16771
+ return;
16772
+ }
16773
+ receivedBytes += result.value.byteLength;
16774
+ if (input.maximumBytes > 0 && receivedBytes > input.maximumBytes) {
16775
+ input.cleanup();
16776
+ await reader.cancel();
16777
+ controller.error(new ApiResponseTooLargeError(input.maximumBytes, input.requestUrl));
16778
+ return;
16779
+ }
16780
+ controller.enqueue(result.value);
16781
+ } catch (error) {
16782
+ input.cleanup();
16783
+ controller.error(input.timeoutController.signal.aborted ? input.timeoutError : error);
16784
+ }
16785
+ },
16786
+ async cancel(reason) {
16787
+ input.cleanup();
16788
+ await reader.cancel(reason);
16789
+ }
16790
+ });
16791
+ return new Response(body, {
16792
+ headers: response.headers,
16793
+ status: response.status,
16794
+ statusText: response.statusText
16795
+ });
16796
+ }
16797
+ function composedSignal(callerSignal, timeoutSignal, timeoutMs) {
16798
+ if (timeoutMs <= 0)
16799
+ return callerSignal ?? void 0;
16800
+ return callerSignal ? AbortSignal.any([callerSignal, timeoutSignal]) : timeoutSignal;
16801
+ }
16802
+ var DEFAULT_OPENPOND_WEB_BASE_URL = "https://openpond.ai";
16803
+ var DEFAULT_OPENPOND_API_BASE_URL2 = "https://api.openpond.ai";
16804
+ async function streamSandboxEventOutput(params) {
16805
+ const response = await apiFetch2(params.sandboxApiUrl, params.apiKey, params.path, { timeoutMs: 0, maxResponseBytes: 0 });
16806
+ if (!response.body) {
16807
+ return;
16808
+ }
16809
+ const reader = response.body.getReader();
16810
+ const decoder = new TextDecoder();
16811
+ let buffered = "";
16812
+ try {
16813
+ while (true) {
16814
+ const { done, value } = await reader.read();
16815
+ if (done)
16816
+ break;
16817
+ buffered += decoder.decode(value, { stream: true });
16818
+ let separatorIndex = buffered.indexOf("\n\n");
16819
+ while (separatorIndex !== -1) {
16820
+ const event2 = buffered.slice(0, separatorIndex);
16821
+ buffered = buffered.slice(separatorIndex + 2);
16822
+ const output = parseProcessOutputEvent(event2);
16823
+ if (output)
16824
+ process.stdout.write(output);
16825
+ separatorIndex = buffered.indexOf("\n\n");
16826
+ }
16827
+ }
16828
+ } finally {
16829
+ reader.releaseLock();
16830
+ }
16831
+ }
16832
+ function normalizePtyInput(input) {
16833
+ if (typeof input === "string") {
16834
+ return { dataBase64: Buffer.from(input, "utf-8").toString("base64") };
16835
+ }
16836
+ if (input instanceof Uint8Array) {
16837
+ return { dataBase64: Buffer.from(input).toString("base64") };
16838
+ }
16839
+ return input;
16840
+ }
16841
+ function parseProcessOutputEvent(event2) {
16842
+ if (!event2.includes("event: output")) {
16843
+ return null;
16844
+ }
16845
+ const dataLines = event2.split(/\r?\n/).filter((line) => line.startsWith("data: ")).map((line) => line.slice("data: ".length));
16846
+ if (dataLines.length === 0) {
16847
+ return null;
16848
+ }
16849
+ try {
16850
+ const parsed = JSON.parse(dataLines.join("\n"));
16851
+ return typeof parsed.output === "string" ? parsed.output : null;
16852
+ } catch {
16853
+ return null;
16854
+ }
16855
+ }
16856
+ function normalizeSandboxApiUrl2(baseUrlOrApiUrl) {
16857
+ const trimmed = baseUrlOrApiUrl.trim().replace(/\/$/, "");
16858
+ if (!trimmed) {
16859
+ throw new Error("sandbox API URL must be non-empty");
16860
+ }
16861
+ const url = new URL(trimmed);
16862
+ const normalizedPath = url.pathname.replace(/\/$/, "");
16863
+ if (normalizedPath.endsWith("/v1/sandboxes") || normalizedPath.endsWith("/api/sandboxes")) {
16864
+ return `${url.origin}${normalizedPath}`;
16865
+ }
16866
+ if (normalizedPath.endsWith("/v1")) {
16867
+ return `${url.origin}${normalizedPath}/sandboxes`;
16868
+ }
16869
+ if (isOpenPondHostedApiHost(url.hostname)) {
16870
+ return `${url.origin}${normalizedPath}/v1/sandboxes`;
16871
+ }
16872
+ if (url.origin === DEFAULT_OPENPOND_WEB_BASE_URL) {
16873
+ return `${DEFAULT_OPENPOND_API_BASE_URL2}/v1/sandboxes`;
16874
+ }
16875
+ return `${url.origin}${normalizedPath}/api/sandboxes`;
16876
+ }
16877
+ function apiRootUrlFromSandboxApiUrl(sandboxApiUrl) {
16878
+ const suffix = "/sandboxes";
16879
+ if (!sandboxApiUrl.endsWith(suffix)) {
16880
+ throw new Error("sandbox API URL must end with /sandboxes");
16881
+ }
16882
+ return sandboxApiUrl.slice(0, -suffix.length);
16883
+ }
16884
+ function isOpenPondHostedApiHost(hostname) {
16885
+ return hostname === "api.openpond.ai" || hostname === "staging-api.openpond.ai" || hostname.startsWith("api") && hostname.endsWith(".openpond.ai");
16886
+ }
16887
+ var OpenPondSandboxInstanceClient = class {
16888
+ apiKey;
16889
+ apiRootUrl;
16890
+ sandboxApiUrl;
16891
+ constructor(options) {
16892
+ this.apiKey = options.apiKey;
16893
+ this.sandboxApiUrl = normalizeSandboxApiUrl2(options.sandboxApiUrl ?? options.baseUrl ?? DEFAULT_OPENPOND_API_BASE_URL2);
16894
+ this.apiRootUrl = apiRootUrlFromSandboxApiUrl(this.sandboxApiUrl);
16895
+ }
16896
+ create(input, options = {}) {
16897
+ return this.request("", {
16898
+ method: "POST",
16899
+ headers: asyncRequestHeaders(options),
16900
+ body: JSON.stringify(input)
16901
+ }).then((payload) => payload.sandbox);
16902
+ }
16903
+ get(sandboxId) {
16904
+ return this.request(`/${encodeURIComponent(sandboxId)}`).then((payload) => payload.sandbox);
16905
+ }
16906
+ exec(sandboxId, input) {
16907
+ return this.request(`/${encodeURIComponent(sandboxId)}/exec`, {
16908
+ method: "POST",
16909
+ body: JSON.stringify(input)
16910
+ });
16911
+ }
16912
+ startProcess(sandboxId, input) {
16913
+ return this.request(`/${encodeURIComponent(sandboxId)}/processes`, {
16914
+ method: "POST",
16915
+ body: JSON.stringify(input)
16916
+ });
16917
+ }
16918
+ listProcesses(sandboxId) {
16919
+ return this.request(`/${encodeURIComponent(sandboxId)}/processes`);
16920
+ }
16921
+ getProcess(sandboxId, processId, input = {}) {
16922
+ const query = new URLSearchParams();
16923
+ if (input.since !== void 0)
16924
+ query.set("since", String(Math.max(0, input.since)));
16925
+ return this.request(`/${encodeURIComponent(sandboxId)}/processes/${encodeURIComponent(processId)}${query.size > 0 ? `?${query.toString()}` : ""}`);
16926
+ }
16927
+ stopProcess(sandboxId, processId) {
16928
+ return this.request(`/${encodeURIComponent(sandboxId)}/processes/${encodeURIComponent(processId)}`, {
16929
+ method: "DELETE"
16930
+ });
16931
+ }
16932
+ async streamProcessOutput(sandboxId, processId, input = {}) {
16933
+ const query = new URLSearchParams();
16934
+ if (input.since !== void 0)
16935
+ query.set("since", String(Math.max(0, input.since)));
16936
+ await streamSandboxEventOutput({
16937
+ sandboxApiUrl: this.sandboxApiUrl,
16938
+ apiKey: this.apiKey,
16939
+ path: `/${encodeURIComponent(sandboxId)}/processes/${encodeURIComponent(processId)}/stream${query.size > 0 ? `?${query.toString()}` : ""}`
16940
+ });
16941
+ }
16942
+ startPty(sandboxId, input = {}) {
16943
+ return this.request(`/${encodeURIComponent(sandboxId)}/pty`, {
16944
+ method: "POST",
16945
+ body: JSON.stringify(input)
16946
+ });
16947
+ }
16948
+ listPtys(sandboxId) {
16949
+ return this.request(`/${encodeURIComponent(sandboxId)}/pty`);
16950
+ }
16951
+ getPty(sandboxId, ptyId, input = {}) {
16952
+ const query = new URLSearchParams();
16953
+ if (input.since !== void 0)
16954
+ query.set("since", String(Math.max(0, input.since)));
16955
+ return this.request(`/${encodeURIComponent(sandboxId)}/pty/${encodeURIComponent(ptyId)}${query.size > 0 ? `?${query.toString()}` : ""}`);
16956
+ }
16957
+ writePtyInput(sandboxId, ptyId, input) {
16958
+ return this.request(`/${encodeURIComponent(sandboxId)}/pty/${encodeURIComponent(ptyId)}/input`, {
16959
+ method: "POST",
16960
+ body: JSON.stringify(normalizePtyInput(input))
16961
+ });
16962
+ }
16963
+ stopPty(sandboxId, ptyId) {
16964
+ return this.request(`/${encodeURIComponent(sandboxId)}/pty/${encodeURIComponent(ptyId)}`, {
16965
+ method: "DELETE"
16966
+ });
16967
+ }
16968
+ async streamPtyOutput(sandboxId, ptyId, input = {}) {
16969
+ const query = new URLSearchParams();
16970
+ if (input.since !== void 0)
16971
+ query.set("since", String(Math.max(0, input.since)));
16972
+ await streamSandboxEventOutput({
16973
+ sandboxApiUrl: this.sandboxApiUrl,
16974
+ apiKey: this.apiKey,
16975
+ path: `/${encodeURIComponent(sandboxId)}/pty/${encodeURIComponent(ptyId)}/stream${query.size > 0 ? `?${query.toString()}` : ""}`
16976
+ });
16977
+ }
16978
+ uploadFile(sandboxId, path37, contents) {
16979
+ return this.uploadFileBase64(sandboxId, path37, Buffer.from(contents, "utf-8").toString("base64"));
16980
+ }
16981
+ uploadFileBase64(sandboxId, path37, contentsBase64) {
16982
+ return this.request(`/${encodeURIComponent(sandboxId)}/files`, {
16983
+ method: "POST",
16984
+ body: JSON.stringify({
16985
+ path: path37,
16986
+ contentsBase64
16987
+ })
16988
+ });
16989
+ }
16990
+ async downloadFile(sandboxId, path37) {
16991
+ const payload = await this.downloadFileResponse(sandboxId, path37);
16992
+ return Buffer.from(payload.file.contentsBase64, "base64").toString("utf-8");
16993
+ }
16994
+ downloadFileResponse(sandboxId, input) {
16995
+ const normalized = typeof input === "string" ? { path: input } : input;
16996
+ const query = new URLSearchParams({ path: normalized.path });
16997
+ if (normalized.offsetBytes !== void 0) {
16998
+ query.set("offsetBytes", String(normalized.offsetBytes));
16999
+ }
17000
+ if (normalized.maxBytes !== void 0) {
17001
+ query.set("maxBytes", String(normalized.maxBytes));
17002
+ }
17003
+ return this.request(`/${encodeURIComponent(sandboxId)}/files?${query.toString()}`);
17004
+ }
17005
+ listFiles(sandboxId, input = {}) {
17006
+ const query = new URLSearchParams({ list: "1" });
17007
+ if (input.path)
17008
+ query.set("path", input.path);
17009
+ if (input.recursive !== void 0)
17010
+ query.set("recursive", String(input.recursive));
17011
+ if (input.maxEntries !== void 0)
17012
+ query.set("maxEntries", String(input.maxEntries));
17013
+ return this.request(`/${encodeURIComponent(sandboxId)}/files?${query.toString()}`);
17014
+ }
17015
+ deleteFile(sandboxId, path37, input = {}) {
17016
+ const query = new URLSearchParams({ path: path37 });
17017
+ if (input.recursive !== void 0)
17018
+ query.set("recursive", String(input.recursive));
17019
+ return this.request(`/${encodeURIComponent(sandboxId)}/files?${query.toString()}`, {
17020
+ method: "DELETE"
17021
+ });
17022
+ }
17023
+ statFile(sandboxId, path37) {
17024
+ const query = new URLSearchParams({ stat: "1", path: path37 });
17025
+ return this.request(`/${encodeURIComponent(sandboxId)}/files?${query.toString()}`);
17026
+ }
17027
+ mkdir(sandboxId, input) {
17028
+ const normalized = typeof input === "string" ? { path: input } : input;
17029
+ const query = new URLSearchParams({ path: normalized.path });
17030
+ if (normalized.recursive !== void 0)
17031
+ query.set("recursive", String(normalized.recursive));
17032
+ return this.request(`/${encodeURIComponent(sandboxId)}/files?${query.toString()}`, {
17033
+ method: "PUT"
17034
+ });
17035
+ }
17036
+ moveFile(sandboxId, input) {
17037
+ const query = new URLSearchParams({
17038
+ fromPath: input.fromPath,
17039
+ toPath: input.toPath
17040
+ });
17041
+ if (input.overwrite !== void 0)
17042
+ query.set("overwrite", String(input.overwrite));
17043
+ return this.request(`/${encodeURIComponent(sandboxId)}/files?${query.toString()}`, {
17044
+ method: "PATCH"
17045
+ });
17046
+ }
17047
+ searchFiles(sandboxId, input) {
17048
+ const query = new URLSearchParams({
17049
+ search: "1",
17050
+ query: input.query
17051
+ });
17052
+ if (input.path)
17053
+ query.set("path", input.path);
17054
+ if (input.maxResults !== void 0)
17055
+ query.set("maxResults", String(input.maxResults));
17056
+ return this.request(`/${encodeURIComponent(sandboxId)}/files?${query.toString()}`);
17057
+ }
17058
+ openPort(sandboxId, input) {
17059
+ return this.request(`/${encodeURIComponent(sandboxId)}/ports`, {
17060
+ method: "POST",
17061
+ body: JSON.stringify(input)
17062
+ });
17063
+ }
17064
+ createSnapshot(sandboxId, input) {
17065
+ return this.request(`/${encodeURIComponent(sandboxId)}/snapshots`, {
17066
+ method: "POST",
17067
+ body: JSON.stringify(input)
17068
+ });
17069
+ }
17070
+ updateSnapshot(sandboxId, snapshotId, input) {
17071
+ return this.request(`/${encodeURIComponent(sandboxId)}/snapshots/${encodeURIComponent(snapshotId)}`, {
17072
+ method: "PATCH",
17073
+ body: JSON.stringify(input)
17074
+ });
17075
+ }
17076
+ validateSnapshot(sandboxId, snapshotId, input = {}) {
17077
+ return this.request(`/${encodeURIComponent(sandboxId)}/snapshots/${encodeURIComponent(snapshotId)}/validate`, {
17078
+ method: "POST",
17079
+ body: JSON.stringify(input)
17080
+ });
17081
+ }
17082
+ publishSnapshot(sandboxId, snapshotId) {
17083
+ return this.request(`/${encodeURIComponent(sandboxId)}/snapshots/${encodeURIComponent(snapshotId)}/publish`, {
17084
+ method: "POST"
17085
+ });
17086
+ }
17087
+ fork(sandboxId, input = {}) {
17088
+ return this.request(`/${encodeURIComponent(sandboxId)}/fork`, {
17089
+ method: "POST",
17090
+ body: JSON.stringify(input)
17091
+ });
17092
+ }
17093
+ stop(sandboxId, options = {}) {
17094
+ const query = new URLSearchParams();
17095
+ if (options.failOnUnpreservedChanges) {
17096
+ query.set("failOnUnpreservedChanges", "true");
17097
+ }
17098
+ return this.request(`/${encodeURIComponent(sandboxId)}/stop${query.size > 0 ? `?${query.toString()}` : ""}`, {
17099
+ method: "POST",
17100
+ headers: asyncRequestHeaders(options)
17101
+ });
17102
+ }
17103
+ start(sandboxId, options = {}) {
17104
+ return this.request(`/${encodeURIComponent(sandboxId)}/start`, {
17105
+ method: "POST",
17106
+ headers: asyncRequestHeaders(options)
17107
+ });
17108
+ }
17109
+ restore(sandboxId) {
17110
+ return this.request(`/${encodeURIComponent(sandboxId)}/restore`, {
17111
+ method: "POST"
17112
+ });
17113
+ }
17114
+ delete(sandboxId, options = {}) {
17115
+ const query = new URLSearchParams();
17116
+ if (options.failOnUnpreservedChanges) {
17117
+ query.set("failOnUnpreservedChanges", "true");
17118
+ }
17119
+ return this.request(`/${encodeURIComponent(sandboxId)}${query.size > 0 ? `?${query.toString()}` : ""}`, {
17120
+ method: "DELETE",
17121
+ headers: asyncRequestHeaders(options)
17122
+ }).then((payload) => payload.sandbox);
17123
+ }
17124
+ receipts(sandboxId) {
17125
+ return this.request(`/${encodeURIComponent(sandboxId)}/receipts`).then((payload) => payload.receipts);
17126
+ }
17127
+ logs(sandboxId) {
17128
+ return this.request(`/${encodeURIComponent(sandboxId)}/logs`).then((payload) => payload.logs);
17129
+ }
17130
+ gitStatus(sandboxId) {
17131
+ return this.request(`/${encodeURIComponent(sandboxId)}/git/status`);
17132
+ }
17133
+ gitDiff(sandboxId, input = {}) {
17134
+ return this.request(`/${encodeURIComponent(sandboxId)}/git/diff`, {
17135
+ method: "POST",
17136
+ body: JSON.stringify(input)
17137
+ });
17138
+ }
17139
+ gitExportPatch(sandboxId, input = {}) {
17140
+ return this.request(`/${encodeURIComponent(sandboxId)}/git/export-patch`, {
17141
+ method: "POST",
17142
+ body: JSON.stringify(input)
17143
+ });
17144
+ }
17145
+ gitBranch(sandboxId, input) {
17146
+ return this.request(`/${encodeURIComponent(sandboxId)}/git/branch`, {
17147
+ method: "POST",
17148
+ body: JSON.stringify(input)
17149
+ });
17150
+ }
17151
+ gitCommit(sandboxId, input) {
17152
+ return this.request(`/${encodeURIComponent(sandboxId)}/git/commit`, {
17153
+ method: "POST",
17154
+ body: JSON.stringify(input)
17155
+ });
17156
+ }
17157
+ gitPull(sandboxId, input = {}) {
17158
+ return this.request(`/${encodeURIComponent(sandboxId)}/git/pull`, {
17159
+ method: "POST",
17160
+ body: JSON.stringify(input)
17161
+ });
17162
+ }
17163
+ gitPush(sandboxId, input = {}) {
17164
+ return this.request(`/${encodeURIComponent(sandboxId)}/git/push`, {
17165
+ method: "POST",
17166
+ body: JSON.stringify(input)
17167
+ });
17168
+ }
17169
+ billing(sandboxId) {
17170
+ return this.request(`/${encodeURIComponent(sandboxId)}/billing`);
17171
+ }
17172
+ pricing() {
17173
+ return this.request("/pricing");
17174
+ }
17175
+ costs(input = {}) {
17176
+ const query = new URLSearchParams();
17177
+ if (input.teamId)
17178
+ query.set("teamId", input.teamId);
17179
+ if (input.projectId)
17180
+ query.set("projectId", input.projectId);
17181
+ if (input.agentId)
17182
+ query.set("agentId", input.agentId);
17183
+ return this.request(`/costs${query.size > 0 ? `?${query.toString()}` : ""}`);
17184
+ }
17185
+ integrationLeases(sandboxId) {
17186
+ return this.request(`/${encodeURIComponent(sandboxId)}/integrations`);
17187
+ }
17188
+ attachIntegrationConnection(sandboxId, input) {
17189
+ return this.request(`/${encodeURIComponent(sandboxId)}/integrations`, {
17190
+ method: "POST",
17191
+ body: JSON.stringify(input)
17192
+ });
17193
+ }
17194
+ removeIntegrationLease(sandboxId, leaseId) {
17195
+ return this.request(`/${encodeURIComponent(sandboxId)}/integrations`, {
17196
+ method: "DELETE",
17197
+ body: JSON.stringify({ leaseId })
17198
+ });
17199
+ }
17200
+ async request(path37, init = {}) {
17201
+ const response = await apiFetch2(this.sandboxApiUrl, this.apiKey, path37, init);
17202
+ return readApiJson(response, "Sandbox request");
17203
+ }
17204
+ async requestApiRoot(path37, init = {}) {
17205
+ const response = await apiFetch2(this.apiRootUrl, this.apiKey, path37, init);
17206
+ return readApiJson(response, "OpenPond API request");
17207
+ }
17208
+ };
17209
+ var OpenPondSandboxClient = class extends OpenPondSandboxInstanceClient {
17210
+ runtimes = createSandboxRuntimeNamespace(this);
17211
+ sandboxes = createSandboxNamespace(this);
17212
+ profile = createSandboxProfileNamespace(this);
17213
+ projects = createSandboxProjectNamespace(this);
17214
+ agents = createSandboxAgentNamespace(this);
17215
+ list(input = {}) {
17216
+ const query = new URLSearchParams();
17217
+ if (input.teamId)
17218
+ query.set("teamId", input.teamId);
17219
+ if (input.projectId)
17220
+ query.set("projectId", input.projectId);
17221
+ if (input.agentId)
17222
+ query.set("agentId", input.agentId);
17223
+ return this.request(query.size > 0 ? `?${query.toString()}` : "").then((payload) => payload.sandboxes);
17224
+ }
17225
+ listSecrets(input = {}) {
17226
+ const query = new URLSearchParams();
17227
+ if (input.teamId)
17228
+ query.set("teamId", input.teamId);
17229
+ return this.requestApiRoot(`/sandbox-secrets${query.size > 0 ? `?${query.toString()}` : ""}`).then((payload) => payload.secrets);
17230
+ }
17231
+ getSecret(secretId, input = {}) {
17232
+ const query = new URLSearchParams();
17233
+ if (input.teamId)
17234
+ query.set("teamId", input.teamId);
17235
+ return this.requestApiRoot(`/sandbox-secrets/${encodeURIComponent(secretId)}${query.size > 0 ? `?${query.toString()}` : ""}`).then((payload) => payload.secret);
17236
+ }
17237
+ createSecret(input) {
17238
+ return this.requestApiRoot("/sandbox-secrets", {
17239
+ method: "POST",
17240
+ body: JSON.stringify(input)
17241
+ }).then((payload) => payload.secret);
17242
+ }
17243
+ rotateSecret(secretId, input) {
17244
+ const query = new URLSearchParams();
17245
+ if (input.teamId)
17246
+ query.set("teamId", input.teamId);
17247
+ const { teamId: _teamId, ...body } = input;
17248
+ return this.requestApiRoot(`/sandbox-secrets/${encodeURIComponent(secretId)}/rotate${query.size > 0 ? `?${query.toString()}` : ""}`, {
17249
+ method: "POST",
17250
+ body: JSON.stringify(body)
17251
+ }).then((payload) => payload.secret);
17252
+ }
17253
+ attachSecret(secretId, input) {
17254
+ const query = new URLSearchParams();
17255
+ if (input.teamId)
17256
+ query.set("teamId", input.teamId);
17257
+ const { teamId: _teamId, ...body } = input;
17258
+ return this.requestApiRoot(`/sandbox-secrets/${encodeURIComponent(secretId)}/attach${query.size > 0 ? `?${query.toString()}` : ""}`, {
17259
+ method: "POST",
17260
+ body: JSON.stringify(body)
17261
+ }).then((payload) => payload.secret);
17262
+ }
17263
+ revokeSecret(secretId, input = {}) {
17264
+ const query = new URLSearchParams();
17265
+ if (input.teamId)
17266
+ query.set("teamId", input.teamId);
17267
+ return this.requestApiRoot(`/sandbox-secrets/${encodeURIComponent(secretId)}/revoke${query.size > 0 ? `?${query.toString()}` : ""}`, { method: "POST" }).then((payload) => payload.secret);
17268
+ }
17269
+ deleteSecret(secretId, input = {}) {
17270
+ const query = new URLSearchParams();
17271
+ if (input.teamId)
17272
+ query.set("teamId", input.teamId);
17273
+ return this.requestApiRoot(`/sandbox-secrets/${encodeURIComponent(secretId)}${query.size > 0 ? `?${query.toString()}` : ""}`, { method: "DELETE" }).then((payload) => payload.secret);
17274
+ }
17275
+ snapshotCatalog(input = {}) {
17276
+ const query = new URLSearchParams();
17277
+ if (input.teamId)
17278
+ query.set("teamId", input.teamId);
17279
+ if (input.projectId)
17280
+ query.set("projectId", input.projectId);
17281
+ if (input.agentId)
17282
+ query.set("agentId", input.agentId);
17283
+ if (input.q)
17284
+ query.set("q", input.q);
17285
+ if (input.kind)
17286
+ query.set("kind", input.kind);
17287
+ if (input.replayState)
17288
+ query.set("replayState", input.replayState);
17289
+ if (input.visibility)
17290
+ query.set("visibility", input.visibility);
17291
+ if (input.tag)
17292
+ query.set("tag", input.tag);
17293
+ if (input.useCase)
17294
+ query.set("useCase", input.useCase);
17295
+ if (input.limit)
17296
+ query.set("limit", String(input.limit));
17297
+ return this.request(`/catalog/snapshots${query.size > 0 ? `?${query.toString()}` : ""}`);
17298
+ }
17299
+ listSandboxRuntimes(input = {}) {
17300
+ const query = new URLSearchParams();
17301
+ if (input.teamId)
17302
+ query.set("teamId", input.teamId);
17303
+ if (input.projectId)
17304
+ query.set("projectId", input.projectId);
17305
+ if (input.agentId)
17306
+ query.set("agentId", input.agentId);
17307
+ return this.requestApiRoot(`/runtimes${query.size > 0 ? `?${query.toString()}` : ""}`).then((payload) => payload.runtimes);
17308
+ }
17309
+ listProjects(input) {
17310
+ const query = new URLSearchParams({ teamId: input.teamId });
17311
+ return this.requestApiRoot(`/projects?${query.toString()}`).then((payload) => payload.projects);
17312
+ }
17313
+ upsertProject(input) {
17314
+ return this.requestApiRoot("/projects", {
17315
+ method: "POST",
17316
+ body: JSON.stringify(input)
17317
+ }).then((payload) => payload.project);
17318
+ }
17319
+ getHostedProfile(input) {
17320
+ const query = new URLSearchParams({ teamId: input.teamId });
17321
+ return this.requestApiRoot(`/profile?${query.toString()}`).then((payload) => payload.profile);
17322
+ }
17323
+ ensureHostedProfile(input) {
17324
+ const query = new URLSearchParams({ teamId: input.teamId });
17325
+ return this.requestApiRoot(`/profile/ensure?${query.toString()}`, { method: "POST" }).then((payload) => {
17326
+ if (!payload.profile) {
17327
+ throw new Error("hosted_profile_missing");
17328
+ }
17329
+ return payload.profile;
17330
+ });
17331
+ }
17332
+ pushHostedProfile(input) {
17333
+ const query = new URLSearchParams({ teamId: input.teamId });
17334
+ const { teamId: _teamId, ...body } = input;
17335
+ return this.requestApiRoot(`/profile/push?${query.toString()}`, {
17336
+ method: "POST",
17337
+ body: JSON.stringify(body)
17338
+ });
17339
+ }
17340
+ async upsertProjectGitRemote(input) {
17341
+ const project = await this.upsertProject(input);
17342
+ return this.ensureProjectGitRemote(project.id, { teamId: input.teamId });
17343
+ }
17344
+ getProject(projectId, input) {
17345
+ const query = new URLSearchParams({ teamId: input.teamId });
17346
+ return this.requestApiRoot(`/projects/${encodeURIComponent(projectId)}?${query.toString()}`).then((payload) => payload.project);
17347
+ }
17348
+ syncProject(projectId, input) {
17349
+ const query = new URLSearchParams({ teamId: input.teamId });
17350
+ return this.requestApiRoot(`/projects/${encodeURIComponent(projectId)}/sync?${query.toString()}`, { method: "POST" }).then((payload) => payload.project);
17351
+ }
17352
+ ensureProjectGitRemote(projectId, input) {
17353
+ const query = new URLSearchParams({ teamId: input.teamId });
17354
+ return this.requestApiRoot(`/projects/${encodeURIComponent(projectId)}/git?${query.toString()}`, { method: "POST" });
17355
+ }
17356
+ uploadProjectSource(projectId, input) {
17357
+ const query = new URLSearchParams({ teamId: input.teamId });
17358
+ const { teamId: _teamId, ...body } = input;
17359
+ return this.requestApiRoot(`/projects/${encodeURIComponent(projectId)}/source?${query.toString()}`, {
17360
+ method: "POST",
17361
+ body: JSON.stringify(body)
17362
+ }).then((payload) => payload.project);
17363
+ }
17364
+ updateProject(projectId, input) {
17365
+ const query = new URLSearchParams({ teamId: input.teamId });
17366
+ const { teamId: _teamId, ...body } = input;
17367
+ return this.requestApiRoot(`/projects/${encodeURIComponent(projectId)}?${query.toString()}`, {
17368
+ method: "PATCH",
17369
+ body: JSON.stringify(body)
17370
+ }).then((payload) => payload.project);
17371
+ }
17372
+ archiveProject(projectId, input) {
17373
+ const query = new URLSearchParams({ teamId: input.teamId });
17374
+ return this.requestApiRoot(`/projects/${encodeURIComponent(projectId)}?${query.toString()}`, { method: "DELETE" }).then((payload) => payload.project);
17375
+ }
17376
+ listAgents(input) {
17377
+ const query = new URLSearchParams({ teamId: input.teamId });
17378
+ return this.requestApiRoot(`/agents?${query.toString()}`).then((payload) => payload.agents);
17379
+ }
17380
+ upsertAgent(input) {
17381
+ return this.requestApiRoot("/agents", {
17382
+ method: "POST",
17383
+ body: JSON.stringify(input)
17384
+ }).then((payload) => payload.agent);
17385
+ }
17386
+ getAgent(agentId, input) {
17387
+ const query = new URLSearchParams({ teamId: input.teamId });
17388
+ return this.requestApiRoot(`/agents/${encodeURIComponent(agentId)}?${query.toString()}`).then((payload) => payload.agent);
17389
+ }
17390
+ archiveAgent(agentId, input) {
17391
+ const query = new URLSearchParams({ teamId: input.teamId });
17392
+ return this.requestApiRoot(`/agents/${encodeURIComponent(agentId)}?${query.toString()}`, { method: "DELETE" }).then((payload) => payload.agent);
17393
+ }
17394
+ updateAgent(agentId, input) {
17395
+ const query = new URLSearchParams({ teamId: input.teamId });
17396
+ const { teamId: _teamId, ...body } = input;
17397
+ return this.requestApiRoot(`/agents/${encodeURIComponent(agentId)}?${query.toString()}`, {
17398
+ method: "PATCH",
17399
+ body: JSON.stringify(body)
17400
+ }).then((payload) => payload.agent);
17401
+ }
17402
+ runAgent(agentId, input) {
17403
+ return this.requestApiRoot(`/agents/${encodeURIComponent(agentId)}/run`, {
17404
+ method: "POST",
17405
+ headers: {
17406
+ Prefer: "respond-async"
17407
+ },
17408
+ body: JSON.stringify(input)
17409
+ });
17410
+ }
17411
+ getAgentSourceDeployPlan(agentId, input) {
17412
+ const query = new URLSearchParams({ teamId: input.teamId });
17413
+ return this.requestApiRoot(`/agents/${encodeURIComponent(agentId)}/source/deploy-plan?${query.toString()}`).then((payload) => payload.deployPlan);
17414
+ }
17415
+ listAgentManifestSnapshots(agentId, input) {
17416
+ const query = new URLSearchParams({ teamId: input.teamId });
17417
+ if (input.limit !== void 0)
17418
+ query.set("limit", String(input.limit));
17419
+ return this.requestApiRoot(`/agents/${encodeURIComponent(agentId)}/source/manifest-snapshots?${query.toString()}`).then((payload) => payload.manifestSnapshots);
17420
+ }
17421
+ requestAgentSourceChecks(agentId, input) {
17422
+ const query = new URLSearchParams({ teamId: input.teamId });
17423
+ const { teamId: _teamId, ...body } = input;
17424
+ return this.requestApiRoot(`/agents/${encodeURIComponent(agentId)}/source/checks?${query.toString()}`, {
17425
+ method: "POST",
17426
+ body: JSON.stringify(body)
17427
+ });
17428
+ }
17429
+ publishAgentSource(agentId, input) {
17430
+ const query = new URLSearchParams({ teamId: input.teamId });
17431
+ const { teamId: _teamId, ...body } = input;
17432
+ return this.requestApiRoot(`/agents/${encodeURIComponent(agentId)}/source/publish?${query.toString()}`, {
17433
+ method: "POST",
17434
+ body: JSON.stringify(body)
17435
+ });
17436
+ }
17437
+ getMicrosoftTeamsBotOverview(input) {
17438
+ const query = new URLSearchParams({ teamId: input.teamId });
17439
+ return this.requestApiRoot(`/teams/bot/overview?${query.toString()}`);
17440
+ }
17441
+ bindMicrosoftTeamsBotConversation(input) {
17442
+ return this.requestApiRoot("/teams/bot/bindings", {
17443
+ method: "POST",
17444
+ body: JSON.stringify(input)
17445
+ });
17446
+ }
17447
+ rebindMicrosoftTeamsBotConversation(bindingId, input) {
17448
+ return this.requestApiRoot(`/teams/bot/bindings/${encodeURIComponent(bindingId)}`, {
17449
+ method: "PATCH",
17450
+ body: JSON.stringify(input)
17451
+ });
17452
+ }
17453
+ unlinkMicrosoftTeamsBotConversation(input) {
17454
+ return this.requestApiRoot(`/teams/bot/bindings/${encodeURIComponent(input.bindingId)}`, {
17455
+ method: "DELETE",
17456
+ body: JSON.stringify({ teamId: input.teamId })
17457
+ });
17458
+ }
17459
+ sendMicrosoftTeamsBotDiagnostic(input) {
17460
+ return this.requestApiRoot("/teams/bot/diagnostics", {
17461
+ method: "POST",
17462
+ body: JSON.stringify(input)
17463
+ });
17464
+ }
17465
+ sendMicrosoftTeamsBotDiagnosticRun(input) {
17466
+ return this.requestApiRoot("/teams/bot/diagnostics/run", {
17467
+ method: "POST",
17468
+ body: JSON.stringify(input)
17469
+ });
17470
+ }
17471
+ createSandboxRuntime(input) {
17472
+ return this.requestApiRoot("/runtimes", {
17473
+ method: "POST",
17474
+ body: JSON.stringify(input)
17475
+ }).then((payload) => payload.runtime);
17476
+ }
17477
+ sandboxRuntime(runtimeId, initial = null) {
17478
+ return createSandboxRuntimeHandle(this, runtimeId, initial);
17479
+ }
17480
+ getSandboxRuntime(runtimeId) {
17481
+ return this.requestApiRoot(`/runtimes/${encodeURIComponent(runtimeId)}`).then((payload) => payload.runtime);
17482
+ }
17483
+ createSandboxRuntimeSandbox(runtimeId, input = {}, options = {}) {
17484
+ return this.requestApiRoot(`/runtimes/${encodeURIComponent(runtimeId)}/sandbox`, {
17485
+ method: "POST",
17486
+ headers: asyncRequestHeaders(options),
17487
+ body: JSON.stringify(input)
17488
+ });
17489
+ }
17490
+ updateSandboxRuntimeStatus(runtimeId, input) {
17491
+ return this.requestApiRoot(`/runtimes/${encodeURIComponent(runtimeId)}/status`, {
17492
+ method: "PATCH",
17493
+ body: JSON.stringify(input)
17494
+ }).then((payload) => payload.runtime);
17495
+ }
17496
+ listSandboxRuntimeEvents(runtimeId) {
17497
+ return this.requestApiRoot(`/runtimes/${encodeURIComponent(runtimeId)}/events`);
17498
+ }
17499
+ emitSandboxRuntimeEvent(runtimeId, input) {
17500
+ return this.requestApiRoot(`/runtimes/${encodeURIComponent(runtimeId)}/events`, {
17501
+ method: "POST",
17502
+ body: JSON.stringify(input)
17503
+ });
17504
+ }
17505
+ checkpointSandboxRuntime(runtimeId, input) {
17506
+ return this.requestApiRoot(`/runtimes/${encodeURIComponent(runtimeId)}/checkpoints`, {
17507
+ method: "POST",
17508
+ body: JSON.stringify(input)
17509
+ }).then((payload) => payload.runtime);
17510
+ }
17511
+ promoteSandboxRuntime(runtimeId, input, options = {}) {
17512
+ const query = new URLSearchParams();
17513
+ if (options.teamId)
17514
+ query.set("teamId", options.teamId);
17515
+ return this.requestApiRoot(`/runtimes/${encodeURIComponent(runtimeId)}/promote${query.size > 0 ? `?${query.toString()}` : ""}`, {
17516
+ method: "POST",
17517
+ body: JSON.stringify(input)
17518
+ });
17519
+ }
17520
+ preserveSandboxRuntimeSource(runtimeId, input = {}, options = {}) {
17521
+ const query = new URLSearchParams();
17522
+ if (options.teamId)
17523
+ query.set("teamId", options.teamId);
17524
+ return this.requestApiRoot(`/runtimes/${encodeURIComponent(runtimeId)}/preserve-source${query.size > 0 ? `?${query.toString()}` : ""}`, {
17525
+ method: "POST",
17526
+ body: JSON.stringify(input)
17527
+ });
17528
+ }
17529
+ forkSnapshot(snapshotId, input = {}, options = {}) {
17530
+ const query = new URLSearchParams();
17531
+ if (input.teamId)
17532
+ query.set("teamId", input.teamId);
17533
+ if (input.projectId)
17534
+ query.set("projectId", input.projectId);
17535
+ if (options.async)
17536
+ query.set("async", "1");
17537
+ const { teamId: _teamId, projectId: _projectId, ...body } = input;
17538
+ return this.request(`/catalog/snapshots/${encodeURIComponent(snapshotId)}/fork${query.size > 0 ? `?${query.toString()}` : ""}`, {
17539
+ method: "POST",
17540
+ headers: options.async ? { Prefer: "respond-async" } : void 0,
17541
+ body: JSON.stringify({
17542
+ ...body,
17543
+ snapshotId
17544
+ })
17545
+ });
17546
+ }
17547
+ templates(input = {}) {
17548
+ const query = new URLSearchParams();
17549
+ if (input.teamId)
17550
+ query.set("teamId", input.teamId);
17551
+ if (input.projectId)
17552
+ query.set("projectId", input.projectId);
17553
+ if (input.q)
17554
+ query.set("q", input.q);
17555
+ if (input.name)
17556
+ query.set("name", input.name);
17557
+ if (input.version)
17558
+ query.set("version", input.version);
17559
+ if (input.visibility)
17560
+ query.set("visibility", input.visibility);
17561
+ if (input.tag)
17562
+ query.set("tag", input.tag);
17563
+ if (input.useCase)
17564
+ query.set("useCase", input.useCase);
17565
+ if (input.limit)
17566
+ query.set("limit", String(input.limit));
17567
+ return this.request(`/templates${query.size > 0 ? `?${query.toString()}` : ""}`);
17568
+ }
17569
+ publishedSnapshots(input = {}) {
17570
+ const query = new URLSearchParams();
17571
+ if (input.teamId)
17572
+ query.set("teamId", input.teamId);
17573
+ if (input.projectId)
17574
+ query.set("projectId", input.projectId);
17575
+ if (input.q)
17576
+ query.set("q", input.q);
17577
+ if (input.name)
17578
+ query.set("name", input.name);
17579
+ if (input.version)
17580
+ query.set("version", input.version);
17581
+ if (input.visibility)
17582
+ query.set("visibility", input.visibility);
17583
+ if (input.tag)
17584
+ query.set("tag", input.tag);
17585
+ if (input.useCase)
17586
+ query.set("useCase", input.useCase);
17587
+ if (input.limit)
17588
+ query.set("limit", String(input.limit));
17589
+ return this.request(`/published-snapshots${query.size > 0 ? `?${query.toString()}` : ""}`).then((payload) => {
17590
+ const publishedSnapshots = payload.publishedSnapshots ?? payload.templates;
17591
+ return {
17592
+ ...payload,
17593
+ templates: publishedSnapshots,
17594
+ publishedSnapshots
17595
+ };
17596
+ });
17597
+ }
17598
+ launchTemplate(input) {
17599
+ const query = new URLSearchParams();
17600
+ if (input.teamId)
17601
+ query.set("teamId", input.teamId);
17602
+ if (input.projectId)
17603
+ query.set("projectId", input.projectId);
17604
+ const { teamId: _teamId, projectId: _projectId, ...body } = input;
17605
+ return this.request(`/templates/launch${query.size > 0 ? `?${query.toString()}` : ""}`, {
17606
+ method: "POST",
17607
+ body: JSON.stringify(body)
17608
+ });
17609
+ }
17610
+ runPublishedSnapshot(input) {
17611
+ const query = new URLSearchParams();
17612
+ if (input.teamId)
17613
+ query.set("teamId", input.teamId);
17614
+ if (input.projectId)
17615
+ query.set("projectId", input.projectId);
17616
+ const { teamId: _teamId, projectId: _projectId, ...body } = input;
17617
+ return this.request(`/published-snapshots/launch${query.size > 0 ? `?${query.toString()}` : ""}`, {
17618
+ method: "POST",
17619
+ body: JSON.stringify(body)
17620
+ }).then((payload) => {
17621
+ const publishedSnapshot = payload.publishedSnapshot ?? payload.template;
17622
+ return {
17623
+ ...payload,
17624
+ template: publishedSnapshot,
17625
+ publishedSnapshot
17626
+ };
17627
+ });
17628
+ }
17629
+ listSchedules(input = {}) {
17630
+ const query = new URLSearchParams();
17631
+ if (input.teamId)
17632
+ query.set("teamId", input.teamId);
17633
+ if (input.projectId)
17634
+ query.set("projectId", input.projectId);
17635
+ if (input.sourceSandboxId)
17636
+ query.set("sourceSandboxId", input.sourceSandboxId);
17637
+ return this.request(`/schedules${query.size > 0 ? `?${query.toString()}` : ""}`);
17638
+ }
17639
+ createSchedule(input) {
17640
+ const query = new URLSearchParams();
17641
+ if (input.projectId)
17642
+ query.set("projectId", input.projectId);
17643
+ const { projectId: _projectId, ...body } = input;
17644
+ return this.request(`/schedules${query.size > 0 ? `?${query.toString()}` : ""}`, {
17645
+ method: "POST",
17646
+ body: JSON.stringify(body)
17647
+ });
17648
+ }
17649
+ getSchedule(scheduleId) {
17650
+ return this.request(`/schedules/${encodeURIComponent(scheduleId)}`);
17651
+ }
17652
+ updateSchedule(scheduleId, input) {
17653
+ return this.request(`/schedules/${encodeURIComponent(scheduleId)}`, {
17654
+ method: "PATCH",
17655
+ body: JSON.stringify(input)
17656
+ });
17657
+ }
17658
+ deleteSchedule(scheduleId) {
17659
+ return this.request(`/schedules/${encodeURIComponent(scheduleId)}`, {
17660
+ method: "DELETE"
17661
+ });
17662
+ }
17663
+ listScheduleRuns(scheduleId, input = {}) {
17664
+ const query = new URLSearchParams();
17665
+ if (input.limit !== void 0)
17666
+ query.set("limit", String(input.limit));
17667
+ return this.request(`/schedules/${encodeURIComponent(scheduleId)}/runs${query.size > 0 ? `?${query.toString()}` : ""}`);
17668
+ }
17669
+ runScheduleNow(scheduleId, input = {}) {
17670
+ return this.request(`/schedules/${encodeURIComponent(scheduleId)}/run`, {
17671
+ method: "POST",
17672
+ body: JSON.stringify(input)
17673
+ });
17674
+ }
17675
+ listTemplateBuilds(input) {
17676
+ const query = new URLSearchParams({ teamId: input.teamId });
17677
+ return this.requestApiRoot(`/sandbox-template-builds?${query.toString()}`).then((payload) => payload.builds);
17678
+ }
17679
+ createTemplateBuild(input) {
17680
+ return this.requestApiRoot("/sandbox-template-builds", {
17681
+ method: "POST",
17682
+ body: JSON.stringify(input)
17683
+ }).then((payload) => payload.build);
17684
+ }
17685
+ getTemplateBuild(buildId) {
17686
+ return this.requestApiRoot(`/sandbox-template-builds/${encodeURIComponent(buildId)}`).then((payload) => payload.build);
17687
+ }
17688
+ getTemplateBuildLogs(buildId) {
17689
+ return this.requestApiRoot(`/sandbox-template-builds/${encodeURIComponent(buildId)}/logs`);
17690
+ }
17691
+ cancelTemplateBuild(buildId) {
17692
+ return this.requestApiRoot(`/sandbox-template-builds/${encodeURIComponent(buildId)}/cancel`, {
17693
+ method: "POST"
17694
+ }).then((payload) => payload.build);
17695
+ }
17696
+ listPublishedSnapshotBuilds(input) {
17697
+ const query = new URLSearchParams({ teamId: input.teamId });
17698
+ return this.requestApiRoot(`/published-snapshot-builds?${query.toString()}`).then((payload) => payload.builds);
17699
+ }
17700
+ createPublishedSnapshotBuild(input) {
17701
+ return this.requestApiRoot("/published-snapshot-builds", {
17702
+ method: "POST",
17703
+ body: JSON.stringify(input)
17704
+ }).then((payload) => payload.build);
17705
+ }
17706
+ getPublishedSnapshotBuild(buildId) {
17707
+ return this.requestApiRoot(`/published-snapshot-builds/${encodeURIComponent(buildId)}`).then((payload) => payload.build);
17708
+ }
17709
+ getPublishedSnapshotBuildLogs(buildId) {
17710
+ return this.requestApiRoot(`/published-snapshot-builds/${encodeURIComponent(buildId)}/logs`);
17711
+ }
17712
+ cancelPublishedSnapshotBuild(buildId) {
17713
+ return this.requestApiRoot(`/published-snapshot-builds/${encodeURIComponent(buildId)}/cancel`, {
17714
+ method: "POST"
17715
+ }).then((payload) => payload.build);
17716
+ }
17717
+ listOrganizations() {
17718
+ return this.requestApiRoot("/organizations").then((payload) => payload.organizations ?? payload.teams ?? []);
17719
+ }
17720
+ createOrganization(input) {
17721
+ return this.requestApiRoot("/organizations", {
17722
+ method: "POST",
17723
+ body: JSON.stringify(input)
17724
+ }).then((payload) => payload.organization);
17725
+ }
17726
+ getOrganization(slug) {
17727
+ return this.requestApiRoot(`/organizations/${encodeURIComponent(slug)}`).then((payload) => payload.organization);
17728
+ }
17729
+ updateOrganization(slug, input) {
17730
+ return this.requestApiRoot(`/organizations/${encodeURIComponent(slug)}`, {
17731
+ method: "PATCH",
17732
+ body: JSON.stringify(input)
17733
+ }).then((payload) => payload.organization);
17734
+ }
17735
+ listOrganizationMembers(slug) {
17736
+ return this.requestApiRoot(`/organizations/${encodeURIComponent(slug)}/members`).then((payload) => payload.members);
17737
+ }
17738
+ upsertOrganizationMember(slug, input) {
17739
+ return this.requestApiRoot(`/organizations/${encodeURIComponent(slug)}/members`, {
17740
+ method: "POST",
17741
+ body: JSON.stringify(input)
17742
+ }).then((payload) => payload.member);
17743
+ }
17744
+ getOrganizationMcpServer(slug) {
17745
+ return this.requestApiRoot(`/organizations/${encodeURIComponent(slug)}/mcp-server`).then((payload) => payload.mcpServer);
17746
+ }
17747
+ generateOrganizationMcpServer(slug, input = {}) {
17748
+ return this.requestApiRoot(`/organizations/${encodeURIComponent(slug)}/mcp-server`, {
17749
+ method: "POST",
17750
+ body: JSON.stringify(input)
17751
+ }).then((payload) => payload.mcpServer);
17752
+ }
17753
+ rotateOrganizationMcpServer(slug) {
17754
+ return this.requestApiRoot(`/organizations/${encodeURIComponent(slug)}/mcp-server/rotate`, {
17755
+ method: "POST"
17756
+ }).then((payload) => payload.mcpServer);
17757
+ }
17758
+ disableOrganizationMcpServer(slug) {
17759
+ return this.requestApiRoot(`/organizations/${encodeURIComponent(slug)}/mcp-server/disable`, {
17760
+ method: "POST"
17761
+ }).then((payload) => payload.mcpServer);
17762
+ }
17763
+ enableOrganizationMcpServer(slug) {
17764
+ return this.requestApiRoot(`/organizations/${encodeURIComponent(slug)}/mcp-server/enable`, {
17765
+ method: "POST"
17766
+ }).then((payload) => payload.mcpServer);
17767
+ }
17768
+ startReplay(input) {
17769
+ const query = new URLSearchParams();
17770
+ if (input.teamId)
17771
+ query.set("teamId", input.teamId);
17772
+ if (input.projectId)
17773
+ query.set("projectId", input.projectId);
17774
+ const { teamId: _teamId, projectId: _projectId, ...body } = input;
17775
+ return this.requestApiRoot(`/sandbox-replays${query.size > 0 ? `?${query.toString()}` : ""}`, {
17776
+ method: "POST",
17777
+ body: JSON.stringify(body)
17778
+ });
17779
+ }
17780
+ listReplays(input = {}) {
17781
+ const query = new URLSearchParams();
17782
+ if (input.teamId)
17783
+ query.set("teamId", input.teamId);
17784
+ if (input.projectId)
17785
+ query.set("projectId", input.projectId);
17786
+ return this.requestApiRoot(`/sandbox-replays${query.size > 0 ? `?${query.toString()}` : ""}`);
17787
+ }
17788
+ getReplay(replayId, input = {}) {
17789
+ const query = new URLSearchParams();
17790
+ if (input.teamId)
17791
+ query.set("teamId", input.teamId);
17792
+ if (input.projectId)
17793
+ query.set("projectId", input.projectId);
17794
+ return this.requestApiRoot(`/sandbox-replays/${encodeURIComponent(replayId)}${query.size > 0 ? `?${query.toString()}` : ""}`);
17795
+ }
17796
+ getReplayLogs(replayId, input = {}) {
17797
+ const query = new URLSearchParams();
17798
+ if (input.teamId)
17799
+ query.set("teamId", input.teamId);
17800
+ if (input.projectId)
17801
+ query.set("projectId", input.projectId);
17802
+ return this.requestApiRoot(`/sandbox-replays/${encodeURIComponent(replayId)}/logs${query.size > 0 ? `?${query.toString()}` : ""}`);
17803
+ }
17804
+ getReplayArtifacts(replayId, input = {}) {
17805
+ const query = new URLSearchParams();
17806
+ if (input.teamId)
17807
+ query.set("teamId", input.teamId);
17808
+ if (input.projectId)
17809
+ query.set("projectId", input.projectId);
17810
+ return this.requestApiRoot(`/sandbox-replays/${encodeURIComponent(replayId)}/artifacts${query.size > 0 ? `?${query.toString()}` : ""}`);
17811
+ }
17812
+ cancelReplay(replayId, input = {}) {
17813
+ const query = new URLSearchParams();
17814
+ if (input.teamId)
17815
+ query.set("teamId", input.teamId);
17816
+ if (input.projectId)
17817
+ query.set("projectId", input.projectId);
17818
+ return this.requestApiRoot(`/sandbox-replays/${encodeURIComponent(replayId)}/cancel${query.size > 0 ? `?${query.toString()}` : ""}`, {
17819
+ method: "POST"
17820
+ });
17821
+ }
17822
+ integrationConnections(input = {}) {
17823
+ const query = new URLSearchParams();
17824
+ if (input.teamId)
17825
+ query.set("teamId", input.teamId);
17826
+ if (input.projectId)
17827
+ query.set("projectId", input.projectId);
17828
+ if (input.agentId)
17829
+ query.set("agentId", input.agentId);
17830
+ if (input.status)
17831
+ query.set("status", input.status);
17832
+ return this.requestApiRoot(`/integrations/connections${query.size > 0 ? `?${query.toString()}` : ""}`);
17833
+ }
17834
+ mcpServerConfig() {
17835
+ return {
17836
+ name: "openpond-sandboxes",
17837
+ transport: "streamable-http",
17838
+ url: `${this.sandboxApiUrl}/mcp`,
17839
+ headers: {
17840
+ "openpond-api-key": this.apiKey
17841
+ }
17842
+ };
17843
+ }
17844
+ smoke(options = {}) {
17845
+ return runSandboxSmoke(this, options);
17846
+ }
17847
+ };
17848
+ function createOpenPondSandboxClient2(options) {
17849
+ return new OpenPondSandboxClient(options);
17850
+ }
17851
+ var MAX_WORK_INPUT_BYTES = 100 * 1024 * 1024;
17852
+ var WORK_OUTPUT_MIME_TYPES = Object.freeze({
17853
+ ".avif": "image/avif",
17854
+ ".csv": "text/csv",
17855
+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
17856
+ ".gif": "image/gif",
17857
+ ".html": "text/html",
17858
+ ".jpeg": "image/jpeg",
17859
+ ".jpg": "image/jpeg",
17860
+ ".json": "application/json",
17861
+ ".m4a": "audio/mp4",
17862
+ ".md": "text/markdown",
17863
+ ".mov": "video/quicktime",
17864
+ ".mp3": "audio/mpeg",
17865
+ ".mp4": "video/mp4",
17866
+ ".pdf": "application/pdf",
17867
+ ".png": "image/png",
17868
+ ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
17869
+ ".svg": "image/svg+xml",
17870
+ ".tsv": "text/tab-separated-values",
17871
+ ".txt": "text/plain",
17872
+ ".wav": "audio/wav",
17873
+ ".webm": "video/webm",
17874
+ ".webp": "image/webp",
17875
+ ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
17876
+ });
17877
+
17878
+ // ../server/src/openpond/sandbox-inputs.ts
17879
+ function normalizeOptionalUrl3(value) {
17880
+ const trimmed = value?.trim();
17881
+ return trimmed ? trimmed.replace(/\/$/, "") : null;
17882
+ }
17883
+ function asRecord4(value) {
17884
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
17885
+ }
17886
+ var UI_PURPOSE_METADATA_KEYS = ["workspacePurpose", "purpose"];
17887
+ function sanitizeCreateMetadata(value) {
17888
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
17889
+ const metadata = { ...value };
17890
+ for (const key of UI_PURPOSE_METADATA_KEYS) {
17891
+ delete metadata[key];
17892
+ }
17893
+ return metadata;
17894
+ }
17895
+ function sanitizeSandboxRuntimeInput(value) {
17896
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
17897
+ const runtime = { ...value };
17898
+ for (const key of UI_PURPOSE_METADATA_KEYS) {
17899
+ delete runtime[key];
17900
+ }
17901
+ const metadata = sanitizeCreateMetadata(runtime.metadata);
17902
+ if (metadata) {
17903
+ runtime.metadata = metadata;
17904
+ } else {
17905
+ delete runtime.metadata;
17906
+ }
17907
+ return runtime;
17908
+ }
17909
+ function normalizeCreateInput(payload) {
17910
+ const input = asRecord4(payload);
17911
+ if (input.sandboxRuntime) {
17912
+ throw new Error(
17913
+ "Sandbox runtime settings must use /v1/runtimes before materializing a sandbox."
17914
+ );
17915
+ }
17916
+ const out = {};
17917
+ if (typeof input.repo === "string" && input.repo.trim()) out.repo = input.repo.trim();
17918
+ if (typeof input.teamId === "string" && input.teamId.trim()) out.teamId = input.teamId.trim();
17919
+ if (typeof input.projectId === "string" && input.projectId.trim()) {
17920
+ out.projectId = input.projectId.trim();
17921
+ }
17922
+ if (typeof input.agentId === "string" && input.agentId.trim()) {
17923
+ out.agentId = input.agentId.trim();
17924
+ }
17925
+ if (typeof input.command === "string" && input.command.trim()) out.command = input.command.trim();
17926
+ if (typeof input.runtimeProfileId === "string" && input.runtimeProfileId.trim()) {
17927
+ out.runtimeProfileId = input.runtimeProfileId.trim();
17928
+ }
17929
+ if (input.workloadSource && typeof input.workloadSource === "object" && !Array.isArray(input.workloadSource)) {
17930
+ out.workloadSource = input.workloadSource;
17931
+ }
17932
+ if (input.sourceArchive && typeof input.sourceArchive === "object" && !Array.isArray(input.sourceArchive)) {
17933
+ out.sourceArchive = input.sourceArchive;
17934
+ }
17935
+ if (input.visibility === "private" || input.visibility === "team") {
17936
+ out.visibility = input.visibility;
17937
+ }
17938
+ if (input.resources && typeof input.resources === "object" && !Array.isArray(input.resources)) {
17939
+ out.resources = input.resources;
17940
+ }
17941
+ if (input.budget && typeof input.budget === "object" && !Array.isArray(input.budget)) {
17942
+ out.budget = input.budget;
17943
+ }
17944
+ if ("env" in input) {
17945
+ out.env = normalizeSandboxEnvRefsForApp(input.env);
17946
+ }
17947
+ if (input.networkPolicy && typeof input.networkPolicy === "object" && !Array.isArray(input.networkPolicy)) {
17948
+ out.networkPolicy = input.networkPolicy;
17949
+ }
17950
+ if (input.quotas && typeof input.quotas === "object" && !Array.isArray(input.quotas)) {
17951
+ out.quotas = input.quotas;
17952
+ }
17953
+ if (Array.isArray(input.volumes)) {
17954
+ out.volumes = input.volumes;
17955
+ }
17956
+ if ("integrationLeases" in input) {
17957
+ out.integrationLeases = normalizeIntegrationLeaseRefsForRuntime(input.integrationLeases);
17958
+ }
17959
+ if (Array.isArray(input.integrationConnectionLeases)) {
17960
+ out.integrationConnectionLeases = input.integrationConnectionLeases;
17961
+ }
17962
+ const metadata = sanitizeCreateMetadata(input.metadata);
17963
+ if (metadata) out.metadata = metadata;
17964
+ return out;
17965
+ }
17966
+ function normalizeSandboxRuntimeCreateInput(payload) {
17967
+ const input = asRecord4(payload);
17968
+ const runtime = sanitizeSandboxRuntimeInput(input) ?? {};
17969
+ const out = {};
17970
+ if (typeof runtime.teamId === "string" && runtime.teamId.trim()) {
17971
+ out.teamId = runtime.teamId.trim();
17972
+ }
17973
+ if (typeof runtime.projectId === "string" && runtime.projectId.trim()) {
17974
+ out.projectId = runtime.projectId.trim();
17975
+ }
17976
+ if (typeof runtime.agentId === "string" && runtime.agentId.trim()) {
17977
+ out.agentId = runtime.agentId.trim();
17978
+ }
17979
+ if (typeof runtime.workflowMode === "string" && runtime.workflowMode.trim()) {
17980
+ out.workflowMode = runtime.workflowMode.trim();
17981
+ } else if (typeof runtime.mode === "string" && runtime.mode.trim()) {
17982
+ out.workflowMode = runtime.mode.trim();
17983
+ }
17984
+ if (typeof runtime.baseBranch === "string" && runtime.baseBranch.trim()) {
17985
+ out.baseBranch = runtime.baseBranch.trim();
17986
+ }
17987
+ if (typeof runtime.baseSha === "string" && runtime.baseSha.trim()) {
17988
+ out.baseSha = runtime.baseSha.trim();
17989
+ }
17990
+ if (typeof runtime.sandboxId === "string" && runtime.sandboxId.trim()) {
17991
+ out.sandboxId = runtime.sandboxId.trim();
17992
+ }
17993
+ if (typeof runtime.rootfsSnapshotId === "string" && runtime.rootfsSnapshotId.trim()) {
17994
+ out.rootfsSnapshotId = runtime.rootfsSnapshotId.trim();
17995
+ }
17996
+ if (typeof runtime.dependencySnapshotId === "string" && runtime.dependencySnapshotId.trim()) {
17997
+ out.dependencySnapshotId = runtime.dependencySnapshotId.trim();
17998
+ }
17999
+ if (typeof runtime.runtimeProfileId === "string" && runtime.runtimeProfileId.trim()) {
18000
+ out.runtimeProfileId = runtime.runtimeProfileId.trim();
18001
+ }
18002
+ if (typeof runtime.promotionPolicy === "string" && runtime.promotionPolicy.trim()) {
18003
+ out.promotionPolicy = runtime.promotionPolicy.trim();
18004
+ }
18005
+ if (runtime.metadata && typeof runtime.metadata === "object" && !Array.isArray(runtime.metadata)) {
18006
+ out.metadata = runtime.metadata;
18007
+ }
18008
+ return out;
18009
+ }
18010
+ function normalizeSandboxRuntimeSandboxCreateInput(payload) {
18011
+ return normalizeCreateInput(payload);
18012
+ }
18013
+ function normalizeSnapshotCreateInput(payload) {
18014
+ return asRecord4(payload);
18015
+ }
18016
+ function normalizeSandboxListInput(payload) {
18017
+ const input = asRecord4(payload);
18018
+ const teamId = typeof input.teamId === "string" ? input.teamId.trim() : "";
18019
+ const projectId = typeof input.projectId === "string" ? input.projectId.trim() : "";
18020
+ const agentId = typeof input.agentId === "string" ? input.agentId.trim() : "";
18021
+ return {
18022
+ ...teamId ? { teamId } : {},
18023
+ ...projectId ? { projectId } : {},
18024
+ ...agentId ? { agentId } : {}
18025
+ };
18026
+ }
18027
+ function normalizeReplayStartInput(payload) {
18028
+ const input = asRecord4(payload);
18029
+ const teamId = typeof input.teamId === "string" ? input.teamId.trim() : "";
18030
+ const projectId = typeof input.projectId === "string" ? input.projectId.trim() : "";
18031
+ const {
18032
+ teamId: _teamId,
18033
+ projectId: _projectId,
18034
+ appId: _appId,
18035
+ ...body
18036
+ } = input;
18037
+ const out = body;
18038
+ if (teamId) out.teamId = teamId;
18039
+ if (projectId) out.projectId = projectId;
18040
+ return out;
18041
+ }
18042
+ function normalizeIntegrationStatusFilter(value) {
18043
+ if (value === "active" || value === "revoked" || value === "error" || value === "all") {
18044
+ return value;
18045
+ }
18046
+ return void 0;
18047
+ }
18048
+ function normalizeIntegrationAttachInput(payload) {
18049
+ const input = asRecord4(payload);
18050
+ const connectionId = typeof input.connectionId === "string" ? input.connectionId.trim() : "";
18051
+ if (!connectionId) {
18052
+ throw new Error("Sandbox integration connection is required.");
18053
+ }
18054
+ const capabilities = normalizeStringArray(input.capabilities);
18055
+ if (capabilities.length === 0) {
18056
+ throw new Error("Sandbox integration capabilities are required.");
18057
+ }
18058
+ validateIntegrationCapabilitiesForProvider(input.provider, capabilities);
18059
+ const scopes = normalizeOptionalStringArray(input.scopes, "Sandbox integration scopes");
18060
+ const expiresAt = normalizeIntegrationExpiresAt(input.expiresAt);
18061
+ const ttlSeconds = normalizeIntegrationTtlSeconds(input.ttlSeconds);
18062
+ const resourcePolicy = normalizeIntegrationResourcePolicy(input.resourcePolicy);
18063
+ return {
18064
+ connectionId,
18065
+ capabilities,
18066
+ ...scopes.length > 0 ? { scopes } : {},
18067
+ ...resourcePolicy ? { resourcePolicy } : {},
18068
+ ...expiresAt ? { expiresAt } : {},
18069
+ ...ttlSeconds !== void 0 ? { ttlSeconds } : {},
18070
+ ...typeof input.required === "boolean" ? { required: input.required } : {}
18071
+ };
18072
+ }
18073
+ function normalizeIntegrationLeaseRefsForRuntime(value) {
18074
+ if (value === void 0 || value === null) return [];
18075
+ if (!Array.isArray(value)) {
18076
+ throw new Error("Sandbox integration leases must be an array.");
18077
+ }
18078
+ return value.map((item) => normalizeIntegrationLeaseRefForRuntime(item));
18079
+ }
18080
+ function normalizeIntegrationLeaseRefForRuntime(value) {
18081
+ const input = asRecord4(value);
18082
+ const leaseId = typeof input.leaseId === "string" ? input.leaseId.trim() : "";
18083
+ if (!leaseId) {
18084
+ throw new Error("Sandbox integration leaseId is required.");
18085
+ }
18086
+ if ("connectionId" in input) {
18087
+ throw new Error("Sandbox integration leases must use leaseId/proxy refs, not connection ids.");
18088
+ }
18089
+ assertNoSensitiveIntegrationLeaseKeys(input);
18090
+ const provider = normalizeLeaseableIntegrationProvider(input.provider);
18091
+ const capabilities = normalizeStringArray(input.capabilities);
18092
+ if (capabilities.length === 0) {
18093
+ throw new Error("Sandbox integration lease capabilities are required.");
18094
+ }
18095
+ validateIntegrationCapabilitiesForProvider(provider, capabilities);
18096
+ const scopes = normalizeOptionalStringArray(input.scopes, "Sandbox integration lease scopes");
18097
+ const resourcePolicy = normalizeIntegrationResourcePolicy(input.resourcePolicy);
18098
+ const expiresAt = normalizeIntegrationExpiresAt(input.expiresAt);
18099
+ const proxyUrl = typeof input.proxyUrl === "string" ? input.proxyUrl.trim() : "";
18100
+ return {
18101
+ leaseId,
18102
+ provider,
18103
+ capabilities,
18104
+ ...scopes.length > 0 ? { scopes } : {},
18105
+ ...resourcePolicy ? { resourcePolicy } : {},
18106
+ ...expiresAt ? { expiresAt } : {},
18107
+ ...proxyUrl ? { proxyUrl } : {},
18108
+ ...typeof input.required === "boolean" ? { required: input.required } : {}
18109
+ };
18110
+ }
18111
+ function normalizeLeaseableIntegrationProvider(value) {
18112
+ if (typeof value !== "string") {
18113
+ throw new Error("Sandbox integration lease provider is required.");
18114
+ }
18115
+ const provider = normalizeConnectedAppProviderFamilyId(value);
18116
+ if (!provider) {
18117
+ throw new Error(`Sandbox integration provider is not supported: ${value}`);
18118
+ }
18119
+ const bundle = connectedAppBundleByProvider(provider);
18120
+ if (!bundle?.leasePolicy.leaseable) {
18121
+ throw new Error(`Sandbox integration provider is not leaseable: ${provider}`);
18122
+ }
18123
+ return provider;
18124
+ }
18125
+ function assertNoSensitiveIntegrationLeaseKeys(value) {
18126
+ for (const key of Object.keys(value)) {
18127
+ if (isSensitivePolicyKey(key)) {
18128
+ throw new Error("Sandbox integration leases must not include secrets or credentials.");
18129
+ }
18130
+ }
18131
+ }
18132
+ function validateIntegrationCapabilitiesForProvider(providerValue, capabilities) {
18133
+ if (providerValue === void 0 || providerValue === null || providerValue === "") {
18134
+ return;
18135
+ }
18136
+ if (typeof providerValue !== "string") {
18137
+ throw new Error("Sandbox integration provider must be a string.");
18138
+ }
18139
+ const provider = normalizeConnectedAppProviderFamilyId(providerValue);
18140
+ if (!provider) {
18141
+ throw new Error(`Sandbox integration provider is not supported: ${providerValue}`);
18142
+ }
18143
+ const bundle = connectedAppBundleByProvider(provider);
18144
+ if (!bundle?.leasePolicy.leaseable) {
18145
+ throw new Error(`Sandbox integration provider is not leaseable: ${provider}`);
18146
+ }
18147
+ const allowedCapabilities = new Set(bundle.leasePolicy.allowedCapabilityIds);
18148
+ const deniedCapabilities = capabilities.filter((capability) => !allowedCapabilities.has(capability));
18149
+ if (deniedCapabilities.length > 0) {
18150
+ throw new Error(
18151
+ `Sandbox integration capabilities are not allowed for ${provider}: ${deniedCapabilities.join(", ")}`
18152
+ );
18153
+ }
18154
+ }
18155
+ function normalizeIntegrationLeaseId(payload) {
18156
+ const input = asRecord4(payload);
18157
+ const leaseId = typeof input.leaseId === "string" ? input.leaseId.trim() : "";
18158
+ if (!leaseId) {
18159
+ throw new Error("Sandbox integration lease is required.");
18160
+ }
18161
+ return leaseId;
18162
+ }
18163
+ function normalizeStringArray(value) {
18164
+ if (!Array.isArray(value)) {
18165
+ return [];
18166
+ }
18167
+ return value.map((item) => typeof item === "string" ? item.trim() : "").filter(Boolean);
18168
+ }
18169
+ function normalizeOptionalStringArray(value, label) {
18170
+ if (value === void 0 || value === null) return [];
18171
+ if (!Array.isArray(value)) {
18172
+ throw new Error(`${label} must be an array of strings.`);
18173
+ }
18174
+ return value.map((item) => {
18175
+ if (typeof item !== "string") {
18176
+ throw new Error(`${label} must contain only strings.`);
18177
+ }
18178
+ const trimmed = item.trim();
18179
+ if (!trimmed) {
18180
+ throw new Error(`${label} must not contain empty values.`);
18181
+ }
18182
+ return trimmed;
18183
+ });
18184
+ }
18185
+ function normalizeIntegrationTtlSeconds(value) {
18186
+ if (value === void 0 || value === null || value === "") return void 0;
18187
+ const ttlSeconds = Number(value);
18188
+ if (!Number.isFinite(ttlSeconds) || ttlSeconds <= 0) {
18189
+ throw new Error("Sandbox integration ttlSeconds must be a positive number.");
18190
+ }
18191
+ return Math.max(1, Math.floor(ttlSeconds));
18192
+ }
18193
+ function normalizeIntegrationExpiresAt(value) {
18194
+ if (value === void 0 || value === null || value === "") return void 0;
18195
+ if (typeof value !== "string") {
18196
+ throw new Error("Sandbox integration expiresAt must be an ISO timestamp string.");
18197
+ }
18198
+ const trimmed = value.trim();
18199
+ if (!trimmed) return void 0;
18200
+ const parsed = Date.parse(trimmed);
18201
+ if (!Number.isFinite(parsed)) {
18202
+ throw new Error("Sandbox integration expiresAt must be a valid ISO timestamp.");
18203
+ }
18204
+ return trimmed;
18205
+ }
18206
+ function normalizeIntegrationResourcePolicy(value) {
18207
+ if (value === void 0 || value === null) return void 0;
18208
+ if (typeof value !== "object" || Array.isArray(value)) {
18209
+ throw new Error("Sandbox integration resourcePolicy must be an object.");
18210
+ }
18211
+ assertNoSensitiveResourcePolicyKeys(value, []);
18212
+ const serialized = JSON.stringify(value);
18213
+ if (serialized.length > 16 * 1024) {
18214
+ throw new Error("Sandbox integration resourcePolicy is too large.");
18215
+ }
18216
+ return value;
18217
+ }
18218
+ function assertNoSensitiveResourcePolicyKeys(value, path37) {
18219
+ if (!value || typeof value !== "object") return;
18220
+ if (path37.length > 8) {
18221
+ throw new Error("Sandbox integration resourcePolicy is too deeply nested.");
18222
+ }
18223
+ if (Array.isArray(value)) {
18224
+ for (const item of value) assertNoSensitiveResourcePolicyKeys(item, path37);
18225
+ return;
18226
+ }
18227
+ for (const [key, child] of Object.entries(value)) {
18228
+ if (isSensitivePolicyKey(key)) {
18229
+ throw new Error("Sandbox integration resourcePolicy must not include secrets or credentials.");
18230
+ }
18231
+ assertNoSensitiveResourcePolicyKeys(child, [...path37, key]);
18232
+ }
18233
+ }
18234
+ function isSensitivePolicyKey(key) {
18235
+ const normalized = key.toLowerCase().replace(/[^a-z0-9]/g, "");
18236
+ return normalized.includes("accesstoken") || normalized.includes("refreshtoken") || normalized.includes("idtoken") || normalized.includes("oauth") || normalized.includes("bearer") || normalized.includes("authorization") || normalized.includes("cookie") || normalized.includes("secret") || normalized.includes("password") || normalized.includes("credential");
18237
+ }
18238
+ function normalizeExecInput(payload) {
18239
+ const input = asRecord4(payload);
18240
+ const command = typeof input.command === "string" ? input.command.trim() : "";
18241
+ if (!command) throw new Error("Sandbox command is required.");
18242
+ const timeoutSeconds = typeof input.timeoutSeconds === "number" && Number.isFinite(input.timeoutSeconds) ? Math.max(1, Math.floor(input.timeoutSeconds)) : void 0;
18243
+ const pipefailCommand = pipefailSandboxShellCommand(command);
18244
+ return timeoutSeconds ? { command: pipefailCommand, timeoutSeconds } : { command: pipefailCommand };
18245
+ }
18246
+ function normalizeProcessStartInput(payload) {
18247
+ const input = asRecord4(payload);
18248
+ const command = typeof input.command === "string" ? input.command.trim() : "";
18249
+ if (!command) throw new Error("Sandbox process command is required.");
18250
+ const timeoutSeconds = typeof input.timeoutSeconds === "number" && Number.isFinite(input.timeoutSeconds) ? Math.max(1, Math.floor(input.timeoutSeconds)) : void 0;
18251
+ return timeoutSeconds ? { command, timeoutSeconds } : { command };
18252
+ }
18253
+ function normalizeProcessCursorInput(payload) {
18254
+ const input = asRecord4(payload);
18255
+ const since = Number(input.since);
18256
+ return Number.isFinite(since) ? { since: Math.max(0, Math.floor(since)) } : {};
18257
+ }
18258
+ function normalizeOpenPortInput(payload) {
18259
+ const input = asRecord4(payload);
18260
+ const port = typeof input.port === "number" ? input.port : Number(input.port);
18261
+ if (!Number.isInteger(port) || port < SANDBOX_TEMPLATE_PREVIEW_PORT_MIN || port > SANDBOX_TEMPLATE_PREVIEW_PORT_MAX) {
18262
+ throw new Error(
18263
+ `Sandbox preview port must be between ${SANDBOX_TEMPLATE_PREVIEW_PORT_MIN} and ${SANDBOX_TEMPLATE_PREVIEW_PORT_MAX}.`
18264
+ );
18265
+ }
18266
+ const label = typeof input.label === "string" && input.label.trim() ? input.label.trim() : void 0;
18267
+ const access3 = input.access === "public" || input.access === "private" ? input.access : void 0;
18268
+ const autoStart = input.autoStart === true;
18269
+ const customDomain = typeof input.customDomain === "string" && input.customDomain.trim() ? input.customDomain.trim() : void 0;
18270
+ const out = {
18271
+ port,
18272
+ ...label ? { label } : {},
18273
+ ...access3 ? { access: access3 } : {},
18274
+ ...autoStart ? { autoStart } : {},
18275
+ ...customDomain ? { customDomain } : {}
18276
+ };
18277
+ if (input.cors && typeof input.cors === "object" && !Array.isArray(input.cors)) {
18278
+ out.cors = input.cors;
18279
+ }
18280
+ if (input.headerPolicy && typeof input.headerPolicy === "object" && !Array.isArray(input.headerPolicy)) {
18281
+ out.headerPolicy = input.headerPolicy;
18282
+ }
18283
+ if (input.authPolicy && typeof input.authPolicy === "object" && !Array.isArray(input.authPolicy)) {
18284
+ out.authPolicy = input.authPolicy;
18285
+ }
18286
+ return out;
18287
+ }
18288
+ function normalizeSnapshotUpdateInput(payload) {
18289
+ const input = asRecord4(payload);
18290
+ const out = {};
18291
+ if (input.template && typeof input.template === "object" && !Array.isArray(input.template)) {
18292
+ const template = asRecord4(input.template);
18293
+ const nextTemplate = {};
18294
+ if (typeof template.description === "string") {
18295
+ nextTemplate.description = template.description.trim();
18296
+ } else if (template.description === null) {
18297
+ nextTemplate.description = null;
18298
+ }
18299
+ if (Array.isArray(template.tags)) {
18300
+ nextTemplate.tags = template.tags.map((item) => typeof item === "string" ? item.trim() : "").filter(Boolean).slice(0, 20);
18301
+ }
18302
+ if (template.visibility === "private" || template.visibility === "team") {
18303
+ nextTemplate.visibility = template.visibility;
18304
+ }
18305
+ if (typeof template.useCase === "string") {
18306
+ nextTemplate.useCase = template.useCase.trim();
18307
+ } else if (template.useCase === null) {
18308
+ nextTemplate.useCase = null;
18309
+ }
18310
+ if (Object.keys(nextTemplate).length > 0) {
18311
+ out.template = nextTemplate;
18312
+ }
18313
+ }
18314
+ if (input.retention && typeof input.retention === "object" && !Array.isArray(input.retention)) {
18315
+ const retention = asRecord4(input.retention);
18316
+ const nextRetention = {};
18317
+ if (retention.class === "ephemeral" || retention.class === "cached" || retention.class === "pinned") {
18318
+ nextRetention.class = retention.class;
18319
+ }
18320
+ if (retention.ttlSeconds === null) {
18321
+ nextRetention.ttlSeconds = null;
18322
+ } else if (typeof retention.ttlSeconds === "number" && Number.isFinite(retention.ttlSeconds)) {
18323
+ nextRetention.ttlSeconds = Math.max(1, Math.floor(retention.ttlSeconds));
18324
+ }
18325
+ if (Object.keys(nextRetention).length > 0) {
18326
+ out.retention = nextRetention;
18327
+ }
18328
+ }
18329
+ if (!out.template && !out.retention) {
18330
+ throw new Error("Snapshot update requires template or retention changes.");
18331
+ }
18332
+ return out;
18333
+ }
18334
+ function normalizeSnapshotValidateInput(payload) {
18335
+ const input = asRecord4(payload);
18336
+ const cleanup = typeof input.cleanup === "string" ? input.cleanup.trim() : "";
18337
+ if (cleanup === "delete" || cleanup === "stop" || cleanup === "archive") {
18338
+ return { cleanup };
18339
+ }
18340
+ return {};
18341
+ }
18342
+ function normalizeForkInput(payload) {
18343
+ const input = asRecord4(payload);
18344
+ const out = {};
18345
+ if (typeof input.snapshotId === "string" && input.snapshotId.trim()) {
18346
+ out.snapshotId = input.snapshotId.trim();
18347
+ }
18348
+ if (input.visibility === "private" || input.visibility === "team") {
18349
+ out.visibility = input.visibility;
18350
+ }
18351
+ if (input.resources && typeof input.resources === "object" && !Array.isArray(input.resources)) {
18352
+ out.resources = input.resources;
18353
+ }
18354
+ if (input.budget && typeof input.budget === "object" && !Array.isArray(input.budget)) {
18355
+ out.budget = input.budget;
18356
+ }
18357
+ if (input.networkPolicy && typeof input.networkPolicy === "object" && !Array.isArray(input.networkPolicy)) {
18358
+ out.networkPolicy = input.networkPolicy;
18359
+ }
18360
+ if (input.quotas && typeof input.quotas === "object" && !Array.isArray(input.quotas)) {
18361
+ out.quotas = input.quotas;
18362
+ }
18363
+ if (Array.isArray(input.volumes)) {
18364
+ out.volumes = input.volumes;
18365
+ }
18366
+ if ("integrationLeases" in input) {
18367
+ out.integrationLeases = normalizeIntegrationLeaseRefsForRuntime(input.integrationLeases);
18368
+ }
18369
+ if ("env" in input) {
18370
+ out.env = normalizeSandboxEnvRefsForApp(input.env);
18371
+ }
18372
+ if (input.metadata && typeof input.metadata === "object" && !Array.isArray(input.metadata)) {
18373
+ out.metadata = input.metadata;
18374
+ }
18375
+ return out;
18376
+ }
18377
+ function normalizeSandboxEnvRefsForApp(value) {
18378
+ if (value === void 0 || value === null) return [];
18379
+ if (!Array.isArray(value)) {
18380
+ throw new Error("Sandbox env must be an array.");
18381
+ }
18382
+ return value.map((item) => {
18383
+ if (!item || typeof item !== "object" || Array.isArray(item)) {
18384
+ throw new Error("Sandbox env entries must be objects.");
18385
+ }
18386
+ const record5 = item;
18387
+ if ("value" in record5) {
18388
+ throw new Error("Sandbox env entries must use secretRef, not inline values.");
18389
+ }
18390
+ const name = typeof record5.name === "string" ? record5.name.trim() : "";
18391
+ const secretRef = typeof record5.secretRef === "string" ? record5.secretRef.trim() : "";
18392
+ if (!name || !secretRef) {
18393
+ throw new Error("Sandbox env entries require name and secretRef.");
18394
+ }
18395
+ return { name, secretRef };
18396
+ });
18397
+ }
18398
+ function normalizeTemplateLaunchInput(payload) {
18399
+ const input = asRecord4(payload);
18400
+ const teamId = typeof input.teamId === "string" ? input.teamId.trim() : "";
18401
+ const projectId = typeof input.projectId === "string" ? input.projectId.trim() : "";
18402
+ const snapshotId = typeof input.snapshotId === "string" ? input.snapshotId.trim() : "";
18403
+ const templateName = typeof input.templateName === "string" ? input.templateName.trim() : "";
18404
+ const version = typeof input.version === "string" ? input.version.trim() : "";
18405
+ const useCase = typeof input.useCase === "string" ? input.useCase.trim() : "";
18406
+ if (!snapshotId && !templateName && !useCase) {
18407
+ throw new Error("Sandbox template launch requires snapshotId, templateName, or useCase.");
18408
+ }
18409
+ return {
18410
+ ...normalizeForkInput(payload),
18411
+ ...teamId ? { teamId } : {},
18412
+ ...projectId ? { projectId } : {},
18413
+ ...snapshotId ? { snapshotId } : {},
18414
+ ...templateName ? { templateName } : {},
18415
+ ...version ? { version } : {},
18416
+ ...useCase ? { useCase } : {}
18417
+ };
18418
+ }
18419
+ function normalizeListFilesInput(payload) {
18420
+ const input = asRecord4(payload);
18421
+ const path37 = typeof input.path === "string" ? input.path.trim() : "";
18422
+ const maxEntries = Number(input.maxEntries);
18423
+ return {
18424
+ ...path37 ? { path: path37 } : {},
18425
+ ...typeof input.recursive === "boolean" ? { recursive: input.recursive } : {},
18426
+ ...Number.isFinite(maxEntries) ? { maxEntries } : {}
18427
+ };
18428
+ }
18429
+ function normalizeSearchFilesInput(payload) {
18430
+ const input = asRecord4(payload);
18431
+ const query = typeof input.query === "string" ? input.query.trim() : "";
18432
+ if (!query) {
18433
+ throw new Error("Sandbox file search query is required.");
18434
+ }
18435
+ const path37 = typeof input.path === "string" ? input.path.trim() : "";
18436
+ const maxResults = Number(input.maxResults);
18437
+ return {
18438
+ query,
18439
+ ...path37 ? { path: path37 } : {},
18440
+ ...Number.isFinite(maxResults) ? { maxResults } : {}
18441
+ };
18442
+ }
18443
+ function normalizeDeleteFileInput(payload) {
18444
+ const input = asRecord4(payload);
18445
+ const path37 = typeof input.path === "string" ? input.path.trim() : "";
18446
+ if (!path37) {
18447
+ throw new Error("Sandbox file path is required.");
18448
+ }
18449
+ return {
18450
+ path: path37,
18451
+ recursive: typeof input.recursive === "boolean" ? input.recursive : void 0
18452
+ };
18453
+ }
18454
+ function normalizeDownloadFileInput(payload) {
18455
+ const input = normalizeDeleteFileInput(payload);
18456
+ const raw = asRecord4(payload);
18457
+ const offsetBytes = Number(raw.offsetBytes);
18458
+ const maxBytes = Number(raw.maxBytes);
18459
+ return {
18460
+ path: input.path,
18461
+ ...Number.isFinite(offsetBytes) ? { offsetBytes } : {},
18462
+ ...Number.isFinite(maxBytes) ? { maxBytes } : {}
18463
+ };
18464
+ }
18465
+ function normalizeUploadFileInput(payload) {
18466
+ const input = asRecord4(payload);
18467
+ const path37 = typeof input.path === "string" ? input.path.trim() : "";
18468
+ const contents = typeof input.contents === "string" ? input.contents : "";
18469
+ const contentsBase64 = typeof input.contentsBase64 === "string" ? input.contentsBase64.trim() : "";
18470
+ if (!path37) {
18471
+ throw new Error("Sandbox file path is required.");
18472
+ }
18473
+ if (!contents && !contentsBase64) {
18474
+ throw new Error("Sandbox file contents are required.");
18475
+ }
18476
+ return {
18477
+ path: path37,
18478
+ contents,
18479
+ contentsBase64
18480
+ };
18481
+ }
18482
+ function normalizeMoveFileInput(payload) {
18483
+ const input = asRecord4(payload);
18484
+ const fromPath = typeof input.fromPath === "string" ? input.fromPath.trim() : "";
18485
+ const toPath = typeof input.toPath === "string" ? input.toPath.trim() : "";
18486
+ if (!fromPath || !toPath) {
18487
+ throw new Error("Sandbox file source and target paths are required.");
18488
+ }
18489
+ return {
18490
+ fromPath,
18491
+ toPath,
18492
+ overwrite: typeof input.overwrite === "boolean" ? input.overwrite : void 0
18493
+ };
18494
+ }
18495
+ function normalizeGitBranchInput(payload) {
18496
+ const input = asRecord4(payload);
18497
+ const branch = typeof input.branch === "string" ? input.branch.trim() : "";
18498
+ const startPoint = typeof input.startPoint === "string" ? input.startPoint.trim() : "";
18499
+ if (!branch) {
18500
+ throw new Error("Sandbox git branch name is required.");
18501
+ }
18502
+ return {
18503
+ branch,
18504
+ create: input.create === true,
18505
+ ...startPoint ? { startPoint } : {}
18506
+ };
18507
+ }
18508
+ function normalizeGitCommitInput(payload) {
18509
+ const input = asRecord4(payload);
18510
+ const message = typeof input.message === "string" ? input.message.trim() : "";
18511
+ const all = input.all === true;
18512
+ const paths = Array.isArray(input.paths) ? input.paths.filter((path37) => typeof path37 === "string" && path37.trim() !== "") : [];
18513
+ if (!message) {
18514
+ throw new Error("Sandbox git commit message is required.");
18515
+ }
18516
+ if (!all && paths.length === 0) {
18517
+ throw new Error("Sandbox git commit requires all=true or at least one path.");
18518
+ }
18519
+ return {
18520
+ message,
18521
+ ...all ? { all: true } : { paths: paths.map((path37) => path37.trim()) }
18522
+ };
18523
+ }
18524
+ function normalizeGitPullInput(payload) {
18525
+ const input = asRecord4(payload);
18526
+ const remote = typeof input.remote === "string" ? input.remote.trim() : "";
18527
+ const branch = typeof input.branch === "string" ? input.branch.trim() : "";
18528
+ const rebase = input.rebase === true;
18529
+ const ffOnly = typeof input.ffOnly === "boolean" ? input.ffOnly : void 0;
18530
+ if (rebase && ffOnly) {
18531
+ throw new Error("Sandbox git pull cannot use rebase and ff-only together.");
18532
+ }
18533
+ return {
18534
+ ...remote ? { remote } : {},
18535
+ ...branch ? { branch } : {},
18536
+ ...rebase ? { rebase } : {},
18537
+ ...typeof ffOnly === "boolean" ? { ffOnly } : {}
18538
+ };
18539
+ }
18540
+ function normalizeGitPushInput(payload) {
18541
+ const input = asRecord4(payload);
18542
+ const remote = typeof input.remote === "string" ? input.remote.trim() : "";
18543
+ const branch = typeof input.branch === "string" ? input.branch.trim() : "";
18544
+ return {
18545
+ ...remote ? { remote } : {},
18546
+ ...branch ? { branch } : {},
18547
+ ...input.setUpstream === true ? { setUpstream: true } : {},
18548
+ ...input.forceWithLease === true ? { forceWithLease: true } : {}
18549
+ };
18550
+ }
18551
+
18552
+ // ../server/src/openpond/sandboxes.ts
18553
+ async function resolveOpenPondSandboxClient() {
18554
+ return (await resolveSandboxClient()).client;
18555
+ }
18556
+ var DEFAULT_OPENPOND_SANDBOX_BASE_URL = "https://api.openpond.ai";
18557
+ async function sandboxRequestPayload(action) {
18558
+ const { client, context, apiKey, sandboxApiUrl } = await resolveSandboxClient();
18559
+ const account = sandboxAccountSummary(context, sandboxApiUrl);
18560
+ if (action.type === "list") {
18561
+ return {
18562
+ sandboxes: await client.list(normalizeSandboxListInput(action.payload)),
18563
+ account
18564
+ };
18565
+ }
18566
+ if (action.type === "snapshot_catalog") {
18567
+ const input = asRecord4(action.payload);
18568
+ const teamId = typeof input.teamId === "string" ? input.teamId.trim() : "";
18569
+ const projectId = typeof input.projectId === "string" ? input.projectId.trim() : "";
18570
+ const agentId = typeof input.agentId === "string" ? input.agentId.trim() : "";
18571
+ const query = typeof input.q === "string" ? input.q.trim() : "";
18572
+ const tag = typeof input.tag === "string" ? input.tag.trim() : "";
18573
+ const useCase = typeof input.useCase === "string" ? input.useCase.trim() : "";
18574
+ const replayState = input.replayState === "draft" || input.replayState === "validated" || input.replayState === "published" ? input.replayState : void 0;
18575
+ return {
18576
+ ...await client.snapshotCatalog({
18577
+ ...teamId ? { teamId } : {},
18578
+ ...projectId ? { projectId } : {},
18579
+ ...agentId ? { agentId } : {},
18580
+ ...query ? { q: query } : {},
18581
+ ...tag ? { tag } : {},
18582
+ ...useCase ? { useCase } : {},
18583
+ ...replayState ? { replayState } : {}
18584
+ }),
18585
+ account
18586
+ };
18587
+ }
18588
+ if (action.type === "snapshot_create") {
18589
+ return {
18590
+ ...await client.createSnapshot(
18591
+ action.sandboxId,
18592
+ normalizeSnapshotCreateInput(action.payload)
18593
+ ),
18594
+ account
18595
+ };
18596
+ }
18597
+ if (action.type === "template_catalog") {
18598
+ const input = asRecord4(action.payload);
18599
+ const teamId = typeof input.teamId === "string" ? input.teamId.trim() : "";
18600
+ const projectId = typeof input.projectId === "string" ? input.projectId.trim() : "";
18601
+ const query = typeof input.q === "string" ? input.q.trim() : "";
18602
+ const name = typeof input.name === "string" ? input.name.trim() : "";
18603
+ const version = typeof input.version === "string" ? input.version.trim() : "";
18604
+ const tag = typeof input.tag === "string" ? input.tag.trim() : "";
18605
+ const useCase = typeof input.useCase === "string" ? input.useCase.trim() : "";
18606
+ return {
18607
+ ...await client.templates({
18608
+ ...teamId ? { teamId } : {},
18609
+ ...projectId ? { projectId } : {},
18610
+ ...query ? { q: query } : {},
18611
+ ...name ? { name } : {},
18612
+ ...version ? { version } : {},
18613
+ ...tag ? { tag } : {},
18614
+ ...useCase ? { useCase } : {}
18615
+ }),
18616
+ account
18617
+ };
18618
+ }
18619
+ if (action.type === "integration_connections") {
18620
+ const input = asRecord4(action.payload);
18621
+ const teamId = typeof input.teamId === "string" ? input.teamId.trim() : "";
18622
+ const projectId = typeof input.projectId === "string" ? input.projectId.trim() : "";
18623
+ const agentId = typeof input.agentId === "string" ? input.agentId.trim() : "";
18624
+ const status = normalizeIntegrationStatusFilter(input.status);
18625
+ const query = {
18626
+ ...projectId ? { projectId } : {},
18627
+ ...agentId ? { agentId } : {},
18628
+ status: status ?? "all"
18629
+ };
18630
+ const result = teamId ? await client.integrationConnections({
18631
+ teamId,
18632
+ ...query
18633
+ }) : await resolveImplicitConnectedAppStatusConnections(client, query);
18634
+ return {
18635
+ ...result,
18636
+ account
18637
+ };
18638
+ }
18639
+ if (action.type === "connected_app_status") {
18640
+ const input = asRecord4(action.payload);
18641
+ const explicitTeamId = typeof input.teamId === "string" ? input.teamId.trim() : "";
18642
+ const projectId = typeof input.projectId === "string" ? input.projectId.trim() : "";
18643
+ const agentId = typeof input.agentId === "string" ? input.agentId.trim() : "";
18644
+ const status = normalizeIntegrationStatusFilter(input.status) ?? "all";
18645
+ const query = {
18646
+ ...projectId ? { projectId } : {},
18647
+ ...agentId ? { agentId } : {},
18648
+ status
18649
+ };
18650
+ const result = explicitTeamId ? await client.integrationConnections({
18651
+ teamId: explicitTeamId,
18652
+ ...query
18653
+ }) : await resolveImplicitConnectedAppStatusConnections(client, query);
18654
+ return {
18655
+ teamId: result.teamId,
18656
+ apps: buildConnectedAppStatusRows({ connections: result.connections }),
18657
+ account
18658
+ };
18659
+ }
18660
+ if (action.type === "sandbox_runtime_list") {
18661
+ return {
18662
+ runtimes: await client.listSandboxRuntimes(
18663
+ normalizeSandboxListInput(action.payload)
18664
+ ),
18665
+ account
18666
+ };
18667
+ }
18668
+ if (action.type === "sandbox_runtime_get") {
18669
+ return {
18670
+ runtime: await client.getSandboxRuntime(action.runtimeId),
18671
+ account
18672
+ };
18673
+ }
18674
+ if (action.type === "sandbox_runtime_create") {
18675
+ return {
18676
+ runtime: await client.createSandboxRuntime(
18677
+ normalizeSandboxRuntimeCreateInput(action.payload)
18678
+ ),
18679
+ account
18680
+ };
18681
+ }
18682
+ if (action.type === "sandbox_runtime_sandbox_create") {
18683
+ return {
18684
+ ...await client.createSandboxRuntimeSandbox(
18685
+ action.runtimeId,
18686
+ normalizeSandboxRuntimeSandboxCreateInput(action.payload),
18687
+ { respondAsync: true }
18688
+ ),
18689
+ account
18690
+ };
18691
+ }
18692
+ if (action.type === "sandbox_runtime_resume") {
18693
+ const sandbox = await client.sandboxRuntime(action.runtimeId).resume(normalizeSandboxRuntimeSandboxCreateInput(action.payload), {
18694
+ respondAsync: true
18695
+ });
18696
+ const runtime = await client.getSandboxRuntime(action.runtimeId);
18697
+ return {
18698
+ runtime,
18699
+ sandbox,
18700
+ account
18701
+ };
18702
+ }
18703
+ if (action.type === "sandbox_runtime_preserve_source") {
18704
+ const input = asRecord4(action.payload);
18705
+ return {
18706
+ ...await client.preserveSandboxRuntimeSource(
18707
+ action.runtimeId,
18708
+ {
18709
+ ...typeof input.sandboxId === "string" && input.sandboxId.trim() ? { sandboxId: input.sandboxId.trim() } : {},
18710
+ ...typeof input.message === "string" && input.message.trim() ? { message: input.message.trim() } : {},
18711
+ ...input.source === "profile" ? { source: "profile" } : {}
18712
+ },
18713
+ normalizeSandboxListInput(action.payload)
18714
+ ),
18715
+ account
18716
+ };
18717
+ }
18718
+ if (action.type === "sandbox_runtime_promote") {
18719
+ const input = asRecord4(action.payload);
18720
+ return {
18721
+ ...await client.promoteSandboxRuntime(
18722
+ action.runtimeId,
18723
+ {
18724
+ expectedTargetSha: typeof input.expectedTargetSha === "string" ? input.expectedTargetSha.trim() : "",
18725
+ ...input.validationState === "pending" || input.validationState === "passed" ? { validationState: input.validationState } : {},
18726
+ ...typeof input.summary === "string" && input.summary.trim() ? { summary: input.summary.trim() } : {}
18727
+ },
18728
+ normalizeSandboxListInput(action.payload)
18729
+ ),
18730
+ account
18731
+ };
18732
+ }
18733
+ if (action.type === "project_list") {
18734
+ return {
18735
+ ...await requestSandboxPublicApiRoot({
18736
+ apiKey,
18737
+ sandboxApiUrl,
18738
+ path: sandboxScopedCollectionPath(
18739
+ "/projects",
18740
+ normalizeSandboxListInput(action.payload)
18741
+ )
18742
+ }),
18743
+ account
18744
+ };
18745
+ }
18746
+ if (action.type === "profile_get") {
18747
+ return {
18748
+ ...await requestSandboxPublicApiRoot({
18749
+ apiKey,
18750
+ sandboxApiUrl,
18751
+ path: sandboxScopedCollectionPath(
18752
+ "/profile",
18753
+ normalizeSandboxListInput(action.payload)
18754
+ )
18755
+ }),
18756
+ account
18757
+ };
18758
+ }
18759
+ if (action.type === "profile_ensure") {
18760
+ return {
18761
+ ...await requestSandboxPublicApiRoot({
18762
+ apiKey,
18763
+ sandboxApiUrl,
18764
+ path: sandboxScopedCollectionPath(
18765
+ "/profile/ensure",
18766
+ normalizeSandboxListInput(action.payload)
18767
+ ),
18768
+ method: "POST"
18769
+ }),
18770
+ account
18771
+ };
18772
+ }
18773
+ if (action.type === "profile_push") {
18774
+ const payload = asRecord4(action.payload);
18775
+ const { teamId: _teamId, ...body } = payload;
18776
+ return {
18777
+ ...await requestSandboxPublicApiRoot({
18778
+ apiKey,
18779
+ sandboxApiUrl,
18780
+ path: sandboxScopedCollectionPath(
18781
+ "/profile/push",
18782
+ normalizeSandboxListInput(payload)
18783
+ ),
18784
+ method: "POST",
18785
+ body
18786
+ }),
18787
+ account
18788
+ };
18789
+ }
18790
+ if (action.type === "project_upsert") {
18791
+ return {
18792
+ ...await requestSandboxPublicApiRoot({
18793
+ apiKey,
18794
+ sandboxApiUrl,
18795
+ path: "/projects",
18796
+ method: "POST",
18797
+ body: asRecord4(action.payload)
18798
+ }),
18799
+ account
18800
+ };
18801
+ }
18802
+ if (action.type === "project_get") {
18803
+ return {
18804
+ ...await requestSandboxPublicApiRoot({
18805
+ apiKey,
18806
+ sandboxApiUrl,
18807
+ path: sandboxScopedCollectionPath(
18808
+ `/projects/${encodeURIComponent(action.projectId)}`,
18809
+ normalizeSandboxListInput(action.payload)
18810
+ )
18811
+ }),
18812
+ account
18813
+ };
18814
+ }
18815
+ if (action.type === "project_git") {
18816
+ return {
18817
+ ...await requestSandboxPublicApiRoot({
18818
+ apiKey,
18819
+ sandboxApiUrl,
18820
+ path: sandboxScopedCollectionPath(
18821
+ `/projects/${encodeURIComponent(action.projectId)}/git`,
18822
+ normalizeSandboxListInput(action.payload)
18823
+ ),
18824
+ method: "POST"
18825
+ }),
18826
+ account
18827
+ };
18828
+ }
18829
+ if (action.type === "project_sync") {
18830
+ return {
18831
+ ...await requestSandboxPublicApiRoot({
18832
+ apiKey,
18833
+ sandboxApiUrl,
18834
+ path: sandboxScopedCollectionPath(
18835
+ `/projects/${encodeURIComponent(action.projectId)}/sync`,
18836
+ normalizeSandboxListInput(action.payload)
18837
+ ),
18838
+ method: "POST"
18839
+ }),
18840
+ account
18841
+ };
18842
+ }
18843
+ if (action.type === "project_source_upload") {
18844
+ const payload = asRecord4(action.payload);
18845
+ const { teamId: _teamId, ...body } = payload;
18846
+ return {
18847
+ ...await requestSandboxPublicApiRoot({
18848
+ apiKey,
18849
+ sandboxApiUrl,
18850
+ path: sandboxScopedCollectionPath(
18851
+ `/projects/${encodeURIComponent(action.projectId)}/source`,
18852
+ normalizeSandboxListInput(payload)
18853
+ ),
18854
+ method: "POST",
18855
+ body
18856
+ }),
18857
+ account
18858
+ };
18859
+ }
18860
+ if (action.type === "project_archive") {
18861
+ return {
18862
+ ...await requestSandboxPublicApiRoot({
18863
+ apiKey,
18864
+ sandboxApiUrl,
18865
+ path: sandboxScopedCollectionPath(
18866
+ `/projects/${encodeURIComponent(action.projectId)}`,
18867
+ normalizeSandboxListInput(action.payload)
18868
+ ),
18869
+ method: "DELETE"
18870
+ }),
18871
+ account
18872
+ };
18873
+ }
18874
+ if (action.type === "agent_list") {
18875
+ return {
18876
+ ...await requestSandboxPublicApiRoot({
18877
+ apiKey,
18878
+ sandboxApiUrl,
18879
+ path: sandboxScopedCollectionPath(
18880
+ "/agents",
18881
+ normalizeSandboxListInput(action.payload)
18882
+ )
18883
+ }),
18884
+ account
18885
+ };
18886
+ }
18887
+ if (action.type === "agent_upsert") {
18888
+ return {
18889
+ ...await requestSandboxPublicApiRoot({
18890
+ apiKey,
18891
+ sandboxApiUrl,
18892
+ path: "/agents",
18893
+ method: "POST",
18894
+ body: asRecord4(action.payload)
18895
+ }),
18896
+ account
18897
+ };
18898
+ }
18899
+ if (action.type === "agent_run") {
18900
+ return {
18901
+ ...await requestSandboxPublicApiRoot({
18902
+ apiKey,
18903
+ sandboxApiUrl,
18904
+ path: `/agents/${encodeURIComponent(action.agentId)}/run`,
18905
+ method: "POST",
18906
+ body: asRecord4(action.payload)
18907
+ }),
18908
+ account
18909
+ };
18910
+ }
18911
+ if (action.type === "agent_source_deploy_plan") {
18912
+ return {
18913
+ ...await requestSandboxPublicApiRoot({
18914
+ apiKey,
18915
+ sandboxApiUrl,
18916
+ path: sandboxScopedCollectionPath(
18917
+ `/agents/${encodeURIComponent(action.agentId)}/source/deploy-plan`,
18918
+ normalizeSandboxListInput(action.payload)
18919
+ )
18920
+ }),
18921
+ account
18922
+ };
18923
+ }
18924
+ if (action.type === "agent_source_checks") {
18925
+ const payload = asRecord4(action.payload);
18926
+ const { teamId: _teamId, ...body } = payload;
18927
+ return {
18928
+ ...await requestSandboxPublicApiRoot({
18929
+ apiKey,
18930
+ sandboxApiUrl,
18931
+ path: sandboxScopedCollectionPath(
18932
+ `/agents/${encodeURIComponent(action.agentId)}/source/checks`,
18933
+ normalizeSandboxListInput(payload)
18934
+ ),
18935
+ method: "POST",
18936
+ body
18937
+ }),
18938
+ account
18939
+ };
18940
+ }
18941
+ if (action.type === "agent_source_publish") {
18942
+ const payload = asRecord4(action.payload);
18943
+ const { teamId: _teamId, ...body } = payload;
18944
+ return {
18945
+ ...await requestSandboxPublicApiRoot({
18946
+ apiKey,
18947
+ sandboxApiUrl,
18948
+ path: sandboxScopedCollectionPath(
18949
+ `/agents/${encodeURIComponent(action.agentId)}/source/publish`,
18950
+ normalizeSandboxListInput(payload)
18951
+ ),
18952
+ method: "POST",
18953
+ body
18954
+ }),
18955
+ account
18956
+ };
18957
+ }
18958
+ if (action.type === "create") {
18959
+ return {
18960
+ sandbox: await client.create(normalizeCreateInput(action.payload)),
18961
+ account
18962
+ };
18963
+ }
18964
+ if (action.type === "get") {
18965
+ return { sandbox: await client.get(action.sandboxId), account };
18966
+ }
18967
+ if (action.type === "start") {
18968
+ return {
18969
+ ...await client.start(action.sandboxId, { respondAsync: true }),
18970
+ account
18971
+ };
18972
+ }
18973
+ if (action.type === "delete") {
18974
+ const options = await sandboxLifecycleRequestOptions(
18975
+ client,
18976
+ action.sandboxId,
18977
+ {
18978
+ failOnUnpreservedChanges: action.failOnUnpreservedChanges
18979
+ }
18980
+ );
18981
+ const sandbox = await client.delete(action.sandboxId, options).catch(
18982
+ (error) => throwSandboxLifecycleRequestFailure(
18983
+ "delete",
18984
+ client,
18985
+ action.sandboxId,
18986
+ error
18987
+ )
18988
+ );
18989
+ assertTerminalSandboxLifecycleSettled("delete", sandbox);
18990
+ return {
18991
+ sandbox,
18992
+ account
18993
+ };
18994
+ }
18995
+ if (action.type === "exec") {
18996
+ return {
18997
+ ...await client.exec(
18998
+ action.sandboxId,
18999
+ normalizeExecInput(action.payload)
19000
+ ),
19001
+ account
19002
+ };
19003
+ }
19004
+ if (action.type === "action_run") {
19005
+ return {
19006
+ ...await requestSandboxApiRoot({
19007
+ apiKey,
19008
+ sandboxApiUrl,
19009
+ path: `/sandboxes/${encodeURIComponent(
19010
+ action.sandboxId
19011
+ )}/actions/${encodeURIComponent(action.actionName)}/run`,
19012
+ method: "POST",
19013
+ body: asRecord4(action.payload)
19014
+ }),
19015
+ account
19016
+ };
19017
+ }
19018
+ if (action.type === "open_port") {
19019
+ return {
19020
+ ...await client.openPort(
19021
+ action.sandboxId,
19022
+ normalizeOpenPortInput(action.payload)
19023
+ ),
19024
+ account
19025
+ };
19026
+ }
19027
+ if (action.type === "snapshot_update") {
19028
+ return {
19029
+ ...await client.updateSnapshot(
19030
+ action.sandboxId,
19031
+ action.snapshotId,
19032
+ normalizeSnapshotUpdateInput(action.payload)
19033
+ ),
19034
+ account
19035
+ };
19036
+ }
19037
+ if (action.type === "snapshot_validate") {
19038
+ return {
19039
+ ...await client.validateSnapshot(
19040
+ action.sandboxId,
19041
+ action.snapshotId,
19042
+ normalizeSnapshotValidateInput(action.payload)
19043
+ ),
19044
+ account
19045
+ };
19046
+ }
19047
+ if (action.type === "snapshot_publish") {
19048
+ return {
19049
+ ...await client.publishSnapshot(action.sandboxId, action.snapshotId),
19050
+ account
19051
+ };
19052
+ }
19053
+ if (action.type === "replays") {
19054
+ return {
19055
+ ...await client.listReplays(normalizeSandboxListInput(action.payload)),
19056
+ account
19057
+ };
19058
+ }
19059
+ if (action.type === "replay_start") {
19060
+ return {
19061
+ ...await client.startReplay(normalizeReplayStartInput(action.payload)),
19062
+ account
19063
+ };
19064
+ }
19065
+ if (action.type === "replay_get") {
19066
+ return {
19067
+ ...await client.getReplay(
19068
+ action.replayId,
19069
+ normalizeSandboxListInput(action.payload)
19070
+ ),
19071
+ account
19072
+ };
19073
+ }
19074
+ if (action.type === "replay_logs") {
19075
+ return {
19076
+ ...await client.getReplayLogs(
19077
+ action.replayId,
19078
+ normalizeSandboxListInput(action.payload)
19079
+ ),
19080
+ account
19081
+ };
19082
+ }
19083
+ if (action.type === "replay_artifacts") {
19084
+ return {
19085
+ ...await client.getReplayArtifacts(
19086
+ action.replayId,
19087
+ normalizeSandboxListInput(action.payload)
19088
+ ),
19089
+ account
19090
+ };
19091
+ }
19092
+ if (action.type === "replay_cancel") {
19093
+ return {
19094
+ ...await client.cancelReplay(
19095
+ action.replayId,
19096
+ normalizeSandboxListInput(action.payload)
19097
+ ),
19098
+ account
19099
+ };
19100
+ }
19101
+ if (action.type === "schedule_create") {
19102
+ return {
19103
+ ...await client.createSchedule(
19104
+ asRecord4(action.payload)
19105
+ ),
19106
+ account
19107
+ };
19108
+ }
19109
+ if (action.type === "template_launch") {
19110
+ return {
19111
+ ...await client.launchTemplate(
19112
+ normalizeTemplateLaunchInput(action.payload)
19113
+ ),
19114
+ account
19115
+ };
19116
+ }
19117
+ if (action.type === "fork") {
19118
+ return {
19119
+ ...await client.fork(
19120
+ action.sandboxId,
19121
+ normalizeForkInput(action.payload)
19122
+ ),
19123
+ account
19124
+ };
19125
+ }
19126
+ if (action.type === "stop") {
19127
+ const options = await sandboxLifecycleRequestOptions(
19128
+ client,
19129
+ action.sandboxId,
19130
+ {
19131
+ failOnUnpreservedChanges: action.failOnUnpreservedChanges
19132
+ }
19133
+ );
19134
+ const result = await client.stop(action.sandboxId, options).catch(
19135
+ (error) => throwSandboxLifecycleRequestFailure(
19136
+ "stop",
19137
+ client,
19138
+ action.sandboxId,
19139
+ error
19140
+ )
19141
+ );
19142
+ assertTerminalSandboxLifecycleSettled("stop", result.sandbox);
19143
+ return {
19144
+ ...result,
19145
+ account
19146
+ };
19147
+ }
19148
+ if (action.type === "receipts") {
19149
+ return { receipts: await client.receipts(action.sandboxId), account };
19150
+ }
19151
+ if (action.type === "logs") {
19152
+ return { logs: await client.logs(action.sandboxId), account };
19153
+ }
19154
+ if (action.type === "integration_leases") {
19155
+ return { ...await client.integrationLeases(action.sandboxId), account };
19156
+ }
19157
+ if (action.type === "integration_attach") {
19158
+ return {
19159
+ ...await client.attachIntegrationConnection(
19160
+ action.sandboxId,
19161
+ normalizeIntegrationAttachInput(action.payload)
19162
+ ),
19163
+ account
19164
+ };
19165
+ }
19166
+ if (action.type === "integration_remove") {
19167
+ return {
19168
+ ...await client.removeIntegrationLease(
19169
+ action.sandboxId,
19170
+ normalizeIntegrationLeaseId(action.payload)
19171
+ ),
19172
+ account
19173
+ };
19174
+ }
19175
+ if (action.type === "process_start") {
19176
+ return {
19177
+ ...await client.startProcess(
19178
+ action.sandboxId,
19179
+ normalizeProcessStartInput(action.payload)
19180
+ ),
19181
+ account
19182
+ };
19183
+ }
19184
+ if (action.type === "process_get") {
19185
+ return {
19186
+ ...await client.getProcess(
19187
+ action.sandboxId,
19188
+ action.processId,
19189
+ normalizeProcessCursorInput(action.payload)
19190
+ ),
19191
+ account
19192
+ };
19193
+ }
19194
+ if (action.type === "upload_file") {
19195
+ const input = normalizeUploadFileInput(action.payload);
19196
+ return {
19197
+ ...input.contentsBase64 ? await client.uploadFileBase64(
19198
+ action.sandboxId,
19199
+ input.path,
19200
+ input.contentsBase64
19201
+ ) : await client.uploadFile(
19202
+ action.sandboxId,
19203
+ input.path,
19204
+ input.contents
19205
+ ),
19206
+ account
19207
+ };
19208
+ }
19209
+ if (action.type === "download_file") {
19210
+ const input = normalizeDownloadFileInput(action.payload);
19211
+ return {
19212
+ ...await client.downloadFileResponse(action.sandboxId, input),
19213
+ account
19214
+ };
19215
+ }
19216
+ if (action.type === "list_files") {
19217
+ return {
19218
+ ...await client.listFiles(
19219
+ action.sandboxId,
19220
+ normalizeListFilesInput(action.payload)
19221
+ ),
19222
+ account
19223
+ };
19224
+ }
19225
+ if (action.type === "search_files") {
19226
+ return {
19227
+ ...await client.searchFiles(
19228
+ action.sandboxId,
19229
+ normalizeSearchFilesInput(action.payload)
19230
+ ),
19231
+ account
19232
+ };
19233
+ }
19234
+ if (action.type === "delete_file") {
19235
+ const input = normalizeDeleteFileInput(action.payload);
19236
+ return {
19237
+ ...await client.deleteFile(action.sandboxId, input.path, {
19238
+ recursive: input.recursive
19239
+ }),
19240
+ account
19241
+ };
19242
+ }
19243
+ if (action.type === "stat_file") {
19244
+ const input = normalizeDeleteFileInput(action.payload);
19245
+ return {
19246
+ ...await client.statFile(action.sandboxId, input.path),
19247
+ account
19248
+ };
19249
+ }
19250
+ if (action.type === "mkdir") {
19251
+ const input = normalizeDeleteFileInput(action.payload);
19252
+ return {
19253
+ ...await client.mkdir(action.sandboxId, {
19254
+ path: input.path,
19255
+ recursive: input.recursive
19256
+ }),
19257
+ account
19258
+ };
19259
+ }
19260
+ if (action.type === "move_file") {
19261
+ const input = normalizeMoveFileInput(action.payload);
19262
+ return {
19263
+ ...await client.moveFile(action.sandboxId, input),
19264
+ account
19265
+ };
19266
+ }
19267
+ if (action.type === "git_status") {
19268
+ return { ...await client.gitStatus(action.sandboxId), account };
19269
+ }
19270
+ if (action.type === "git_diff") {
19271
+ const input = asRecord4(action.payload);
19272
+ const baseRef = typeof input.baseRef === "string" ? input.baseRef.trim() : "";
19273
+ return {
19274
+ ...await client.gitDiff(action.sandboxId, {
19275
+ ...baseRef ? { baseRef } : {}
19276
+ }),
19277
+ account
19278
+ };
19279
+ }
19280
+ if (action.type === "git_export_patch") {
19281
+ const input = asRecord4(action.payload);
19282
+ const baseRef = typeof input.baseRef === "string" ? input.baseRef.trim() : "";
19283
+ return {
19284
+ ...await client.gitExportPatch(action.sandboxId, {
19285
+ ...baseRef ? { baseRef } : {}
19286
+ }),
19287
+ account
19288
+ };
19289
+ }
19290
+ if (action.type === "git_branch") {
19291
+ return {
19292
+ ...await client.gitBranch(
19293
+ action.sandboxId,
19294
+ normalizeGitBranchInput(action.payload)
19295
+ ),
19296
+ account
19297
+ };
19298
+ }
19299
+ if (action.type === "git_commit") {
19300
+ return {
19301
+ ...await client.gitCommit(
19302
+ action.sandboxId,
19303
+ normalizeGitCommitInput(action.payload)
19304
+ ),
19305
+ account
19306
+ };
19307
+ }
19308
+ if (action.type === "git_pull") {
19309
+ return {
19310
+ ...await client.gitPull(
19311
+ action.sandboxId,
19312
+ normalizeGitPullInput(action.payload)
19313
+ ),
19314
+ account
19315
+ };
19316
+ }
19317
+ if (action.type === "git_push") {
19318
+ return {
19319
+ ...await client.gitPush(
19320
+ action.sandboxId,
19321
+ normalizeGitPushInput(action.payload)
19322
+ ),
19323
+ account
19324
+ };
19325
+ }
19326
+ throw new Error(
19327
+ `Unsupported sandbox action: ${action.type}`
19328
+ );
19329
+ }
19330
+ async function listSandboxIntegrationConnections(input = {}) {
19331
+ const { client } = await resolveSandboxClient();
19332
+ if (input.teamId) return client.integrationConnections(input);
19333
+ return resolveImplicitConnectedAppStatusConnections(client, {
19334
+ ...input.projectId ? { projectId: input.projectId } : {},
19335
+ ...input.agentId ? { agentId: input.agentId } : {},
19336
+ status: input.status ?? "all"
19337
+ });
19338
+ }
19339
+ async function sandboxLifecycleRequestOptions(client, sandboxId, input = {}) {
19340
+ const respondAsync = await client.get(sandboxId).then((sandbox) => !sandboxLifecycleRequiresSynchronousAccounting(sandbox)).catch(() => true);
19341
+ return {
19342
+ failOnUnpreservedChanges: input.failOnUnpreservedChanges,
19343
+ ...respondAsync ? { respondAsync: true } : {}
19344
+ };
19345
+ }
19346
+ function sandboxLifecycleRequiresSynchronousAccounting(sandbox) {
19347
+ return sandbox.reservation.status === "reserved" && (sandbox.state === "creating" || terminalSandboxLifecycleStates.has(sandbox.state));
19348
+ }
19349
+ function assertTerminalSandboxLifecycleSettled(operation, sandbox) {
19350
+ if (!terminalSandboxLifecycleStates.has(sandbox.state)) return;
19351
+ if (sandbox.reservation.status !== "reserved") return;
19352
+ throw new Error(
19353
+ `Sandbox ${operation} reached ${sandbox.state}, but reservation ${sandbox.reservation.id} is still reserved. Cleanup accounting has not settled; retry status before treating cleanup as complete.`
19354
+ );
19355
+ }
19356
+ async function throwSandboxLifecycleRequestFailure(operation, client, sandboxId, error) {
19357
+ const latest = await client.get(sandboxId).catch(() => null);
19358
+ if (latest && sandboxLifecycleRequiresSynchronousAccounting(latest)) {
19359
+ const originalMessage = error instanceof Error ? error.message : String(error);
19360
+ throw new Error(
19361
+ `Sandbox ${operation} failed while sandbox ${sandboxId} is still creating with active reservation ${latest.reservation.id}. Cleanup accounting has not settled; retry status before treating cleanup as complete. Original error: ${originalMessage}`
19362
+ );
19363
+ }
19364
+ throw error instanceof Error ? error : new Error(String(error));
19365
+ }
19366
+ var terminalSandboxLifecycleStates = /* @__PURE__ */ new Set([
19367
+ "stopped",
19368
+ "archived",
19369
+ "deleted",
19370
+ "error"
19371
+ ]);
19372
+ async function resolveImplicitConnectedAppStatusConnections(client, query) {
19373
+ const organizations = await client.listOrganizations().catch(() => {
19374
+ throw new Error(
19375
+ "Connected app status is unavailable because organizations could not be loaded."
19376
+ );
19377
+ });
19378
+ const teamIds = implicitConnectedAppStatusTeamIds(organizations);
19379
+ const fallbackTeamId = selectImplicitConnectedAppStatusTeamId(organizations) || null;
19380
+ if (teamIds.length === 0) {
19381
+ return {
19382
+ teamId: fallbackTeamId,
19383
+ connections: []
19384
+ };
19385
+ }
19386
+ const results = await Promise.all(
19387
+ teamIds.map(
19388
+ (teamId) => client.integrationConnections({
19389
+ teamId,
19390
+ ...query.projectId ? { projectId: query.projectId } : {},
19391
+ ...query.agentId ? { agentId: query.agentId } : {},
19392
+ status: query.status
19393
+ }).catch(() => null)
19394
+ )
19395
+ );
19396
+ const successfulResults = successfulConnectedAppStatusConnectionResults(results);
19397
+ return {
19398
+ teamId: connectedAppStatusTeamIdWithConnections(successfulResults) ?? fallbackTeamId ?? successfulResults.find((result) => result.teamId.trim())?.teamId.trim() ?? null,
19399
+ connections: mergeConnectedAppStatusConnectionResults(successfulResults)
19400
+ };
19401
+ }
19402
+ function connectedAppStatusTeamIdWithConnections(results) {
19403
+ for (const result of results) {
19404
+ if ((result.connections?.length ?? 0) === 0) continue;
19405
+ const teamId = result.teamId?.trim();
19406
+ if (teamId) return teamId;
19407
+ }
19408
+ return null;
19409
+ }
19410
+ function mergeConnectedAppStatusConnectionResults(results) {
19411
+ const out = [];
19412
+ const seen = /* @__PURE__ */ new Set();
19413
+ for (const result of results) {
19414
+ for (const connection of result.connections ?? []) {
19415
+ const key = connection.id.trim() || [
19416
+ connection.teamId,
19417
+ connection.provider,
19418
+ connection.providerAccountId
19419
+ ].join(":");
19420
+ if (seen.has(key)) continue;
19421
+ seen.add(key);
19422
+ out.push(connection);
19423
+ }
19424
+ }
19425
+ return out;
19426
+ }
19427
+ function successfulConnectedAppStatusConnectionResults(results) {
19428
+ const successfulResults = results.filter(
19429
+ (result) => result !== null
19430
+ );
19431
+ const failedCount = results.length - successfulResults.length;
19432
+ const successfulConnectionCount = successfulResults.reduce(
19433
+ (count, result) => count + (result.connections?.length ?? 0),
19434
+ 0
19435
+ );
19436
+ if (failedCount > 0 && successfulConnectionCount === 0) {
19437
+ throw new Error(
19438
+ "Connected app status is unavailable because one or more team integration connection lookups could not be loaded."
19439
+ );
19440
+ }
19441
+ return successfulResults;
19442
+ }
19443
+ function selectImplicitConnectedAppStatusTeamId(organizations) {
19444
+ const active = organizations.filter(
19445
+ (organization) => organizationStatus(organization) === "active"
19446
+ );
19447
+ return organizationTeamId(
19448
+ active.find((organization) => organization.role === "owner")
19449
+ ) ?? organizationTeamId(
19450
+ active.find((organization) => organization.role === "admin")
19451
+ ) ?? organizationTeamId(active[0]) ?? "";
19452
+ }
19453
+ function implicitConnectedAppStatusTeamIds(organizations) {
19454
+ const out = [];
19455
+ const seen = /* @__PURE__ */ new Set();
19456
+ for (const organization of organizations) {
19457
+ if (organizationStatus(organization) !== "active") continue;
19458
+ const teamId = organizationTeamId(organization);
19459
+ if (!teamId || seen.has(teamId)) continue;
19460
+ seen.add(teamId);
19461
+ out.push(teamId);
19462
+ }
19463
+ return out;
19464
+ }
19465
+ function organizationTeamId(organization) {
19466
+ if (!organization) return null;
19467
+ const legacyId = organization.id;
19468
+ const value = typeof organization.teamId === "string" ? organization.teamId : typeof legacyId === "string" ? legacyId : "";
19469
+ const trimmed = value.trim();
19470
+ return trimmed || null;
19471
+ }
19472
+ function organizationStatus(organization) {
19473
+ return typeof organization.status === "string" ? organization.status : "active";
19474
+ }
19475
+ async function resolveSandboxClient() {
19476
+ const configuredSandboxApiUrl = normalizeOptionalUrl3(
19477
+ process.env.OPENPOND_SANDBOX_API_URL
19478
+ );
19479
+ const configuredSandboxApiKey = process.env.OPENPOND_SANDBOX_API_KEY?.trim();
19480
+ if (configuredSandboxApiKey && configuredSandboxApiUrl) {
19481
+ return {
19482
+ client: createOpenPondSandboxClient2({
19483
+ apiKey: configuredSandboxApiKey,
19484
+ sandboxApiUrl: configuredSandboxApiUrl
19485
+ }),
19486
+ context: await loadOpenPondAccountContext().catch(() => null),
19487
+ apiKey: configuredSandboxApiKey,
19488
+ sandboxApiUrl: normalizeSandboxApiUrl2(configuredSandboxApiUrl)
19489
+ };
19490
+ }
19491
+ const context = await loadOpenPondAccountContext();
19492
+ const apiKey = context.token?.trim();
19493
+ if (!apiKey) {
19494
+ throw new Error(
19495
+ "OpenPond account API key is required to manage sandboxes."
19496
+ );
19497
+ }
19498
+ if (configuredSandboxApiUrl) {
19499
+ return {
19500
+ client: createOpenPondSandboxClient2({
19501
+ apiKey,
19502
+ sandboxApiUrl: configuredSandboxApiUrl
19503
+ }),
19504
+ context,
19505
+ apiKey,
19506
+ sandboxApiUrl: normalizeSandboxApiUrl2(configuredSandboxApiUrl)
19507
+ };
19508
+ }
19509
+ const baseUrl = resolveSandboxBaseUrl(context);
19510
+ return {
19511
+ client: createOpenPondSandboxClient2({ apiKey, baseUrl }),
19512
+ context,
19513
+ apiKey,
19514
+ sandboxApiUrl: normalizeSandboxApiUrl2(baseUrl)
19515
+ };
19516
+ }
19517
+ function sandboxApiRootUrl(sandboxApiUrl) {
19518
+ return normalizeSandboxApiUrl2(sandboxApiUrl).replace(/\/sandboxes\/?$/, "");
19519
+ }
19520
+ function sandboxPublicApiRootUrl(sandboxApiUrl) {
19521
+ const normalized = normalizeSandboxApiUrl2(sandboxApiUrl);
19522
+ if (/\/api\/sandboxes\/?$/.test(normalized)) {
19523
+ return normalized.replace(/\/api\/sandboxes\/?$/, "/v1");
19524
+ }
19525
+ return normalized.replace(/\/sandboxes\/?$/, "");
19526
+ }
19527
+ function sandboxScopedCollectionPath(path37, queryInput) {
19528
+ const query = new URLSearchParams();
19529
+ if (queryInput.teamId) query.set("teamId", queryInput.teamId);
19530
+ if (queryInput.projectId) query.set("projectId", queryInput.projectId);
19531
+ if (queryInput.agentId) query.set("agentId", queryInput.agentId);
19532
+ return `${path37}${query.size > 0 ? `?${query.toString()}` : ""}`;
19533
+ }
19534
+ async function requestSandboxApiRoot(params) {
19535
+ const response = await apiFetch(
19536
+ sandboxApiRootUrl(params.sandboxApiUrl),
19537
+ params.apiKey,
19538
+ params.path,
19539
+ {
19540
+ method: params.method ?? "GET",
19541
+ ...params.body ? { body: JSON.stringify(params.body) } : {}
19542
+ }
19543
+ );
19544
+ const payload = await response.json().catch(() => ({}));
19545
+ if (!response.ok) {
19546
+ const error = typeof payload.error === "string" ? payload.error : `Sandbox API request failed with status ${response.status}`;
19547
+ throw new Error(error);
19548
+ }
19549
+ return payload;
19550
+ }
19551
+ async function requestSandboxPublicApiRoot(params) {
19552
+ const response = await apiFetch(
19553
+ sandboxPublicApiRootUrl(params.sandboxApiUrl),
19554
+ params.apiKey,
19555
+ params.path,
19556
+ {
19557
+ method: params.method ?? "GET",
19558
+ ...params.body ? { body: JSON.stringify(params.body) } : {}
19559
+ }
19560
+ );
19561
+ const payload = await response.json().catch(() => ({}));
19562
+ if (!response.ok) {
19563
+ const error = typeof payload.error === "string" ? payload.error : `Sandbox API request failed with status ${response.status}`;
19564
+ throw new Error(error);
19565
+ }
19566
+ return payload;
19567
+ }
19568
+ async function requestOpenPondPublicApi(params) {
19569
+ const { apiKey, sandboxApiUrl } = await resolveSandboxClient();
19570
+ return requestSandboxPublicApiRoot({
19571
+ apiKey,
19572
+ sandboxApiUrl,
19573
+ ...params
19574
+ });
19575
+ }
19576
+ function sandboxAccountSummary(context, sandboxApiUrl) {
19577
+ if (!context) {
19578
+ return {
19579
+ label: "Sandbox API",
19580
+ handle: null,
19581
+ baseUrl: null,
19582
+ sandboxApiUrl,
19583
+ state: "signed_out"
19584
+ };
19585
+ }
19586
+ const account = context.accountState;
19587
+ return {
19588
+ label: account.label,
19589
+ handle: account.activeProfile?.handle ?? context.account?.handle ?? null,
19590
+ baseUrl: account.baseUrl ?? context.account?.baseUrl ?? null,
19591
+ sandboxApiUrl,
19592
+ state: account.state
19593
+ };
19594
+ }
19595
+ function resolveSandboxBaseUrl(context) {
19596
+ return normalizeOptionalUrl3(process.env.OPENPOND_SANDBOX_BASE_URL) ?? normalizeOptionalUrl3(process.env.OPENPOND_API_URL) ?? normalizeOptionalUrl3(context.apiBaseUrl) ?? normalizeOptionalUrl3(context.account?.baseUrl) ?? normalizeOptionalUrl3(context.config.baseUrl) ?? DEFAULT_OPENPOND_SANDBOX_BASE_URL;
19597
+ }
19598
+
19599
+ // ../server/src/runtime/app-server-sandbox-tools.ts
19600
+ var REMOTE_SANDBOX_ACTIONS = /* @__PURE__ */ new Set([
19601
+ "sandbox_status",
19602
+ "sandbox_start",
19603
+ "sandbox_list_files",
19604
+ "sandbox_read_file",
19605
+ "sandbox_search_files",
19606
+ "sandbox_upload_file",
19607
+ "sandbox_write_file",
19608
+ "sandbox_edit_file",
19609
+ "sandbox_delete_file",
19610
+ "sandbox_mkdir",
19611
+ "sandbox_move_file",
19612
+ "sandbox_exec",
19613
+ "sandbox_open_port",
19614
+ "sandbox_snapshot_create"
19615
+ ]);
19616
+ async function executeAppServerSandboxTool(input) {
19617
+ if (!REMOTE_SANDBOX_ACTIONS.has(input.request.action)) return null;
19618
+ if (input.session.workspaceKind !== "sandbox" || !input.session.workspaceId) {
19619
+ throw new Error("The hosted Work task is not attached to a sandbox.");
19620
+ }
19621
+ const args = input.request.args ?? {};
19622
+ const sandboxId = input.session.workspaceId;
19623
+ const requestedSandboxId = optionalString(args.sandboxId);
19624
+ if (requestedSandboxId && requestedSandboxId !== sandboxId) {
19625
+ throw new Error("Hosted Work cannot target a different sandbox.");
19626
+ }
19627
+ const action = input.request.action;
19628
+ let data;
19629
+ if (action === "sandbox_status") {
19630
+ data = await input.sandboxRequest({ type: "get", sandboxId });
19631
+ } else if (action === "sandbox_start") {
19632
+ data = await input.sandboxRequest({ type: "start", sandboxId });
19633
+ } else if (action === "sandbox_list_files") {
19634
+ data = await input.sandboxRequest({
19635
+ type: "list_files",
19636
+ sandboxId,
19637
+ payload: {
19638
+ path: optionalString(args.path) || ".",
19639
+ recursive: args.recursive === true,
19640
+ ...numberValue2(args.maxEntries) === null ? {} : { maxEntries: numberValue2(args.maxEntries) }
19641
+ }
19642
+ });
19643
+ } else if (action === "sandbox_read_file") {
19644
+ data = await input.sandboxRequest({
19645
+ type: "download_file",
19646
+ sandboxId,
19647
+ payload: {
19648
+ path: requiredString(args.path, "path"),
19649
+ maxBytes: numberValue2(args.maxBytes) ?? 512 * 1024
19650
+ }
19651
+ });
19652
+ } else if (action === "sandbox_search_files") {
19653
+ data = await input.sandboxRequest({
19654
+ type: "search_files",
19655
+ sandboxId,
19656
+ payload: {
19657
+ query: requiredString(args.query, "query"),
19658
+ path: optionalString(args.path) || ".",
19659
+ ...numberValue2(args.maxResults) === null ? {} : { maxResults: numberValue2(args.maxResults) }
19660
+ }
19661
+ });
19662
+ } else if (action === "sandbox_upload_file") {
19663
+ data = await input.sandboxRequest({
19664
+ type: "upload_file",
19665
+ sandboxId,
19666
+ payload: {
19667
+ path: requiredString(args.path, "path"),
19668
+ contentsBase64: requiredString(args.contentsBase64, "contentsBase64")
19669
+ }
19670
+ });
19671
+ } else if (action === "sandbox_write_file") {
19672
+ data = await input.sandboxRequest({
19673
+ type: "upload_file",
19674
+ sandboxId,
19675
+ payload: {
19676
+ path: requiredString(args.path, "path"),
19677
+ contents: stringValue5(args.content)
19678
+ }
19679
+ });
19680
+ } else if (action === "sandbox_edit_file") {
19681
+ data = await editRemoteSandboxFile({
19682
+ sandboxId,
19683
+ args,
19684
+ sandboxRequest: input.sandboxRequest
19685
+ });
19686
+ } else if (action === "sandbox_delete_file") {
19687
+ data = await input.sandboxRequest({
19688
+ type: "delete_file",
19689
+ sandboxId,
19690
+ payload: {
19691
+ path: requiredString(args.path, "path"),
19692
+ recursive: args.recursive === true
19693
+ }
19694
+ });
19695
+ } else if (action === "sandbox_mkdir") {
19696
+ data = await input.sandboxRequest({
19697
+ type: "mkdir",
19698
+ sandboxId,
19699
+ payload: {
19700
+ path: requiredString(args.path, "path"),
19701
+ recursive: args.recursive !== false
19702
+ }
19703
+ });
19704
+ } else if (action === "sandbox_move_file") {
19705
+ data = await input.sandboxRequest({
19706
+ type: "move_file",
19707
+ sandboxId,
19708
+ payload: {
19709
+ fromPath: requiredString(args.fromPath, "fromPath"),
19710
+ toPath: requiredString(args.toPath, "toPath"),
19711
+ overwrite: args.overwrite === true
19712
+ }
19713
+ });
19714
+ } else if (action === "sandbox_exec") {
19715
+ data = await input.sandboxRequest({
19716
+ type: "exec",
19717
+ sandboxId,
19718
+ payload: {
19719
+ command: requiredString(args.command, "command"),
19720
+ timeoutSeconds: numberValue2(args.timeoutSeconds) ?? 120
19721
+ }
19722
+ });
19723
+ } else if (action === "sandbox_open_port") {
19724
+ data = await input.sandboxRequest({
19725
+ type: "open_port",
19726
+ sandboxId,
19727
+ payload: {
19728
+ port: requiredNumber(args.port, "port"),
19729
+ label: optionalString(args.label) || "Work preview",
19730
+ access: "private",
19731
+ autoStart: true
19732
+ }
19733
+ });
19734
+ } else {
19735
+ data = await input.sandboxRequest({
19736
+ type: "snapshot_create",
19737
+ sandboxId,
19738
+ payload: { name: requiredString(args.name, "name") }
19739
+ });
19740
+ }
19741
+ return WorkspaceToolResultSchema.parse({
19742
+ ok: true,
19743
+ action,
19744
+ output: `${action} completed in the attached Work sandbox.`,
19745
+ data
19746
+ });
19747
+ }
19748
+ async function editRemoteSandboxFile(input) {
19749
+ const path37 = requiredString(input.args.path, "path");
19750
+ const oldText = requiredString(input.args.oldText, "oldText");
19751
+ const newText = stringValue5(input.args.newText);
19752
+ const downloaded = asRecord5(
19753
+ await input.sandboxRequest({
19754
+ type: "download_file",
19755
+ sandboxId: input.sandboxId,
19756
+ payload: { path: path37, maxBytes: 1024 * 1024 }
19757
+ })
19758
+ );
19759
+ const file = asRecord5(downloaded.file);
19760
+ const content = optionalString(downloaded.contents) || optionalString(downloaded.content) || optionalString(file.contents) || optionalString(file.content);
19761
+ if (!content.includes(oldText)) {
19762
+ throw new Error(`Text to replace was not found in ${path37}.`);
19763
+ }
19764
+ if (input.args.replaceAll !== true && content.indexOf(oldText) !== content.lastIndexOf(oldText)) {
19765
+ throw new Error(`Text to replace is not unique in ${path37}.`);
19766
+ }
19767
+ const nextContent = input.args.replaceAll === true ? content.split(oldText).join(newText) : content.replace(oldText, newText);
19768
+ return input.sandboxRequest({
19769
+ type: "upload_file",
19770
+ sandboxId: input.sandboxId,
19771
+ payload: { path: path37, contents: nextContent }
19772
+ });
19773
+ }
19774
+ function asRecord5(value) {
19775
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
19776
+ }
19777
+ function stringValue5(value) {
19778
+ return typeof value === "string" ? value : "";
19779
+ }
19780
+ function optionalString(value) {
19781
+ return stringValue5(value).trim();
19782
+ }
19783
+ function requiredString(value, name) {
19784
+ const result = stringValue5(value);
19785
+ if (!result.trim()) throw new Error(`${name} is required.`);
19786
+ return result;
19787
+ }
19788
+ function numberValue2(value) {
19789
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
19790
+ }
19791
+ function requiredNumber(value, name) {
19792
+ const result = numberValue2(value);
19793
+ if (result === null) throw new Error(`${name} is required.`);
19794
+ return result;
19795
+ }
19796
+
16143
19797
  // ../server/src/runtime/app-server-workspace.ts
16144
19798
  function createAppServerWorkspace(input) {
16145
19799
  const workspaceDir = path19.resolve(input.workspaceDir);
@@ -16204,9 +19858,18 @@ function createAppServerWorkspace(input) {
16204
19858
  );
16205
19859
  try {
16206
19860
  if (request.action.startsWith("sandbox_")) {
16207
- throw new Error(
16208
- "Nested sandbox operations are not available inside the app-server placement."
16209
- );
19861
+ const result2 = await executeAppServerSandboxTool({
19862
+ session,
19863
+ request,
19864
+ sandboxRequest: input.sandboxRequest ?? sandboxRequestPayload
19865
+ });
19866
+ if (!result2) {
19867
+ throw new Error(
19868
+ `Sandbox action ${request.action} is not available in app-server placement.`
19869
+ );
19870
+ }
19871
+ await recordResult(session, result2, options.turnId, startedAt);
19872
+ return result2;
16210
19873
  }
16211
19874
  const { app, state } = await workspaceForSession(session);
16212
19875
  const result = await handleActiveWorkspaceToolAction({
@@ -17433,7 +21096,7 @@ function redactConnectedAppToolArguments(toolName, args) {
17433
21096
  return redacted && typeof redacted === "object" && !Array.isArray(redacted) ? redacted : {};
17434
21097
  }
17435
21098
  async function executeConnectedAppToolDefinition(input) {
17436
- const provider = normalizeConnectedAppProviderFamilyId(stringValue5(input.context.args.provider));
21099
+ const provider = normalizeConnectedAppProviderFamilyId(stringValue6(input.context.args.provider));
17437
21100
  if (!provider) {
17438
21101
  return connectedAppToolFailure(input.context.callId, input.toolName, "Connected app provider is required.");
17439
21102
  }
@@ -17473,7 +21136,7 @@ async function executeConnectedAppToolDefinition(input) {
17473
21136
  }
17474
21137
  );
17475
21138
  }
17476
- if (input.operation === "write" && !stringValue5(input.context.args.explicitUserIntent)) {
21139
+ if (input.operation === "write" && !stringValue6(input.context.args.explicitUserIntent)) {
17477
21140
  return connectedAppToolFailure(
17478
21141
  input.context.callId,
17479
21142
  input.toolName,
@@ -17565,7 +21228,7 @@ async function executeConnectedAppToolDefinition(input) {
17565
21228
  function inferredProviderOperationCapabilityIds(input) {
17566
21229
  const providerOperation = connectedAppProviderOperationById(
17567
21230
  input.provider,
17568
- stringValue5(input.args.operation)
21231
+ stringValue6(input.args.operation)
17569
21232
  );
17570
21233
  if (!providerOperation || providerOperation.operation !== input.operation) return null;
17571
21234
  return providerOperation.capabilityIds;
@@ -17581,9 +21244,9 @@ function connectedAppProviderErrorSummary(data) {
17581
21244
  const record5 = data;
17582
21245
  const result = isRecord2(record5.result) ? record5.result : null;
17583
21246
  const metadata = isRecord2(record5.metadata) ? record5.metadata : null;
17584
- const httpStatus = numberValue2(metadata?.httpStatus) ?? numberValue2(result?.status);
17585
- const title = stringValue5(result?.title);
17586
- const detail = stringValue5(result?.detail);
21247
+ const httpStatus = numberValue3(metadata?.httpStatus) ?? numberValue3(result?.status);
21248
+ const title = stringValue6(result?.title);
21249
+ const detail = stringValue6(result?.detail);
17587
21250
  if (!httpStatus && !title && !detail) return null;
17588
21251
  const statusText = httpStatus ? `Provider returned HTTP ${httpStatus}` : "Provider returned an error";
17589
21252
  const titleText = title ? ` ${title}` : "";
@@ -17661,10 +21324,10 @@ function dedupeContexts(contexts) {
17661
21324
  }
17662
21325
  return [...byProvider.values()];
17663
21326
  }
17664
- function stringValue5(value) {
21327
+ function stringValue6(value) {
17665
21328
  return typeof value === "string" && value.trim() ? value.trim() : null;
17666
21329
  }
17667
- function numberValue2(value) {
21330
+ function numberValue3(value) {
17668
21331
  return typeof value === "number" && Number.isFinite(value) ? value : null;
17669
21332
  }
17670
21333
  function stringArray(value) {
@@ -18109,7 +21772,7 @@ function goalContextPreview(event2) {
18109
21772
  function subagentEventPreview(event2) {
18110
21773
  const run = subagentRunFromEvent(event2);
18111
21774
  if (!run) return eventPreview(event2);
18112
- const usage = asRecord4(run.metadata.usage);
21775
+ const usage = asRecord6(run.metadata.usage);
18113
21776
  const report = run.report;
18114
21777
  return [
18115
21778
  `run: subagent-run:${run.id}`,
@@ -18162,8 +21825,8 @@ function isDurableResourceRef(value) {
18162
21825
  return /^(workspace:(?:file|dir):|sandbox:(?:file|dir):|git:|event:|message:|artifact:|goal-context:|session:|subagent-run:)/.test(value);
18163
21826
  }
18164
21827
  function subagentRunFromEvent(event2) {
18165
- const data = asRecord4(event2.data);
18166
- const parsed = SubagentRunSchema.safeParse(asRecord4(data?.run));
21828
+ const data = asRecord6(event2.data);
21829
+ const parsed = SubagentRunSchema.safeParse(asRecord6(data?.run));
18167
21830
  return parsed.success ? parsed.data : null;
18168
21831
  }
18169
21832
  function subagentRefsPreview(refs, label) {
@@ -18181,8 +21844,8 @@ function subagentDurableRef(ref) {
18181
21844
  return ref.id.startsWith("workspace:") || ref.id.startsWith("sandbox:") ? ref.id : `workspace:file:${ref.id}`;
18182
21845
  }
18183
21846
  function subagentUsagePreview(usage) {
18184
- const totalTokens = numberValue3(usage.totalTokens);
18185
- const requestCount = numberValue3(usage.requestCount);
21847
+ const totalTokens = numberValue4(usage.totalTokens);
21848
+ const requestCount = numberValue4(usage.requestCount);
18186
21849
  if (totalTokens <= 0 && requestCount <= 0) return null;
18187
21850
  return `usage: ${totalTokens} tokens across ${requestCount} ${requestCount === 1 ? "request" : "requests"}`;
18188
21851
  }
@@ -18202,10 +21865,10 @@ function extractFilePaths2(value) {
18202
21865
  }
18203
21866
  return [...paths].slice(0, 20);
18204
21867
  }
18205
- function asRecord4(value) {
21868
+ function asRecord6(value) {
18206
21869
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
18207
21870
  }
18208
- function numberValue3(value) {
21871
+ function numberValue4(value) {
18209
21872
  return typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
18210
21873
  }
18211
21874
  function truncate2(value, maxChars) {
@@ -18930,7 +22593,7 @@ function openInput(context) {
18930
22593
  return {
18931
22594
  ...baseInput(context),
18932
22595
  ...optionalTabId(context.args) ? { tabId: optionalTabId(context.args) } : {},
18933
- ...optionalString(context.args, "url", BROWSER_URL_MAX_LENGTH) ? { url: optionalString(context.args, "url", BROWSER_URL_MAX_LENGTH) } : {}
22596
+ ...optionalString2(context.args, "url", BROWSER_URL_MAX_LENGTH) ? { url: optionalString2(context.args, "url", BROWSER_URL_MAX_LENGTH) } : {}
18934
22597
  };
18935
22598
  }
18936
22599
  function snapshotInput(context) {
@@ -19050,8 +22713,8 @@ function optionalTarget(args) {
19050
22713
  return refTarget ?? point;
19051
22714
  }
19052
22715
  function optionalRefTarget(args) {
19053
- const targetRef = optionalString(args, "targetRef", BROWSER_ID_MAX_LENGTH);
19054
- const snapshotId = optionalString(args, "snapshotId", BROWSER_ID_MAX_LENGTH);
22716
+ const targetRef = optionalString2(args, "targetRef", BROWSER_ID_MAX_LENGTH);
22717
+ const snapshotId = optionalString2(args, "snapshotId", BROWSER_ID_MAX_LENGTH);
19055
22718
  if (!targetRef && !snapshotId) return void 0;
19056
22719
  if (!targetRef || !snapshotId) throw new Error("targetRef requires snapshotId");
19057
22720
  return { kind: "ref", snapshotId, targetRef };
@@ -19114,7 +22777,7 @@ function targetParameters(input = {}) {
19114
22777
  };
19115
22778
  }
19116
22779
  function optionalTabId(args) {
19117
- return optionalString(args, "tabId", BROWSER_ID_MAX_LENGTH);
22780
+ return optionalString2(args, "tabId", BROWSER_ID_MAX_LENGTH);
19118
22781
  }
19119
22782
  function stringArg2(args, key, maxLength) {
19120
22783
  const value = args[key];
@@ -19123,7 +22786,7 @@ function stringArg2(args, key, maxLength) {
19123
22786
  if (trimmed.length > maxLength) throw new Error(`${key} is too long`);
19124
22787
  return trimmed;
19125
22788
  }
19126
- function optionalString(args, key, maxLength) {
22789
+ function optionalString2(args, key, maxLength) {
19127
22790
  const value = args[key];
19128
22791
  if (value === void 0 || value === null) return null;
19129
22792
  if (typeof value !== "string" || !value.trim()) throw new Error(`${key} must be a non-empty string`);
@@ -19174,7 +22837,7 @@ var NativeToolCallAccumulator = class {
19174
22837
  toolCalls.forEach((toolCall, ordinal) => {
19175
22838
  const record5 = toolCall;
19176
22839
  const index = typeof record5.index === "number" && Number.isInteger(record5.index) ? record5.index : null;
19177
- const id = stringValue6(toolCall.id);
22840
+ const id = stringValue7(toolCall.id);
19178
22841
  const key = index !== null ? `index:${index}` : id ? `id:${id}` : `ordinal:${ordinal}`;
19179
22842
  const current = this.calls.get(key) ?? {
19180
22843
  key,
@@ -19185,10 +22848,10 @@ var NativeToolCallAccumulator = class {
19185
22848
  argumentsJson: ""
19186
22849
  };
19187
22850
  if (id) current.id = id;
19188
- const type = stringValue6(toolCall.type);
22851
+ const type = stringValue7(toolCall.type);
19189
22852
  if (type) current.type = type;
19190
22853
  const fn = toolCall.function && typeof toolCall.function === "object" ? toolCall.function : {};
19191
- const nameChunk = stringValue6(fn.name);
22854
+ const nameChunk = stringValue7(fn.name);
19192
22855
  if (nameChunk) current.name += nameChunk;
19193
22856
  if (typeof fn.arguments === "string") current.argumentsJson += fn.arguments;
19194
22857
  this.calls.set(key, current);
@@ -19290,7 +22953,7 @@ function completedToolCall(call, sequence) {
19290
22953
  hostedToolCall
19291
22954
  };
19292
22955
  }
19293
- function stringValue6(value) {
22956
+ function stringValue7(value) {
19294
22957
  return typeof value === "string" && value.trim() ? value : null;
19295
22958
  }
19296
22959
  function replayableNativeToolArguments(argumentsJson) {
@@ -20040,7 +23703,7 @@ function createResourceModelToolDefinitions(deps) {
20040
23703
  scope,
20041
23704
  query: stringArg3(context.args, "query"),
20042
23705
  ...typeof context.args.limit === "number" ? { limit: context.args.limit } : {},
20043
- ...asRecord5(context.args.filters) ? { filters: asRecord5(context.args.filters) } : {}
23706
+ ...asRecord7(context.args.filters) ? { filters: asRecord7(context.args.filters) } : {}
20044
23707
  }
20045
23708
  });
20046
23709
  return resourceSearchResultToModelToolResult(context.callId, result2);
@@ -20054,7 +23717,7 @@ function createResourceModelToolDefinitions(deps) {
20054
23717
  args: {
20055
23718
  query: stringArg3(context.args, "query"),
20056
23719
  ...typeof context.args.limit === "number" ? { maxResults: context.args.limit } : {},
20057
- ...typeof asRecord5(context.args.filters)?.path === "string" ? { path: asRecord5(context.args.filters)?.path } : {}
23720
+ ...typeof asRecord7(context.args.filters)?.path === "string" ? { path: asRecord7(context.args.filters)?.path } : {}
20058
23721
  },
20059
23722
  source: "chat_action"
20060
23723
  },
@@ -20810,7 +24473,7 @@ function createOpenPondActionModelToolDefinitions(deps) {
20810
24473
  })
20811
24474
  })) : [];
20812
24475
  const directAgentActions = deps.actionCatalog.filter((action) => {
20813
- const implementation = asRecord5(action.implementation);
24476
+ const implementation = asRecord7(action.implementation);
20814
24477
  const actionName = action.sourceActionId ?? action.name ?? action.id;
20815
24478
  return !CROSS_SYSTEM_TOOL_NAMES.includes(actionName) && (Boolean(action.agentId) || implementation?.type === "openpond-profile-action");
20816
24479
  });
@@ -20913,9 +24576,9 @@ function createOpenPondActionModelToolDefinitions(deps) {
20913
24576
  deps,
20914
24577
  resultToolName: "openpond_action_run",
20915
24578
  compactProfileResultForModel: true,
20916
- input: asRecord5(context.args.input) ?? {},
20917
- requestedProjectId: stringValue7(context.args.projectId) ?? void 0,
20918
- requestedAgentId: stringValue7(context.args.agentId) ?? void 0
24579
+ input: asRecord7(context.args.input) ?? {},
24580
+ requestedProjectId: stringValue8(context.args.projectId) ?? void 0,
24581
+ requestedAgentId: stringValue8(context.args.agentId) ?? void 0
20919
24582
  });
20920
24583
  }
20921
24584
  }
@@ -20928,11 +24591,11 @@ function directOpenPondActionToolName(action) {
20928
24591
  return `agent_${slug}_${suffix}`;
20929
24592
  }
20930
24593
  function directOpenPondActionAliasName(action) {
20931
- const name = stringValue7(asRecord5(action.implementation)?.actionId) ?? action.sourceActionId ?? action.name ?? action.id;
24594
+ const name = stringValue8(asRecord7(action.implementation)?.actionId) ?? action.sourceActionId ?? action.name ?? action.id;
20932
24595
  return /^[A-Za-z0-9_-]{1,64}$/.test(name) ? name : null;
20933
24596
  }
20934
24597
  function actionInputSchema(action) {
20935
- const schema = asRecord5(action.inputSchema);
24598
+ const schema = asRecord7(action.inputSchema);
20936
24599
  if (schema?.type === "object") return structuredClone(schema);
20937
24600
  return {
20938
24601
  type: "object",
@@ -20942,7 +24605,7 @@ function actionInputSchema(action) {
20942
24605
  }
20943
24606
  async function executeScopedOpenPondAction(input) {
20944
24607
  const { action, context, deps, resultToolName } = input;
20945
- const implementation = asRecord5(action.implementation);
24608
+ const implementation = asRecord7(action.implementation);
20946
24609
  if (implementation?.type === "openpond-profile-action") {
20947
24610
  const executionTarget = resolveWorkspaceExecutionTarget({ session: context.session });
20948
24611
  if (isSandboxExecutionTarget(executionTarget)) {
@@ -20959,8 +24622,8 @@ async function executeScopedOpenPondAction(input) {
20959
24622
  `Action ${action.id} is a profile action, but profile action execution is not configured.`
20960
24623
  );
20961
24624
  }
20962
- const profileActionId = stringValue7(implementation.actionId) ?? action.id;
20963
- const prompt = stringValue7(input.input.prompt) ?? stringValue7(input.input.message) ?? context.userPrompt;
24625
+ const profileActionId = stringValue8(implementation.actionId) ?? action.id;
24626
+ const prompt = stringValue8(input.input.prompt) ?? stringValue8(input.input.message) ?? context.userPrompt;
20964
24627
  const result2 = await deps.executeProfileAction({
20965
24628
  action: profileActionId,
20966
24629
  input: {
@@ -21000,7 +24663,7 @@ async function executeScopedOpenPondAction(input) {
21000
24663
  actionName: action.sourceActionId ?? action.name ?? action.id,
21001
24664
  input: input.input
21002
24665
  };
21003
- const allowedProjectId = stringValue7(implementation?.projectId);
24666
+ const allowedProjectId = stringValue8(implementation?.projectId);
21004
24667
  if (input.requestedProjectId) {
21005
24668
  if (!allowedProjectId || input.requestedProjectId !== allowedProjectId) {
21006
24669
  return failedActionToolResult(
@@ -21013,7 +24676,7 @@ async function executeScopedOpenPondAction(input) {
21013
24676
  } else if (allowedProjectId) {
21014
24677
  payloadArgs.projectId = allowedProjectId;
21015
24678
  }
21016
- const allowedAgentId = action.agentId ?? stringValue7(implementation?.agentId);
24679
+ const allowedAgentId = action.agentId ?? stringValue8(implementation?.agentId);
21017
24680
  if (input.requestedAgentId) {
21018
24681
  if (!allowedAgentId || input.requestedAgentId !== allowedAgentId) {
21019
24682
  return failedActionToolResult(
@@ -21041,8 +24704,8 @@ async function executeScopedOpenPondAction(input) {
21041
24704
  return workspaceToolResultToModelToolResult(context.callId, resultToolName, result);
21042
24705
  }
21043
24706
  function compactProfileActionResult(value) {
21044
- const execution = asRecord5(value);
21045
- const stdout = stringValue7(execution?.stdout);
24707
+ const execution = asRecord7(value);
24708
+ const stdout = stringValue8(execution?.stdout);
21046
24709
  if (!stdout) return value;
21047
24710
  let payload;
21048
24711
  try {
@@ -21050,13 +24713,13 @@ function compactProfileActionResult(value) {
21050
24713
  } catch {
21051
24714
  return value;
21052
24715
  }
21053
- const actionResult = asRecord5(payload)?.result ?? payload;
21054
- const actionResultRecord = asRecord5(actionResult);
21055
- const metadata = asRecord5(actionResultRecord?.metadata);
24716
+ const actionResult = asRecord7(payload)?.result ?? payload;
24717
+ const actionResultRecord = asRecord7(actionResult);
24718
+ const metadata = asRecord7(actionResultRecord?.metadata);
21056
24719
  for (const key of ["snapshot", "decision", "submission", "receipt"]) {
21057
24720
  if (metadata && Object.hasOwn(metadata, key)) return metadata[key];
21058
24721
  }
21059
- const text = stringValue7(actionResultRecord?.text);
24722
+ const text = stringValue8(actionResultRecord?.text);
21060
24723
  if (text) {
21061
24724
  try {
21062
24725
  return JSON.parse(text);
@@ -21315,26 +24978,26 @@ function sandboxResourceRefForExecutionTarget(ref, target) {
21315
24978
  return null;
21316
24979
  }
21317
24980
  function gitChangedFileRefs(value, sandboxMode = false) {
21318
- const record5 = asRecord5(value);
21319
- const status = asRecord5(record5?.status);
24981
+ const record5 = asRecord7(value);
24982
+ const status = asRecord7(record5?.status);
21320
24983
  const files = Array.isArray(record5?.files) ? record5.files : Array.isArray(status?.files) ? status.files : [];
21321
- return files.filter((item) => Boolean(item) && typeof item === "object" && !Array.isArray(item)).map((item) => stringValue7(item.path)).filter((item) => Boolean(item)).map((filePath) => `${sandboxMode ? "sandbox" : "workspace"}:file:${filePath}`);
24984
+ return files.filter((item) => Boolean(item) && typeof item === "object" && !Array.isArray(item)).map((item) => stringValue8(item.path)).filter((item) => Boolean(item)).map((filePath) => `${sandboxMode ? "sandbox" : "workspace"}:file:${filePath}`);
21322
24985
  }
21323
24986
  function gitDiffText(value) {
21324
- const record5 = asRecord5(value);
21325
- return stringValue7(record5?.diff) ?? stringValue7(asRecord5(record5?.result)?.diff);
24987
+ const record5 = asRecord7(value);
24988
+ return stringValue8(record5?.diff) ?? stringValue8(asRecord7(record5?.result)?.diff);
21326
24989
  }
21327
24990
  function sandboxPathItems(value) {
21328
24991
  const records = nestedArraysForKeys(value, ["matches", "files", "entries"]);
21329
24992
  const items = [];
21330
24993
  for (const record5 of records) {
21331
- const path37 = stringValue7(record5.path) ?? stringValue7(record5.name);
24994
+ const path37 = stringValue8(record5.path) ?? stringValue8(record5.name);
21332
24995
  if (!path37) continue;
21333
24996
  items.push({
21334
24997
  path: path37,
21335
- snippet: stringValue7(record5.text) ?? stringValue7(record5.snippet) ?? stringValue7(record5.content) ?? void 0,
24998
+ snippet: stringValue8(record5.text) ?? stringValue8(record5.snippet) ?? stringValue8(record5.content) ?? void 0,
21336
24999
  line: typeof record5.line === "number" ? record5.line : null,
21337
- kind: stringValue7(record5.kind) ?? stringValue7(record5.type)
25000
+ kind: stringValue8(record5.kind) ?? stringValue8(record5.type)
21338
25001
  });
21339
25002
  }
21340
25003
  return items;
@@ -21357,17 +25020,17 @@ function nestedArraysForKeys(value, keys) {
21357
25020
  return output;
21358
25021
  }
21359
25022
  function sandboxFileContent(value) {
21360
- const record5 = asRecord5(value);
25023
+ const record5 = asRecord7(value);
21361
25024
  const file = sandboxFileRecord(value);
21362
- const encoded = stringValue7(file?.contentsBase64) ?? stringValue7(record5?.contentsBase64);
21363
- if (encoded && !sandboxFileMetadata(value, stringValue7(file?.path) ?? "").binary) {
25025
+ const encoded = stringValue8(file?.contentsBase64) ?? stringValue8(record5?.contentsBase64);
25026
+ if (encoded && !sandboxFileMetadata(value, stringValue8(file?.path) ?? "").binary) {
21364
25027
  try {
21365
25028
  return Buffer.from(encoded, "base64").toString("utf8");
21366
25029
  } catch {
21367
25030
  return null;
21368
25031
  }
21369
25032
  }
21370
- return stringValue7(record5?.content) ?? stringValue7(record5?.text) ?? stringValue7(record5?.contents) ?? stringValue7(file?.content) ?? stringValue7(file?.text);
25033
+ return stringValue8(record5?.content) ?? stringValue8(record5?.text) ?? stringValue8(record5?.contents) ?? stringValue8(file?.content) ?? stringValue8(file?.text);
21371
25034
  }
21372
25035
  function contentTypeForResourcePath(value) {
21373
25036
  const lower = value.toLowerCase();
@@ -21377,13 +25040,13 @@ function contentTypeForResourcePath(value) {
21377
25040
  return null;
21378
25041
  }
21379
25042
  function sandboxFileRecord(value) {
21380
- const record5 = asRecord5(value);
21381
- return asRecord5(record5?.file) ?? asRecord5(asRecord5(record5?.result)?.file);
25043
+ const record5 = asRecord7(value);
25044
+ return asRecord7(record5?.file) ?? asRecord7(asRecord7(record5?.result)?.file);
21382
25045
  }
21383
25046
  function sandboxFileMetadata(value, resourcePath) {
21384
25047
  const file = sandboxFileRecord(value);
21385
- const contentType = stringValue7(file?.contentType) ?? stringValue7(file?.mimeType) ?? contentTypeForResourcePath(resourcePath);
21386
- const sizeBytes = numberValue4(file?.sizeBytes) ?? numberValue4(file?.size);
25048
+ const contentType = stringValue8(file?.contentType) ?? stringValue8(file?.mimeType) ?? contentTypeForResourcePath(resourcePath);
25049
+ const sizeBytes = numberValue5(file?.sizeBytes) ?? numberValue5(file?.size);
21387
25050
  const binary = file?.binary === true || file?.isBinary === true || (contentType ? isBinaryContentType(contentType) : isLikelyBinaryResourcePath(resourcePath));
21388
25051
  return { binary, contentType, ...sizeBytes !== null ? { sizeBytes } : {} };
21389
25052
  }
@@ -21458,7 +25121,7 @@ function actionCatalogText(action) {
21458
25121
  ].filter((value) => typeof value === "string" && value.trim().length > 0).join(" ").toLowerCase();
21459
25122
  }
21460
25123
  function actionCatalogItemForModel(action) {
21461
- const implementation = asRecord5(action.implementation);
25124
+ const implementation = asRecord7(action.implementation);
21462
25125
  const directRunAllowed = implementation?.type !== "openpond-profile-action";
21463
25126
  return {
21464
25127
  actionId: action.id,
@@ -21468,8 +25131,8 @@ function actionCatalogItemForModel(action) {
21468
25131
  directRunAllowed,
21469
25132
  inputSchema: action.inputSchema ?? null,
21470
25133
  outputSchema: action.outputSchema ?? null,
21471
- agentId: action.agentId ?? stringValue7(implementation?.agentId),
21472
- projectId: stringValue7(implementation?.projectId),
25134
+ agentId: action.agentId ?? stringValue8(implementation?.agentId),
25135
+ projectId: stringValue8(implementation?.projectId),
21473
25136
  sourceActionId: action.sourceActionId ?? null
21474
25137
  };
21475
25138
  }
@@ -21489,13 +25152,13 @@ function failedActionToolResult(callId, name, message) {
21489
25152
  )
21490
25153
  };
21491
25154
  }
21492
- function asRecord5(value) {
25155
+ function asRecord7(value) {
21493
25156
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
21494
25157
  }
21495
- function stringValue7(value) {
25158
+ function stringValue8(value) {
21496
25159
  return typeof value === "string" && value.trim() ? value.trim() : null;
21497
25160
  }
21498
- function numberValue4(value) {
25161
+ function numberValue5(value) {
21499
25162
  return typeof value === "number" && Number.isFinite(value) ? value : null;
21500
25163
  }
21501
25164
 
@@ -24040,7 +27703,7 @@ async function workInputBytes(input) {
24040
27703
  return bytes;
24041
27704
  }
24042
27705
  function workPath(rawArea, rawPath, allowedAreas = ["inputs", "work", "outputs"]) {
24043
- const area = requiredString(rawArea);
27706
+ const area = requiredString2(rawArea);
24044
27707
  if (!allowedAreas.includes(area)) {
24045
27708
  throw new Error(`Unknown Work area: ${area}`);
24046
27709
  }
@@ -24059,7 +27722,7 @@ async function waitForWorkSandboxReady(readStatus, options = {}) {
24059
27722
  const timeoutMs = options.timeoutMs ?? WORK_SANDBOX_STARTUP_TIMEOUT_MS;
24060
27723
  const pollMs = options.pollMs ?? WORK_SANDBOX_STARTUP_POLL_MS;
24061
27724
  const now2 = options.now ?? Date.now;
24062
- const sleep3 = options.sleep ?? ((milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)));
27725
+ const sleep4 = options.sleep ?? ((milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)));
24063
27726
  const startedAt = now2();
24064
27727
  let lastState = "";
24065
27728
  while (now2() - startedAt <= timeoutMs) {
@@ -24070,7 +27733,7 @@ async function waitForWorkSandboxReady(readStatus, options = {}) {
24070
27733
  if (TERMINAL_WORK_SANDBOX_STATES.has(lastState)) {
24071
27734
  throw new Error(`Work sandbox entered ${lastState} during startup.`);
24072
27735
  }
24073
- await sleep3(pollMs);
27736
+ await sleep4(pollMs);
24074
27737
  }
24075
27738
  throw new Error(
24076
27739
  `Work sandbox did not become ready within ${timeoutMs}ms${lastState ? ` (last state: ${lastState})` : ""}.`
@@ -24080,7 +27743,7 @@ async function waitForWorkReceiptSettlement(readReceipts, options = {}) {
24080
27743
  const timeoutMs = options.timeoutMs ?? WORK_RECEIPT_SETTLEMENT_TIMEOUT_MS;
24081
27744
  const pollMs = options.pollMs ?? WORK_RECEIPT_SETTLEMENT_POLL_MS;
24082
27745
  const now2 = options.now ?? Date.now;
24083
- const sleep3 = options.sleep ?? ((milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)));
27746
+ const sleep4 = options.sleep ?? ((milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)));
24084
27747
  const startedAt = now2();
24085
27748
  let lastResult = null;
24086
27749
  while (now2() - startedAt <= timeoutMs) {
@@ -24088,11 +27751,11 @@ async function waitForWorkReceiptSettlement(readReceipts, options = {}) {
24088
27751
  if (!lastResult.ok || receiptSettlementComplete(lastResult.data)) {
24089
27752
  return lastResult;
24090
27753
  }
24091
- await sleep3(pollMs);
27754
+ await sleep4(pollMs);
24092
27755
  }
24093
27756
  return lastResult ?? readReceipts();
24094
27757
  }
24095
- function requiredString(value) {
27758
+ function requiredString2(value) {
24096
27759
  if (typeof value !== "string" || !value.trim()) {
24097
27760
  throw new Error("A required string argument is missing.");
24098
27761
  }
@@ -24285,7 +27948,7 @@ function createWorkModelToolDefinitions(deps) {
24285
27948
  "work_list_files",
24286
27949
  "sandbox_list_files",
24287
27950
  (context) => ({
24288
- path: workPath(context.args.area, optionalString2(context.args.path)),
27951
+ path: workPath(context.args.area, optionalString3(context.args.path)),
24289
27952
  recursive: typeof context.args.recursive === "boolean" ? context.args.recursive : true
24290
27953
  })
24291
27954
  )
@@ -24311,7 +27974,7 @@ function createWorkModelToolDefinitions(deps) {
24311
27974
  "work_read_file",
24312
27975
  "sandbox_read_file",
24313
27976
  (context) => ({
24314
- path: workPath(context.args.area, requiredString2(context.args.path)),
27977
+ path: workPath(context.args.area, requiredString3(context.args.path)),
24315
27978
  maxBytes: typeof context.args.maxBytes === "number" ? Math.min(
24316
27979
  Math.max(Math.floor(context.args.maxBytes), 1),
24317
27980
  1e6
@@ -24339,11 +28002,11 @@ function createWorkModelToolDefinitions(deps) {
24339
28002
  "work_write_file",
24340
28003
  "sandbox_write_file",
24341
28004
  (context) => ({
24342
- path: workPath(context.args.area, requiredString2(context.args.path), [
28005
+ path: workPath(context.args.area, requiredString3(context.args.path), [
24343
28006
  "work",
24344
28007
  "outputs"
24345
28008
  ]),
24346
- content: requiredString2(context.args.content, true),
28009
+ content: requiredString3(context.args.content, true),
24347
28010
  autoPreserveSource: false
24348
28011
  })
24349
28012
  )
@@ -24370,12 +28033,12 @@ function createWorkModelToolDefinitions(deps) {
24370
28033
  "work_edit_file",
24371
28034
  "sandbox_edit_file",
24372
28035
  (context) => ({
24373
- path: workPath(context.args.area, requiredString2(context.args.path), [
28036
+ path: workPath(context.args.area, requiredString3(context.args.path), [
24374
28037
  "work",
24375
28038
  "outputs"
24376
28039
  ]),
24377
- oldText: requiredString2(context.args.oldText),
24378
- newText: requiredString2(context.args.newText, true),
28040
+ oldText: requiredString3(context.args.oldText),
28041
+ newText: requiredString3(context.args.newText, true),
24379
28042
  replaceAll: context.args.replaceAll === true,
24380
28043
  autoPreserveSource: false
24381
28044
  })
@@ -24401,7 +28064,7 @@ function createWorkModelToolDefinitions(deps) {
24401
28064
  "work_delete_file",
24402
28065
  "sandbox_delete_file",
24403
28066
  (context) => ({
24404
- path: workPath(context.args.area, requiredString2(context.args.path), [
28067
+ path: workPath(context.args.area, requiredString3(context.args.path), [
24405
28068
  "work",
24406
28069
  "outputs"
24407
28070
  ]),
@@ -24427,7 +28090,7 @@ function createWorkModelToolDefinitions(deps) {
24427
28090
  required: ["command"]
24428
28091
  },
24429
28092
  execute: withSandbox("work_exec", "sandbox_exec", (context) => ({
24430
- command: `cd /workspace/work && ${requiredString2(context.args.command)}`,
28093
+ command: `cd /workspace/work && ${requiredString3(context.args.command)}`,
24431
28094
  timeoutSeconds: typeof context.args.timeoutSeconds === "number" ? Math.min(
24432
28095
  Math.max(Math.floor(context.args.timeoutSeconds), 1),
24433
28096
  3600
@@ -24452,7 +28115,7 @@ function createWorkModelToolDefinitions(deps) {
24452
28115
  "sandbox_open_port",
24453
28116
  (context) => ({
24454
28117
  port: context.args.port,
24455
- label: optionalString2(context.args.label) || "Work preview",
28118
+ label: optionalString3(context.args.label) || "Work preview",
24456
28119
  access: "private",
24457
28120
  autoStart: true
24458
28121
  })
@@ -24473,7 +28136,7 @@ function createWorkModelToolDefinitions(deps) {
24473
28136
  "work_checkpoint",
24474
28137
  "sandbox_snapshot_create",
24475
28138
  (context) => ({
24476
- name: requiredString2(context.args.name)
28139
+ name: requiredString3(context.args.name)
24477
28140
  })
24478
28141
  )
24479
28142
  },
@@ -24505,8 +28168,8 @@ function createWorkModelToolDefinitions(deps) {
24505
28168
  "work_prepare_agent",
24506
28169
  "sandbox_prepare_agent",
24507
28170
  (context) => ({
24508
- directory: requiredString2(context.args.directory),
24509
- template: requiredString2(context.args.template)
28171
+ directory: requiredString3(context.args.directory),
28172
+ template: requiredString3(context.args.template)
24510
28173
  })
24511
28174
  )
24512
28175
  },
@@ -24540,9 +28203,9 @@ function createWorkModelToolDefinitions(deps) {
24540
28203
  "work_save_agent_package",
24541
28204
  "sandbox_save_agent_package",
24542
28205
  (context) => ({
24543
- directory: requiredString2(context.args.directory),
24544
- agentId: optionalString2(context.args.agentId) || void 0,
24545
- title: optionalString2(context.args.title) || void 0
28206
+ directory: requiredString3(context.args.directory),
28207
+ agentId: optionalString3(context.args.agentId) || void 0,
28208
+ title: optionalString3(context.args.title) || void 0
24546
28209
  })
24547
28210
  )
24548
28211
  },
@@ -24592,10 +28255,10 @@ function createWorkModelToolDefinitions(deps) {
24592
28255
  "work_save_output",
24593
28256
  "sandbox_save_output",
24594
28257
  (context) => ({
24595
- path: workPath("outputs", requiredString2(context.args.path), [
28258
+ path: workPath("outputs", requiredString3(context.args.path), [
24596
28259
  "outputs"
24597
28260
  ]),
24598
- suggestedName: optionalString2(context.args.suggestedName) || void 0,
28261
+ suggestedName: optionalString3(context.args.suggestedName) || void 0,
24599
28262
  validation: Array.isArray(context.args.validation) ? context.args.validation : []
24600
28263
  })
24601
28264
  )
@@ -24642,9 +28305,9 @@ function createWorkModelToolDefinitions(deps) {
24642
28305
  required: ["kind", "title", "resourceId", "url"]
24643
28306
  },
24644
28307
  execute: async (context) => {
24645
- const kind = requiredString2(context.args.kind);
24646
- const title = requiredString2(context.args.title);
24647
- const resourceId = requiredString2(context.args.resourceId);
28308
+ const kind = requiredString3(context.args.kind);
28309
+ const title = requiredString3(context.args.title);
28310
+ const resourceId = requiredString3(context.args.resourceId);
24648
28311
  const url = validHttpUrl(context.args.url);
24649
28312
  const validation = Array.isArray(context.args.validation) ? context.args.validation : [];
24650
28313
  const identity = {
@@ -24664,10 +28327,10 @@ function createWorkModelToolDefinitions(deps) {
24664
28327
  } : {
24665
28328
  ...identity,
24666
28329
  kind: "external_resource",
24667
- provider: optionalString2(context.args.provider) || "external",
28330
+ provider: optionalString3(context.args.provider) || "external",
24668
28331
  resourceId,
24669
28332
  url,
24670
- contentType: optionalString2(context.args.contentType) || null
28333
+ contentType: optionalString3(context.args.contentType) || null
24671
28334
  };
24672
28335
  return {
24673
28336
  toolCallId: context.callId,
@@ -24790,17 +28453,17 @@ function workAreaProperty() {
24790
28453
  enum: ["inputs", "work", "outputs"]
24791
28454
  };
24792
28455
  }
24793
- function requiredString2(value, allowEmpty = false) {
28456
+ function requiredString3(value, allowEmpty = false) {
24794
28457
  if (typeof value !== "string" || !allowEmpty && !value.trim()) {
24795
28458
  throw new Error("A required string argument is missing.");
24796
28459
  }
24797
28460
  return allowEmpty ? value : value.trim();
24798
28461
  }
24799
- function optionalString2(value) {
28462
+ function optionalString3(value) {
24800
28463
  return typeof value === "string" ? value.trim() : "";
24801
28464
  }
24802
28465
  function validHttpUrl(value) {
24803
- const text = requiredString2(value);
28466
+ const text = requiredString3(value);
24804
28467
  const url = new URL(text);
24805
28468
  if (url.protocol !== "http:" && url.protocol !== "https:") {
24806
28469
  throw new Error("Work output URLs must use HTTP or HTTPS.");
@@ -25819,7 +29482,7 @@ async function assertGeneratedSdkArtifacts(target, requireEvalPass = true) {
25819
29482
  );
25820
29483
  }
25821
29484
  const missingMetadata = actions.filter(
25822
- (action) => typeof action.id === "string" && (!stringValue8(action.label) || !stringValue8(action.description) || typeof action.timeoutSeconds !== "number")
29485
+ (action) => typeof action.id === "string" && (!stringValue9(action.label) || !stringValue9(action.description) || typeof action.timeoutSeconds !== "number")
25823
29486
  );
25824
29487
  if (missingMetadata.length > 0) {
25825
29488
  throw new Error(
@@ -25829,7 +29492,7 @@ async function assertGeneratedSdkArtifacts(target, requireEvalPass = true) {
25829
29492
  const setupGate = buildOpenPondProfileSetupGate({
25830
29493
  actionCatalog: actions.filter((action) => typeof action.id === "string").map((action) => ({
25831
29494
  id: action.id,
25832
- name: stringValue8(action.name),
29495
+ name: stringValue9(action.name),
25833
29496
  setupRequirements: recordArray(action.setupRequirements) ?? []
25834
29497
  })),
25835
29498
  actionId: target.defaultAction
@@ -25860,49 +29523,49 @@ function parseJsonOutput(stdout) {
25860
29523
  return null;
25861
29524
  }
25862
29525
  }
25863
- function asRecord6(value) {
29526
+ function asRecord8(value) {
25864
29527
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
25865
29528
  }
25866
29529
  function recordArray(value) {
25867
29530
  if (!Array.isArray(value)) return null;
25868
29531
  return value.filter(
25869
- (item) => Boolean(asRecord6(item))
29532
+ (item) => Boolean(asRecord8(item))
25870
29533
  );
25871
29534
  }
25872
29535
  function traceRefFromCommandResult(value) {
25873
- const record5 = asRecord6(value);
25874
- const ref = stringValue8(record5?.traceArtifactRef);
29536
+ const record5 = asRecord8(value);
29537
+ const ref = stringValue9(record5?.traceArtifactRef);
25875
29538
  return ref?.startsWith(".openpond/") ? ref : null;
25876
29539
  }
25877
29540
  function summaryFromCommandResult(commandName, value) {
25878
- const record5 = asRecord6(value);
29541
+ const record5 = asRecord8(value);
25879
29542
  if (!record5) return null;
25880
29543
  if (commandName === "inspect") {
25881
29544
  return {
25882
29545
  actionCount: Array.isArray(record5.actionCatalog) ? record5.actionCatalog.length : null,
25883
- defaultAction: asRecord6(record5.agent)?.defaultAction ?? null,
25884
- projectName: asRecord6(record5.project)?.name ?? null
29546
+ defaultAction: asRecord8(record5.agent)?.defaultAction ?? null,
29547
+ projectName: asRecord8(record5.project)?.name ?? null
25885
29548
  };
25886
29549
  }
25887
29550
  if (commandName === "validate") {
25888
29551
  return {
25889
29552
  status: record5.status ?? null,
25890
- errors: asRecord6(record5.summary)?.errors ?? null,
25891
- warnings: asRecord6(record5.summary)?.warnings ?? null
29553
+ errors: asRecord8(record5.summary)?.errors ?? null,
29554
+ warnings: asRecord8(record5.summary)?.warnings ?? null
25892
29555
  };
25893
29556
  }
25894
29557
  if (commandName === "eval") {
25895
- return asRecord6(record5.summary);
29558
+ return asRecord8(record5.summary);
25896
29559
  }
25897
29560
  if (commandName === "direct-run") {
25898
29561
  return {
25899
- hasResult: Boolean(asRecord6(record5.result)),
25900
- resultKeys: Object.keys(asRecord6(record5.result) ?? {})
29562
+ hasResult: Boolean(asRecord8(record5.result)),
29563
+ resultKeys: Object.keys(asRecord8(record5.result) ?? {})
25901
29564
  };
25902
29565
  }
25903
29566
  return null;
25904
29567
  }
25905
- function stringValue8(value) {
29568
+ function stringValue9(value) {
25906
29569
  return typeof value === "string" && value.trim() ? value.trim() : null;
25907
29570
  }
25908
29571
 
@@ -26127,7 +29790,7 @@ function agentCandidateId(runId) {
26127
29790
  return `agent_candidate_${runId}`;
26128
29791
  }
26129
29792
  function checkSummary(metadata) {
26130
- const evaluation = asRecord7(metadata?.eval);
29793
+ const evaluation = asRecord9(metadata?.eval);
26131
29794
  const total = typeof evaluation?.total === "number" ? evaluation.total : null;
26132
29795
  return total === null ? "Agent SDK checks and deterministic Evals passed." : `${total} Agent SDK Eval${total === 1 ? "" : "s"} passed.`;
26133
29796
  }
@@ -26314,14 +29977,14 @@ async function applyPreparedHarnessSourceApplication(snapshot, target, env = pro
26314
29977
  );
26315
29978
  if (!existsSync2(manifestPath)) return false;
26316
29979
  const manifest = JSON.parse(await readFile3(manifestPath, "utf8"));
26317
- const root = asRecord7(manifest);
29980
+ const root = asRecord9(manifest);
26318
29981
  if (root?.schema !== "openpond.harnessPreparedSource.v1") {
26319
29982
  throw new Error(
26320
29983
  `${HARNESS_PREPARED_SOURCE_MANIFEST} must use schema openpond.harnessPreparedSource.v1.`
26321
29984
  );
26322
29985
  }
26323
- const agents = asRecord7(root.agents);
26324
- const agent = asRecord7(agents?.[target.agentId]);
29986
+ const agents = asRecord9(root.agents);
29987
+ const agent = asRecord9(agents?.[target.agentId]);
26325
29988
  const operation = asHarnessPreparedSourceOperation(
26326
29989
  agent?.[snapshot.operation]
26327
29990
  );
@@ -26360,14 +30023,14 @@ async function applyPreparedHarnessSourceApplication(snapshot, target, env = pro
26360
30023
  return true;
26361
30024
  }
26362
30025
  function asHarnessPreparedSourceOperation(value) {
26363
- const operation = asRecord7(value);
30026
+ const operation = asRecord9(value);
26364
30027
  if (!operation || typeof operation.source !== "string" || !operation.source.trim())
26365
30028
  return null;
26366
30029
  if (operation.registrations !== void 0 && !Array.isArray(operation.registrations)) {
26367
30030
  throw new Error("Prepared harness source registrations must be an array.");
26368
30031
  }
26369
30032
  const registrations = (operation.registrations ?? []).map((value2) => {
26370
- const registration = asRecord7(value2);
30033
+ const registration = asRecord9(value2);
26371
30034
  if (!registration || typeof registration.source !== "string" || !registration.source.trim() || typeof registration.target !== "string" || !registration.target.trim()) {
26372
30035
  throw new Error(
26373
30036
  "Prepared harness source registrations require source and target paths."
@@ -26404,7 +30067,7 @@ async function waitForTimedOutSourceApplication(target) {
26404
30067
  const deadline = Date.now() + LOCAL_CREATE_TIMEOUT_RECOVERY_MS;
26405
30068
  while (Date.now() < deadline) {
26406
30069
  if (await localCreateSourceLayoutIsStable(target)) return true;
26407
- await sleep2(LOCAL_CREATE_TIMEOUT_RECOVERY_POLL_MS);
30070
+ await sleep3(LOCAL_CREATE_TIMEOUT_RECOVERY_POLL_MS);
26408
30071
  }
26409
30072
  return false;
26410
30073
  }
@@ -26412,7 +30075,7 @@ async function localCreateSourceLayoutIsStable(target) {
26412
30075
  try {
26413
30076
  await assertLocalCreateSourceLayout(target);
26414
30077
  const before = await sourceLayoutFingerprint(target);
26415
- await sleep2(LOCAL_CREATE_TIMEOUT_RECOVERY_STABLE_MS);
30078
+ await sleep3(LOCAL_CREATE_TIMEOUT_RECOVERY_STABLE_MS);
26416
30079
  await assertLocalCreateSourceLayout(target);
26417
30080
  const after = await sourceLayoutFingerprint(target);
26418
30081
  return before === after;
@@ -26435,7 +30098,7 @@ async function sourceLayoutFingerprint(target) {
26435
30098
  );
26436
30099
  return parts.join("\n---\n");
26437
30100
  }
26438
- function sleep2(ms) {
30101
+ function sleep3(ms) {
26439
30102
  return new Promise((resolve) => setTimeout(resolve, ms));
26440
30103
  }
26441
30104
  function localCreatePipelinePrompt(snapshot, target) {
@@ -26498,7 +30161,7 @@ function normalizeActionId(value) {
26498
30161
  const trimmed = value?.trim();
26499
30162
  return trimmed || null;
26500
30163
  }
26501
- function asRecord7(value) {
30164
+ function asRecord9(value) {
26502
30165
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
26503
30166
  }
26504
30167
  function sourceActionIdForAgent(actionId, agentId) {
@@ -27265,7 +30928,7 @@ async function executeAgentTasksetEvaluation(input) {
27265
30928
  task.id,
27266
30929
  0
27267
30930
  ]).slice(0, 24)}`;
27268
- const traceRef = stringValue9(parsed?.traceArtifactRef);
30931
+ const traceRef = stringValue10(parsed?.traceArtifactRef);
27269
30932
  const attempt = TaskAttemptResultSchema.parse({
27270
30933
  schemaVersion: "openpond.taskAttempt.v1",
27271
30934
  id: attemptId,
@@ -27335,7 +30998,7 @@ function parseAgentRunPayload(stdout) {
27335
30998
  function recordValue(value) {
27336
30999
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
27337
31000
  }
27338
- function stringValue9(value) {
31001
+ function stringValue10(value) {
27339
31002
  return typeof value === "string" && value.trim() ? value.trim() : null;
27340
31003
  }
27341
31004
 
@@ -27348,17 +31011,17 @@ async function runNormalizedAgentEvaluation(input) {
27348
31011
  throwOnFailure: false
27349
31012
  });
27350
31013
  const payload = parseAgentEvalPayload(result.stdout);
27351
- const total = numberValue5(payload.summary?.total) ?? 0;
27352
- const passed = numberValue5(payload.summary?.passed) ?? 0;
27353
- const failed = numberValue5(payload.summary?.failed) ?? Math.max(0, total - passed);
31014
+ const total = numberValue6(payload.summary?.total) ?? 0;
31015
+ const passed = numberValue6(payload.summary?.passed) ?? 0;
31016
+ const failed = numberValue6(payload.summary?.failed) ?? Math.max(0, total - passed);
27354
31017
  const publishGate = payload.publishGate?.status === "passed" ? "passed" : "failed";
27355
31018
  const results = Array.isArray(payload.results) ? payload.results : [];
27356
- const sdkEvalRefs = results.map((evaluation) => stringValue10(evaluation.name)).filter((value) => Boolean(value));
31019
+ const sdkEvalRefs = results.map((evaluation) => stringValue11(evaluation.name)).filter((value) => Boolean(value));
27357
31020
  const artifactRefs = /* @__PURE__ */ new Set([
27358
31021
  path29.posix.join(input.sourceRef, ".openpond/eval-results.json")
27359
31022
  ]);
27360
31023
  for (const evaluation of results) {
27361
- const trace = stringValue10(evaluation.traceArtifactRef);
31024
+ const trace = stringValue11(evaluation.traceArtifactRef);
27362
31025
  if (trace)
27363
31026
  artifactRefs.add(path29.posix.join(input.sourceRef, normalizeRef(trace)));
27364
31027
  for (const artifact of stringArray3(evaluation.artifacts)) {
@@ -27412,20 +31075,20 @@ async function runNormalizedAgentEvaluation(input) {
27412
31075
  summary: `${input.subject === "active" ? "Active" : input.subject === "candidate" ? "Candidate" : "Post-release"} Agent SDK and Taskset Evals: ${combinedPassed}/${combinedTotal} passed${combinedPublishGate === "failed" ? "; publish gate failed" : ""}.`,
27413
31076
  createdAt: timestamp,
27414
31077
  metadata: {
27415
- schemaVersion: stringValue10(payload.schemaVersion),
27416
- schema: stringValue10(payload.schema),
31078
+ schemaVersion: stringValue11(payload.schemaVersion),
31079
+ schema: stringValue11(payload.schema),
27417
31080
  project: {
27418
- name: stringValue10(payload.project?.name),
27419
- version: stringValue10(payload.project?.version)
31081
+ name: stringValue11(payload.project?.name),
31082
+ version: stringValue11(payload.project?.version)
27420
31083
  },
27421
31084
  source: {
27422
- configPath: stringValue10(payload.source?.configPath),
27423
- configHash: stringValue10(payload.source?.configHash)
31085
+ configPath: stringValue11(payload.source?.configPath),
31086
+ configHash: stringValue11(payload.source?.configHash)
27424
31087
  },
27425
31088
  publishGate: {
27426
- total: numberValue5(payload.publishGate?.total),
27427
- passed: numberValue5(payload.publishGate?.passed),
27428
- failed: numberValue5(payload.publishGate?.failed),
31089
+ total: numberValue6(payload.publishGate?.total),
31090
+ passed: numberValue6(payload.publishGate?.passed),
31091
+ failed: numberValue6(payload.publishGate?.failed),
27429
31092
  blockingFailures: stringArray3(payload.publishGate?.blockingFailures)
27430
31093
  },
27431
31094
  command: {
@@ -27438,10 +31101,10 @@ async function runNormalizedAgentEvaluation(input) {
27438
31101
  executionContractHash: tasksetExecution?.executionContractHash ?? null,
27439
31102
  gradeRefs: tasksetExecution?.gradeRefs ?? [],
27440
31103
  results: results.map((evaluation) => ({
27441
- name: stringValue10(evaluation.name),
27442
- status: stringValue10(evaluation.status),
27443
- error: stringValue10(evaluation.error),
27444
- traceArtifactRef: stringValue10(evaluation.traceArtifactRef)
31104
+ name: stringValue11(evaluation.name),
31105
+ status: stringValue11(evaluation.status),
31106
+ error: stringValue11(evaluation.error),
31107
+ traceArtifactRef: stringValue11(evaluation.traceArtifactRef)
27445
31108
  }))
27446
31109
  }
27447
31110
  };
@@ -27480,14 +31143,14 @@ function parseAgentEvalPayload(stdout) {
27480
31143
  function normalizeRef(value) {
27481
31144
  return value.replace(/^\.\//, "").replaceAll("\\", "/");
27482
31145
  }
27483
- function stringValue10(value) {
31146
+ function stringValue11(value) {
27484
31147
  return typeof value === "string" && value.trim() ? value.trim() : null;
27485
31148
  }
27486
- function numberValue5(value) {
31149
+ function numberValue6(value) {
27487
31150
  return typeof value === "number" && Number.isFinite(value) ? value : null;
27488
31151
  }
27489
31152
  function stringArray3(value) {
27490
- return Array.isArray(value) ? value.map(stringValue10).filter((item) => Boolean(item)) : [];
31153
+ return Array.isArray(value) ? value.map(stringValue11).filter((item) => Boolean(item)) : [];
27491
31154
  }
27492
31155
 
27493
31156
  // ../server/src/runtime/create-pipeline/agent-improvement-git.ts
@@ -27710,13 +31373,13 @@ async function listPullRequestsForBranch(command, cwd, branch) {
27710
31373
  function normalizePullRequest(raw, openedAt = (/* @__PURE__ */ new Date()).toISOString(), updatedAt = (/* @__PURE__ */ new Date()).toISOString()) {
27711
31374
  const number = typeof raw.number === "number" ? raw.number : Number(raw.number);
27712
31375
  const stateValue = typeof raw.state === "string" ? raw.state.toLowerCase() : "";
27713
- const mergedAt = stringValue11(raw.mergedAt);
31376
+ const mergedAt = stringValue12(raw.mergedAt);
27714
31377
  const state = mergedAt || stateValue === "merged" ? "merged" : stateValue === "open" ? "open" : "closed";
27715
31378
  const mergeCommitRecord = raw.mergeCommit && typeof raw.mergeCommit === "object" ? raw.mergeCommit : null;
27716
- const mergeCommit = stringValue11(mergeCommitRecord?.oid) ?? stringValue11(raw.mergeCommit);
27717
- const url = stringValue11(raw.url);
27718
- const baseBranch = stringValue11(raw.baseRefName);
27719
- const headBranch = stringValue11(raw.headRefName);
31379
+ const mergeCommit = stringValue12(mergeCommitRecord?.oid) ?? stringValue12(raw.mergeCommit);
31380
+ const url = stringValue12(raw.url);
31381
+ const baseBranch = stringValue12(raw.baseRefName);
31382
+ const headBranch = stringValue12(raw.headRefName);
27720
31383
  if (!Number.isInteger(number) || number <= 0 || !url || !baseBranch || !headBranch) {
27721
31384
  throw new Error("GitHub returned an incomplete pull request payload.");
27722
31385
  }
@@ -27768,7 +31431,7 @@ function assertCommand(result, message) {
27768
31431
  if (result.code === 0) return;
27769
31432
  throw new Error(result.stderr.trim() || result.stdout.trim() || message);
27770
31433
  }
27771
- function stringValue11(value) {
31434
+ function stringValue12(value) {
27772
31435
  return typeof value === "string" && value.trim() ? value.trim() : null;
27773
31436
  }
27774
31437
  function defaultCommandRunner(command, args, cwd, env = {}) {
@@ -28340,9 +32003,9 @@ async function readAgentPackageOrigin(agentRootPath, manifestHash) {
28340
32003
  ".openpond",
28341
32004
  "agent-package-origin.json"
28342
32005
  );
28343
- const origin = await fs20.readFile(originPath, "utf8").then((raw) => asRecord8(JSON.parse(raw))).catch(() => ({}));
28344
- const versionId = stringValue12(origin.versionId);
28345
- const digest = stringValue12(origin.digest);
32006
+ const origin = await fs20.readFile(originPath, "utf8").then((raw) => asRecord10(JSON.parse(raw))).catch(() => ({}));
32007
+ const versionId = stringValue13(origin.versionId);
32008
+ const digest = stringValue13(origin.digest);
28346
32009
  if (versionId && digest && /^[a-f0-9]{64}$/.test(digest) && versionId === `agent-${digest.slice(0, 20)}`) {
28347
32010
  return {
28348
32011
  versionId,
@@ -28358,10 +32021,10 @@ async function readAgentPackageOrigin(agentRootPath, manifestHash) {
28358
32021
  evalReceiptIds: []
28359
32022
  };
28360
32023
  }
28361
- function asRecord8(value) {
32024
+ function asRecord10(value) {
28362
32025
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
28363
32026
  }
28364
- function stringValue12(value) {
32027
+ function stringValue13(value) {
28365
32028
  return typeof value === "string" && value.trim() ? value.trim() : null;
28366
32029
  }
28367
32030
  function stringArray4(value) {
@@ -29435,7 +33098,7 @@ function uniqueEvidence(run, evidence) {
29435
33098
  }
29436
33099
  async function verifyAppliedProfileCommit(input) {
29437
33100
  const command = input.command ?? (async (name, args, cwd, env) => {
29438
- const { runWorkspaceCommand } = await import("./workspaces-XC3QBD2Y.js");
33101
+ const { runWorkspaceCommand } = await import("./workspaces-C3DGNUX2.js");
29439
33102
  return runWorkspaceCommand(name, args, cwd, env);
29440
33103
  });
29441
33104
  const result = await command("git", ["rev-parse", "HEAD"], input.repoPath);
@@ -36886,7 +40549,8 @@ async function createOpenPondAppServer(options = {}) {
36886
40549
  workspaceDir,
36887
40550
  logger,
36888
40551
  getSession,
36889
- appendRuntimeEvent
40552
+ appendRuntimeEvent,
40553
+ sandboxRequest: options.sandboxRequest
36890
40554
  });
36891
40555
  const upsertApproval = async (approval) => {
36892
40556
  await store.upsertApproval(approval);
@@ -37092,7 +40756,6 @@ export {
37092
40756
  createLocalHarnessImprovementRuntime,
37093
40757
  createLocalHarnessModelToolDefinitions,
37094
40758
  resolveWorkspaceExecutionTarget,
37095
- pipefailSandboxShellCommand,
37096
40759
  SELECT_PROJECT_MESSAGE,
37097
40760
  createOpenPondCommandAccessService,
37098
40761
  commandResultForModel,
@@ -37123,6 +40786,10 @@ export {
37123
40786
  getWorkspaceDeploymentSource,
37124
40787
  handleActiveWorkspaceToolAction,
37125
40788
  MUTATING_WORKSPACE_TOOL_ACTIONS,
40789
+ resolveOpenPondSandboxClient,
40790
+ sandboxRequestPayload,
40791
+ listSandboxIntegrationConnections,
40792
+ requestOpenPondPublicApi,
37126
40793
  isBundledAuthoringSkillName,
37127
40794
  loadBundledAuthoringSkills,
37128
40795
  readBundledAuthoringProfileSkill,