@constal/sdk 4.4.0 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -96,29 +96,6 @@ configuration, and control-plane operations. Returned objects are independent
96
96
  copies. A configured operation is not a promise of authorization: Policy still
97
97
  applies when it is invoked.
98
98
 
99
- ## Agent delivery
100
-
101
- Bind another Agent Resource to the caller, then address that bound Agent by CRN:
102
-
103
- ```ts
104
- const peer = ctx.resources.reviewer;
105
- const receipt = await ctx.send(peer, { request: "Review this change" },
106
- { session: "review-123" });
107
-
108
- const delivery = await ctx.send<{ verdict: string }>(peer,
109
- { request: "Review this change" }, { completion: "run-result" });
110
- const answer = await delivery.result;
111
- ```
112
-
113
- Each delivery queues a distinct Run in the target Agent's Session. Receipt mode
114
- requires a Session and acknowledges the durable enqueue; result mode may omit
115
- the Session to create a fresh one and returns a cancellable Handle for the target
116
- Run's result. The target executes under the initiating principal's authority.
117
- Policy evaluates `agent:invoke` on the exact bound target for each new send, and
118
- the platform rechecks that authority when the target accepts the message.
119
- Session and Run reads remain separate Policy actions. `ctx.commit` continues to
120
- address the caller's own ledger.
121
-
122
99
  For model-selected operations, add the optional `resourceTools` to the Agent's
123
100
  ordinary Tool catalog:
124
101
 
@@ -181,6 +158,56 @@ array. Declare its normal `needs` and `maxEffect` when loading uses Resources.
181
158
  source when supplied, and content hash. These are ordinary authorized Tool calls.
182
159
  Skill instructions do not grant additional authority.
183
160
 
161
+ ## Ledger addresses and delivery
162
+
163
+ A ledger address names a Session's main ledger,
164
+ `agent:<agent>/session:<session>`, or a spawned loop's,
165
+ `agent:<agent>/session:<session>/spawn:<handle>`, within the Run's tenant,
166
+ namespace, and Customer. `ctx.run.ledger` is the current Run's own address (null
167
+ for an operator branch, an eval fork, a compensation, or a loop one of them
168
+ spawned, and for a Run of an existing Session whose id has a `/` or a control
169
+ character or is longer than 256 characters, which ingress no longer accepts for
170
+ a new one), and the Handle
171
+ `ctx.spawn` returns names its loop in `ledger`, the same across the spawn's
172
+ retries. A Run omits `of` and `to` for its own ledger; `session:<id>` is
173
+ refused.
174
+
175
+ ```ts
176
+ const notes = await ctx.ledger.view("notes", { of: "agent:memory/session:team" });
177
+ await ctx.commit({ text: "Fix the failing build", data: { issue: 7 } },
178
+ { to: "agent:task/session:fix-7", deliver: "live", delegate: true });
179
+ const investigation = ctx.spawn(investigate, { issue: 7 });
180
+ await ctx.commit("Also check the flaky test", { to: investigation.ledger, deliver: "live" });
181
+ const woken = ctx.await("next", { afterRun: "delivery", timeout: 3_600_000 });
182
+ ```
183
+
184
+ `ctx.ledger.view` reads another ledger at its head. `ctx.commit` with `to` is
185
+ the one way agent code delivers to another ledger: `deliver: "queue"`, the
186
+ default, queues the item; `"live"` steers the addressed Run or starts one. A
187
+ live item is a non-empty string or `{ text, data? }`, and a delivery to a spawn
188
+ is live. `delegate: true` makes this Session the owner of the receiving Session,
189
+ which takes its owner only before its first Run. A delegation to a Session whose
190
+ live Run's cancel awaits its Driver waits behind that Run and starts the next
191
+ one; any other live delivery steers that Run. The platform then delivers to
192
+ the owner, as a `RunReport`, each end of that Session's root Runs (`complete`
193
+ with its result, `failed`, `stopped`) but one a stop of the owner's ledger
194
+ caused, each hold of one at its turn or spend limit (`held`), and each refused
195
+ or dropped start of one whose event did not come from the owner's Session
196
+ (`refused`). A delivery refused when it reaches
197
+ its Session, or failing there for good, is reported to its sender as a
198
+ `RunReport` with status `refused`. `ctx.await(label, { afterRun: "delivery" })`
199
+ settles when a delivery steers the waiting Run and resolves to `{ seq, eventId }`
200
+ of the steer that woke it; the delivery itself stays in the ledger.
201
+
202
+ Policy decides a view of another Session (`ledger:read`; the pages its cursor
203
+ then reads need no further check) and a delivery to another Session at its
204
+ commit (`agent:invoke` on the receiving Agent, `session:steer` when live,
205
+ `run:cancel` when delegating). A refused view or
206
+ delivery throws its refusal, which is journaled, so a replay throws the same
207
+ error at the same position: a Policy denial is `PolicyDecisionFailed` with its
208
+ `decisionHash`, and any other refusal an `Error` with the platform's message and
209
+ `status`.
210
+
184
211
  ## Session schedules
185
212
 
186
213
  Schedule a future invocation of the current Agent and Session:
@@ -200,8 +227,7 @@ Recurring schedules preserve missed occurrences by default; explicitly request
200
227
 
201
228
  `ctx.listSchedules()` pages the owning Session's schedules; calling `schedule()`
202
229
  again with the same name replaces future work. `ctx.cancelSchedule(name)` stops
203
- future work and identifies accepted or unresolved deliveries. Another bound
204
- Agent can be selected with `agent` and an explicit `session`. Use `ctx.await()`
230
+ future work and identifies accepted or unresolved deliveries. Use `ctx.await()`
205
231
  for sleeping within the current Run.
206
232
 
207
233
  See [Schedule Agent follow-ups](https://constal.ai/docs/agents/schedules) for replay,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@constal/sdk",
3
- "version": "4.4.0",
3
+ "version": "5.1.0",
4
4
  "description": "Public TypeScript SDK for authoring Constal agents, integrations, policies, channels, and credential providers",
5
5
  "keywords": [
6
6
  "constal",
package/publish/api.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "package": "@constal/sdk",
3
- "version": "4.4.0",
3
+ "version": "5.1.0",
4
4
  "exports": [
5
5
  "AGENT_UI_DEFAULTS",
6
6
  "Action",
@@ -14,11 +14,8 @@
14
14
  "Agent",
15
15
  "AgentCredentialSetupRequirement",
16
16
  "AgentDef",
17
- "AgentDeliveryReceipt",
18
17
  "AgentDeployPolicy",
19
18
  "AgentGovernanceMeter",
20
- "AgentResultDelivery",
21
- "AgentSendOpts",
22
19
  "AgentSetupMetadata",
23
20
  "AgentSetupRequirement",
24
21
  "AgentSetupWorkflow",
@@ -62,6 +59,10 @@
62
59
  "CatalogTool",
63
60
  "Channel",
64
61
  "ChannelContext",
62
+ "ChannelDeliveryError",
63
+ "ChannelDeliveryEvent",
64
+ "ChannelDeliveryOutcome",
65
+ "ChannelDeliveryReport",
65
66
  "ChannelFailure",
66
67
  "ChannelIngressEvent",
67
68
  "ChannelIngressSource",
@@ -253,6 +254,7 @@
253
254
  "MemoryStoreBinding",
254
255
  "Mode",
255
256
  "ModelAdvertisedPricing",
257
+ "ModelCacheHint",
256
258
  "ModelCompletion",
257
259
  "ModelCredentialHeader",
258
260
  "ModelGatewayBinding",
@@ -262,8 +264,10 @@
262
264
  "ModelGovernanceControls",
263
265
  "ModelGovernanceMeter",
264
266
  "ModelHistoryMessage",
267
+ "ModelHistoryToolCall",
265
268
  "ModelInvocationArgs",
266
269
  "ModelInvocationResult",
270
+ "ModelProtocolRequestOptions",
267
271
  "ModelTechnicalCapabilities",
268
272
  "ModelTool",
269
273
  "NondeterministicReplay",
@@ -316,15 +320,20 @@
316
320
  "RunReport",
317
321
  "RunStatusDetail",
318
322
  "RunSuiteRequest",
323
+ "SANDBOX_EGRESS_LIMITS",
319
324
  "Sandbox",
320
325
  "SandboxCommandCollectionError",
321
326
  "SandboxCommandExecution",
322
327
  "SandboxCommandResult",
328
+ "SandboxEgressCredentialRule",
329
+ "SandboxEgressPolicy",
330
+ "SandboxEgressRule",
323
331
  "SandboxExecInput",
324
332
  "SandboxFileResult",
325
333
  "SandboxGovernanceControls",
326
334
  "SandboxGovernanceMeter",
327
335
  "SandboxImage",
336
+ "SandboxLabels",
328
337
  "SandboxMutationResult",
329
338
  "SandboxNetworkMode",
330
339
  "SandboxNetworkPolicy",
@@ -433,6 +442,7 @@
433
442
  "TrainingUsageUnits",
434
443
  "TurnDraft",
435
444
  "TurnGate",
445
+ "TurnHistoryMessage",
436
446
  "TurnRecord",
437
447
  "TurnSpec",
438
448
  "UI_ASSET_CONTENT_TYPES",
@@ -539,6 +549,9 @@
539
549
  "modelProtocolResult",
540
550
  "murmur3_32",
541
551
  "normalizeModelGatewayConfig",
552
+ "normalizeSandboxEgressCredentialRules",
553
+ "normalizeSandboxEgressPolicy",
554
+ "normalizeSandboxLabels",
542
555
  "normalizeSandboxNetworkPolicy",
543
556
  "normalizeSandboxWorkspacePath",
544
557
  "noulDecision",
@@ -564,6 +577,8 @@
564
577
  "resourceSelector",
565
578
  "resourceTools",
566
579
  "sandboxControls",
580
+ "sandboxEgressDecision",
581
+ "sandboxEgressHostMatches",
567
582
  "sandboxLimit",
568
583
  "scopedBindingKey",
569
584
  "scopedCredentialRef",
@@ -149,7 +149,9 @@ declare class ApiError extends Error {
149
149
  readonly status: number;
150
150
  readonly body: string;
151
151
  readonly disposition: "terminal" | "uncertain";
152
- constructor(status: number, body: string, disposition?: "terminal" | "uncertain");
152
+ readonly retryAfterMs?: number | undefined;
153
+ /** `retryAfterMs`: the interval the remote API stated, such as its `retry-after`; absent when it stated none. */
154
+ constructor(status: number, body: string, disposition?: "terminal" | "uncertain", retryAfterMs?: number | undefined);
153
155
  }
154
156
  /** The integration can prove that no external request was sent. */
155
157
  declare class IntegrationRequestNotSent extends Error {
@@ -634,6 +636,8 @@ interface ModelInvocationArgs extends ModelGenerationOptions {
634
636
  toolChoice?: "auto" | "required";
635
637
  feedback?: string[];
636
638
  stream?: boolean;
639
+ /** Opt in to provider prompt caching for this request. */
640
+ cache?: ModelCacheHint;
637
641
  /** Host-adapter escape hatch for a qualified upstream SDK wire request. Credentials and the selected model remain platform-owned. */
638
642
  rawProtocol?: {
639
643
  protocol: RawModelProtocol;
@@ -684,7 +688,9 @@ interface ModelInvocationResult {
684
688
  usage: {
685
689
  input: number;
686
690
  output: number;
691
+ /** Input tokens read from the provider's prompt cache; 0 when the provider reports none. */
687
692
  cached: number;
693
+ /** Input tokens written to the provider's prompt cache, present only when the provider reports it. */
688
694
  cacheWrite?: number;
689
695
  /** Exact upstream inference cost when the Gateway can establish it; null means unavailable. */
690
696
  costUsd?: number | null;
@@ -696,17 +702,60 @@ interface ModelInvocationResult {
696
702
  }
697
703
  declare function normalizeModelGatewayConfig(value: unknown): NormalizedModelGatewayConfig;
698
704
  declare function modelGatewayEndpoint(config: Pick<ModelGatewayConfig, "baseUrl" | "protocol">): URL;
699
- interface ModelHistoryMessage {
700
- role: "user" | "assistant";
705
+ /** One Tool call an earlier assistant message made. `id` is the call's id in its turn's record (`ToolCallRecord.id`), which
706
+ * the tool message answering it names; `args` is the JSON value the model gave (`ToolCallRecord.args`). An OpenAI-protocol
707
+ * request sends it as the arguments text; an Anthropic `tool_use` input must be an object, so a value that is not one is
708
+ * sent as `{ value }`, as the Constal Gateway does for such a call. */
709
+ interface ModelHistoryToolCall {
710
+ id: string;
711
+ name: string;
712
+ args: unknown;
713
+ }
714
+ /** One earlier message, oldest first. User and assistant text is as it always was; an assistant message may also carry the
715
+ * Tool calls it made, and a tool message returns one call's result to the model. The tool messages right after an
716
+ * assistant message answer each of its calls once, before any other message. */
717
+ type ModelHistoryMessage = {
718
+ role: "user";
719
+ content: string;
720
+ } | {
721
+ role: "assistant";
722
+ content: string;
723
+ toolCalls?: ModelHistoryToolCall[];
724
+ } | {
725
+ role: "tool";
726
+ toolCallId: string;
701
727
  content: string;
728
+ isError?: boolean;
729
+ };
730
+ /** Opt-in prompt caching. With a hint, an Anthropic-protocol request marks cache breakpoints on its stable prefix (Tools and
731
+ * system prompt) and on the last history message; an OpenAI-protocol request sent with `contentCacheControl` marks the same
732
+ * breakpoints on the system prompt's and the last history message's text. Each value reaches the provider only when given;
733
+ * without one the provider's default applies. */
734
+ interface ModelCacheHint {
735
+ /** OpenAI-protocol `prompt_cache_key`, such as the caller's Session id: requests that share it share cached prefixes. */
736
+ key?: string;
737
+ /** OpenAI-protocol `prompt_cache_retention`. */
738
+ retention?: string;
739
+ /** Anthropic `cache_control.ttl` of every breakpoint. */
740
+ ttl?: string;
702
741
  }
703
742
  /** Canonical (sorted-key) JSON: the same objective and context render to the same text whether their objects were built live
704
743
  * or loaded back from storage, so a provider's prompt cache keeps matching from one turn to the next. */
705
744
  declare function modelPrompt(args: ModelInvocationArgs): string;
706
- /** The messages of one turn: the static objective and context first, then each earlier exchange as its own message, then
707
- * feedback about the previous attempt. Without history this is the single prompt message it always was. */
745
+ /** The messages of one turn: the static objective and context first (when the turn has either, or its history opens with an
746
+ * assistant message), then each earlier exchange as its own message, then feedback about the previous attempt. Without
747
+ * history this is the single prompt message it always was. */
708
748
  declare function modelMessages(args: ModelInvocationArgs): ModelHistoryMessage[];
709
- declare function modelProtocolRequest(protocol: ModelGatewayProtocol, model: string, maxOutputTokens: number | null, temperature: number | null, args: ModelInvocationArgs): Record<string, unknown>;
749
+ /** Choices an OpenAI-protocol request makes for the endpoint it is sent to. Without them the request is plain Chat
750
+ * Completions, as every OpenAI-compatible endpoint takes it. */
751
+ interface ModelProtocolRequestOptions {
752
+ /** Send a cache hint's breakpoints as Anthropic `cache_control` on the text of the system prompt and of the last history
753
+ * message, for an endpoint that reads them there, such as the Constal Gateway or OpenRouter. */
754
+ contentCacheControl?: boolean;
755
+ /** Name an error Tool result `tool_error`, which the Constal Gateway sends to Anthropic as `is_error`. */
756
+ toolErrorName?: boolean;
757
+ }
758
+ declare function modelProtocolRequest(protocol: ModelGatewayProtocol, model: string, maxOutputTokens: number | null, temperature: number | null, args: ModelInvocationArgs, options?: ModelProtocolRequestOptions): Record<string, unknown>;
710
759
  declare function modelProtocolResult(protocol: ModelGatewayProtocol, raw: unknown, provider: string, model: string): ModelInvocationResult;
711
760
 
712
761
  interface GatewayCredentialSlotSetup {
@@ -1012,10 +1061,16 @@ type AgentResourceBinding = CRN | ScopedResourceRef;
1012
1061
  type ResourceCredentialBinding = CredentialCRN | ScopedCredentialRef;
1013
1062
  interface InvocationCredentialUse {
1014
1063
  binding: ResourceCredentialBinding;
1064
+ /** Who receives the value: a sandbox process (an env variable or a memory-backed file), or a sandbox's egress gate,
1065
+ * which adds it to requests as the named header and never shows it to the sandbox. */
1015
1066
  consumer: {
1016
1067
  kind: "process";
1017
1068
  delivery: "env" | "file";
1018
1069
  name: string;
1070
+ } | {
1071
+ kind: "egress";
1072
+ delivery: "header";
1073
+ name: string;
1019
1074
  };
1020
1075
  }
1021
1076
  interface BindingAssignmentRevision {
@@ -1597,12 +1652,90 @@ declare function containerImageSelection(value: unknown): ContainerImageSelectio
1597
1652
  * manifest. The caller owns registry authentication and transport Policy. */
1598
1653
  declare function resolveContainerImageSource(reference: string, platform: ContainerImageSource["platform"], request: ContainerRegistryRequest, authorization?: string): Promise<ContainerImageSource>;
1599
1654
 
1655
+ /**
1656
+ * A sandbox's own egress settings: an ordered host policy that narrows its pool's network, Credentials its pool's
1657
+ * egress gate adds to requests, and labels every egress event carries. They are provider-neutral declarations; a pool
1658
+ * whose provider has no egress gate refuses them rather than ignoring them.
1659
+ */
1660
+ /** One ordered rule: the first rule whose host matches a request decides it. */
1661
+ interface SandboxEgressRule {
1662
+ action: "allow" | "deny";
1663
+ /** An exact host name, or `*.example.com` for the apex and every name under it. */
1664
+ host: string;
1665
+ }
1666
+ /**
1667
+ * A sandbox's narrowing of its pool's network. It never widens it: a request must be admitted by the pool and by this
1668
+ * policy. A host no rule matches takes `default` (`deny` when omitted). The pool's control host stays reachable.
1669
+ */
1670
+ interface SandboxEgressPolicy {
1671
+ rules: SandboxEgressRule[];
1672
+ default?: "allow" | "deny";
1673
+ }
1674
+ /**
1675
+ * For requests to matching hosts, the egress gate adds one header built from a Credential, resolved at each request
1676
+ * through the platform's Credential use (binding controls, scope, Policy, a use record naming the destination). The
1677
+ * sandbox never sees the value, and the gate redacts it from what the response echoes back.
1678
+ */
1679
+ interface SandboxEgressCredentialRule {
1680
+ /** Exact host names, or `*.example.com` for the apex and every name under it. Requests must be https. */
1681
+ hosts: string[];
1682
+ /** A Credential slot the pool declares. */
1683
+ slot?: string;
1684
+ /** Only on createSandbox: a Credential (or a scoped binding to one) the call delegates to this sandbox. */
1685
+ binding?: ResourceCredentialBinding;
1686
+ /** The header to set; `authorization` when omitted. A header the sandbox sent under the same name is replaced. */
1687
+ header?: string;
1688
+ /** The header value, with `{value}` exactly once where the Credential goes; `Bearer {value}` when omitted. */
1689
+ value?: string;
1690
+ /** Instead of `value`: HTTP basic auth, `Basic base64(username:value)`, or `Basic base64(value)` without a username. */
1691
+ basic?: {
1692
+ username?: string;
1693
+ };
1694
+ }
1695
+ /** A rule as the pool receives it: a delegated binding arrives as the invocation's Credential use `egress-<n>` (`use`). */
1696
+ interface SandboxEgressCredentialGrant extends SandboxEgressCredentialRule {
1697
+ use?: string;
1698
+ }
1699
+ /** Caller-supplied labels a sandbox's events carry: at most 16, short keys, values of at most 256 characters. */
1700
+ type SandboxLabels = Record<string, string>;
1701
+ declare const SANDBOX_EGRESS_LIMITS: {
1702
+ readonly rules: 64;
1703
+ readonly credentialRules: 16;
1704
+ readonly hostsPerRule: 32;
1705
+ readonly labels: 16;
1706
+ readonly labelValueLength: 256;
1707
+ };
1708
+ /** Whether `pattern` (exact, or `*.d` for `d` and every name under it) admits `hostname`. */
1709
+ declare function sandboxEgressHostMatches(pattern: string, hostname: string): boolean;
1710
+ declare function normalizeSandboxEgressPolicy(value: unknown): SandboxEgressPolicy;
1711
+ /** The decision a policy gives a host: the first matching rule, else its default. Null admits everything. */
1712
+ declare function sandboxEgressDecision(policy: SandboxEgressPolicy | null | undefined, hostname: string): {
1713
+ allowed: boolean;
1714
+ rule: string;
1715
+ };
1716
+ /**
1717
+ * Egress Credential rules. `bindings` admits a rule that delegates a binding (createSandbox); a pool's own rules name its
1718
+ * slots. The pool receives a delegated rule as `use` (the invocation's `egress-<n>` Credential use) in place of `binding`.
1719
+ */
1720
+ declare function normalizeSandboxEgressCredentialRules(value: unknown, options?: {
1721
+ bindings?: boolean;
1722
+ uses?: boolean;
1723
+ }): SandboxEgressCredentialGrant[];
1724
+ declare function normalizeSandboxLabels(value: unknown): SandboxLabels;
1725
+
1600
1726
  /** Canonicalize one provider-neutral path and keep it inside the logical workspace. */
1601
1727
  declare function normalizeSandboxWorkspacePath(path: string, cwd?: string): string;
1602
1728
  interface CreateSandboxOptions {
1603
1729
  image?: SandboxImage;
1604
1730
  resetImage?: boolean;
1605
1731
  execution?: ContainerImageSelection;
1732
+ /** Narrows the pool's network for this sandbox; `Sandbox.updateNetwork` replaces it later. */
1733
+ network?: SandboxEgressPolicy;
1734
+ /** Headers the pool's egress gate adds from Credentials, beside the pool's own rules. A rule naming a `binding` is
1735
+ * delegated by this call; calling createSandbox again for the Session renews the delegation. */
1736
+ credentials?: SandboxEgressCredentialRule[];
1737
+ /** Labels every egress event of this sandbox carries. */
1738
+ labels?: SandboxLabels;
1606
1739
  }
1607
1740
  /**
1608
1741
  * Optional immutable identity for a prepared image. Cache keys are supplied as
@@ -1784,6 +1917,8 @@ interface SandboxWorkspace {
1784
1917
  /** Explicit physical handle used only for lifecycle/image selection controls. */
1785
1918
  interface Sandbox extends SandboxWorkspace {
1786
1919
  readonly id: string;
1920
+ /** Replace this sandbox's narrowing of its pool's network, live; null removes it. */
1921
+ updateNetwork(network: SandboxEgressPolicy | null, opts?: InvokeOpts): Promise<void>;
1787
1922
  suspend(opts?: InvokeOpts): Promise<void>;
1788
1923
  resume(opts?: InvokeOpts): Promise<void>;
1789
1924
  delete(opts?: InvokeOpts): Promise<void>;
@@ -1943,13 +2078,9 @@ type ScheduleWhen = {
1943
2078
  after?: never;
1944
2079
  missed?: ScheduleMissed;
1945
2080
  };
1946
- /** Future invocations of this Agent, or an explicitly bound Agent in an explicit Session. */
2081
+ /** Future invocations of this Agent in this Session. A scheduled Run reaches another ledger with ctx.commit(item, { to }). */
1947
2082
  type ScheduleOptions<Input = unknown> = ScheduleWhen & {
1948
2083
  input: Input;
1949
- /** Omission selects the current Agent and its normal Session routing. */
1950
- agent?: CRN;
1951
- /** Omission selects the current Session. Another Agent requires an explicit Session. */
1952
- session?: string;
1953
2084
  };
1954
2085
  type ScheduleTiming = {
1955
2086
  kind: "after";
@@ -2153,7 +2284,68 @@ type WaitResolvedEvent = EventBase & {
2153
2284
  promiseId: string;
2154
2285
  outcome: "resolved" | "timeout" | "cancelled" | "failed";
2155
2286
  };
2156
- type LedgerEvent = SteerEvent | ControlEvent | WaitResolvedEvent | (EventBase & {
2287
+ /** Why a Channel delivery failed, as far as the platform saw it. */
2288
+ interface ChannelDeliveryError {
2289
+ /** `ChannelDeliveryFailed` when the Channel's receipt says it failed, with the receipt's reason as `message`; else the
2290
+ * failing provider call's error code (such as `ApiError`), `ChannelHandlerFailed` when its send() answered no receipt, or
2291
+ * `ChannelUnavailable` when the platform could not run its send() (or, for a `channel.send`, its request was refused or
2292
+ * not answered). */
2293
+ name: string;
2294
+ message: string;
2295
+ /** The HTTP status the provider answered the failing call with: with a failed receipt, the call the delivery ended on,
2296
+ * when that call failed. Null when no such provider call failed, and for a `channel.send`. */
2297
+ status: number | null;
2298
+ /** The interval the provider stated before a retry (its `Retry-After`), in milliseconds; null when it stated none. */
2299
+ retryAfterMs: number | null;
2300
+ /** The provider may have acted anyway, so the message may have been posted: check before sending it again. With a failed
2301
+ * receipt, the Channel's word that it did not deliver stands unless a provider call of the delivery had not finished or
2302
+ * ended with nothing to show it did nothing: its outcome unknown (a 5xx, for one), or failed after a dispatch that got no
2303
+ * answer. With no receipt, a provider call that completed counts too; for a `channel.send`, its Channel answered no
2304
+ * receipt or its request was not answered. */
2305
+ outcomeUnknown: boolean;
2306
+ }
2307
+ /** What became of one message the platform sent through a Channel for a Run. */
2308
+ interface ChannelDeliveryOutcome {
2309
+ /** "presentation": a presentation a commit or a wait carried, which the Channel that admitted the Run delivers from the
2310
+ * Session's outbox; "send": a `channel.send` the Run made through the Constal API. */
2311
+ via: "presentation" | "send";
2312
+ /** The Run that presented or sent the message. */
2313
+ run: string;
2314
+ channel: CRN;
2315
+ /** The message's id, by which the Channel dedupes it. */
2316
+ message: string;
2317
+ destination: string;
2318
+ /** The Channel's receipt ("delivered" or "accepted"), or "failed", after which nothing retries it. */
2319
+ status: "delivered" | "accepted" | "failed";
2320
+ /** The provider's id of the posted message (Slack's `ts`), when the Channel's receipt names one. */
2321
+ externalId: string | null;
2322
+ /** Null unless it failed. */
2323
+ error: ChannelDeliveryError | null;
2324
+ /** Attempts at the Channel's send(): the first, and one for each retry the provider paced with a stated interval. */
2325
+ attempts: number;
2326
+ }
2327
+ /**
2328
+ * A Channel delivery's outcome, written by the platform once into the main ledger of the Session whose Run presented or sent
2329
+ * the message, when it is delivered or fails for good. A view over "events" reads it; a failed presentation also reaches the
2330
+ * Session as a ChannelDeliveryReport.
2331
+ */
2332
+ type ChannelDeliveryEvent = EventBase & {
2333
+ kind: "channel-delivery";
2334
+ } & ChannelDeliveryOutcome;
2335
+ /**
2336
+ * A presentation its Channel failed to deliver, delivered by the platform as the live body { text, data } to the Session
2337
+ * whose Run presented it: it steers that Session's live Run, or starts one. A delivered outcome is only written to the ledger.
2338
+ */
2339
+ interface ChannelDeliveryReport {
2340
+ /** One sentence the platform writes: that the message was not delivered, or, when `error.outcomeUnknown`, that it may
2341
+ * already have been posted and should be checked before it is sent again. */
2342
+ text: string;
2343
+ data: {
2344
+ object: "constal.channel.delivery";
2345
+ version: 1;
2346
+ } & ChannelDeliveryOutcome;
2347
+ }
2348
+ type LedgerEvent = SteerEvent | ControlEvent | WaitResolvedEvent | ChannelDeliveryEvent | (EventBase & {
2157
2349
  kind: "fact";
2158
2350
  fact: Fact;
2159
2351
  }) | (EventBase & {
@@ -2262,7 +2454,9 @@ interface SpawnBudget {
2262
2454
  wallMs: number;
2263
2455
  }
2264
2456
  /** Exact local Resource and Tool names retained by a child Run. Omitted names
2265
- * are unavailable to the child even when they are bound to the parent. */
2457
+ * are unavailable to the child even when they are bound to the parent.
2458
+ * Attenuation bounds what the child runs, not what it reads or the Runs its deliveries start: Policy decides its
2459
+ * views and its deliveries, and a Run that a delivery starts runs under the receiving ledger's own grants. */
2266
2460
  interface SpawnAttenuation {
2267
2461
  bindings: readonly string[];
2268
2462
  tools: readonly string[];
@@ -2292,7 +2486,8 @@ interface AwaitOpts<T> {
2292
2486
  /** Optional caller-selected response size limit, in UTF-8 bytes. */
2293
2487
  maxBytes?: number;
2294
2488
  /** "message": the Session's next queued input answers the wait with its value. "delivery": the wait settles when a
2295
- * delivery steers this Run after the wait opened; it returns no value and the delivery stays in the ledger. */
2489
+ * delivery steers this Run after the wait opened, and resolves to `{ seq, eventId }` of the steer that woke it; the
2490
+ * delivery itself stays in the ledger and is consumed by nothing. */
2296
2491
  afterRun?: "ignore" | "message" | "delivery";
2297
2492
  /** Explicitly public presentation; never include Credential material or private evidence. */
2298
2493
  presentation?: AwaitPresentation;
@@ -2313,28 +2508,10 @@ interface InvocationHandle<T> extends Handle<T> {
2313
2508
  }
2314
2509
  /** A spawn's Handle names the spawned loop's ledger, the same across the spawn's retries. */
2315
2510
  interface SpawnHandle<T> extends Handle<T> {
2511
+ /** Reading it throws a TypeError in a Session whose id the address grammar excludes (more than 256 characters, a `/` or
2512
+ * a control character): such a Session has no ledger addresses. */
2316
2513
  readonly ledger: LedgerAddress;
2317
2514
  }
2318
- /** A message to an exactly bound Agent creates one distinct target Run. */
2319
- type AgentSendOpts = {
2320
- session: string;
2321
- completion?: "receipt";
2322
- } | {
2323
- session?: string;
2324
- completion: "run-result";
2325
- timeoutMs?: number;
2326
- };
2327
- interface AgentDeliveryReceipt {
2328
- id: string;
2329
- state: "enqueued";
2330
- target: {
2331
- agent: CRN;
2332
- session: string;
2333
- };
2334
- }
2335
- interface AgentResultDelivery<T> extends AgentDeliveryReceipt {
2336
- result: Handle<T>;
2337
- }
2338
2515
  interface CommitOpts {
2339
2516
  tier?: Tier;
2340
2517
  gate?: string | GateEvidence | {
@@ -2343,15 +2520,22 @@ interface CommitOpts {
2343
2520
  /** Filled by the runtime after a scorer-backed gate; callers must not provide it. */
2344
2521
  gateVerdict?: GateVerdict;
2345
2522
  compensate?: Compensation;
2523
+ /** Delivers the item to another ledger: `agent:<agent>/session:<session>` (that Session's main ledger) or
2524
+ * `agent:<agent>/session:<session>/spawn:<handle>` (a spawned loop's); or commits it to `memory`. Omit it for this
2525
+ * Run's own ledger; `session:<id>` is refused. */
2346
2526
  to?: LedgerAddress;
2347
2527
  checkpoint?: {
2348
2528
  upTo: FactRef;
2349
2529
  };
2350
2530
  expectedHead?: FactRef;
2531
+ /** "queue" (the default) or "live", which steers the addressed Run or starts one. A live item is a non-empty string or
2532
+ * { text, data? } with a non-empty text. A delivery to a spawn is live. */
2351
2533
  deliver?: DeliveryMode;
2352
2534
  /** Makes this Run's Session the owner of the Session whose main ledger `to` names. */
2353
2535
  delegate?: boolean;
2354
- /** Explicitly public presentation delivered by the originating Channel when this Run was admitted through one. */
2536
+ /** Explicitly public presentation delivered by the originating Channel when this Run was admitted through one. Its outcome
2537
+ * is written to the Session's main ledger as a `channel-delivery` event; a failure also reaches the Session as a
2538
+ * ChannelDeliveryReport. */
2355
2539
  presentation?: AwaitPresentation;
2356
2540
  }
2357
2541
  /** A Run's end, hold or refused start, delivered by the platform as the body { text, data } to the Session's owner, to the
@@ -2396,6 +2580,8 @@ interface Cost {
2396
2580
  priceTable: PriceTableRef | null;
2397
2581
  };
2398
2582
  };
2583
+ /** Billed token totals. `cached` and `cacheWrite` are 0 both when the provider reported none and when it reported nothing;
2584
+ * a model invocation's own `usage.cacheWrite` is absent in the second case. */
2399
2585
  tokens: {
2400
2586
  input: number;
2401
2587
  output: number;
@@ -2430,12 +2616,15 @@ type GateResult = boolean | {
2430
2616
  pass: boolean;
2431
2617
  evidence?: unknown;
2432
2618
  };
2619
+ /** A generated turn before its Tools run. The runtime gives each Tool call the id its TurnRecord's ToolCallRecord will carry;
2620
+ * `id` is optional so a draft built by hand (for example to test a gate) needs none. */
2433
2621
  interface TurnDraft {
2434
2622
  message: {
2435
2623
  role: "assistant";
2436
2624
  content: string;
2437
2625
  };
2438
2626
  toolCalls: {
2627
+ id?: string;
2439
2628
  name: string;
2440
2629
  args: unknown;
2441
2630
  }[];
@@ -2455,17 +2644,21 @@ interface TurnGate {
2455
2644
  feedback?(rec: TurnRecord | TurnDraft): string;
2456
2645
  onExhausted?: "fail" | "commit-with-verdict";
2457
2646
  }
2458
- /** One prior exchange the model sees as a message of its own, so a provider's prompt cache extends over it. */
2459
- interface TurnHistoryMessage {
2460
- role: "user" | "assistant";
2461
- content: string;
2462
- }
2647
+ /** One prior exchange the model sees as a message of its own, so a provider's prompt cache extends over it: user or
2648
+ * assistant text, an assistant message with the Tool calls it made (each with the id its TurnRecord reported), or a tool
2649
+ * message answering one of those calls by id. */
2650
+ type TurnHistoryMessage = ModelHistoryMessage;
2463
2651
  interface TurnSpec extends ModelGenerationOptions {
2464
2652
  system: string;
2465
2653
  objective?: unknown;
2466
2654
  context?: unknown;
2467
- /** Earlier exchanges, oldest first, sent as messages after the objective and context rather than inside them. */
2655
+ /** Earlier exchanges, oldest first, sent as messages after the objective and context rather than inside them. With
2656
+ * neither an objective nor a context, a history that opens with a user message forms the request alone; one that opens
2657
+ * with an assistant message is still preceded by the prompt message (objective and context both null), since Anthropic
2658
+ * requires the first message to be a user message. */
2468
2659
  history?: TurnHistoryMessage[];
2660
+ /** Opt in to provider prompt caching; see ModelCacheHint. */
2661
+ cache?: ModelCacheHint;
2469
2662
  tools?: string[];
2470
2663
  /** Require one of the offered Tools for this model generation. */
2471
2664
  toolChoice?: "auto" | "required";
@@ -2477,6 +2670,8 @@ interface TurnSpec extends ModelGenerationOptions {
2477
2670
  stream?: boolean;
2478
2671
  }
2479
2672
  interface ToolCallRecord {
2673
+ /** The provider's id for the call, or, when the provider gave none, an empty one or one already used, a `call_` id the
2674
+ * runtime derived from the turn's Run and position. A later turn's history names it to pair the call with its result. */
2480
2675
  id: string;
2481
2676
  pos: string;
2482
2677
  name: string;
@@ -2705,8 +2900,8 @@ interface RunInfo {
2705
2900
  };
2706
2901
  mode: Mode;
2707
2902
  /** This Run's own ledger address: its Session's main ledger for a root Run, its spawn's for a spawned Run, null for a
2708
- * Run that nothing addresses (an operator branch, an eval fork, a compensation). */
2709
- ledger?: LedgerAddress | null;
2903
+ * Run that nothing addresses (an operator branch, an eval fork, a compensation, or a loop one of them spawned). */
2904
+ ledger: LedgerAddress | null;
2710
2905
  /** Present for an independently scheduled invocation; input remains unchanged. */
2711
2906
  schedule?: ScheduleTrigger;
2712
2907
  }
@@ -2770,6 +2965,9 @@ interface Ctx {
2770
2965
  /** Judge one state with constrained, probabilistic answers instead of a generated turn. Journaled and priced like a model call. */
2771
2966
  evaluate<Q extends EvaluationQuestions>(spec: EvaluationSpec<Q>): Promise<EvaluationRecord<Q>>;
2772
2967
  ledger: {
2968
+ /** `of` names another ledger: `agent:<agent>/session:<session>` (that Session's main ledger, read at its head),
2969
+ * `agent:<agent>/session:<session>/spawn:<handle>` (a spawned loop's), `memory` or `table:<table>@<branch>`.
2970
+ * Omit it for this Run's own ledger, pinned at dispatch; `session:<id>` is refused. */
2773
2971
  view<S = HistoryView>(name?: string, opts?: {
2774
2972
  of?: LedgerAddress;
2775
2973
  }): Promise<S>;
@@ -2788,7 +2986,7 @@ interface Ctx {
2788
2986
  cancelSchedule(name: string): Promise<ScheduleCancellation>;
2789
2987
  /** Inspect this Session's schedules through a journaled, paginated read. */
2790
2988
  listSchedules(options?: ListSchedulesOptions): Promise<SchedulePage>;
2791
- spawn<T>(task: Task<T>, input: unknown, opts?: SpawnOpts): Handle<T>;
2989
+ spawn<T>(task: Task<T>, input: unknown, opts?: SpawnOpts): SpawnHandle<T>;
2792
2990
  map<I, O, R = never>(f: PartitionFn<I, O, R>, over: Over<I>, opts: MapOpts): Handle<MapFact>;
2793
2991
  reduce<I, O>(g: FoldFn<I, O> | SqlFold, over: Over<I>, opts?: ReduceOpts): Handle<ReduceFact>;
2794
2992
  step<T>(name: string, fn: () => Promise<T>): Promise<T>;
@@ -2799,13 +2997,6 @@ interface Ctx {
2799
2997
  sandboxPool(resource: CRN): SandboxPool;
2800
2998
  invoke<T>(resource: CRN, op: string, args: unknown, opts?: InvokeOpts): Promise<T>;
2801
2999
  invokeAsync<T>(resource: CRN, op: string, args: unknown, opts?: InvokeOpts): InvocationHandle<T>;
2802
- send<T>(agent: CRN, input: unknown, opts: AgentSendOpts & {
2803
- completion: "run-result";
2804
- }): Promise<AgentResultDelivery<T>>;
2805
- send(agent: CRN, input: unknown, opts: {
2806
- session: string;
2807
- completion?: "receipt";
2808
- }): Promise<AgentDeliveryReceipt>;
2809
3000
  request(policy: PolicyCRN, grant: CapabilityGrant): Handle<CapabilityRef>;
2810
3001
  analytics: AnalyticsClient;
2811
3002
  run: RunInfo;
@@ -2961,7 +3152,8 @@ interface CanonicalEventDraft<T = unknown> {
2961
3152
  occurredAt?: number;
2962
3153
  deliver?: DeliveryMode;
2963
3154
  /** When respond() runs: "receipt" once the event is durably in its Session's inbox; "run-result" once the Run it
2964
- * starts settles, up to 120 s. Default: "receipt" for queue, "run-result" for live. */
3155
+ * starts settles, up to 120 s. Default: "receipt" for queue, "run-result" for live. `queue` with "run-result" is an
3156
+ * invalid draft. */
2965
3157
  completion?: "receipt" | "run-result";
2966
3158
  /** Channel-owned reply address pinned at admission; Agent input cannot replace it. */
2967
3159
  reply?: {
@@ -2974,6 +3166,9 @@ interface IgnoredChannelEvent {
2974
3166
  ignored: true;
2975
3167
  reason: string;
2976
3168
  response: ChannelResponse;
3169
+ /** Names of this Channel's bindings whose Credentials the platform checks with their providers before it answers,
3170
+ * such as on a provider's own installation lifecycle event. Only a request with a Customer resolves them. */
3171
+ recheck?: string[];
2977
3172
  }
2978
3173
  /** Authenticated source delivery captured once and dispatched to authorized subscribers. */
2979
3174
  interface ChannelIngressEvent {
@@ -4330,6 +4525,10 @@ interface CredentialVerifyResult {
4330
4525
  verified: boolean;
4331
4526
  /** Non-secret external identity and access facts verified by this provider. */
4332
4527
  claims?: Record<string, string | number | boolean | string[]>;
4528
+ /** With verified:false only: the provider states that the installation this version stands for no longer exists.
4529
+ * The platform revokes this version and the Credential's older live versions. A failure that may pass, and any
4530
+ * answer that is not such a statement (a suspension, a mismatch, a refusal), is thrown instead. */
4531
+ revoked?: true;
4333
4532
  }
4334
4533
  interface CredentialDestroyResult {
4335
4534
  destroyed: boolean;
@@ -4671,5 +4870,5 @@ declare function parseLedgerAddress(value: unknown): LedgerAddressParts | null;
4671
4870
  /** Formats ledger address parts; throws when a part breaks its id rule. */
4672
4871
  declare function formatLedgerAddress(parts: LedgerAddressParts): LedgerAddress;
4673
4872
 
4674
- export { AGENT_UI_DEFAULTS, AfterYield, ApiError, CONSTAL_API_CAPABILITY, CONSTAL_API_GET_KINDS, CONSTAL_API_MODEL_TOOL_DESCRIPTIONS, CONSTAL_API_OPERATIONS, CONSTAL_API_OPERATION_SCHEMAS, CONSTAL_API_QUERY_KINDS, CONSTAL_API_VERSION, CommitConflict, CommitGateRejected, CredentialRevoked, CredentialUnavailable, DirectNetworkDenied, EVALUATION_LIMITS, EffectCeilingExceeded, EmptyJoin, GateExhausted, IntegrationRequestNotSent, LeaseLost, MCP_CLIENT_CAPABILITY, MCP_PROTOCOL_VERSION, MEMORY_OPERATION_DECLARATIONS, MODEL_CHECKPOINT_IMPORT_CAPABILITY, MODEL_COMPLETION_CAPABILITY, MODEL_EVALUATION_CAPABILITY, McpClient, NondeterministicReplay, OutcomeUnknown, PolicyConstraintFailed, PolicyDecisionFailed, RESOURCE_CREDENTIAL_BINDING_SCHEMA, RESOURCE_KINDS, ResourceDisabled, ResourceInvalid, ResourceUnbound, RollbackTargetInvalid, SessionDeleted, SpawnCardinality, SwallowedYield, TRAINING_PROVIDER_CAPABILITY, TerminalIntegrationFailure, ToolUnavailable, UI_ASSET_CONTENT_TYPES, UI_BUNDLE_BOUNDS, UnknownTool, WEB_FETCH_ARGUMENT_SCHEMA, WEB_SEARCH_ARGUMENT_SCHEMA, action, actionPattern, agent, agentLimit, agentResourceBinding, agentSetupMetadata, agentSetupRequirements, agentUiBundleManifest, agentUiDeclaration, all, analyticsEvent, approximateTokens, authProvider, authProviderName, bindingName, bucketFor, canonicalJson, capabilityContractRef, casTool, channel, channelIngressRequest, channelIngressSource, channelSourceEvidence, channelSubscriptionRequest, channelTarget, checkpointArtifactRef, checkpointDeploymentRequest, checkpointImportMetadata, checkpointImportRequest, codeScorerIR, containerImageReference, containerImageSelection, containerImageSource, credentialEvidence, credentialInteractionAction, credentialInteractionEvent, credentialInteractionResult, credentialName, credentialProvider, credentialProviderConfigSchema, credentialProviderName, credentialProviderSetupMetadata, credentialRotationDefaults, credentialSetupState, customerTenantName, cutBatches, cutPartitions, datasetName, evaluateCodeScorer, evaluatePolicyDefinition, evaluationArguments, evaluationProtocolRequest, evaluationProtocolResult, formatLedgerAddress, gateway, gatewayModelOffer, gatewayPackageMetadata, hash, hashValue, immutableContainerImageReference, integrationEgressPolicy, invocationCredentialUses, labelSelector, matchesAction, matchesLabelSelector, matchesResource, mcpToolDescription, mcpToolResult, memoryStoreBinding, modelAdvertisedPricing, modelControls, modelGatewayBinding, modelGatewayEndpoint, modelGenerationOptions, modelLimit, modelMessages, modelPrompt, modelProtocolRequest, modelProtocolResult, murmur3_32, normalizeModelGatewayConfig, normalizeSandboxNetworkPolicy, normalizeSandboxWorkspacePath, noulDecision, opTool, opTools, parseLedgerAddress, parseResourceName, policy, policyName, race, renderTrainingCompletion, resolveBindingOwner, resolveContainerImageSource, resolveGatewayEgress, resolveResourceDependencyRef, resourceContractRef, resourceCredentialBinding, resourceDependencyRef, resourceLabelMap, resourceName, resourceNeed, resourcePattern, resourceSelector, resourceTools, sandboxControls, sandboxLimit, scopedBindingKey, scopedCredentialRef, scopedResourceRef, scoreLevel, scorerName, select, selectableResourceLabels, setupAwait, setupCredentialReceipt, setupPanelProviderIsCrn, setupScreen, setupScreenView, setupSubmission, sha256Hex, skills, stageOutput, startTrainingRequest, subtask, tableDescribe, tableQuery, trainingProvider, trainingProviderMetadata, trainingRecipe, uiAssetContentType, uiBundle, uiBundleManifest, uiLimit, uiName, validateBatchSpec, validateFoldFn, validateJsonSchema, validateJsonSchemaDefinition, validatePartitionFn, validatePartitionSpec, validateStageOutputSpec, validateTool, validateView, webFetch, webSearch };
4675
- export type { Action, ActionPattern, Actor, AdmissionLimitConstraint, AdmissionLimitInput, AdmissionLimitScope, AdmissionLimitWindow, Agent, AgentCredentialSetupRequirement, AgentDef, AgentDeliveryReceipt, AgentDeployPolicy, AgentGovernanceMeter, AgentResultDelivery, AgentSendOpts, AgentSetupMetadata, AgentSetupRequirement, AgentSetupWorkflow, AgentUiDeclaration, AnalyticsClient, AnalyticsDimensionValue, AnalyticsEventDefinition, AnalyticsIntent, AnalyticsValues, AuthProvider, AuthProviderCRN, AuthProviderContext, AuthProviderRequest, AuthProviderResult, AwaitOpts, AwaitPresentation, BatchSpec, BindingCRN, BindingOwnerContext, BindingOwnerScope, BoundOperation, BoundResourceCapabilities, BranchRef, CRN, CRNKind, CanonicalEvent, CanonicalEventDraft, CapabilityContractRef, CapabilityGrant, CapabilityRef, CaptureCaseRequest, CaseRow, CatalogTool, Channel, ChannelContext, ChannelFailure, ChannelIngressEvent, ChannelIngressSource, ChannelMessage, ChannelProtocol, ChannelReceiveResult, ChannelRequest, ChannelResponse, ChannelSourceEvidence, ChannelSubscriptionRequest, ChannelTarget, CheckpointDeploymentRequest, CheckpointImportMetadata, CheckpointImportRequest, ChoiceAnswer, ChoiceQuestion, CodeScoreResult, CodeScorerIR, CodeScorerRule, CommitOpts, CompareSuitesRequest, Compensation, ConnectionCancelRequest, ConnectionIdentity, ConnectionOperation, ConnectionRecoveryRequest, ConnectionRecoveryResult, ConnectionRequest, ConnectionUsageReport, ConstalApiApplyRequest, ConstalApiChangePlan, ConstalApiChangePlanRef, ConstalApiChangePlanRequest, ConstalApiChangeReceipt, ConstalApiOperationReceipt, ContainerImageReference, ContainerImageSelection, ContainerImageSource, ContainerRegistryRequest, ContainerRegistryResponse, ControlEvent, Cost, CreateSandboxImageOptions, CreateSandboxOptions, CredentialCRN, CredentialDestroyResult, CredentialEvidence, CredentialInteractionAction, CredentialInteractionAdvanceRequest, CredentialInteractionEvent, CredentialInteractionPrimaryAction, CredentialInteractionProof, CredentialInteractionResult, CredentialInteractionStartRequest, CredentialMaterialRequest, CredentialMintRequest, CredentialMintResult, CredentialProviderCRN, CredentialProviderContext, CredentialProviderCredentialSlotSetup, CredentialProviderDefinition, CredentialProviderPackage, CredentialProviderPackageMetadata, CredentialProviderSecretInput, CredentialProviderSetupMetadata, CredentialSetupState, CredentialUninstallRequest, CredentialUninstallResult, CredentialVerifyResult, Ctx, CustomerTenantCRN, DataManifest, DatasetCRN, DatasetDraft, DatasetRef, DelegatedGrant, DelegationCeiling, DeliveryMode, DeliveryReceipt, DispatchResult, EffectClass, EvalComparison, EvalDivergence, EvalMode, EvalSubject, EvalSubjectSource, EvaluationAnswer, EvaluationAnswerFor, EvaluationAnswers, EvaluationEntry, EvaluationInvocationArgs, EvaluationInvocationResult, EvaluationProtocol, EvaluationQuestion, EvaluationQuestions, EvaluationRecord, EvaluationSpec, EventBase, Fact, FactRef, FileEntry, FixedMemoryStoreRef, FixedModelGatewayRef, FoldFn, GateEvidence, GateResult, GateVerdict, GatewayCancelRequest, GatewayConfigEgressBinding, GatewayContext, GatewayCredentialSlotSetup, GatewayDefinition, GatewayDiscoverySetup, GatewayModelOffer, GatewayOperation, GatewayPackage, GatewayPackageMetadata, GatewayRecoveryRequest, GatewayRecoveryResult, GatewayRequest, GovernanceContractRef, Handle, HandleOutcome, Hash, HistoryView, HmacVerification, IgnoredChannelEvent, IngressRequest, IngressTarget, IntegrationArtifactEgressRequest, IntegrationArtifactEgressResponse, IntegrationAttachment, IntegrationContext, IntegrationEgressPolicy, IntegrationEgressRequest, IntegrationEgressResponse, IntegrationEgressRule, IntegrationLifecycle, IntegrationReleaseContext, IntegrationSecret, IntegrationState, InvocationCredentialUse, InvocationHandle, InvokableKind, InvokeOpts, JoinOutcome, JsonScalar, JsonValue, LabelRequest, LabelSelector, LabelSelectorOperator, LabelSelectorRequirement, LedgerAddress, LedgerAddressParts, LedgerEvent, ListSchedulesOptions, LoadedSkill, LocalResourceRef, ManifestIndexPage, MapFact, MapOpts, McpClientOptions, McpClientState, McpMessageTransport, MemoryDeleteArgs, MemoryGetArgs, MemoryRecord, MemoryRememberArgs, MemorySearchArgs, MemorySearchHit, MemoryStoreBinding, Mode, ModelAdvertisedPricing, ModelCompletion, ModelCredentialHeader, ModelGatewayBinding, ModelGatewayConfig, ModelGatewayProtocol, ModelGenerationOptions, ModelGovernanceControls, ModelGovernanceMeter, ModelHistoryMessage, ModelInvocationArgs, ModelInvocationResult, ModelTechnicalCapabilities, ModelTool, NormalizedModelGatewayConfig, NoulAnswer, NoulQuestion, Out, Over, PartitionFn, PartitionSpec, Partitioning, PolicyCRN, PolicyConstraint, PolicyContextValue, PolicyDefinition, PolicyInput, PolicyInvocationOrigin, PolicyOutcome, Principal, PrincipalKind, Provenance, RawModelProtocol, Recovery, ReduceFact, ReduceOpts, Ref, RequestLabelRequest, ResourceContractRef, ResourceControlsConstraint, ResourceCredentialBinding, ResourceDependencyRef, ResourceKind, ResourceName, ResourceNameParts, ResourceNeed, ResourcePattern, ResourceSelector, RollbackReport, RunIdentityView, RunInfo, RunReport, RunStatusDetail, RunSuiteRequest, Sandbox, SandboxCommandCollectionError, SandboxCommandExecution, SandboxCommandResult, SandboxExecInput, SandboxFileResult, SandboxGovernanceControls, SandboxGovernanceMeter, SandboxImage, SandboxMutationResult, SandboxNetworkMode, SandboxNetworkPolicy, SandboxPool, SandboxProcess, SandboxProcessCredentials, SandboxProcessIoOperation, SandboxProcessOperation, SandboxProcessReadInput, SandboxProcessReadResult, SandboxProcessStatus, SandboxProcessWriteResult, SandboxReadFileOptions, SandboxReadFileResult, SandboxWorkspace, SandboxWriteFileResult, Schedule, ScheduleCancellation, ScheduleDuration, ScheduleMissed, ScheduleOccurrence, ScheduleOccurrencePage, ScheduleOptions, SchedulePage, ScheduleState, ScheduleTarget, ScheduleTiming, ScheduleTrigger, ScheduleWhen, ScopedBindingKey, ScopedCredentialRef, ScopedMemoryStoreRef, ScopedModelGatewayRef, ScopedResourceRef, ScoreAnswer, ScoreQuestion, ScoreRequest, ScorerApplies, ScorerCRN, ScorerDef, ScorerEvaluation, ScorerKind, ScorerRef, ScorerVerdictIntent, SetEvalBaselineRequest, SetupAction, SetupCredentialCandidate, SetupCredentialInteractionPanel, SetupCredentialReceipt, SetupFormPanel, SetupPanel, SetupProgressPanel, SetupReviewPanel, SetupScreen, SetupStepStatus, SetupStepSummary, SetupSubmission, SetupTerminalPanel, SetupWorkflowStatus, Skill, SkillDescription, SkillLibrary, SkillSource, SortField, SpawnAttenuation, SpawnBudget, SpawnHandle, SpawnOpts, SqlFold, StageInfo, StageOutputSpec, StartTrainingRequest, SteerEvent, SuiteFact, TableAggregate, TableDescribeArgs, TableFilter, TableFilterOperation, TableOrder, TableQueryArgs, TableQueryPlan, TableQueryResult, TableScalar, TableSnapshotDescription, Task, Tier, Tool, ToolCallRecord, TrainingJobFact, TrainingJobReference, TrainingJobState, TrainingJobStatus, TrainingMethod, TrainingModelOffer, TrainingProviderDefinition, TrainingProviderMetadata, TrainingProviderPin, TrainingRecipe, TrainingResumePoint, TrainingUsageUnits, TurnDraft, TurnGate, TurnRecord, TurnSpec, UiAccess, UiBundle, UiBundleManifest, UiCRN, UiCapability, UiExecution, UiGovernanceMeter, UiHandler, UiResource, UiRuntimeContext, UiSource, UiSqlResult, UiState, UpstreamPayer, Verdict, VerdictSamplingMode, ViewDef, WaitResolvedEvent };
4873
+ export { AGENT_UI_DEFAULTS, AfterYield, ApiError, CONSTAL_API_CAPABILITY, CONSTAL_API_GET_KINDS, CONSTAL_API_MODEL_TOOL_DESCRIPTIONS, CONSTAL_API_OPERATIONS, CONSTAL_API_OPERATION_SCHEMAS, CONSTAL_API_QUERY_KINDS, CONSTAL_API_VERSION, CommitConflict, CommitGateRejected, CredentialRevoked, CredentialUnavailable, DirectNetworkDenied, EVALUATION_LIMITS, EffectCeilingExceeded, EmptyJoin, GateExhausted, IntegrationRequestNotSent, LeaseLost, MCP_CLIENT_CAPABILITY, MCP_PROTOCOL_VERSION, MEMORY_OPERATION_DECLARATIONS, MODEL_CHECKPOINT_IMPORT_CAPABILITY, MODEL_COMPLETION_CAPABILITY, MODEL_EVALUATION_CAPABILITY, McpClient, NondeterministicReplay, OutcomeUnknown, PolicyConstraintFailed, PolicyDecisionFailed, RESOURCE_CREDENTIAL_BINDING_SCHEMA, RESOURCE_KINDS, ResourceDisabled, ResourceInvalid, ResourceUnbound, RollbackTargetInvalid, SANDBOX_EGRESS_LIMITS, SessionDeleted, SpawnCardinality, SwallowedYield, TRAINING_PROVIDER_CAPABILITY, TerminalIntegrationFailure, ToolUnavailable, UI_ASSET_CONTENT_TYPES, UI_BUNDLE_BOUNDS, UnknownTool, WEB_FETCH_ARGUMENT_SCHEMA, WEB_SEARCH_ARGUMENT_SCHEMA, action, actionPattern, agent, agentLimit, agentResourceBinding, agentSetupMetadata, agentSetupRequirements, agentUiBundleManifest, agentUiDeclaration, all, analyticsEvent, approximateTokens, authProvider, authProviderName, bindingName, bucketFor, canonicalJson, capabilityContractRef, casTool, channel, channelIngressRequest, channelIngressSource, channelSourceEvidence, channelSubscriptionRequest, channelTarget, checkpointArtifactRef, checkpointDeploymentRequest, checkpointImportMetadata, checkpointImportRequest, codeScorerIR, containerImageReference, containerImageSelection, containerImageSource, credentialEvidence, credentialInteractionAction, credentialInteractionEvent, credentialInteractionResult, credentialName, credentialProvider, credentialProviderConfigSchema, credentialProviderName, credentialProviderSetupMetadata, credentialRotationDefaults, credentialSetupState, customerTenantName, cutBatches, cutPartitions, datasetName, evaluateCodeScorer, evaluatePolicyDefinition, evaluationArguments, evaluationProtocolRequest, evaluationProtocolResult, formatLedgerAddress, gateway, gatewayModelOffer, gatewayPackageMetadata, hash, hashValue, immutableContainerImageReference, integrationEgressPolicy, invocationCredentialUses, labelSelector, matchesAction, matchesLabelSelector, matchesResource, mcpToolDescription, mcpToolResult, memoryStoreBinding, modelAdvertisedPricing, modelControls, modelGatewayBinding, modelGatewayEndpoint, modelGenerationOptions, modelLimit, modelMessages, modelPrompt, modelProtocolRequest, modelProtocolResult, murmur3_32, normalizeModelGatewayConfig, normalizeSandboxEgressCredentialRules, normalizeSandboxEgressPolicy, normalizeSandboxLabels, normalizeSandboxNetworkPolicy, normalizeSandboxWorkspacePath, noulDecision, opTool, opTools, parseLedgerAddress, parseResourceName, policy, policyName, race, renderTrainingCompletion, resolveBindingOwner, resolveContainerImageSource, resolveGatewayEgress, resolveResourceDependencyRef, resourceContractRef, resourceCredentialBinding, resourceDependencyRef, resourceLabelMap, resourceName, resourceNeed, resourcePattern, resourceSelector, resourceTools, sandboxControls, sandboxEgressDecision, sandboxEgressHostMatches, sandboxLimit, scopedBindingKey, scopedCredentialRef, scopedResourceRef, scoreLevel, scorerName, select, selectableResourceLabels, setupAwait, setupCredentialReceipt, setupPanelProviderIsCrn, setupScreen, setupScreenView, setupSubmission, sha256Hex, skills, stageOutput, startTrainingRequest, subtask, tableDescribe, tableQuery, trainingProvider, trainingProviderMetadata, trainingRecipe, uiAssetContentType, uiBundle, uiBundleManifest, uiLimit, uiName, validateBatchSpec, validateFoldFn, validateJsonSchema, validateJsonSchemaDefinition, validatePartitionFn, validatePartitionSpec, validateStageOutputSpec, validateTool, validateView, webFetch, webSearch };
4874
+ export type { Action, ActionPattern, Actor, AdmissionLimitConstraint, AdmissionLimitInput, AdmissionLimitScope, AdmissionLimitWindow, Agent, AgentCredentialSetupRequirement, AgentDef, AgentDeployPolicy, AgentGovernanceMeter, AgentSetupMetadata, AgentSetupRequirement, AgentSetupWorkflow, AgentUiDeclaration, AnalyticsClient, AnalyticsDimensionValue, AnalyticsEventDefinition, AnalyticsIntent, AnalyticsValues, AuthProvider, AuthProviderCRN, AuthProviderContext, AuthProviderRequest, AuthProviderResult, AwaitOpts, AwaitPresentation, BatchSpec, BindingCRN, BindingOwnerContext, BindingOwnerScope, BoundOperation, BoundResourceCapabilities, BranchRef, CRN, CRNKind, CanonicalEvent, CanonicalEventDraft, CapabilityContractRef, CapabilityGrant, CapabilityRef, CaptureCaseRequest, CaseRow, CatalogTool, Channel, ChannelContext, ChannelDeliveryError, ChannelDeliveryEvent, ChannelDeliveryOutcome, ChannelDeliveryReport, ChannelFailure, ChannelIngressEvent, ChannelIngressSource, ChannelMessage, ChannelProtocol, ChannelReceiveResult, ChannelRequest, ChannelResponse, ChannelSourceEvidence, ChannelSubscriptionRequest, ChannelTarget, CheckpointDeploymentRequest, CheckpointImportMetadata, CheckpointImportRequest, ChoiceAnswer, ChoiceQuestion, CodeScoreResult, CodeScorerIR, CodeScorerRule, CommitOpts, CompareSuitesRequest, Compensation, ConnectionCancelRequest, ConnectionIdentity, ConnectionOperation, ConnectionRecoveryRequest, ConnectionRecoveryResult, ConnectionRequest, ConnectionUsageReport, ConstalApiApplyRequest, ConstalApiChangePlan, ConstalApiChangePlanRef, ConstalApiChangePlanRequest, ConstalApiChangeReceipt, ConstalApiOperationReceipt, ContainerImageReference, ContainerImageSelection, ContainerImageSource, ContainerRegistryRequest, ContainerRegistryResponse, ControlEvent, Cost, CreateSandboxImageOptions, CreateSandboxOptions, CredentialCRN, CredentialDestroyResult, CredentialEvidence, CredentialInteractionAction, CredentialInteractionAdvanceRequest, CredentialInteractionEvent, CredentialInteractionPrimaryAction, CredentialInteractionProof, CredentialInteractionResult, CredentialInteractionStartRequest, CredentialMaterialRequest, CredentialMintRequest, CredentialMintResult, CredentialProviderCRN, CredentialProviderContext, CredentialProviderCredentialSlotSetup, CredentialProviderDefinition, CredentialProviderPackage, CredentialProviderPackageMetadata, CredentialProviderSecretInput, CredentialProviderSetupMetadata, CredentialSetupState, CredentialUninstallRequest, CredentialUninstallResult, CredentialVerifyResult, Ctx, CustomerTenantCRN, DataManifest, DatasetCRN, DatasetDraft, DatasetRef, DelegatedGrant, DelegationCeiling, DeliveryMode, DeliveryReceipt, DispatchResult, EffectClass, EvalComparison, EvalDivergence, EvalMode, EvalSubject, EvalSubjectSource, EvaluationAnswer, EvaluationAnswerFor, EvaluationAnswers, EvaluationEntry, EvaluationInvocationArgs, EvaluationInvocationResult, EvaluationProtocol, EvaluationQuestion, EvaluationQuestions, EvaluationRecord, EvaluationSpec, EventBase, Fact, FactRef, FileEntry, FixedMemoryStoreRef, FixedModelGatewayRef, FoldFn, GateEvidence, GateResult, GateVerdict, GatewayCancelRequest, GatewayConfigEgressBinding, GatewayContext, GatewayCredentialSlotSetup, GatewayDefinition, GatewayDiscoverySetup, GatewayModelOffer, GatewayOperation, GatewayPackage, GatewayPackageMetadata, GatewayRecoveryRequest, GatewayRecoveryResult, GatewayRequest, GovernanceContractRef, Handle, HandleOutcome, Hash, HistoryView, HmacVerification, IgnoredChannelEvent, IngressRequest, IngressTarget, IntegrationArtifactEgressRequest, IntegrationArtifactEgressResponse, IntegrationAttachment, IntegrationContext, IntegrationEgressPolicy, IntegrationEgressRequest, IntegrationEgressResponse, IntegrationEgressRule, IntegrationLifecycle, IntegrationReleaseContext, IntegrationSecret, IntegrationState, InvocationCredentialUse, InvocationHandle, InvokableKind, InvokeOpts, JoinOutcome, JsonScalar, JsonValue, LabelRequest, LabelSelector, LabelSelectorOperator, LabelSelectorRequirement, LedgerAddress, LedgerAddressParts, LedgerEvent, ListSchedulesOptions, LoadedSkill, LocalResourceRef, ManifestIndexPage, MapFact, MapOpts, McpClientOptions, McpClientState, McpMessageTransport, MemoryDeleteArgs, MemoryGetArgs, MemoryRecord, MemoryRememberArgs, MemorySearchArgs, MemorySearchHit, MemoryStoreBinding, Mode, ModelAdvertisedPricing, ModelCacheHint, ModelCompletion, ModelCredentialHeader, ModelGatewayBinding, ModelGatewayConfig, ModelGatewayProtocol, ModelGenerationOptions, ModelGovernanceControls, ModelGovernanceMeter, ModelHistoryMessage, ModelHistoryToolCall, ModelInvocationArgs, ModelInvocationResult, ModelProtocolRequestOptions, ModelTechnicalCapabilities, ModelTool, NormalizedModelGatewayConfig, NoulAnswer, NoulQuestion, Out, Over, PartitionFn, PartitionSpec, Partitioning, PolicyCRN, PolicyConstraint, PolicyContextValue, PolicyDefinition, PolicyInput, PolicyInvocationOrigin, PolicyOutcome, Principal, PrincipalKind, Provenance, RawModelProtocol, Recovery, ReduceFact, ReduceOpts, Ref, RequestLabelRequest, ResourceContractRef, ResourceControlsConstraint, ResourceCredentialBinding, ResourceDependencyRef, ResourceKind, ResourceName, ResourceNameParts, ResourceNeed, ResourcePattern, ResourceSelector, RollbackReport, RunIdentityView, RunInfo, RunReport, RunStatusDetail, RunSuiteRequest, Sandbox, SandboxCommandCollectionError, SandboxCommandExecution, SandboxCommandResult, SandboxEgressCredentialRule, SandboxEgressPolicy, SandboxEgressRule, SandboxExecInput, SandboxFileResult, SandboxGovernanceControls, SandboxGovernanceMeter, SandboxImage, SandboxLabels, SandboxMutationResult, SandboxNetworkMode, SandboxNetworkPolicy, SandboxPool, SandboxProcess, SandboxProcessCredentials, SandboxProcessIoOperation, SandboxProcessOperation, SandboxProcessReadInput, SandboxProcessReadResult, SandboxProcessStatus, SandboxProcessWriteResult, SandboxReadFileOptions, SandboxReadFileResult, SandboxWorkspace, SandboxWriteFileResult, Schedule, ScheduleCancellation, ScheduleDuration, ScheduleMissed, ScheduleOccurrence, ScheduleOccurrencePage, ScheduleOptions, SchedulePage, ScheduleState, ScheduleTarget, ScheduleTiming, ScheduleTrigger, ScheduleWhen, ScopedBindingKey, ScopedCredentialRef, ScopedMemoryStoreRef, ScopedModelGatewayRef, ScopedResourceRef, ScoreAnswer, ScoreQuestion, ScoreRequest, ScorerApplies, ScorerCRN, ScorerDef, ScorerEvaluation, ScorerKind, ScorerRef, ScorerVerdictIntent, SetEvalBaselineRequest, SetupAction, SetupCredentialCandidate, SetupCredentialInteractionPanel, SetupCredentialReceipt, SetupFormPanel, SetupPanel, SetupProgressPanel, SetupReviewPanel, SetupScreen, SetupStepStatus, SetupStepSummary, SetupSubmission, SetupTerminalPanel, SetupWorkflowStatus, Skill, SkillDescription, SkillLibrary, SkillSource, SortField, SpawnAttenuation, SpawnBudget, SpawnHandle, SpawnOpts, SqlFold, StageInfo, StageOutputSpec, StartTrainingRequest, SteerEvent, SuiteFact, TableAggregate, TableDescribeArgs, TableFilter, TableFilterOperation, TableOrder, TableQueryArgs, TableQueryPlan, TableQueryResult, TableScalar, TableSnapshotDescription, Task, Tier, Tool, ToolCallRecord, TrainingJobFact, TrainingJobReference, TrainingJobState, TrainingJobStatus, TrainingMethod, TrainingModelOffer, TrainingProviderDefinition, TrainingProviderMetadata, TrainingProviderPin, TrainingRecipe, TrainingResumePoint, TrainingUsageUnits, TurnDraft, TurnGate, TurnHistoryMessage, TurnRecord, TurnSpec, UiAccess, UiBundle, UiBundleManifest, UiCRN, UiCapability, UiExecution, UiGovernanceMeter, UiHandler, UiResource, UiRuntimeContext, UiSource, UiSqlResult, UiState, UpstreamPayer, Verdict, VerdictSamplingMode, ViewDef, WaitResolvedEvent };
package/publish/index.js CHANGED
@@ -891,7 +891,7 @@ function invocationCredentialUses(value) {
891
891
  const result = {};
892
892
  for (const [slot, raw] of Object.entries(source).sort(([left], [right]) => left.localeCompare(right))) {
893
893
  const use = record2(raw), consumer = record2(use?.consumer);
894
- if (!NAME2.test(slot) || !use || Object.keys(use).some((key) => key !== "binding" && key !== "consumer") || !consumer || Object.keys(consumer).some((key) => !["kind", "delivery", "name"].includes(key)) || consumer.kind !== "process" || consumer.delivery !== "env" && consumer.delivery !== "file" || typeof consumer.name !== "string" || !consumer.name || consumer.name.includes("=") || /[\u0000-\u001f\u007f]/u.test(consumer.name)) throw new TypeError("invocation Credential selection is invalid");
894
+ if (!NAME2.test(slot) || !use || Object.keys(use).some((key) => key !== "binding" && key !== "consumer") || !consumer || Object.keys(consumer).some((key) => !["kind", "delivery", "name"].includes(key)) || !(consumer.kind === "process" && (consumer.delivery === "env" || consumer.delivery === "file") || consumer.kind === "egress" && consumer.delivery === "header") || typeof consumer.name !== "string" || !consumer.name || consumer.name.includes("=") || /[\u0000-\u001f\u007f]/u.test(consumer.name)) throw new TypeError("invocation Credential selection is invalid");
895
895
  result[slot] = { binding: resourceCredentialBinding(use.binding), consumer };
896
896
  }
897
897
  return result;
@@ -1096,6 +1096,9 @@ function normalizeCidrs(values, allowPrivate) {
1096
1096
  }
1097
1097
  return result.map((entry2) => entry2.text);
1098
1098
  }
1099
+ function normalizeSandboxDomains(values) {
1100
+ return normalizeDomains(values);
1101
+ }
1099
1102
  function normalizeDomains(values) {
1100
1103
  if (!Array.isArray(values) || values.length === 0) throw new TypeError("sandbox network domains must contain at least one entry");
1101
1104
  const domains = values.map((raw) => {
@@ -2667,16 +2670,19 @@ var MEMORY_OPERATION_DECLARATIONS = [
2667
2670
 
2668
2671
  // packages/sdk/src/integration.ts
2669
2672
  var ApiError = class extends Error {
2670
- constructor(status, body, disposition = "uncertain") {
2673
+ /** `retryAfterMs`: the interval the remote API stated, such as its `retry-after`; absent when it stated none. */
2674
+ constructor(status, body, disposition = "uncertain", retryAfterMs) {
2671
2675
  super(`${status}: ${body}`);
2672
2676
  this.status = status;
2673
2677
  this.body = body;
2674
2678
  this.disposition = disposition;
2679
+ this.retryAfterMs = retryAfterMs;
2675
2680
  this.name = "ApiError";
2676
2681
  }
2677
2682
  status;
2678
2683
  body;
2679
2684
  disposition;
2685
+ retryAfterMs;
2680
2686
  };
2681
2687
  var IntegrationRequestNotSent = class extends Error {
2682
2688
  constructor(message2 = "integration request was not sent") {
@@ -2848,6 +2854,93 @@ async function resolveContainerImageSource(reference, platform, request, authori
2848
2854
  });
2849
2855
  }
2850
2856
 
2857
+ // packages/sdk/src/sandbox-egress.ts
2858
+ var SANDBOX_EGRESS_LIMITS = { rules: 64, credentialRules: 16, hostsPerRule: 32, labels: 16, labelValueLength: 256 };
2859
+ var HEADER = /^[a-z0-9!#$%&'*+.^_`|~-]{1,64}$/u;
2860
+ var RESERVED_HEADERS = /* @__PURE__ */ new Set([
2861
+ "connection",
2862
+ "content-length",
2863
+ "host",
2864
+ "keep-alive",
2865
+ "proxy-connection",
2866
+ "te",
2867
+ "trailer",
2868
+ "transfer-encoding",
2869
+ "upgrade"
2870
+ ]);
2871
+ var SLOT = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;
2872
+ var USE = /^egress-(?:0|[1-9][0-9]?)$/u;
2873
+ var LABEL = /^[a-z0-9][a-z0-9._-]{0,62}$/u;
2874
+ function object4(value) {
2875
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
2876
+ }
2877
+ function sandboxEgressHostMatches(pattern, hostname) {
2878
+ const host2 = hostname.toLowerCase().replace(/\.$/u, "");
2879
+ return pattern.startsWith("*.") ? host2 === pattern.slice(2) || host2.endsWith(pattern.slice(1)) : host2 === pattern;
2880
+ }
2881
+ function host(value) {
2882
+ const [normalized] = normalizeSandboxDomains([value]);
2883
+ return normalized;
2884
+ }
2885
+ function normalizeSandboxEgressPolicy(value) {
2886
+ const input = object4(value);
2887
+ 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") {
2888
+ throw new TypeError("sandbox egress policy is invalid");
2889
+ }
2890
+ const rules = input.rules.map((raw) => {
2891
+ const rule = object4(raw);
2892
+ if (!rule || Object.keys(rule).some((key) => key !== "action" && key !== "host") || rule.action !== "allow" && rule.action !== "deny") {
2893
+ throw new TypeError("sandbox egress rule is invalid");
2894
+ }
2895
+ return { action: rule.action, host: host(rule.host) };
2896
+ });
2897
+ return { rules, default: input.default === "allow" ? "allow" : "deny" };
2898
+ }
2899
+ function sandboxEgressDecision(policy2, hostname) {
2900
+ if (!policy2) return { allowed: true, rule: "pool" };
2901
+ const index = policy2.rules.findIndex((rule) => sandboxEgressHostMatches(rule.host, hostname));
2902
+ if (index < 0) return { allowed: policy2.default === "allow", rule: "sandbox:default" };
2903
+ return { allowed: policy2.rules[index].action === "allow", rule: `sandbox:${index}` };
2904
+ }
2905
+ function normalizeSandboxEgressCredentialRules(value, options = {}) {
2906
+ if (value === void 0) return [];
2907
+ if (!Array.isArray(value) || value.length > SANDBOX_EGRESS_LIMITS.credentialRules) throw new TypeError("sandbox egress Credential rules are invalid");
2908
+ return value.map((raw) => {
2909
+ const rule = object4(raw);
2910
+ const allowed = ["hosts", "slot", "header", "value", "basic", ...options.bindings ? ["binding"] : [], ...options.uses ? ["use"] : []];
2911
+ if (!rule || Object.keys(rule).some((key) => !allowed.includes(key)) || !Array.isArray(rule.hosts) || rule.hosts.length === 0 || rule.hosts.length > SANDBOX_EGRESS_LIMITS.hostsPerRule) throw new TypeError("sandbox egress Credential rule is invalid");
2912
+ const sources = [rule.slot, rule.binding, rule.use].filter((source) => source !== void 0);
2913
+ if (sources.length !== 1 || rule.slot !== void 0 && (typeof rule.slot !== "string" || !SLOT.test(rule.slot)) || rule.use !== void 0 && (typeof rule.use !== "string" || !USE.test(rule.use))) {
2914
+ throw new TypeError("sandbox egress Credential rule names exactly one slot or binding");
2915
+ }
2916
+ const header = rule.header === void 0 ? "authorization" : rule.header;
2917
+ if (typeof header !== "string" || !HEADER.test(header.toLowerCase()) || RESERVED_HEADERS.has(header.toLowerCase()) || header.toLowerCase().startsWith("x-constal-")) throw new TypeError("sandbox egress Credential header is invalid");
2918
+ if (rule.value !== void 0 && rule.basic !== void 0) throw new TypeError("sandbox egress Credential rule takes value or basic, not both");
2919
+ if (rule.value !== void 0 && (typeof rule.value !== "string" || rule.value.length > 256 || /[\r\n\0]/u.test(rule.value) || rule.value.split("{value}").length !== 2)) throw new TypeError("sandbox egress Credential value must contain {value} exactly once");
2920
+ const basic = rule.basic === void 0 ? void 0 : object4(rule.basic);
2921
+ if (rule.basic !== void 0 && (!basic || Object.keys(basic).some((key) => key !== "username") || basic.username !== void 0 && (typeof basic.username !== "string" || !basic.username || basic.username.length > 128 || /[:\r\n\0]/u.test(basic.username)))) throw new TypeError("sandbox egress Credential basic auth is invalid");
2922
+ return {
2923
+ hosts: normalizeSandboxDomains(rule.hosts),
2924
+ ...rule.slot !== void 0 ? { slot: rule.slot } : {},
2925
+ ...rule.binding !== void 0 ? { binding: resourceCredentialBinding(rule.binding) } : {},
2926
+ ...rule.use !== void 0 ? { use: rule.use } : {},
2927
+ header: header.toLowerCase(),
2928
+ ...basic ? { basic: basic.username === void 0 ? {} : { username: basic.username } } : { value: rule.value ?? "Bearer {value}" }
2929
+ };
2930
+ });
2931
+ }
2932
+ function normalizeSandboxLabels(value) {
2933
+ if (value === void 0) return {};
2934
+ const input = object4(value);
2935
+ if (!input || Object.keys(input).length > SANDBOX_EGRESS_LIMITS.labels) throw new TypeError("sandbox labels are invalid");
2936
+ const labels = {};
2937
+ for (const [key, label] of Object.entries(input).sort(([left], [right]) => left.localeCompare(right))) {
2938
+ 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");
2939
+ labels[key] = label;
2940
+ }
2941
+ return labels;
2942
+ }
2943
+
2851
2944
  // packages/sdk/src/sandbox-pool.ts
2852
2945
  var WORKSPACE_ROOT = "/workspace";
2853
2946
  function absoluteSandboxPath(value) {
@@ -3050,15 +3143,15 @@ function modelGenerationOptions(source) {
3050
3143
  };
3051
3144
  }
3052
3145
  var NAME4 = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
3053
- var HEADER = /^[a-z0-9][a-z0-9-]{0,63}$/u;
3054
- var RESERVED_HEADERS = /* @__PURE__ */ new Set(["connection", "content-type", "host", "anthropic-version", "proxy-authorization", "transfer-encoding"]);
3146
+ var HEADER2 = /^[a-z0-9][a-z0-9-]{0,63}$/u;
3147
+ var RESERVED_HEADERS2 = /* @__PURE__ */ new Set(["connection", "content-type", "host", "anthropic-version", "proxy-authorization", "transfer-encoding"]);
3055
3148
  function record7(value) {
3056
3149
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
3057
3150
  }
3058
3151
  function credentialHeader(value, name) {
3059
3152
  if (value === null || value === void 0) return null;
3060
3153
  const source = record7(value);
3061
- if (!source || typeof source.slot !== "string" || !NAME4.test(source.slot) || typeof source.header !== "string" || !HEADER.test(source.header.toLowerCase()) || RESERVED_HEADERS.has(source.header.toLowerCase()) || source.header.toLowerCase().startsWith("cf-") || source.scheme !== "bearer" && source.scheme !== "raw") throw new TypeError(`${name} is invalid`);
3154
+ if (!source || typeof source.slot !== "string" || !NAME4.test(source.slot) || typeof source.header !== "string" || !HEADER2.test(source.header.toLowerCase()) || RESERVED_HEADERS2.has(source.header.toLowerCase()) || source.header.toLowerCase().startsWith("cf-") || source.scheme !== "bearer" && source.scheme !== "raw") throw new TypeError(`${name} is invalid`);
3062
3155
  return { slot: source.slot, header: source.header.toLowerCase(), scheme: source.scheme };
3063
3156
  }
3064
3157
  function normalizeModelGatewayConfig(value) {
@@ -3108,42 +3201,141 @@ function modelGatewayEndpoint(config) {
3108
3201
  endpoint.pathname = `${endpoint.pathname.replace(/\/+$/u, "")}/${suffix}`.replace(/^\/+/u, "/");
3109
3202
  return endpoint;
3110
3203
  }
3111
- function modelPrompt(args) {
3112
- return canonicalJson({ objective: args.objective ?? null, context: args.context ?? null, feedback: args.feedback ?? [] });
3204
+ var CACHE_HINT_FIELDS = ["key", "retention", "ttl"];
3205
+ function nonempty(value) {
3206
+ return typeof value === "string" && value.trim().length > 0;
3113
3207
  }
3114
- function modelHistory(args) {
3115
- const history = args.history ?? [];
3116
- if (!Array.isArray(history)) throw new TypeError("model history must be an array of messages");
3117
- return history.map((message2) => {
3118
- const source = record7(message2);
3119
- if (!source || source.role !== "user" && source.role !== "assistant" || typeof source.content !== "string") {
3120
- throw new TypeError("model history messages need a user or assistant role and text content");
3208
+ function modelCacheHint(value) {
3209
+ if (value === void 0) return void 0;
3210
+ const source = record7(value);
3211
+ if (!source) throw new TypeError("model cache hint must be an object");
3212
+ const unknown = Object.keys(source).find((key) => !CACHE_HINT_FIELDS.includes(key));
3213
+ if (unknown !== void 0) throw new TypeError(`model cache hint has an unknown field: ${unknown}`);
3214
+ const hint = {};
3215
+ for (const field2 of CACHE_HINT_FIELDS) {
3216
+ const candidate = source[field2];
3217
+ if (candidate === void 0) continue;
3218
+ if (!nonempty(candidate)) throw new TypeError(`model cache hint ${field2} must be a nonempty string`);
3219
+ hint[field2] = candidate;
3220
+ }
3221
+ return hint;
3222
+ }
3223
+ function modelHistoryMessages(value) {
3224
+ if (value === void 0) return [];
3225
+ if (!Array.isArray(value)) throw new TypeError("model history must be an array of messages");
3226
+ const ids = /* @__PURE__ */ new Set();
3227
+ const unanswered = /* @__PURE__ */ new Set();
3228
+ const messages = value.map((candidate, index) => {
3229
+ const at = `model history message ${index}`;
3230
+ const source = record7(candidate);
3231
+ if (!source || typeof source.content !== "string" || source.role !== "user" && source.role !== "assistant" && source.role !== "tool") {
3232
+ throw new TypeError(`${at} needs a user, assistant or tool role and text content`);
3121
3233
  }
3122
- return { role: source.role, content: source.content };
3234
+ const foreign = source.role === "tool" ? ["toolCalls"] : source.role === "user" ? ["toolCalls", "toolCallId", "isError"] : ["toolCallId", "isError"];
3235
+ const misplaced = foreign.find((field2) => source[field2] !== void 0);
3236
+ if (misplaced !== void 0) throw new TypeError(`${at} has the ${source.role} role, which cannot carry ${misplaced}`);
3237
+ if (source.role === "tool") {
3238
+ if (!nonempty(source.toolCallId)) throw new TypeError(`${at} needs the toolCallId of the Tool call it answers`);
3239
+ if (!unanswered.delete(source.toolCallId)) {
3240
+ throw new TypeError(`${at} answers Tool call ${source.toolCallId}, which is not an unanswered call of the assistant message before it`);
3241
+ }
3242
+ if (source.isError !== void 0 && typeof source.isError !== "boolean") throw new TypeError(`${at} isError must be a boolean`);
3243
+ return {
3244
+ role: "tool",
3245
+ toolCallId: source.toolCallId,
3246
+ content: source.content,
3247
+ ...source.isError === void 0 ? {} : { isError: source.isError }
3248
+ };
3249
+ }
3250
+ const open2 = unanswered.values().next();
3251
+ if (!open2.done) throw new TypeError(`model history Tool call ${open2.value} has no tool message answering it before message ${index}`);
3252
+ if (source.role === "user" || source.toolCalls === void 0) return { role: source.role, content: source.content };
3253
+ if (!Array.isArray(source.toolCalls)) throw new TypeError(`${at} toolCalls must be an array`);
3254
+ const toolCalls = source.toolCalls.map((call, position) => {
3255
+ const entry2 = record7(call);
3256
+ if (!entry2 || !nonempty(entry2.id) || !nonempty(entry2.name)) throw new TypeError(`${at} Tool call ${position} needs an id and a name`);
3257
+ if (ids.has(entry2.id)) throw new TypeError(`${at} repeats Tool call id ${entry2.id}`);
3258
+ try {
3259
+ canonicalJson(entry2.args);
3260
+ } catch {
3261
+ throw new TypeError(`${at} Tool call ${entry2.id} args must be a JSON value`);
3262
+ }
3263
+ ids.add(entry2.id);
3264
+ unanswered.add(entry2.id);
3265
+ return { id: entry2.id, name: entry2.name, args: entry2.args };
3266
+ });
3267
+ return { role: "assistant", content: source.content, ...toolCalls.length ? { toolCalls } : {} };
3123
3268
  });
3269
+ const open = unanswered.values().next();
3270
+ if (!open.done) throw new TypeError(`model history Tool call ${open.value} has no tool message answering it`);
3271
+ return messages;
3124
3272
  }
3125
- function modelMessages(args) {
3126
- const history = modelHistory(args);
3127
- if (!history.length) return [{ role: "user", content: modelPrompt(args) }];
3273
+ function modelPrompt(args) {
3274
+ return canonicalJson({ objective: args.objective ?? null, context: args.context ?? null, feedback: args.feedback ?? [] });
3275
+ }
3276
+ function turnMessages(args) {
3277
+ const history = modelHistoryMessages(args.history);
3278
+ if (!history.length) return { messages: [{ role: "user", content: modelPrompt(args) }], lastHistory: null };
3128
3279
  const feedback = args.feedback ?? [];
3129
- return [
3130
- { role: "user", content: canonicalJson({ objective: args.objective ?? null, context: args.context ?? null }) },
3131
- ...history,
3132
- ...feedback.length ? [{ role: "user", content: canonicalJson({ feedback }) }] : []
3133
- ];
3280
+ const prompt = args.objective == null && args.context == null && history[0].role === "user" ? [] : [{ role: "user", content: canonicalJson({ objective: args.objective ?? null, context: args.context ?? null }) }];
3281
+ return {
3282
+ messages: [...prompt, ...history, ...feedback.length ? [{ role: "user", content: canonicalJson({ feedback }) }] : []],
3283
+ lastHistory: prompt.length + history.length - 1
3284
+ };
3285
+ }
3286
+ function modelMessages(args) {
3287
+ return turnMessages(args).messages;
3288
+ }
3289
+ function anthropicBlocks(content2) {
3290
+ return typeof content2 !== "string" ? content2 : content2 ? [{ type: "text", text: content2 }] : [];
3291
+ }
3292
+ function anthropicMessage(message2) {
3293
+ if (message2.role === "tool") return { role: "user", content: [{
3294
+ type: "tool_result",
3295
+ tool_use_id: message2.toolCallId,
3296
+ content: message2.content,
3297
+ ...message2.isError ? { is_error: true } : {}
3298
+ }] };
3299
+ if (message2.role === "assistant" && message2.toolCalls) return { role: "assistant", content: [
3300
+ ...anthropicBlocks(message2.content),
3301
+ ...message2.toolCalls.map((call) => {
3302
+ const args = JSON.parse(canonicalJson(call.args));
3303
+ return { type: "tool_use", id: call.id, name: call.name, input: record7(args) ?? { value: args } };
3304
+ })
3305
+ ] };
3306
+ return { role: message2.role, content: message2.content };
3134
3307
  }
3135
3308
  function alternating(messages) {
3136
3309
  const merged = [];
3137
3310
  for (const message2 of messages) {
3138
3311
  const last = merged.at(-1);
3139
- if (last && last.role === message2.role) last.content = `${last.content}
3312
+ if (!last || last.role !== message2.role) merged.push({ ...message2 });
3313
+ else if (typeof last.content === "string" && typeof message2.content === "string") last.content = `${last.content}
3140
3314
 
3141
3315
  ${message2.content}`;
3142
- else merged.push({ ...message2 });
3316
+ else last.content = [...anthropicBlocks(last.content), ...anthropicBlocks(message2.content)];
3143
3317
  }
3144
3318
  return merged;
3145
3319
  }
3146
- function modelProtocolRequest(protocol, model, maxOutputTokens, temperature, args) {
3320
+ function openAiMessage(message2, options) {
3321
+ if (message2.role === "tool") return {
3322
+ role: "tool",
3323
+ tool_call_id: message2.toolCallId,
3324
+ content: message2.content,
3325
+ ...options.toolErrorName && message2.isError ? { name: "tool_error" } : {}
3326
+ };
3327
+ if (message2.role === "assistant" && message2.toolCalls) return {
3328
+ role: "assistant",
3329
+ content: message2.content || null,
3330
+ tool_calls: message2.toolCalls.map((call) => ({
3331
+ id: call.id,
3332
+ type: "function",
3333
+ function: { name: call.name, arguments: canonicalJson(call.args) }
3334
+ }))
3335
+ };
3336
+ return { role: message2.role, content: message2.content };
3337
+ }
3338
+ function modelProtocolRequest(protocol, model, maxOutputTokens, temperature, args, options = {}) {
3147
3339
  const { effort } = modelGenerationOptions(args);
3148
3340
  if (args.toolChoice !== void 0 && args.toolChoice !== "auto" && args.toolChoice !== "required") {
3149
3341
  throw new TypeError("model Tool choice is invalid");
@@ -3151,37 +3343,66 @@ function modelProtocolRequest(protocol, model, maxOutputTokens, temperature, arg
3151
3343
  if (args.toolChoice === "required" && !args.tools?.length) {
3152
3344
  throw new TypeError("required model Tool choice needs at least one offered Tool");
3153
3345
  }
3154
- const messages = modelMessages(args);
3155
- if (protocol === "anthropic") return {
3156
- model,
3157
- system: args.system ?? "",
3158
- messages: alternating(messages),
3159
- ...maxOutputTokens === null ? {} : { max_tokens: maxOutputTokens },
3160
- ...effort === void 0 ? {} : { output_config: { effort } },
3161
- ...temperature === null ? {} : { temperature },
3162
- ...args.tools?.length ? { tools: args.tools.map((tool) => ({ name: tool.name, description: tool.description, input_schema: tool.schema })) } : {},
3163
- ...args.toolChoice === void 0 ? {} : { tool_choice: { type: args.toolChoice === "required" ? "any" : "auto" } }
3164
- };
3165
- if (protocol === "openai") return {
3166
- model,
3167
- messages: [
3168
- ...args.system ? [{ role: "developer", content: args.system }] : [],
3169
- ...messages
3170
- ],
3171
- ...maxOutputTokens === null ? {} : { max_completion_tokens: maxOutputTokens },
3172
- ...effort === void 0 ? {} : { reasoning_effort: effort },
3173
- ...temperature === null ? {} : { temperature },
3174
- ...args.tools?.length ? { tools: args.tools.map((tool) => ({
3175
- type: "function",
3176
- function: { name: tool.name, description: tool.description, parameters: tool.schema }
3177
- })) } : {},
3178
- ...args.toolChoice === void 0 ? {} : { tool_choice: args.toolChoice }
3179
- };
3346
+ const cache = modelCacheHint(args.cache);
3347
+ const { messages, lastHistory } = turnMessages(args);
3348
+ const breakpoint = cache ? { type: "ephemeral", ...cache.ttl === void 0 ? {} : { ttl: cache.ttl } } : null;
3349
+ if (protocol === "anthropic") {
3350
+ const anthropic = messages.map(anthropicMessage);
3351
+ const marked = breakpoint && lastHistory !== null ? anthropicBlocks(anthropic[lastHistory].content) : [];
3352
+ if (breakpoint && lastHistory !== null && marked.length) {
3353
+ anthropic[lastHistory] = { ...anthropic[lastHistory], content: [...marked.slice(0, -1), { ...marked.at(-1), cache_control: breakpoint }] };
3354
+ }
3355
+ const tools = args.tools ?? [];
3356
+ return {
3357
+ model,
3358
+ system: breakpoint && args.system ? [{ type: "text", text: args.system, cache_control: breakpoint }] : args.system ?? "",
3359
+ messages: alternating(anthropic),
3360
+ ...maxOutputTokens === null ? {} : { max_tokens: maxOutputTokens },
3361
+ ...effort === void 0 ? {} : { output_config: { effort } },
3362
+ ...temperature === null ? {} : { temperature },
3363
+ ...tools.length ? { tools: tools.map((tool, index) => ({
3364
+ name: tool.name,
3365
+ description: tool.description,
3366
+ input_schema: tool.schema,
3367
+ ...breakpoint && index === tools.length - 1 ? { cache_control: breakpoint } : {}
3368
+ })) } : {},
3369
+ ...args.toolChoice === void 0 ? {} : { tool_choice: { type: args.toolChoice === "required" ? "any" : "auto" } }
3370
+ };
3371
+ }
3372
+ if (protocol === "openai") {
3373
+ const marks = options.contentCacheControl === true ? breakpoint : null;
3374
+ const marked = (text2) => marks && text2 ? [{ type: "text", text: text2, cache_control: marks }] : text2;
3375
+ const openai = messages.map((message2, index) => {
3376
+ const entry2 = openAiMessage(message2, options);
3377
+ return index === lastHistory && typeof entry2.content === "string" ? { ...entry2, content: marked(entry2.content) } : entry2;
3378
+ });
3379
+ return {
3380
+ model,
3381
+ messages: [
3382
+ ...args.system ? [{ role: "developer", content: marked(args.system) }] : [],
3383
+ ...openai
3384
+ ],
3385
+ ...maxOutputTokens === null ? {} : { max_completion_tokens: maxOutputTokens },
3386
+ ...effort === void 0 ? {} : { reasoning_effort: effort },
3387
+ ...temperature === null ? {} : { temperature },
3388
+ ...args.tools?.length ? { tools: args.tools.map((tool) => ({
3389
+ type: "function",
3390
+ function: { name: tool.name, description: tool.description, parameters: tool.schema }
3391
+ })) } : {},
3392
+ ...args.toolChoice === void 0 ? {} : { tool_choice: args.toolChoice },
3393
+ ...cache?.key === void 0 ? {} : { prompt_cache_key: cache.key },
3394
+ ...cache?.retention === void 0 ? {} : { prompt_cache_retention: cache.retention }
3395
+ };
3396
+ }
3180
3397
  throw new TypeError("model gateway protocol is invalid");
3181
3398
  }
3182
3399
  function integer2(value) {
3183
3400
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : 0;
3184
3401
  }
3402
+ function cacheWrite(usage) {
3403
+ const value = usage.cache_creation_input_tokens ?? record7(usage.prompt_tokens_details)?.cache_write_tokens;
3404
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? { cacheWrite: value } : {};
3405
+ }
3185
3406
  function costMetadata(usage) {
3186
3407
  const cost = usage.cost;
3187
3408
  const costUsd = cost === null ? null : typeof cost === "number" && Number.isFinite(cost) && cost >= 0 ? cost : void 0;
@@ -3217,6 +3438,7 @@ function modelProtocolResult(protocol, raw, provider, model) {
3217
3438
  input: integer2(values.input_tokens) + integer2(values.cache_creation_input_tokens) + cached,
3218
3439
  output: integer2(values.output_tokens),
3219
3440
  cached,
3441
+ ...cacheWrite(values),
3220
3442
  ...costMetadata(values)
3221
3443
  };
3222
3444
  } else if (protocol === "openai") {
@@ -3246,6 +3468,7 @@ function modelProtocolResult(protocol, raw, provider, model) {
3246
3468
  input: integer2(values.prompt_tokens),
3247
3469
  output: integer2(values.completion_tokens),
3248
3470
  cached: integer2(record7(values.prompt_tokens_details)?.cached_tokens),
3471
+ ...cacheWrite(values),
3249
3472
  ...costMetadata(values)
3250
3473
  };
3251
3474
  } else throw new TypeError("model gateway protocol is invalid");
@@ -3273,7 +3496,7 @@ function modelCompletionStatus(protocol, raw) {
3273
3496
  async function checkpointArtifactRef(value) {
3274
3497
  return await sha256Hex(canonicalJson(value));
3275
3498
  }
3276
- var SLOT = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
3499
+ var SLOT2 = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
3277
3500
  var HASH3 = /^[a-f0-9]{64}$/u;
3278
3501
  var MODEL_RESOURCE_ID = /^[a-z0-9][a-z0-9-]{0,62}$/u;
3279
3502
  function httpsUrl(value, field2) {
@@ -3293,7 +3516,7 @@ function slotMetadata(value) {
3293
3516
  const output = {};
3294
3517
  for (const [slot, raw] of entries) {
3295
3518
  const item = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : null;
3296
- if (!SLOT.test(slot) || !item || typeof item.title !== "string" || !item.title || item.description !== void 0 && typeof item.description !== "string" || item.required !== void 0 && typeof item.required !== "boolean" || item.provider !== void 0 && (typeof item.provider !== "string" || !SLOT.test(item.provider)) || Object.keys(item).some((key) => !["title", "description", "documentationUrl", "required", "provider"].includes(key))) {
3519
+ if (!SLOT2.test(slot) || !item || typeof item.title !== "string" || !item.title || item.description !== void 0 && typeof item.description !== "string" || item.required !== void 0 && typeof item.required !== "boolean" || item.provider !== void 0 && (typeof item.provider !== "string" || !SLOT2.test(item.provider)) || Object.keys(item).some((key) => !["title", "description", "documentationUrl", "required", "provider"].includes(key))) {
3297
3520
  throw new TypeError("Gateway Credential slots are invalid");
3298
3521
  }
3299
3522
  httpsUrl(item.documentationUrl, "Gateway Credential slot documentation URL");
@@ -3306,7 +3529,7 @@ function configEgressBindings(value) {
3306
3529
  if (!Array.isArray(value)) throw new TypeError("Gateway config egress bindings are invalid");
3307
3530
  return value.map((raw) => {
3308
3531
  const item = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : null;
3309
- if (!item || !SLOT.test(String(item.urlProperty ?? "")) || !Array.isArray(item.operations) || item.operations.length === 0 || item.operations.some((operation) => typeof operation !== "string" || operation !== "*" && !/^[A-Za-z][A-Za-z0-9._-]{0,127}$/u.test(operation)) || !Array.isArray(item.methods) || item.methods.length === 0 || item.methods.some((method) => typeof method !== "string" || !/^(?:GET|POST|PUT|PATCH|DELETE)$/u.test(method)) || Object.keys(item).some((key) => !["urlProperty", "operations", "methods"].includes(key))) {
3532
+ if (!item || !SLOT2.test(String(item.urlProperty ?? "")) || !Array.isArray(item.operations) || item.operations.length === 0 || item.operations.some((operation) => typeof operation !== "string" || operation !== "*" && !/^[A-Za-z][A-Za-z0-9._-]{0,127}$/u.test(operation)) || !Array.isArray(item.methods) || item.methods.length === 0 || item.methods.some((method) => typeof method !== "string" || !/^(?:GET|POST|PUT|PATCH|DELETE)$/u.test(method)) || Object.keys(item).some((key) => !["urlProperty", "operations", "methods"].includes(key))) {
3310
3533
  throw new TypeError("Gateway config egress bindings are invalid");
3311
3534
  }
3312
3535
  return {
@@ -3319,7 +3542,7 @@ function configEgressBindings(value) {
3319
3542
  function discoverySetup(value) {
3320
3543
  if (value === void 0) return void 0;
3321
3544
  const item = value && typeof value === "object" && !Array.isArray(value) ? value : null;
3322
- if (!item || !/^[A-Za-z][A-Za-z0-9._-]{0,127}$/u.test(String(item.operation ?? "")) || !SLOT.test(String(item.resultConfigProperty ?? "")) || Object.keys(item).some((key) => !["operation", "resultConfigProperty"].includes(key))) {
3545
+ if (!item || !/^[A-Za-z][A-Za-z0-9._-]{0,127}$/u.test(String(item.operation ?? "")) || !SLOT2.test(String(item.resultConfigProperty ?? "")) || Object.keys(item).some((key) => !["operation", "resultConfigProperty"].includes(key))) {
3323
3546
  throw new TypeError("Gateway discovery setup is invalid");
3324
3547
  }
3325
3548
  return { operation: String(item.operation), resultConfigProperty: String(item.resultConfigProperty) };
@@ -3384,7 +3607,7 @@ function gatewayModelOffer(value) {
3384
3607
  const modalities = (field2) => {
3385
3608
  const values = source[field2];
3386
3609
  if (values === void 0) return void 0;
3387
- if (!Array.isArray(values) || values.length === 0 || values.some((item) => typeof item !== "string" || !SLOT.test(item)) || new Set(values).size !== values.length) {
3610
+ if (!Array.isArray(values) || values.length === 0 || values.some((item) => typeof item !== "string" || !SLOT2.test(item)) || new Set(values).size !== values.length) {
3388
3611
  throw new TypeError("Gateway Model offer is invalid");
3389
3612
  }
3390
3613
  return values;
@@ -4478,6 +4701,7 @@ export {
4478
4701
  ResourceInvalid,
4479
4702
  ResourceUnbound,
4480
4703
  RollbackTargetInvalid,
4704
+ SANDBOX_EGRESS_LIMITS,
4481
4705
  SessionDeleted,
4482
4706
  SpawnCardinality,
4483
4707
  SwallowedYield,
@@ -4570,6 +4794,9 @@ export {
4570
4794
  modelProtocolResult,
4571
4795
  murmur3_32,
4572
4796
  normalizeModelGatewayConfig,
4797
+ normalizeSandboxEgressCredentialRules,
4798
+ normalizeSandboxEgressPolicy,
4799
+ normalizeSandboxLabels,
4573
4800
  normalizeSandboxNetworkPolicy,
4574
4801
  normalizeSandboxWorkspacePath,
4575
4802
  noulDecision,
@@ -4595,6 +4822,8 @@ export {
4595
4822
  resourceSelector,
4596
4823
  resourceTools,
4597
4824
  sandboxControls,
4825
+ sandboxEgressDecision,
4826
+ sandboxEgressHostMatches,
4598
4827
  sandboxLimit,
4599
4828
  scopedBindingKey,
4600
4829
  scopedCredentialRef,