@constal/sdk 6.9.1 → 6.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/publish/index.js CHANGED
@@ -563,47 +563,48 @@ var casTool = {
563
563
  };
564
564
 
565
565
  // packages/sdk/src/skills.ts
566
- async function required(workspace, skill, cmd, args, timeoutMs) {
567
- const result = timeoutMs === void 0 ? await workspace.exec({ cmd, args }) : await workspace.exec({ cmd, args, timeoutMs }, { timeoutMs });
568
- if (result.status !== "completed" || result.exitCode !== 0) {
569
- throw new Error(`Copying skill ${skill} into the workspace failed: ${cmd} ended ${result.status} with exit code ${result.exitCode}. ${result.stderrPreview}`);
566
+ async function required(sandbox, skill, cmd, args, timeoutMs) {
567
+ const result = timeoutMs === void 0 ? await sandbox.exec({ cmd, args }) : await sandbox.exec({ cmd, args, timeoutMs }, { timeoutMs });
568
+ if (result.state !== "exited" || result.exitCode !== 0) {
569
+ throw new Error(`Copying skill ${skill} into the sandbox failed: ${cmd} ended ${result.state} with exit code ${result.exitCode}. ${result.stderr}`);
570
570
  }
571
571
  }
572
- function skills(binding = "skills", sandbox = "sandbox") {
572
+ function skills(binding = "skills", pool = "sandbox") {
573
573
  const prefix = binding.replaceAll(/[.-]/gu, "_");
574
574
  const find = opTool(binding, "find", { name: `${prefix}_find` });
575
575
  const read = opTool(binding, "read", { name: `${prefix}_read` });
576
576
  const run = {
577
577
  name: `${prefix}_run`,
578
- version: "1",
579
- description: "Runs one command in the sandbox workspace with its working directory set to a copy of a skill's folder, which holds the skill's SKILL.md and every file it bundles. Returns the folder's path and the command's result: its status, exit code and output.",
580
- schema: { type: "object", required: ["skill", "cmd"], additionalProperties: false, properties: {
578
+ version: "2",
579
+ description: "Runs one command in a sandbox with its working directory set to a copy of a skill's folder, which holds the skill's SKILL.md and every file it bundles. Returns the folder's path and the command's result: its state, exit code and output.",
580
+ schema: { type: "object", required: ["skill", "sandbox", "cmd"], additionalProperties: false, properties: {
581
581
  skill: { type: "string", minLength: 1, description: "The skill's name." },
582
+ sandbox: { type: "string", minLength: 1, description: "The id of the running sandbox to run it in." },
582
583
  cmd: { type: "string", minLength: 1, description: "The program to run." },
583
584
  args: { type: "array", items: { type: "string" }, description: "The program's arguments." },
584
585
  env: { type: "object", additionalProperties: { type: "string" }, description: "Environment variables for the command." },
585
586
  stdin: { type: "string", description: "Text the command reads on its standard input." },
586
- timeoutMs: { type: "integer", minimum: 1, description: "How long each command may run, in milliseconds: the program, and each command that copies the skill's folder into the workspace." }
587
+ timeoutMs: { type: "integer", minimum: 1, description: "How long each command may run, in milliseconds: the program, and each command that copies the skill's folder into the sandbox." }
587
588
  } },
588
589
  maxEffect: "reconcilable",
589
- needs: [{ binding, kind: "skills", ops: ["bundle"] }, { binding: sandbox, kind: "sandbox-pool", ops: ["exec", "putFile"] }],
590
+ needs: [{ binding, kind: "skills", ops: ["bundle"] }, { binding: pool, kind: "sandbox-pool", ops: ["exec", "writeFile"] }],
590
591
  async run(args, ctx) {
591
592
  const { ref } = await ctx.invoke(ctx.resources[binding], "bundle", { skill: args.skill });
592
- const workspace = ctx.sandboxPool(ctx.resources[sandbox]).workspace();
593
+ const sandbox = ctx.sandboxPool(ctx.resources[pool]).sandbox(args.sandbox);
593
594
  const path2 = `/workspace/skills/${ref}`;
594
595
  const bound = args.timeoutMs === void 0 ? void 0 : { timeoutMs: args.timeoutMs };
595
- const present = await workspace.exec({ cmd: "test", args: ["-e", path2], ...bound }, bound);
596
- if (present.status !== "completed" || present.exitCode !== 0) {
596
+ const present = await sandbox.exec({ cmd: "test", args: ["-e", path2], ...bound }, bound);
597
+ if (present.state !== "exited" || present.exitCode !== 0) {
597
598
  const archive = `/workspace/.constal/imports/${ref}.tar.gz`;
598
599
  const staging = `/workspace/.constal/staging/${ref}`;
599
- await required(workspace, args.skill, "mkdir", ["-p", "--", "/workspace/.constal/imports", staging, "/workspace/skills"], args.timeoutMs);
600
- await workspace.putFile(archive, ref, bound && { invoke: bound });
601
- await required(workspace, args.skill, "tar", ["-xzf", archive, "-C", staging, "--no-same-owner", "--no-same-permissions"], args.timeoutMs);
602
- await required(workspace, args.skill, "mv", ["--", staging, path2], args.timeoutMs);
603
- await required(workspace, args.skill, "rm", ["-f", "--", archive], args.timeoutMs);
600
+ await required(sandbox, args.skill, "mkdir", ["-p", "--", "/workspace/.constal/imports", staging, "/workspace/skills"], args.timeoutMs);
601
+ await sandbox.writeFile(archive, { ref }, bound);
602
+ await required(sandbox, args.skill, "tar", ["-xzf", archive, "-C", staging, "--no-same-owner", "--no-same-permissions"], args.timeoutMs);
603
+ await required(sandbox, args.skill, "mv", ["--", staging, path2], args.timeoutMs);
604
+ await required(sandbox, args.skill, "rm", ["-f", "--", archive], args.timeoutMs);
604
605
  }
605
- const { skill: _skill, ...command } = args;
606
- return { path: path2, ...await workspace.exec({ ...command, cwd: path2 }, bound) };
606
+ const { skill: _skill, sandbox: _sandbox, ...command } = args;
607
+ return { path: path2, ...await sandbox.exec({ ...command, cwd: path2 }, bound) };
607
608
  }
608
609
  };
609
610
  return { [find.name]: find, [read.name]: read, [run.name]: run };
@@ -1420,16 +1421,6 @@ function normalizeSandboxNetworkPolicy(value, options = {}) {
1420
1421
  if (Object.keys(input).some((key) => key !== "mode" && key !== "domains")) throw new TypeError("sandbox network policy has unexpected fields");
1421
1422
  return { mode: "domain-allow", domains: normalizeDomains(input.domains) };
1422
1423
  }
1423
- if (input.mode === "managed-http") {
1424
- if (input.transport !== "bridge" && input.transport !== "proxy") throw new TypeError("sandbox managed HTTP transport is invalid");
1425
- if (typeof input.egress !== "string" || parseResourceName(input.egress).kind !== "service") throw new TypeError("sandbox managed HTTP egress must be a Service CRN");
1426
- if (input.transport === "bridge") {
1427
- if (Object.keys(input).some((key) => !["mode", "transport", "egress"].includes(key))) throw new TypeError("sandbox network policy has unexpected fields");
1428
- return { mode: "managed-http", transport: "bridge", egress: input.egress };
1429
- }
1430
- if (Object.keys(input).some((key) => !["mode", "transport", "egress", "domains"].includes(key))) throw new TypeError("sandbox network policy has unexpected fields");
1431
- return { mode: "managed-http", transport: "proxy", egress: input.egress, domains: normalizeDomains(input.domains) };
1432
- }
1433
1424
  throw new TypeError("sandbox network policy mode is invalid");
1434
1425
  }
1435
1426
 
@@ -1533,7 +1524,7 @@ function executable(value, path2) {
1533
1524
  function channel(definition) {
1534
1525
  executable(definition, "channel");
1535
1526
  executable(definition.protocol, "channel.protocol");
1536
- if (typeof definition.protocol.receive !== "function" || typeof definition.protocol.respond !== "function" || definition.protocol.send !== void 0 && typeof definition.protocol.send !== "function" || definition.protocol.failed !== void 0 && typeof definition.protocol.failed !== "function" || definition.protocol.authorizeSubscription !== void 0 && typeof definition.protocol.authorizeSubscription !== "function") {
1527
+ if (typeof definition.protocol.receive !== "function" || typeof definition.protocol.respond !== "function" || definition.protocol.send !== void 0 && typeof definition.protocol.send !== "function" || definition.protocol.failed !== void 0 && typeof definition.protocol.failed !== "function" || definition.protocol.authorizeSubscription !== void 0 && typeof definition.protocol.authorizeSubscription !== "function" || definition.protocol.presence !== void 0 && typeof definition.protocol.presence !== "function" || definition.protocol.fetch !== void 0 && typeof definition.protocol.fetch !== "function") {
1537
1528
  throw new TypeError("channel.protocol must define receive and respond; optional handlers must be functions");
1538
1529
  }
1539
1530
  resourceDependencyRef(definition.authProvider, ["auth-provider"]);
@@ -2376,8 +2367,8 @@ var CONSTAL_API_OPERATION_SCHEMAS = {
2376
2367
  // packages/sdk/src/sandbox-policy-contract.ts
2377
2368
  var SANDBOX_CONTRACT_REF = {
2378
2369
  id: "constal.sandbox-pool",
2379
- version: "2",
2380
- hash: "89c34a8870f861811e6548d8388eddfc2d9b74e642fabeaf37c89f6d21df1c8e"
2370
+ version: "3",
2371
+ hash: "6d987430d15960a25d3642b13997286b2b83d84f86db1c826630310b318708f4"
2381
2372
  };
2382
2373
  var SANDBOX_CONTROLS_SCHEMA = {
2383
2374
  type: "object",
@@ -2386,15 +2377,11 @@ var SANDBOX_CONTROLS_SCHEMA = {
2386
2377
  command_timeout_ms: { type: "integer", minimum: 1 },
2387
2378
  cpu: { type: "number", exclusiveMinimum: 0 },
2388
2379
  disk_gib: { type: "number", minimum: 0 },
2389
- idle_stop_ms: { type: "integer", minimum: 1 },
2390
- max_concurrent_commands: { type: "integer", minimum: 1 },
2391
2380
  max_file_bytes: { type: "integer", minimum: 1 },
2392
2381
  memory_gib: { type: "number", exclusiveMinimum: 0 },
2393
2382
  network_cidrs: { type: "array", minItems: 1, items: { type: "string" } },
2394
2383
  network_domains: { type: "array", minItems: 1, items: { type: "string" } },
2395
- network_egress: { type: ["string", "null"] },
2396
- network_mode: { enum: ["block-all", "cidr-allow", "domain-allow", "managed-http", "unrestricted"] },
2397
- network_transport: { enum: [null, "bridge", "proxy"] },
2384
+ network_mode: { enum: ["block-all", "cidr-allow", "domain-allow", "unrestricted"] },
2398
2385
  permitted_paths: { type: "array", minItems: 1, items: { type: "string" } }
2399
2386
  }
2400
2387
  };
@@ -2446,7 +2433,7 @@ function sandboxControls(values) {
2446
2433
  return controls(SANDBOX_CONTRACT, values, sandboxSchema);
2447
2434
  }
2448
2435
  function sandboxLimit(input) {
2449
- return limit(SANDBOX_CONTRACT, ["commands", "compute_ms", "file_bytes", "requests"], input);
2436
+ return limit(SANDBOX_CONTRACT, ["commands", "requests"], input);
2450
2437
  }
2451
2438
  function modelControls(values, contract = MODEL_CONTRACT) {
2452
2439
  return controls(contract, values, modelSchema);
@@ -2986,6 +2973,37 @@ function modelCacheHint(value) {
2986
2973
  }
2987
2974
  return hint;
2988
2975
  }
2976
+ var REF = /^[a-f0-9]{64}$/u;
2977
+ var MEDIA_TYPE = /^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]*\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]*$/u;
2978
+ var FILE_PART_FIELDS = ["type", "ref", "bytes", "mediaType", "name", "object"];
2979
+ function modelMessageContent(value, at) {
2980
+ if (typeof value === "string") return value;
2981
+ if (!Array.isArray(value)) throw new TypeError(`${at} content must be text or an array of text and file parts`);
2982
+ return value.map((candidate, index) => {
2983
+ const part = record7(candidate);
2984
+ const where = `${at} content part ${index}`;
2985
+ if (part?.type === "text") {
2986
+ if (typeof part.text !== "string" || Object.keys(part).some((key) => key !== "type" && key !== "text")) {
2987
+ throw new TypeError(`${where} is a text part, which carries its text and nothing else`);
2988
+ }
2989
+ return { type: "text", text: part.text };
2990
+ }
2991
+ if (part?.type !== "file") throw new TypeError(`${where} must be a text or file part`);
2992
+ const unknown = Object.keys(part).find((key) => !FILE_PART_FIELDS.includes(key));
2993
+ if (unknown !== void 0) throw new TypeError(`${where} has an unknown field: ${unknown}`);
2994
+ if (typeof part.ref !== "string" || !REF.test(part.ref) || !Number.isSafeInteger(part.bytes) || Number(part.bytes) < 0 || typeof part.mediaType !== "string" || !MEDIA_TYPE.test(part.mediaType) || part.name !== void 0 && !nonempty(part.name) || part.object !== void 0 && !nonempty(part.object)) {
2995
+ throw new TypeError(`${where} needs a stored value's ref, its size in bytes and its media type`);
2996
+ }
2997
+ return {
2998
+ type: "file",
2999
+ ref: part.ref,
3000
+ bytes: Number(part.bytes),
3001
+ mediaType: part.mediaType,
3002
+ ...part.name === void 0 ? {} : { name: part.name },
3003
+ ...part.object === void 0 ? {} : { object: part.object }
3004
+ };
3005
+ });
3006
+ }
2989
3007
  function modelHistoryMessages(value) {
2990
3008
  if (value === void 0) return [];
2991
3009
  if (!Array.isArray(value)) throw new TypeError("model history must be an array of messages");
@@ -2994,9 +3012,10 @@ function modelHistoryMessages(value) {
2994
3012
  const messages = value.map((candidate, index) => {
2995
3013
  const at = `model history message ${index}`;
2996
3014
  const source = record7(candidate);
2997
- if (!source || typeof source.content !== "string" || source.role !== "user" && source.role !== "assistant" && source.role !== "tool") {
3015
+ if (!source || source.role !== "user" && source.role !== "assistant" && source.role !== "tool" || source.role === "assistant" && typeof source.content !== "string") {
2998
3016
  throw new TypeError(`${at} needs a user, assistant or tool role and text content`);
2999
3017
  }
3018
+ const content2 = modelMessageContent(source.content, at);
3000
3019
  const foreign = source.role === "tool" ? ["toolCalls"] : source.role === "user" ? ["toolCalls", "toolCallId", "isError"] : ["toolCallId", "isError"];
3001
3020
  const misplaced = foreign.find((field2) => source[field2] !== void 0);
3002
3021
  if (misplaced !== void 0) throw new TypeError(`${at} has the ${source.role} role, which cannot carry ${misplaced}`);
@@ -3009,13 +3028,15 @@ function modelHistoryMessages(value) {
3009
3028
  return {
3010
3029
  role: "tool",
3011
3030
  toolCallId: source.toolCallId,
3012
- content: source.content,
3031
+ content: content2,
3013
3032
  ...source.isError === void 0 ? {} : { isError: source.isError }
3014
3033
  };
3015
3034
  }
3016
3035
  const open2 = unanswered.values().next();
3017
3036
  if (!open2.done) throw new TypeError(`model history Tool call ${open2.value} has no tool message answering it before message ${index}`);
3018
- if (source.role === "user" || source.toolCalls === void 0) return { role: source.role, content: source.content };
3037
+ if (source.role === "user") return { role: "user", content: content2 };
3038
+ if (typeof content2 !== "string") throw new TypeError(`${at} needs a user, assistant or tool role and text content`);
3039
+ if (source.toolCalls === void 0) return { role: "assistant", content: content2 };
3019
3040
  if (!Array.isArray(source.toolCalls)) throw new TypeError(`${at} toolCalls must be an array`);
3020
3041
  const toolCalls = source.toolCalls.map((call, position2) => {
3021
3042
  const entry2 = record7(call);
@@ -3030,7 +3051,7 @@ function modelHistoryMessages(value) {
3030
3051
  unanswered.add(entry2.id);
3031
3052
  return { id: entry2.id, name: entry2.name, args: entry2.args };
3032
3053
  });
3033
- return { role: "assistant", content: source.content, ...toolCalls.length ? { toolCalls } : {} };
3054
+ return { role: "assistant", content: content2, ...toolCalls.length ? { toolCalls } : {} };
3034
3055
  });
3035
3056
  const open = unanswered.values().next();
3036
3057
  if (!open.done) throw new TypeError(`model history Tool call ${open.value} has no tool message answering it`);
@@ -3052,14 +3073,50 @@ function turnMessages(args) {
3052
3073
  function modelMessages(args) {
3053
3074
  return turnMessages(args).messages;
3054
3075
  }
3076
+ var InlineModelFile = class {
3077
+ constructor(ref, prefix) {
3078
+ this.ref = ref;
3079
+ this.prefix = prefix;
3080
+ }
3081
+ ref;
3082
+ prefix;
3083
+ toJSON() {
3084
+ throw new TypeError("a request with inline files is sent as modelProtocolBody segments");
3085
+ }
3086
+ };
3087
+ function resolvedFile(part, files) {
3088
+ const file = files?.get(part.ref);
3089
+ if (!file) throw new TypeError(`model file ${part.ref} is not resolved for this request`);
3090
+ return file;
3091
+ }
3092
+ function fileLabel(part) {
3093
+ return part.name ? `The file ${part.name}` : "The file";
3094
+ }
3095
+ function imageFile(part) {
3096
+ return part.mediaType.toLowerCase().startsWith("image/");
3097
+ }
3098
+ function pdfFile(part) {
3099
+ return part.mediaType.toLowerCase() === "application/pdf";
3100
+ }
3055
3101
  function anthropicBlocks(content2) {
3056
3102
  return typeof content2 !== "string" ? content2 : content2 ? [{ type: "text", text: content2 }] : [];
3057
3103
  }
3058
- function anthropicMessage(message2) {
3104
+ function anthropicContent(content2, files) {
3105
+ if (typeof content2 === "string") return content2;
3106
+ return content2.map((part) => {
3107
+ if (part.type === "text") return { type: "text", text: part.text };
3108
+ const file = resolvedFile(part, files);
3109
+ if (file.kind === "refused") return { type: "text", text: file.reason };
3110
+ const type = imageFile(part) ? "image" : pdfFile(part) ? "document" : null;
3111
+ if (type === null) return { type: "text", text: `${fileLabel(part)} is ${part.mediaType}, which this model is not shown.` };
3112
+ return { type, source: file.kind === "provider" ? { type: "file", file_id: file.id } : { type: "base64", media_type: part.mediaType, data: new InlineModelFile(part.ref, "") } };
3113
+ });
3114
+ }
3115
+ function anthropicMessage(message2, files) {
3059
3116
  if (message2.role === "tool") return { role: "user", content: [{
3060
3117
  type: "tool_result",
3061
3118
  tool_use_id: message2.toolCallId,
3062
- content: message2.content,
3119
+ content: anthropicContent(message2.content, files),
3063
3120
  ...message2.isError ? { is_error: true } : {}
3064
3121
  }] };
3065
3122
  if (message2.role === "assistant" && message2.toolCalls) return { role: "assistant", content: [
@@ -3069,7 +3126,7 @@ function anthropicMessage(message2) {
3069
3126
  return { type: "tool_use", id: call.id, name: call.name, input: record7(args) ?? { value: args } };
3070
3127
  })
3071
3128
  ] };
3072
- return { role: message2.role, content: message2.content };
3129
+ return { role: message2.role, content: anthropicContent(message2.content, files) };
3073
3130
  }
3074
3131
  function alternating(messages) {
3075
3132
  const merged = [];
@@ -3083,11 +3140,21 @@ ${message2.content}`;
3083
3140
  }
3084
3141
  return merged;
3085
3142
  }
3143
+ function openAiPart(part, files) {
3144
+ if (part.type === "text") return { type: "text", text: part.text };
3145
+ if (!files) return { ...part };
3146
+ const file = resolvedFile(part, files);
3147
+ if (file.kind === "refused") return { type: "text", text: file.reason };
3148
+ if (file.kind === "provider") return { type: "file", file: { file_id: file.id } };
3149
+ const data = new InlineModelFile(part.ref, `data:${part.mediaType};base64,`);
3150
+ return imageFile(part) ? { type: "image_url", image_url: { url: data } } : { type: "file", file: { filename: part.name ?? "file", file_data: data } };
3151
+ }
3086
3152
  function openAiMessage(message2, options = {}) {
3153
+ const content2 = (value) => typeof value === "string" ? value : value.map((part) => openAiPart(part, options.files));
3087
3154
  if (message2.role === "tool") return {
3088
3155
  role: "tool",
3089
3156
  tool_call_id: message2.toolCallId,
3090
- content: message2.content,
3157
+ content: content2(message2.content),
3091
3158
  ...options.toolErrorName && message2.isError ? { name: "tool_error" } : {}
3092
3159
  };
3093
3160
  if (message2.role === "assistant" && message2.toolCalls) return {
@@ -3099,10 +3166,29 @@ function openAiMessage(message2, options = {}) {
3099
3166
  function: { name: call.name, arguments: canonicalJson(call.args) }
3100
3167
  }))
3101
3168
  };
3102
- return { role: message2.role, content: message2.content };
3169
+ return { role: message2.role, content: content2(message2.content) };
3170
+ }
3171
+ function openAiMessages(messages, options, mark) {
3172
+ const openai = [];
3173
+ let carried = [];
3174
+ const release = () => {
3175
+ if (carried.length) openai.push({ role: "user", content: carried.map((part) => openAiPart(part, options.files)) });
3176
+ carried = [];
3177
+ };
3178
+ messages.forEach((message2, index) => {
3179
+ if (message2.role !== "tool") release();
3180
+ if (message2.role === "tool" && typeof message2.content !== "string") {
3181
+ carried.push(...message2.content.filter((part) => part.type === "file"));
3182
+ const text2 = message2.content.flatMap((part) => part.type === "text" ? [part.text] : []).join("\n");
3183
+ openai.push(mark(openAiMessage({ ...message2, content: text2 }, options), index));
3184
+ } else openai.push(mark(openAiMessage(message2, options), index));
3185
+ });
3186
+ release();
3187
+ return openai;
3103
3188
  }
3104
3189
  function modelProtocolRequest(protocol, model, maxOutputTokens, temperature, args, options = {}) {
3105
3190
  const { effort } = modelGenerationOptions(args);
3191
+ const files = options.files ?? /* @__PURE__ */ new Map();
3106
3192
  if (args.toolChoice !== void 0 && args.toolChoice !== "auto" && args.toolChoice !== "required") {
3107
3193
  throw new TypeError("model Tool choice is invalid");
3108
3194
  }
@@ -3113,7 +3199,7 @@ function modelProtocolRequest(protocol, model, maxOutputTokens, temperature, arg
3113
3199
  const { messages, lastHistory } = turnMessages(args);
3114
3200
  const breakpoint = cache ? { type: "ephemeral", ...cache.ttl === void 0 ? {} : { ttl: cache.ttl } } : null;
3115
3201
  if (protocol === "anthropic") {
3116
- const anthropic = messages.map(anthropicMessage);
3202
+ const anthropic = messages.map((message2) => anthropicMessage(message2, files));
3117
3203
  const marked = breakpoint && lastHistory !== null ? anthropicBlocks(anthropic[lastHistory].content) : [];
3118
3204
  if (breakpoint && lastHistory !== null && marked.length) {
3119
3205
  anthropic[lastHistory] = { ...anthropic[lastHistory], content: [...marked.slice(0, -1), { ...marked.at(-1), cache_control: breakpoint }] };
@@ -3138,9 +3224,11 @@ function modelProtocolRequest(protocol, model, maxOutputTokens, temperature, arg
3138
3224
  if (protocol === "openai") {
3139
3225
  const marks = options.contentCacheControl === true ? breakpoint : null;
3140
3226
  const marked = (text2) => marks && text2 ? [{ type: "text", text: text2, cache_control: marks }] : text2;
3141
- const openai = messages.map((message2, index) => {
3142
- const entry2 = openAiMessage(message2, options);
3143
- return index === lastHistory && typeof entry2.content === "string" ? { ...entry2, content: marked(entry2.content) } : entry2;
3227
+ const openai = openAiMessages(messages, { ...options, files }, (entry2, index) => {
3228
+ if (index !== lastHistory) return entry2;
3229
+ if (typeof entry2.content === "string") return { ...entry2, content: marked(entry2.content) };
3230
+ const parts = Array.isArray(entry2.content) ? entry2.content : [];
3231
+ return marks && parts.at(-1)?.type === "text" ? { ...entry2, content: [...parts.slice(0, -1), { ...parts.at(-1), cache_control: marks }] } : entry2;
3144
3232
  });
3145
3233
  return {
3146
3234
  model,
@@ -3319,7 +3407,8 @@ function toolCall(value, field2) {
3319
3407
  function chatMessage(value, index) {
3320
3408
  const source = record8(value);
3321
3409
  const field2 = `chat message ${index}`;
3322
- if (!source || typeof source.content !== "string") throw new TypeError(`${field2} is invalid`);
3410
+ if (!source || source.role === "assistant" && typeof source.content !== "string") throw new TypeError(`${field2} is invalid`);
3411
+ if (source.role !== "assistant") modelMessageContent(source.content, field2);
3323
3412
  if (source.role === "user" && exactKeys3(source, ["role", "content"])) return source;
3324
3413
  if (source.role === "tool" && typeof source.toolCallId === "string" && source.toolCallId && (source.isError === void 0 || typeof source.isError === "boolean") && exactKeys3(source, ["role", "toolCallId", "content"], ["isError"])) return source;
3325
3414
  if (source.role === "assistant" && exactKeys3(source, ["role", "content"], ["toolCalls", "reasoning"]) && (source.reasoning === void 0 || typeof source.reasoning === "string") && (source.toolCalls === void 0 || Array.isArray(source.toolCalls))) {
@@ -3390,271 +3479,37 @@ function chatParsed(value) {
3390
3479
  return source;
3391
3480
  }
3392
3481
 
3393
- // packages/sdk/src/container-image.ts
3394
- var REPOSITORY = /^[a-z0-9]+(?:(?:\.|_|__|-+)[a-z0-9]+)*(?:\/[a-z0-9]+(?:(?:\.|_|__|-+)[a-z0-9]+)*)*$/u;
3395
- var TAG = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$/u;
3396
- var DIGEST = /^[a-z][a-z0-9+._-]*:[A-Za-z0-9=_-]+$/u;
3397
- var SHA256 = /^sha256:[a-f0-9]{64}$/u;
3398
- function containerImageReference(value) {
3399
- if (typeof value !== "string" || !value || /[\s?#\\]/u.test(value) || value.includes("://")) throw new TypeError("container image reference is invalid");
3400
- const components = value.split("@");
3401
- if (components.length > 2) throw new TypeError("container image reference is invalid");
3402
- let name = components[0];
3403
- const digest = components[1] ?? null;
3404
- if (digest !== null && (!DIGEST.test(digest) || digest.startsWith("sha256:") && !SHA256.test(digest))) {
3405
- throw new TypeError("container image digest is invalid");
3406
- }
3407
- const separator = name.lastIndexOf(":"), slash = name.lastIndexOf("/");
3408
- const tag = separator > slash ? name.slice(separator + 1) : null;
3409
- if (tag !== null) {
3410
- if (!TAG.test(tag)) throw new TypeError("container image tag is invalid");
3411
- name = name.slice(0, separator);
3412
- }
3413
- const parts = name.split("/"), explicit = parts.length > 1 && (/[.:]/u.test(parts[0]) || parts[0] === "localhost");
3414
- const registryInput = explicit ? parts.shift() : "docker.io";
3415
- let registryUrl;
3416
- try {
3417
- registryUrl = new URL(`https://${registryInput}`);
3418
- } catch {
3419
- throw new TypeError("container image registry is invalid");
3420
- }
3421
- if (registryUrl.username || registryUrl.password || registryUrl.pathname !== "/" || !registryUrl.hostname) throw new TypeError("container image registry is invalid");
3422
- const registry = registryUrl.host === "index.docker.io" ? "docker.io" : registryUrl.host;
3423
- if (registry === "docker.io" && parts.length === 1) parts.unshift("library");
3424
- const repository = parts.join("/");
3425
- if (!REPOSITORY.test(repository)) throw new TypeError("container image repository is invalid");
3426
- const selectedTag = tag ?? (digest === null ? "latest" : null);
3427
- return {
3428
- registry,
3429
- repository,
3430
- tag: selectedTag,
3431
- digest,
3432
- reference: `${registry}/${repository}${digest === null ? `:${selectedTag}` : `@${digest}`}`
3433
- };
3434
- }
3435
- function immutableContainerImageReference(value) {
3436
- const image = containerImageReference(value);
3437
- if (!image.digest || !SHA256.test(image.digest)) throw new TypeError("container image must be resolved to a SHA-256 digest");
3438
- return image;
3439
- }
3440
- function containerImageSource(value) {
3441
- const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
3442
- const platform = source?.platform && typeof source.platform === "object" && !Array.isArray(source.platform) ? source.platform : null;
3443
- const image = typeof source?.reference === "string" ? immutableContainerImageReference(source.reference) : null;
3444
- if (!source || !image || source.digest !== image.digest || typeof source.mediaType !== "string" || !source.mediaType || !Number.isSafeInteger(source.bytes) || Number(source.bytes) < 1 || !platform || typeof platform.os !== "string" || !platform.os || typeof platform.architecture !== "string" || !platform.architecture || platform.variant !== void 0 && (typeof platform.variant !== "string" || !platform.variant)) {
3445
- throw new TypeError("container image source is invalid");
3446
- }
3447
- return structuredClone(source);
3448
- }
3449
- function containerImageSelection(value) {
3450
- const selection = value && typeof value === "object" && !Array.isArray(value) ? value : null;
3451
- const platform = selection?.platform && typeof selection.platform === "object" && !Array.isArray(selection.platform) ? selection.platform : null;
3452
- const image = typeof selection?.reference === "string" ? immutableContainerImageReference(selection.reference) : null;
3453
- if (!selection || !image || !platform || typeof platform.os !== "string" || !platform.os || typeof platform.architecture !== "string" || !platform.architecture || platform.variant !== void 0 && (typeof platform.variant !== "string" || !platform.variant) || Object.keys(selection).some((key) => key !== "reference" && key !== "platform") || Object.keys(platform).some((key) => key !== "os" && key !== "architecture" && key !== "variant")) {
3454
- throw new TypeError("container image selection is invalid");
3455
- }
3456
- return { reference: image.reference, platform: structuredClone(platform) };
3457
- }
3458
- var OCI_MANIFEST = "application/vnd.oci.image.manifest.v1+json";
3459
- var OCI_INDEX = "application/vnd.oci.image.index.v1+json";
3460
- var DOCKER_MANIFEST = "application/vnd.docker.distribution.manifest.v2+json";
3461
- var DOCKER_INDEX = "application/vnd.docker.distribution.manifest.list.v2+json";
3462
- var ACCEPT = [OCI_MANIFEST, OCI_INDEX, DOCKER_MANIFEST, DOCKER_INDEX].join(", ");
3463
- var MANIFEST_BYTES = 4194304;
3464
- function object3(value) {
3465
- return value && typeof value === "object" && !Array.isArray(value) ? value : null;
3466
- }
3467
- async function manifest(image, reference, request, authorization) {
3468
- const response = await request({
3469
- url: `https://${image.registry}/v2/${image.repository}/manifests/${encodeURIComponent(reference)}`,
3470
- method: "GET",
3471
- headers: { accept: ACCEPT, ...authorization ? { authorization } : {} },
3472
- maximumBytes: MANIFEST_BYTES
3473
- });
3474
- if (response.status < 200 || response.status >= 300) throw Object.assign(new Error(`container registry manifest request returned ${response.status}`), { status: response.status });
3475
- if (response.body.byteLength === 0 || response.body.byteLength > MANIFEST_BYTES) throw new TypeError("container registry manifest size is invalid");
3476
- let value;
3477
- try {
3478
- value = object3(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(response.body)));
3479
- } catch {
3480
- value = null;
3481
- }
3482
- if (!value || value.schemaVersion !== 2) throw new TypeError("container registry manifest is invalid");
3483
- const declared = typeof value.mediaType === "string" ? value.mediaType : response.headers["content-type"]?.split(";", 1)[0];
3484
- if (![OCI_MANIFEST, OCI_INDEX, DOCKER_MANIFEST, DOCKER_INDEX].includes(String(declared))) throw new TypeError("container registry manifest media type is unsupported");
3485
- const digest = `sha256:${await sha256Hex(response.body)}`;
3486
- const header = response.headers["docker-content-digest"];
3487
- if (header !== void 0 && header !== digest) throw new TypeError("container registry digest header differs from manifest bytes");
3488
- return { value, mediaType: declared, digest };
3489
- }
3490
- async function resolveContainerImageSource(reference, platform, request, authorization) {
3491
- const image = containerImageReference(reference);
3492
- if (!platform || typeof platform.os !== "string" || !platform.os || typeof platform.architecture !== "string" || !platform.architecture || platform.variant !== void 0 && !platform.variant) throw new TypeError("container image platform is invalid");
3493
- const requested = image.digest ?? image.tag;
3494
- let selected = await manifest(image, requested, request, authorization);
3495
- if (image.digest && selected.digest !== image.digest) throw new TypeError("container image digest does not match its manifest");
3496
- if (selected.mediaType === OCI_INDEX || selected.mediaType === DOCKER_INDEX) {
3497
- if (!Array.isArray(selected.value.manifests)) throw new TypeError("container image index has no manifests");
3498
- const matches = selected.value.manifests.filter((raw) => {
3499
- const item = object3(raw), target = object3(item?.platform);
3500
- return item && target && target.os === platform.os && target.architecture === platform.architecture && (platform.variant === void 0 ? target.variant === void 0 : target.variant === platform.variant);
3501
- }).map((item) => object3(item));
3502
- if (matches.length !== 1 || typeof matches[0].digest !== "string" || !SHA256.test(matches[0].digest)) {
3503
- throw new TypeError("container image index does not contain one exact requested platform");
3504
- }
3505
- selected = await manifest(image, matches[0].digest, request, authorization);
3506
- if (selected.digest !== matches[0].digest) throw new TypeError("container image platform descriptor differs from its manifest");
3507
- }
3508
- if (selected.mediaType !== OCI_MANIFEST && selected.mediaType !== DOCKER_MANIFEST) throw new TypeError("container image did not resolve to an image manifest");
3509
- const config = object3(selected.value.config), layers = selected.value.layers;
3510
- if (!config || !Number.isSafeInteger(config.size) || Number(config.size) < 0 || !Array.isArray(layers) || layers.some((layer) => !object3(layer) || !Number.isSafeInteger(object3(layer).size) || Number(object3(layer).size) < 0)) {
3511
- throw new TypeError("container image manifest descriptors are invalid");
3512
- }
3513
- const bytes = Number(config.size) + layers.reduce((sum, layer) => sum + Number(object3(layer).size), 0);
3514
- return containerImageSource({
3515
- reference: `${image.registry}/${image.repository}@${selected.digest}`,
3516
- digest: selected.digest,
3517
- mediaType: selected.mediaType,
3518
- bytes,
3519
- platform
3520
- });
3521
- }
3522
-
3523
- // packages/sdk/src/sandbox-egress.ts
3524
- function normalizeSandboxConnectionKeys(value) {
3525
- if (!Array.isArray(value)) throw new TypeError("sandbox connection keys must be an array");
3526
- return [...new Set(value.map((key) => scopedBindingKey(key)))].sort();
3527
- }
3528
- var SANDBOX_EGRESS_LIMITS = { rules: 64, labels: 16, labelValueLength: 256 };
3529
- var HEADER2 = /^[a-z0-9!#$%&'*+.^_`|~-]+$/u;
3530
- var RESERVED_HEADERS2 = /* @__PURE__ */ new Set([
3531
- "connection",
3532
- "content-length",
3533
- "host",
3534
- "keep-alive",
3535
- "proxy-connection",
3536
- "te",
3537
- "trailer",
3538
- "transfer-encoding",
3539
- "upgrade"
3540
- ]);
3541
- var LABEL = /^[a-z0-9][a-z0-9._-]{0,62}$/u;
3542
- function object4(value) {
3543
- return value && typeof value === "object" && !Array.isArray(value) ? value : null;
3544
- }
3545
- function sandboxEgressHostMatches(pattern, hostname) {
3546
- const host2 = hostname.toLowerCase().replace(/\.$/u, "");
3547
- return pattern.startsWith("*.") ? host2 === pattern.slice(2) || host2.endsWith(pattern.slice(1)) : host2 === pattern;
3548
- }
3549
- function host(value) {
3550
- const [normalized] = normalizeSandboxDomains([value]);
3551
- return normalized;
3552
- }
3553
- function presentation(present) {
3554
- const header = present.header === void 0 ? "authorization" : present.header;
3555
- if (typeof header !== "string" || !HEADER2.test(header.toLowerCase()) || RESERVED_HEADERS2.has(header.toLowerCase()) || header.toLowerCase().startsWith("x-constal-")) throw new TypeError("Credential destination header is invalid");
3556
- if (present.value !== void 0 && present.basic !== void 0) throw new TypeError("Credential destination takes value or basic, not both");
3557
- if (present.value !== void 0 && (typeof present.value !== "string" || /[\r\n\0]/u.test(present.value) || present.value.split("{value}").length !== 2)) throw new TypeError("Credential destination value must contain {value} exactly once");
3558
- const basic = present.basic === void 0 ? void 0 : object4(present.basic);
3559
- if (present.basic !== void 0 && (!basic || Object.keys(basic).some((key) => key !== "username") || basic.username !== void 0 && (typeof basic.username !== "string" || !basic.username || /[:\r\n\0]/u.test(basic.username)))) throw new TypeError("Credential destination basic auth is invalid");
3560
- if (present.field !== void 0 && (typeof present.field !== "string" || !present.field.startsWith("/") || SPACE_OR_CONTROL.test(present.field) || /~(?![01])/u.test(present.field))) throw new TypeError("Credential destination field must be a JSON Pointer");
3561
- if (present.code !== void 0 && present.code !== "totp") throw new TypeError("Credential destination code must be totp");
3562
- return {
3563
- header: header.toLowerCase(),
3564
- ...basic ? { basic: basic.username === void 0 ? {} : { username: basic.username } } : { value: present.value ?? "Bearer {value}" },
3565
- ...present.field !== void 0 ? { field: present.field } : {},
3566
- ...present.code !== void 0 ? { code: "totp" } : {}
3567
- };
3568
- }
3569
- var SPACE_OR_CONTROL = /[\s\u0000-\u001f\u007f]/u;
3570
- function path(raw) {
3571
- if (typeof raw !== "string" || !raw.startsWith("/") || /[%?#\\]/u.test(raw) || SPACE_OR_CONTROL.test(raw)) {
3572
- throw new TypeError("Credential destination path is invalid");
3573
- }
3574
- const prefix = raw.length > 1 && raw.endsWith("/") ? raw.slice(0, -1) : raw;
3575
- if (prefix.slice(1).split("/").some((segment) => segment === "" || segment === "." || segment === "..")) {
3576
- throw new TypeError("Credential destination path is invalid");
3577
- }
3578
- return prefix;
3579
- }
3580
- function normalizeCredentialDestinations(value) {
3581
- if (value === void 0) return [];
3582
- if (!Array.isArray(value)) throw new TypeError("Credential destinations are invalid");
3583
- const destinations = value.map((raw) => {
3584
- const destination = object4(raw);
3585
- const present = object4(destination?.present);
3586
- if (!destination || Object.keys(destination).some((key) => !["origin", "path", "present"].includes(key)) || typeof destination.origin !== "string" || !destination.origin.startsWith("https://") || !present || Object.keys(present).some((key) => !["header", "value", "basic", "field", "code"].includes(key))) {
3587
- throw new TypeError("Credential destination is invalid");
3588
- }
3589
- return {
3590
- origin: `https://${host(destination.origin.slice("https://".length))}`,
3591
- ...destination.path !== void 0 ? { path: path(destination.path) } : {},
3592
- present: presentation(present)
3593
- };
3594
- });
3595
- const headers = destinations.map((destination) => JSON.stringify([destination.origin, destination.path ?? null, destination.present.header]));
3596
- if (new Set(headers).size !== headers.length) throw new TypeError("Credential destinations of one origin and path name a header twice");
3597
- return destinations;
3598
- }
3599
- function normalizeSandboxEgressPolicy(value) {
3600
- const input = object4(value);
3601
- if (!input || Object.keys(input).some((key) => key !== "rules" && key !== "default") || !Array.isArray(input.rules) || input.rules.length > SANDBOX_EGRESS_LIMITS.rules || input.default !== void 0 && input.default !== "allow" && input.default !== "deny") {
3602
- throw new TypeError("sandbox egress policy is invalid");
3603
- }
3604
- const rules = input.rules.map((raw) => {
3605
- const rule = object4(raw);
3606
- if (!rule || Object.keys(rule).some((key) => key !== "action" && key !== "host") || rule.action !== "allow" && rule.action !== "deny") {
3607
- throw new TypeError("sandbox egress rule is invalid");
3608
- }
3609
- return { action: rule.action, host: host(rule.host) };
3610
- });
3611
- return { rules, default: input.default === "allow" ? "allow" : "deny" };
3612
- }
3613
- function sandboxEgressDecision(policy2, hostname) {
3614
- if (!policy2) return { allowed: true, rule: "pool" };
3615
- const index = policy2.rules.findIndex((rule) => sandboxEgressHostMatches(rule.host, hostname));
3616
- if (index < 0) return { allowed: policy2.default === "allow", rule: "sandbox:default" };
3617
- return { allowed: policy2.rules[index].action === "allow", rule: `sandbox:${index}` };
3618
- }
3619
- function normalizeSandboxLabels(value) {
3620
- if (value === void 0) return {};
3621
- const input = object4(value);
3622
- if (!input || Object.keys(input).length > SANDBOX_EGRESS_LIMITS.labels) throw new TypeError("sandbox labels are invalid");
3623
- const labels = {};
3624
- for (const [key, label] of Object.entries(input).sort(([left], [right]) => left.localeCompare(right))) {
3625
- if (!LABEL.test(key) || typeof label !== "string" || label.length > SANDBOX_EGRESS_LIMITS.labelValueLength || /[\u0000-\u001f\u007f]/u.test(label)) throw new TypeError("sandbox label is invalid");
3626
- labels[key] = label;
3627
- }
3628
- return labels;
3629
- }
3630
-
3631
3482
  // packages/sdk/src/sandbox-pool.ts
3632
- var WORKSPACE_ROOT = "/workspace";
3633
- function absoluteSandboxPath(value) {
3634
- const segments = [];
3635
- for (const segment of value.split("/")) {
3636
- if (!segment || segment === ".") continue;
3637
- if (segment === "..") segments.pop();
3638
- else segments.push(segment);
3639
- }
3640
- return `/${segments.join("/")}`;
3641
- }
3642
- function normalizeSandboxWorkspacePath(path2, cwd = WORKSPACE_ROOT) {
3643
- if (typeof path2 !== "string" || !path2 || typeof cwd !== "string" || !cwd || /[\u0000-\u001f\u007f]/u.test(path2) || /[\u0000-\u001f\u007f]/u.test(cwd)) {
3644
- throw new TypeError("sandbox workspace path is invalid");
3645
- }
3646
- const base = absoluteSandboxPath(cwd.startsWith("/") ? cwd : `${WORKSPACE_ROOT}/${cwd}`);
3647
- if (base !== WORKSPACE_ROOT && !base.startsWith(`${WORKSPACE_ROOT}/`)) {
3648
- throw new TypeError("sandbox working directory is outside /workspace");
3649
- }
3650
- const normalized = absoluteSandboxPath(path2.startsWith("/") ? path2 : `${base}/${path2}`);
3651
- if (normalized !== WORKSPACE_ROOT && !normalized.startsWith(`${WORKSPACE_ROOT}/`)) {
3652
- throw new TypeError("sandbox path is outside /workspace");
3653
- }
3654
- return normalized;
3483
+ var SANDBOX_POOL_OPERATIONS = [
3484
+ "create",
3485
+ "get",
3486
+ "start",
3487
+ "stop",
3488
+ "delete",
3489
+ "update",
3490
+ "exec",
3491
+ "execution",
3492
+ "cancel",
3493
+ "readFile",
3494
+ "writeFile",
3495
+ "deleteFile",
3496
+ "snapshot",
3497
+ "deleteSnapshot"
3498
+ ];
3499
+ var SANDBOX_PROVIDER_UNAVAILABLE = "ProviderUnavailable";
3500
+ var SANDBOX_PROVIDER_FAILURE_CLASSES = ["capacity", "rate_limited", "quota", "region", "outage"];
3501
+ function isFailureClass(value) {
3502
+ return typeof value === "string" && SANDBOX_PROVIDER_FAILURE_CLASSES.includes(value);
3503
+ }
3504
+ function sandboxProviderUnavailable(value) {
3505
+ const source = value && typeof value === "object" ? value : null;
3506
+ if (!source || source.code !== SANDBOX_PROVIDER_UNAVAILABLE && source.name !== SANDBOX_PROVIDER_UNAVAILABLE) return null;
3507
+ const cause = source.cause && typeof source.cause === "object" ? source.cause : null;
3508
+ const reason = isFailureClass(source.reason) ? source.reason : isFailureClass(cause?.code) ? cause.code : "outage";
3509
+ const retryAfterMs = typeof source.retryAfterMs === "number" && Number.isSafeInteger(source.retryAfterMs) && source.retryAfterMs >= 0 ? source.retryAfterMs : 0;
3510
+ const message2 = typeof source.message === "string" ? source.message : `sandbox provider is unavailable (${reason})`;
3511
+ return { code: SANDBOX_PROVIDER_UNAVAILABLE, reason, retryAfterMs, message: message2 };
3655
3512
  }
3656
- var SANDBOX_PROCESS_IO_OPERATIONS = ["process.status", "process.read", "process.write", "process.close"];
3657
- var SANDBOX_PROCESS_OPERATIONS = ["process.resolve", ...SANDBOX_PROCESS_IO_OPERATIONS, "process.stop"];
3658
3513
 
3659
3514
  // packages/sdk/src/training.ts
3660
3515
  var HASH4 = /^[a-f0-9]{64}$/u;
@@ -4218,6 +4073,114 @@ var MCP_CLIENT_CAPABILITY = {
4218
4073
  hash: "a694af71191432e75980dc73962d9239dc8ea324aff084f183a2f45603bd2267"
4219
4074
  };
4220
4075
 
4076
+ // packages/sdk/src/sandbox-egress.ts
4077
+ function normalizeSandboxConnectionKeys(value) {
4078
+ if (!Array.isArray(value)) throw new TypeError("sandbox connection keys must be an array");
4079
+ return [...new Set(value.map((key) => scopedBindingKey(key)))].sort();
4080
+ }
4081
+ var SANDBOX_EGRESS_LIMITS = { rules: 64, labels: 16, labelValueLength: 256 };
4082
+ var HEADER2 = /^[a-z0-9!#$%&'*+.^_`|~-]+$/u;
4083
+ var RESERVED_HEADERS2 = /* @__PURE__ */ new Set([
4084
+ "connection",
4085
+ "content-length",
4086
+ "host",
4087
+ "keep-alive",
4088
+ "proxy-connection",
4089
+ "te",
4090
+ "trailer",
4091
+ "transfer-encoding",
4092
+ "upgrade"
4093
+ ]);
4094
+ var LABEL = /^[a-z0-9][a-z0-9._-]{0,62}$/u;
4095
+ function object3(value) {
4096
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
4097
+ }
4098
+ function sandboxEgressHostMatches(pattern, hostname) {
4099
+ const host2 = hostname.toLowerCase().replace(/\.$/u, "");
4100
+ return pattern.startsWith("*.") ? host2 === pattern.slice(2) || host2.endsWith(pattern.slice(1)) : host2 === pattern;
4101
+ }
4102
+ function host(value) {
4103
+ const [normalized] = normalizeSandboxDomains([value]);
4104
+ return normalized;
4105
+ }
4106
+ function presentation(present) {
4107
+ const header = present.header === void 0 ? "authorization" : present.header;
4108
+ if (typeof header !== "string" || !HEADER2.test(header.toLowerCase()) || RESERVED_HEADERS2.has(header.toLowerCase()) || header.toLowerCase().startsWith("x-constal-")) throw new TypeError("Credential destination header is invalid");
4109
+ if (present.value !== void 0 && present.basic !== void 0) throw new TypeError("Credential destination takes value or basic, not both");
4110
+ if (present.value !== void 0 && (typeof present.value !== "string" || /[\r\n\0]/u.test(present.value) || present.value.split("{value}").length !== 2)) throw new TypeError("Credential destination value must contain {value} exactly once");
4111
+ const basic = present.basic === void 0 ? void 0 : object3(present.basic);
4112
+ if (present.basic !== void 0 && (!basic || Object.keys(basic).some((key) => key !== "username") || basic.username !== void 0 && (typeof basic.username !== "string" || !basic.username || /[:\r\n\0]/u.test(basic.username)))) throw new TypeError("Credential destination basic auth is invalid");
4113
+ if (present.field !== void 0 && (typeof present.field !== "string" || !present.field.startsWith("/") || SPACE_OR_CONTROL.test(present.field) || /~(?![01])/u.test(present.field))) throw new TypeError("Credential destination field must be a JSON Pointer");
4114
+ if (present.code !== void 0 && present.code !== "totp") throw new TypeError("Credential destination code must be totp");
4115
+ return {
4116
+ header: header.toLowerCase(),
4117
+ ...basic ? { basic: basic.username === void 0 ? {} : { username: basic.username } } : { value: present.value ?? "Bearer {value}" },
4118
+ ...present.field !== void 0 ? { field: present.field } : {},
4119
+ ...present.code !== void 0 ? { code: "totp" } : {}
4120
+ };
4121
+ }
4122
+ var SPACE_OR_CONTROL = /[\s\u0000-\u001f\u007f]/u;
4123
+ function path(raw) {
4124
+ if (typeof raw !== "string" || !raw.startsWith("/") || /[%?#\\]/u.test(raw) || SPACE_OR_CONTROL.test(raw)) {
4125
+ throw new TypeError("Credential destination path is invalid");
4126
+ }
4127
+ const prefix = raw.length > 1 && raw.endsWith("/") ? raw.slice(0, -1) : raw;
4128
+ if (prefix.slice(1).split("/").some((segment) => segment === "" || segment === "." || segment === "..")) {
4129
+ throw new TypeError("Credential destination path is invalid");
4130
+ }
4131
+ return prefix;
4132
+ }
4133
+ function normalizeCredentialDestinations(value) {
4134
+ if (value === void 0) return [];
4135
+ if (!Array.isArray(value)) throw new TypeError("Credential destinations are invalid");
4136
+ const destinations = value.map((raw) => {
4137
+ const destination = object3(raw);
4138
+ const present = object3(destination?.present);
4139
+ if (!destination || Object.keys(destination).some((key) => !["origin", "path", "present"].includes(key)) || typeof destination.origin !== "string" || !destination.origin.startsWith("https://") || !present || Object.keys(present).some((key) => !["header", "value", "basic", "field", "code"].includes(key))) {
4140
+ throw new TypeError("Credential destination is invalid");
4141
+ }
4142
+ return {
4143
+ origin: `https://${host(destination.origin.slice("https://".length))}`,
4144
+ ...destination.path !== void 0 ? { path: path(destination.path) } : {},
4145
+ present: presentation(present)
4146
+ };
4147
+ });
4148
+ const headers = destinations.map((destination) => JSON.stringify([destination.origin, destination.path ?? null, destination.present.header]));
4149
+ if (new Set(headers).size !== headers.length) throw new TypeError("Credential destinations of one origin and path name a header twice");
4150
+ return destinations;
4151
+ }
4152
+ function normalizeSandboxEgressPolicy(value) {
4153
+ const input = object3(value);
4154
+ if (!input || Object.keys(input).some((key) => key !== "rules" && key !== "default") || !Array.isArray(input.rules) || input.rules.length > SANDBOX_EGRESS_LIMITS.rules || input.default !== void 0 && input.default !== "allow" && input.default !== "deny") {
4155
+ throw new TypeError("sandbox egress policy is invalid");
4156
+ }
4157
+ const rules = input.rules.map((raw) => {
4158
+ const rule = object3(raw);
4159
+ if (!rule || Object.keys(rule).some((key) => key !== "action" && key !== "host") || rule.action !== "allow" && rule.action !== "deny") {
4160
+ throw new TypeError("sandbox egress rule is invalid");
4161
+ }
4162
+ return { action: rule.action, host: host(rule.host) };
4163
+ });
4164
+ return { rules, default: input.default === "allow" ? "allow" : "deny" };
4165
+ }
4166
+ function sandboxEgressDecision(policy2, hostname) {
4167
+ if (!policy2) return { allowed: true, rule: "pool" };
4168
+ const index = policy2.rules.findIndex((rule) => sandboxEgressHostMatches(rule.host, hostname));
4169
+ if (index < 0) return { allowed: policy2.default === "allow", rule: "sandbox:default" };
4170
+ return { allowed: policy2.rules[index].action === "allow", rule: `sandbox:${index}` };
4171
+ }
4172
+ function normalizeSandboxLabels(value) {
4173
+ if (value === void 0) return {};
4174
+ const input = object3(value);
4175
+ if (!input || Object.keys(input).length > SANDBOX_EGRESS_LIMITS.labels) throw new TypeError("sandbox labels are invalid");
4176
+ const labels = {};
4177
+ for (const [key, label] of Object.entries(input).sort(([left], [right]) => left.localeCompare(right))) {
4178
+ if (!LABEL.test(key) || typeof label !== "string" || label.length > SANDBOX_EGRESS_LIMITS.labelValueLength || /[\u0000-\u001f\u007f]/u.test(label)) throw new TypeError("sandbox label is invalid");
4179
+ labels[key] = label;
4180
+ }
4181
+ return labels;
4182
+ }
4183
+
4221
4184
  // packages/sdk/src/credential-provider.ts
4222
4185
  function assertNonSecretConfigSchema(value, field2 = "config") {
4223
4186
  if (!value || typeof value !== "object" || Array.isArray(value)) return;
@@ -4641,6 +4604,152 @@ function scoreLevel(answer2) {
4641
4604
  return Math.min(Object.keys(answer2.legend).length - 1, Math.max(0, Math.round(answer2.score)));
4642
4605
  }
4643
4606
 
4607
+ // packages/sdk/src/sandbox-door.ts
4608
+ var SANDBOX_DOOR_MAX_WAIT_MS = 25e3;
4609
+ var SANDBOX_DOOR_ERRORS = {
4610
+ Invalid: 400,
4611
+ AccountBalanceExceeded: 402,
4612
+ Forbidden: 403,
4613
+ NotFound: 404,
4614
+ AlreadyExists: 409,
4615
+ Conflict: 409,
4616
+ NotRunning: 409,
4617
+ Unsupported: 422,
4618
+ ProviderError: 502,
4619
+ [SANDBOX_PROVIDER_UNAVAILABLE]: 503,
4620
+ BillingAdmissionUnavailable: 503
4621
+ };
4622
+
4623
+ // packages/sdk/src/container-image.ts
4624
+ var REPOSITORY = /^[a-z0-9]+(?:(?:\.|_|__|-+)[a-z0-9]+)*(?:\/[a-z0-9]+(?:(?:\.|_|__|-+)[a-z0-9]+)*)*$/u;
4625
+ var TAG = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$/u;
4626
+ var DIGEST = /^[a-z][a-z0-9+._-]*:[A-Za-z0-9=_-]+$/u;
4627
+ var SHA256 = /^sha256:[a-f0-9]{64}$/u;
4628
+ function containerImageReference(value) {
4629
+ if (typeof value !== "string" || !value || /[\s?#\\]/u.test(value) || value.includes("://")) throw new TypeError("container image reference is invalid");
4630
+ const components = value.split("@");
4631
+ if (components.length > 2) throw new TypeError("container image reference is invalid");
4632
+ let name = components[0];
4633
+ const digest = components[1] ?? null;
4634
+ if (digest !== null && (!DIGEST.test(digest) || digest.startsWith("sha256:") && !SHA256.test(digest))) {
4635
+ throw new TypeError("container image digest is invalid");
4636
+ }
4637
+ const separator = name.lastIndexOf(":"), slash = name.lastIndexOf("/");
4638
+ const tag = separator > slash ? name.slice(separator + 1) : null;
4639
+ if (tag !== null) {
4640
+ if (!TAG.test(tag)) throw new TypeError("container image tag is invalid");
4641
+ name = name.slice(0, separator);
4642
+ }
4643
+ const parts = name.split("/"), explicit = parts.length > 1 && (/[.:]/u.test(parts[0]) || parts[0] === "localhost");
4644
+ const registryInput = explicit ? parts.shift() : "docker.io";
4645
+ let registryUrl;
4646
+ try {
4647
+ registryUrl = new URL(`https://${registryInput}`);
4648
+ } catch {
4649
+ throw new TypeError("container image registry is invalid");
4650
+ }
4651
+ if (registryUrl.username || registryUrl.password || registryUrl.pathname !== "/" || !registryUrl.hostname) throw new TypeError("container image registry is invalid");
4652
+ const registry = registryUrl.host === "index.docker.io" ? "docker.io" : registryUrl.host;
4653
+ if (registry === "docker.io" && parts.length === 1) parts.unshift("library");
4654
+ const repository = parts.join("/");
4655
+ if (!REPOSITORY.test(repository)) throw new TypeError("container image repository is invalid");
4656
+ const selectedTag = tag ?? (digest === null ? "latest" : null);
4657
+ return {
4658
+ registry,
4659
+ repository,
4660
+ tag: selectedTag,
4661
+ digest,
4662
+ reference: `${registry}/${repository}${digest === null ? `:${selectedTag}` : `@${digest}`}`
4663
+ };
4664
+ }
4665
+ function immutableContainerImageReference(value) {
4666
+ const image = containerImageReference(value);
4667
+ if (!image.digest || !SHA256.test(image.digest)) throw new TypeError("container image must be resolved to a SHA-256 digest");
4668
+ return image;
4669
+ }
4670
+ function containerImageSource(value) {
4671
+ const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
4672
+ const platform = source?.platform && typeof source.platform === "object" && !Array.isArray(source.platform) ? source.platform : null;
4673
+ const image = typeof source?.reference === "string" ? immutableContainerImageReference(source.reference) : null;
4674
+ if (!source || !image || source.digest !== image.digest || typeof source.mediaType !== "string" || !source.mediaType || !Number.isSafeInteger(source.bytes) || Number(source.bytes) < 1 || !platform || typeof platform.os !== "string" || !platform.os || typeof platform.architecture !== "string" || !platform.architecture || platform.variant !== void 0 && (typeof platform.variant !== "string" || !platform.variant)) {
4675
+ throw new TypeError("container image source is invalid");
4676
+ }
4677
+ return structuredClone(source);
4678
+ }
4679
+ function containerImageSelection(value) {
4680
+ const selection = value && typeof value === "object" && !Array.isArray(value) ? value : null;
4681
+ const platform = selection?.platform && typeof selection.platform === "object" && !Array.isArray(selection.platform) ? selection.platform : null;
4682
+ const image = typeof selection?.reference === "string" ? immutableContainerImageReference(selection.reference) : null;
4683
+ if (!selection || !image || !platform || typeof platform.os !== "string" || !platform.os || typeof platform.architecture !== "string" || !platform.architecture || platform.variant !== void 0 && (typeof platform.variant !== "string" || !platform.variant) || Object.keys(selection).some((key) => key !== "reference" && key !== "platform") || Object.keys(platform).some((key) => key !== "os" && key !== "architecture" && key !== "variant")) {
4684
+ throw new TypeError("container image selection is invalid");
4685
+ }
4686
+ return { reference: image.reference, platform: structuredClone(platform) };
4687
+ }
4688
+ var OCI_MANIFEST = "application/vnd.oci.image.manifest.v1+json";
4689
+ var OCI_INDEX = "application/vnd.oci.image.index.v1+json";
4690
+ var DOCKER_MANIFEST = "application/vnd.docker.distribution.manifest.v2+json";
4691
+ var DOCKER_INDEX = "application/vnd.docker.distribution.manifest.list.v2+json";
4692
+ var ACCEPT = [OCI_MANIFEST, OCI_INDEX, DOCKER_MANIFEST, DOCKER_INDEX].join(", ");
4693
+ var MANIFEST_BYTES = 4194304;
4694
+ function object4(value) {
4695
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
4696
+ }
4697
+ async function manifest(image, reference, request, authorization) {
4698
+ const response = await request({
4699
+ url: `https://${image.registry}/v2/${image.repository}/manifests/${encodeURIComponent(reference)}`,
4700
+ method: "GET",
4701
+ headers: { accept: ACCEPT, ...authorization ? { authorization } : {} },
4702
+ maximumBytes: MANIFEST_BYTES
4703
+ });
4704
+ if (response.status < 200 || response.status >= 300) throw Object.assign(new Error(`container registry manifest request returned ${response.status}`), { status: response.status });
4705
+ if (response.body.byteLength === 0 || response.body.byteLength > MANIFEST_BYTES) throw new TypeError("container registry manifest size is invalid");
4706
+ let value;
4707
+ try {
4708
+ value = object4(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(response.body)));
4709
+ } catch {
4710
+ value = null;
4711
+ }
4712
+ if (!value || value.schemaVersion !== 2) throw new TypeError("container registry manifest is invalid");
4713
+ const declared = typeof value.mediaType === "string" ? value.mediaType : response.headers["content-type"]?.split(";", 1)[0];
4714
+ if (![OCI_MANIFEST, OCI_INDEX, DOCKER_MANIFEST, DOCKER_INDEX].includes(String(declared))) throw new TypeError("container registry manifest media type is unsupported");
4715
+ const digest = `sha256:${await sha256Hex(response.body)}`;
4716
+ const header = response.headers["docker-content-digest"];
4717
+ if (header !== void 0 && header !== digest) throw new TypeError("container registry digest header differs from manifest bytes");
4718
+ return { value, mediaType: declared, digest };
4719
+ }
4720
+ async function resolveContainerImageSource(reference, platform, request, authorization) {
4721
+ const image = containerImageReference(reference);
4722
+ if (!platform || typeof platform.os !== "string" || !platform.os || typeof platform.architecture !== "string" || !platform.architecture || platform.variant !== void 0 && !platform.variant) throw new TypeError("container image platform is invalid");
4723
+ const requested = image.digest ?? image.tag;
4724
+ let selected = await manifest(image, requested, request, authorization);
4725
+ if (image.digest && selected.digest !== image.digest) throw new TypeError("container image digest does not match its manifest");
4726
+ if (selected.mediaType === OCI_INDEX || selected.mediaType === DOCKER_INDEX) {
4727
+ if (!Array.isArray(selected.value.manifests)) throw new TypeError("container image index has no manifests");
4728
+ const matches = selected.value.manifests.filter((raw) => {
4729
+ const item = object4(raw), target = object4(item?.platform);
4730
+ return item && target && target.os === platform.os && target.architecture === platform.architecture && (platform.variant === void 0 ? target.variant === void 0 : target.variant === platform.variant);
4731
+ }).map((item) => object4(item));
4732
+ if (matches.length !== 1 || typeof matches[0].digest !== "string" || !SHA256.test(matches[0].digest)) {
4733
+ throw new TypeError("container image index does not contain one exact requested platform");
4734
+ }
4735
+ selected = await manifest(image, matches[0].digest, request, authorization);
4736
+ if (selected.digest !== matches[0].digest) throw new TypeError("container image platform descriptor differs from its manifest");
4737
+ }
4738
+ if (selected.mediaType !== OCI_MANIFEST && selected.mediaType !== DOCKER_MANIFEST) throw new TypeError("container image did not resolve to an image manifest");
4739
+ const config = object4(selected.value.config), layers = selected.value.layers;
4740
+ if (!config || !Number.isSafeInteger(config.size) || Number(config.size) < 0 || !Array.isArray(layers) || layers.some((layer) => !object4(layer) || !Number.isSafeInteger(object4(layer).size) || Number(object4(layer).size) < 0)) {
4741
+ throw new TypeError("container image manifest descriptors are invalid");
4742
+ }
4743
+ const bytes = Number(config.size) + layers.reduce((sum, layer) => sum + Number(object4(layer).size), 0);
4744
+ return containerImageSource({
4745
+ reference: `${image.registry}/${image.repository}@${selected.digest}`,
4746
+ digest: selected.digest,
4747
+ mediaType: selected.mediaType,
4748
+ bytes,
4749
+ platform
4750
+ });
4751
+ }
4752
+
4644
4753
  // packages/sdk/src/mcp.ts
4645
4754
  var MCP_PROTOCOL_VERSION = "2025-06-18";
4646
4755
  function record11(value) {
@@ -5252,7 +5361,11 @@ export {
5252
5361
  ResourceInvalid,
5253
5362
  ResourceUnbound,
5254
5363
  RollbackTargetInvalid,
5364
+ SANDBOX_DOOR_MAX_WAIT_MS,
5255
5365
  SANDBOX_EGRESS_LIMITS,
5366
+ SANDBOX_POOL_OPERATIONS,
5367
+ SANDBOX_PROVIDER_FAILURE_CLASSES,
5368
+ SANDBOX_PROVIDER_UNAVAILABLE,
5256
5369
  SessionDeleted,
5257
5370
  SpawnCardinality,
5258
5371
  SwallowedYield,
@@ -5361,7 +5474,6 @@ export {
5361
5474
  normalizeSandboxEgressPolicy,
5362
5475
  normalizeSandboxLabels,
5363
5476
  normalizeSandboxNetworkPolicy,
5364
- normalizeSandboxWorkspacePath,
5365
5477
  noulDecision,
5366
5478
  opTool,
5367
5479
  opTools,
@@ -5388,6 +5500,7 @@ export {
5388
5500
  sandboxEgressDecision,
5389
5501
  sandboxEgressHostMatches,
5390
5502
  sandboxLimit,
5503
+ sandboxProviderUnavailable,
5391
5504
  scopedBindingKey,
5392
5505
  scopedCredentialRef,
5393
5506
  scopedResourceRef,