@constal/sdk 5.0.0 → 5.3.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@constal/sdk",
3
- "version": "5.0.0",
3
+ "version": "5.3.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": "5.0.0",
3
+ "version": "5.3.0",
4
4
  "exports": [
5
5
  "AGENT_UI_DEFAULTS",
6
6
  "Action",
@@ -59,6 +59,10 @@
59
59
  "CatalogTool",
60
60
  "Channel",
61
61
  "ChannelContext",
62
+ "ChannelDeliveryError",
63
+ "ChannelDeliveryEvent",
64
+ "ChannelDeliveryOutcome",
65
+ "ChannelDeliveryReport",
62
66
  "ChannelFailure",
63
67
  "ChannelIngressEvent",
64
68
  "ChannelIngressSource",
@@ -250,6 +254,7 @@
250
254
  "MemoryStoreBinding",
251
255
  "Mode",
252
256
  "ModelAdvertisedPricing",
257
+ "ModelCacheHint",
253
258
  "ModelCompletion",
254
259
  "ModelCredentialHeader",
255
260
  "ModelGatewayBinding",
@@ -259,8 +264,10 @@
259
264
  "ModelGovernanceControls",
260
265
  "ModelGovernanceMeter",
261
266
  "ModelHistoryMessage",
267
+ "ModelHistoryToolCall",
262
268
  "ModelInvocationArgs",
263
269
  "ModelInvocationResult",
270
+ "ModelProtocolRequestOptions",
264
271
  "ModelTechnicalCapabilities",
265
272
  "ModelTool",
266
273
  "NondeterministicReplay",
@@ -313,15 +320,20 @@
313
320
  "RunReport",
314
321
  "RunStatusDetail",
315
322
  "RunSuiteRequest",
323
+ "SANDBOX_EGRESS_LIMITS",
316
324
  "Sandbox",
317
325
  "SandboxCommandCollectionError",
318
326
  "SandboxCommandExecution",
319
327
  "SandboxCommandResult",
328
+ "SandboxEgressCredentialRule",
329
+ "SandboxEgressPolicy",
330
+ "SandboxEgressRule",
320
331
  "SandboxExecInput",
321
332
  "SandboxFileResult",
322
333
  "SandboxGovernanceControls",
323
334
  "SandboxGovernanceMeter",
324
335
  "SandboxImage",
336
+ "SandboxLabels",
325
337
  "SandboxMutationResult",
326
338
  "SandboxNetworkMode",
327
339
  "SandboxNetworkPolicy",
@@ -430,6 +442,7 @@
430
442
  "TrainingUsageUnits",
431
443
  "TurnDraft",
432
444
  "TurnGate",
445
+ "TurnHistoryMessage",
433
446
  "TurnRecord",
434
447
  "TurnSpec",
435
448
  "UI_ASSET_CONTENT_TYPES",
@@ -536,6 +549,9 @@
536
549
  "modelProtocolResult",
537
550
  "murmur3_32",
538
551
  "normalizeModelGatewayConfig",
552
+ "normalizeSandboxEgressCredentialRules",
553
+ "normalizeSandboxEgressPolicy",
554
+ "normalizeSandboxLabels",
539
555
  "normalizeSandboxNetworkPolicy",
540
556
  "normalizeSandboxWorkspacePath",
541
557
  "noulDecision",
@@ -561,6 +577,8 @@
561
577
  "resourceSelector",
562
578
  "resourceTools",
563
579
  "sandboxControls",
580
+ "sandboxEgressDecision",
581
+ "sandboxEgressHostMatches",
564
582
  "sandboxLimit",
565
583
  "scopedBindingKey",
566
584
  "scopedCredentialRef",
@@ -636,6 +636,8 @@ interface ModelInvocationArgs extends ModelGenerationOptions {
636
636
  toolChoice?: "auto" | "required";
637
637
  feedback?: string[];
638
638
  stream?: boolean;
639
+ /** Opt in to provider prompt caching for this request. */
640
+ cache?: ModelCacheHint;
639
641
  /** Host-adapter escape hatch for a qualified upstream SDK wire request. Credentials and the selected model remain platform-owned. */
640
642
  rawProtocol?: {
641
643
  protocol: RawModelProtocol;
@@ -686,7 +688,9 @@ interface ModelInvocationResult {
686
688
  usage: {
687
689
  input: number;
688
690
  output: number;
691
+ /** Input tokens read from the provider's prompt cache; 0 when the provider reports none. */
689
692
  cached: number;
693
+ /** Input tokens written to the provider's prompt cache, present only when the provider reports it. */
690
694
  cacheWrite?: number;
691
695
  /** Exact upstream inference cost when the Gateway can establish it; null means unavailable. */
692
696
  costUsd?: number | null;
@@ -698,17 +702,60 @@ interface ModelInvocationResult {
698
702
  }
699
703
  declare function normalizeModelGatewayConfig(value: unknown): NormalizedModelGatewayConfig;
700
704
  declare function modelGatewayEndpoint(config: Pick<ModelGatewayConfig, "baseUrl" | "protocol">): URL;
701
- interface ModelHistoryMessage {
702
- 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;
703
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;
704
741
  }
705
742
  /** Canonical (sorted-key) JSON: the same objective and context render to the same text whether their objects were built live
706
743
  * or loaded back from storage, so a provider's prompt cache keeps matching from one turn to the next. */
707
744
  declare function modelPrompt(args: ModelInvocationArgs): string;
708
- /** The messages of one turn: the static objective and context first, then each earlier exchange as its own message, then
709
- * 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. */
710
748
  declare function modelMessages(args: ModelInvocationArgs): ModelHistoryMessage[];
711
- 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>;
712
759
  declare function modelProtocolResult(protocol: ModelGatewayProtocol, raw: unknown, provider: string, model: string): ModelInvocationResult;
713
760
 
714
761
  interface GatewayCredentialSlotSetup {
@@ -1014,10 +1061,16 @@ type AgentResourceBinding = CRN | ScopedResourceRef;
1014
1061
  type ResourceCredentialBinding = CredentialCRN | ScopedCredentialRef;
1015
1062
  interface InvocationCredentialUse {
1016
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. */
1017
1066
  consumer: {
1018
1067
  kind: "process";
1019
1068
  delivery: "env" | "file";
1020
1069
  name: string;
1070
+ } | {
1071
+ kind: "egress";
1072
+ delivery: "header";
1073
+ name: string;
1021
1074
  };
1022
1075
  }
1023
1076
  interface BindingAssignmentRevision {
@@ -1599,12 +1652,90 @@ declare function containerImageSelection(value: unknown): ContainerImageSelectio
1599
1652
  * manifest. The caller owns registry authentication and transport Policy. */
1600
1653
  declare function resolveContainerImageSource(reference: string, platform: ContainerImageSource["platform"], request: ContainerRegistryRequest, authorization?: string): Promise<ContainerImageSource>;
1601
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
+
1602
1726
  /** Canonicalize one provider-neutral path and keep it inside the logical workspace. */
1603
1727
  declare function normalizeSandboxWorkspacePath(path: string, cwd?: string): string;
1604
1728
  interface CreateSandboxOptions {
1605
1729
  image?: SandboxImage;
1606
1730
  resetImage?: boolean;
1607
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;
1608
1739
  }
1609
1740
  /**
1610
1741
  * Optional immutable identity for a prepared image. Cache keys are supplied as
@@ -1786,6 +1917,8 @@ interface SandboxWorkspace {
1786
1917
  /** Explicit physical handle used only for lifecycle/image selection controls. */
1787
1918
  interface Sandbox extends SandboxWorkspace {
1788
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>;
1789
1922
  suspend(opts?: InvokeOpts): Promise<void>;
1790
1923
  resume(opts?: InvokeOpts): Promise<void>;
1791
1924
  delete(opts?: InvokeOpts): Promise<void>;
@@ -2151,7 +2284,68 @@ type WaitResolvedEvent = EventBase & {
2151
2284
  promiseId: string;
2152
2285
  outcome: "resolved" | "timeout" | "cancelled" | "failed";
2153
2286
  };
2154
- 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 & {
2155
2349
  kind: "fact";
2156
2350
  fact: Fact;
2157
2351
  }) | (EventBase & {
@@ -2339,7 +2533,9 @@ interface CommitOpts {
2339
2533
  deliver?: DeliveryMode;
2340
2534
  /** Makes this Run's Session the owner of the Session whose main ledger `to` names. */
2341
2535
  delegate?: boolean;
2342
- /** 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. */
2343
2539
  presentation?: AwaitPresentation;
2344
2540
  }
2345
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
@@ -2384,6 +2580,8 @@ interface Cost {
2384
2580
  priceTable: PriceTableRef | null;
2385
2581
  };
2386
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. */
2387
2585
  tokens: {
2388
2586
  input: number;
2389
2587
  output: number;
@@ -2418,12 +2616,15 @@ type GateResult = boolean | {
2418
2616
  pass: boolean;
2419
2617
  evidence?: unknown;
2420
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. */
2421
2621
  interface TurnDraft {
2422
2622
  message: {
2423
2623
  role: "assistant";
2424
2624
  content: string;
2425
2625
  };
2426
2626
  toolCalls: {
2627
+ id?: string;
2427
2628
  name: string;
2428
2629
  args: unknown;
2429
2630
  }[];
@@ -2443,17 +2644,21 @@ interface TurnGate {
2443
2644
  feedback?(rec: TurnRecord | TurnDraft): string;
2444
2645
  onExhausted?: "fail" | "commit-with-verdict";
2445
2646
  }
2446
- /** One prior exchange the model sees as a message of its own, so a provider's prompt cache extends over it. */
2447
- interface TurnHistoryMessage {
2448
- role: "user" | "assistant";
2449
- content: string;
2450
- }
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;
2451
2651
  interface TurnSpec extends ModelGenerationOptions {
2452
2652
  system: string;
2453
2653
  objective?: unknown;
2454
2654
  context?: unknown;
2455
- /** 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. */
2456
2659
  history?: TurnHistoryMessage[];
2660
+ /** Opt in to provider prompt caching; see ModelCacheHint. */
2661
+ cache?: ModelCacheHint;
2457
2662
  tools?: string[];
2458
2663
  /** Require one of the offered Tools for this model generation. */
2459
2664
  toolChoice?: "auto" | "required";
@@ -2465,6 +2670,8 @@ interface TurnSpec extends ModelGenerationOptions {
2465
2670
  stream?: boolean;
2466
2671
  }
2467
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. */
2468
2675
  id: string;
2469
2676
  pos: string;
2470
2677
  name: string;
@@ -4184,22 +4391,45 @@ interface MemoryRememberArgs {
4184
4391
  id?: string;
4185
4392
  content: string;
4186
4393
  metadata?: Record<string, unknown>;
4187
- /** Optional host-derived subpartition within the already authenticated Memory owner partition. */
4394
+ /**
4395
+ * One level of the invocation's authenticated Memory partition. Each level has its own records and ids, and remember,
4396
+ * get, delete and search reach only that level; an omitted scope is the partition's unscoped level, and purge removes
4397
+ * every level. The caller chooses the scope: it subdivides the partition but is not an authority boundary.
4398
+ */
4188
4399
  scope?: string;
4189
4400
  }
4401
+ /**
4402
+ * A search reads one level and sees every write to it that returned before the search started. A record whose remember
4403
+ * returned is a candidate, scored on its current content, until it is deleted or expires; it is returned when it ranks
4404
+ * within `limit` and passes the Memory's `minScore`. A record whose delete returned is never returned. No wait is needed.
4405
+ */
4190
4406
  interface MemorySearchArgs {
4191
4407
  query: string;
4192
4408
  limit?: number;
4193
- /** Must match the host-derived scope used while remembering records. */
4409
+ /** The level to search; see {@link MemoryRememberArgs.scope}. */
4194
4410
  scope?: string;
4411
+ /**
4412
+ * Only the records whose metadata holds each named top-level key with this value and JSON type (`true`, `1` and `"1"`
4413
+ * differ). A key that no record of the level has held a string, number or boolean under matches no record. A level can
4414
+ * filter on the first ten keys that held one; a search filtering on a later key is refused.
4415
+ */
4416
+ filter?: Record<string, string | number | boolean>;
4195
4417
  }
4196
4418
  interface MemoryGetArgs {
4197
4419
  id: string;
4420
+ /** The level that holds the record; see {@link MemoryRememberArgs.scope}. */
4421
+ scope?: string;
4198
4422
  }
4199
4423
  interface MemoryDeleteArgs {
4200
4424
  id: string;
4425
+ /** The level that holds the record; see {@link MemoryRememberArgs.scope}. */
4426
+ scope?: string;
4201
4427
  }
4202
4428
  interface MemorySearchHit extends MemoryRecord {
4429
+ /**
4430
+ * In semantic mode, the record's similarity to the query, in [0, 1]. In hybrid mode, its fused rank divided by the
4431
+ * fused rank of a record first in both rankings, in (0, 1].
4432
+ */
4203
4433
  score: number;
4204
4434
  }
4205
4435
  /** The stable Agent-facing contract shared by logical Memories and Memory Store Connections. */
@@ -4663,5 +4893,5 @@ declare function parseLedgerAddress(value: unknown): LedgerAddressParts | null;
4663
4893
  /** Formats ledger address parts; throws when a part breaks its id rule. */
4664
4894
  declare function formatLedgerAddress(parts: LedgerAddressParts): LedgerAddress;
4665
4895
 
4666
- 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 };
4667
- 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, 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 };
4896
+ 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 };
4897
+ 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) => {
@@ -2611,7 +2614,12 @@ var MEMORY_OPERATION_DECLARATIONS = [
2611
2614
  type: "object",
2612
2615
  required: ["query"],
2613
2616
  additionalProperties: false,
2614
- properties: { query: { type: "string", minLength: 1 }, limit: { type: "integer", minimum: 1 }, scope }
2617
+ properties: {
2618
+ query: { type: "string", minLength: 1 },
2619
+ limit: { type: "integer", minimum: 1 },
2620
+ scope,
2621
+ filter: { type: "object", additionalProperties: { anyOf: [{ type: "string" }, { type: "number" }, { type: "boolean" }] } }
2622
+ }
2615
2623
  },
2616
2624
  resultSchema: {
2617
2625
  type: "object",
@@ -2631,7 +2639,7 @@ var MEMORY_OPERATION_DECLARATIONS = [
2631
2639
  {
2632
2640
  op: "get",
2633
2641
  description: "Read one record from the invocation's authenticated Memory partition.",
2634
- schema: { type: "object", required: ["id"], additionalProperties: false, properties: { id } },
2642
+ schema: { type: "object", required: ["id"], additionalProperties: false, properties: { id, scope } },
2635
2643
  resultSchema: { anyOf: [record5, { type: "null" }] },
2636
2644
  effect: "read-only",
2637
2645
  recovery: { kind: "repeat" },
@@ -2641,7 +2649,7 @@ var MEMORY_OPERATION_DECLARATIONS = [
2641
2649
  {
2642
2650
  op: "delete",
2643
2651
  description: "Delete one record from the invocation's authenticated Memory partition.",
2644
- schema: { type: "object", required: ["id"], additionalProperties: false, properties: { id } },
2652
+ schema: { type: "object", required: ["id"], additionalProperties: false, properties: { id, scope } },
2645
2653
  resultSchema: { type: "object", required: ["deleted"], additionalProperties: false, properties: { deleted: { type: "boolean" } } },
2646
2654
  effect: "idempotent",
2647
2655
  recovery: { kind: "idempotency-key" },
@@ -2851,6 +2859,93 @@ async function resolveContainerImageSource(reference, platform, request, authori
2851
2859
  });
2852
2860
  }
2853
2861
 
2862
+ // packages/sdk/src/sandbox-egress.ts
2863
+ var SANDBOX_EGRESS_LIMITS = { rules: 64, credentialRules: 16, hostsPerRule: 32, labels: 16, labelValueLength: 256 };
2864
+ var HEADER = /^[a-z0-9!#$%&'*+.^_`|~-]{1,64}$/u;
2865
+ var RESERVED_HEADERS = /* @__PURE__ */ new Set([
2866
+ "connection",
2867
+ "content-length",
2868
+ "host",
2869
+ "keep-alive",
2870
+ "proxy-connection",
2871
+ "te",
2872
+ "trailer",
2873
+ "transfer-encoding",
2874
+ "upgrade"
2875
+ ]);
2876
+ var SLOT = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;
2877
+ var USE = /^egress-(?:0|[1-9][0-9]?)$/u;
2878
+ var LABEL = /^[a-z0-9][a-z0-9._-]{0,62}$/u;
2879
+ function object4(value) {
2880
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
2881
+ }
2882
+ function sandboxEgressHostMatches(pattern, hostname) {
2883
+ const host2 = hostname.toLowerCase().replace(/\.$/u, "");
2884
+ return pattern.startsWith("*.") ? host2 === pattern.slice(2) || host2.endsWith(pattern.slice(1)) : host2 === pattern;
2885
+ }
2886
+ function host(value) {
2887
+ const [normalized] = normalizeSandboxDomains([value]);
2888
+ return normalized;
2889
+ }
2890
+ function normalizeSandboxEgressPolicy(value) {
2891
+ const input = object4(value);
2892
+ 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") {
2893
+ throw new TypeError("sandbox egress policy is invalid");
2894
+ }
2895
+ const rules = input.rules.map((raw) => {
2896
+ const rule = object4(raw);
2897
+ if (!rule || Object.keys(rule).some((key) => key !== "action" && key !== "host") || rule.action !== "allow" && rule.action !== "deny") {
2898
+ throw new TypeError("sandbox egress rule is invalid");
2899
+ }
2900
+ return { action: rule.action, host: host(rule.host) };
2901
+ });
2902
+ return { rules, default: input.default === "allow" ? "allow" : "deny" };
2903
+ }
2904
+ function sandboxEgressDecision(policy2, hostname) {
2905
+ if (!policy2) return { allowed: true, rule: "pool" };
2906
+ const index = policy2.rules.findIndex((rule) => sandboxEgressHostMatches(rule.host, hostname));
2907
+ if (index < 0) return { allowed: policy2.default === "allow", rule: "sandbox:default" };
2908
+ return { allowed: policy2.rules[index].action === "allow", rule: `sandbox:${index}` };
2909
+ }
2910
+ function normalizeSandboxEgressCredentialRules(value, options = {}) {
2911
+ if (value === void 0) return [];
2912
+ if (!Array.isArray(value) || value.length > SANDBOX_EGRESS_LIMITS.credentialRules) throw new TypeError("sandbox egress Credential rules are invalid");
2913
+ return value.map((raw) => {
2914
+ const rule = object4(raw);
2915
+ const allowed = ["hosts", "slot", "header", "value", "basic", ...options.bindings ? ["binding"] : [], ...options.uses ? ["use"] : []];
2916
+ 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");
2917
+ const sources = [rule.slot, rule.binding, rule.use].filter((source) => source !== void 0);
2918
+ 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))) {
2919
+ throw new TypeError("sandbox egress Credential rule names exactly one slot or binding");
2920
+ }
2921
+ const header = rule.header === void 0 ? "authorization" : rule.header;
2922
+ 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");
2923
+ if (rule.value !== void 0 && rule.basic !== void 0) throw new TypeError("sandbox egress Credential rule takes value or basic, not both");
2924
+ 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");
2925
+ const basic = rule.basic === void 0 ? void 0 : object4(rule.basic);
2926
+ 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");
2927
+ return {
2928
+ hosts: normalizeSandboxDomains(rule.hosts),
2929
+ ...rule.slot !== void 0 ? { slot: rule.slot } : {},
2930
+ ...rule.binding !== void 0 ? { binding: resourceCredentialBinding(rule.binding) } : {},
2931
+ ...rule.use !== void 0 ? { use: rule.use } : {},
2932
+ header: header.toLowerCase(),
2933
+ ...basic ? { basic: basic.username === void 0 ? {} : { username: basic.username } } : { value: rule.value ?? "Bearer {value}" }
2934
+ };
2935
+ });
2936
+ }
2937
+ function normalizeSandboxLabels(value) {
2938
+ if (value === void 0) return {};
2939
+ const input = object4(value);
2940
+ if (!input || Object.keys(input).length > SANDBOX_EGRESS_LIMITS.labels) throw new TypeError("sandbox labels are invalid");
2941
+ const labels = {};
2942
+ for (const [key, label] of Object.entries(input).sort(([left], [right]) => left.localeCompare(right))) {
2943
+ 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");
2944
+ labels[key] = label;
2945
+ }
2946
+ return labels;
2947
+ }
2948
+
2854
2949
  // packages/sdk/src/sandbox-pool.ts
2855
2950
  var WORKSPACE_ROOT = "/workspace";
2856
2951
  function absoluteSandboxPath(value) {
@@ -3053,15 +3148,15 @@ function modelGenerationOptions(source) {
3053
3148
  };
3054
3149
  }
3055
3150
  var NAME4 = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
3056
- var HEADER = /^[a-z0-9][a-z0-9-]{0,63}$/u;
3057
- var RESERVED_HEADERS = /* @__PURE__ */ new Set(["connection", "content-type", "host", "anthropic-version", "proxy-authorization", "transfer-encoding"]);
3151
+ var HEADER2 = /^[a-z0-9][a-z0-9-]{0,63}$/u;
3152
+ var RESERVED_HEADERS2 = /* @__PURE__ */ new Set(["connection", "content-type", "host", "anthropic-version", "proxy-authorization", "transfer-encoding"]);
3058
3153
  function record7(value) {
3059
3154
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
3060
3155
  }
3061
3156
  function credentialHeader(value, name) {
3062
3157
  if (value === null || value === void 0) return null;
3063
3158
  const source = record7(value);
3064
- 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`);
3159
+ 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`);
3065
3160
  return { slot: source.slot, header: source.header.toLowerCase(), scheme: source.scheme };
3066
3161
  }
3067
3162
  function normalizeModelGatewayConfig(value) {
@@ -3111,42 +3206,141 @@ function modelGatewayEndpoint(config) {
3111
3206
  endpoint.pathname = `${endpoint.pathname.replace(/\/+$/u, "")}/${suffix}`.replace(/^\/+/u, "/");
3112
3207
  return endpoint;
3113
3208
  }
3114
- function modelPrompt(args) {
3115
- return canonicalJson({ objective: args.objective ?? null, context: args.context ?? null, feedback: args.feedback ?? [] });
3209
+ var CACHE_HINT_FIELDS = ["key", "retention", "ttl"];
3210
+ function nonempty(value) {
3211
+ return typeof value === "string" && value.trim().length > 0;
3116
3212
  }
3117
- function modelHistory(args) {
3118
- const history = args.history ?? [];
3119
- if (!Array.isArray(history)) throw new TypeError("model history must be an array of messages");
3120
- return history.map((message2) => {
3121
- const source = record7(message2);
3122
- if (!source || source.role !== "user" && source.role !== "assistant" || typeof source.content !== "string") {
3123
- throw new TypeError("model history messages need a user or assistant role and text content");
3213
+ function modelCacheHint(value) {
3214
+ if (value === void 0) return void 0;
3215
+ const source = record7(value);
3216
+ if (!source) throw new TypeError("model cache hint must be an object");
3217
+ const unknown = Object.keys(source).find((key) => !CACHE_HINT_FIELDS.includes(key));
3218
+ if (unknown !== void 0) throw new TypeError(`model cache hint has an unknown field: ${unknown}`);
3219
+ const hint = {};
3220
+ for (const field2 of CACHE_HINT_FIELDS) {
3221
+ const candidate = source[field2];
3222
+ if (candidate === void 0) continue;
3223
+ if (!nonempty(candidate)) throw new TypeError(`model cache hint ${field2} must be a nonempty string`);
3224
+ hint[field2] = candidate;
3225
+ }
3226
+ return hint;
3227
+ }
3228
+ function modelHistoryMessages(value) {
3229
+ if (value === void 0) return [];
3230
+ if (!Array.isArray(value)) throw new TypeError("model history must be an array of messages");
3231
+ const ids = /* @__PURE__ */ new Set();
3232
+ const unanswered = /* @__PURE__ */ new Set();
3233
+ const messages = value.map((candidate, index) => {
3234
+ const at = `model history message ${index}`;
3235
+ const source = record7(candidate);
3236
+ if (!source || typeof source.content !== "string" || source.role !== "user" && source.role !== "assistant" && source.role !== "tool") {
3237
+ throw new TypeError(`${at} needs a user, assistant or tool role and text content`);
3238
+ }
3239
+ const foreign = source.role === "tool" ? ["toolCalls"] : source.role === "user" ? ["toolCalls", "toolCallId", "isError"] : ["toolCallId", "isError"];
3240
+ const misplaced = foreign.find((field2) => source[field2] !== void 0);
3241
+ if (misplaced !== void 0) throw new TypeError(`${at} has the ${source.role} role, which cannot carry ${misplaced}`);
3242
+ if (source.role === "tool") {
3243
+ if (!nonempty(source.toolCallId)) throw new TypeError(`${at} needs the toolCallId of the Tool call it answers`);
3244
+ if (!unanswered.delete(source.toolCallId)) {
3245
+ throw new TypeError(`${at} answers Tool call ${source.toolCallId}, which is not an unanswered call of the assistant message before it`);
3246
+ }
3247
+ if (source.isError !== void 0 && typeof source.isError !== "boolean") throw new TypeError(`${at} isError must be a boolean`);
3248
+ return {
3249
+ role: "tool",
3250
+ toolCallId: source.toolCallId,
3251
+ content: source.content,
3252
+ ...source.isError === void 0 ? {} : { isError: source.isError }
3253
+ };
3124
3254
  }
3125
- return { role: source.role, content: source.content };
3255
+ const open2 = unanswered.values().next();
3256
+ if (!open2.done) throw new TypeError(`model history Tool call ${open2.value} has no tool message answering it before message ${index}`);
3257
+ if (source.role === "user" || source.toolCalls === void 0) return { role: source.role, content: source.content };
3258
+ if (!Array.isArray(source.toolCalls)) throw new TypeError(`${at} toolCalls must be an array`);
3259
+ const toolCalls = source.toolCalls.map((call, position) => {
3260
+ const entry2 = record7(call);
3261
+ if (!entry2 || !nonempty(entry2.id) || !nonempty(entry2.name)) throw new TypeError(`${at} Tool call ${position} needs an id and a name`);
3262
+ if (ids.has(entry2.id)) throw new TypeError(`${at} repeats Tool call id ${entry2.id}`);
3263
+ try {
3264
+ canonicalJson(entry2.args);
3265
+ } catch {
3266
+ throw new TypeError(`${at} Tool call ${entry2.id} args must be a JSON value`);
3267
+ }
3268
+ ids.add(entry2.id);
3269
+ unanswered.add(entry2.id);
3270
+ return { id: entry2.id, name: entry2.name, args: entry2.args };
3271
+ });
3272
+ return { role: "assistant", content: source.content, ...toolCalls.length ? { toolCalls } : {} };
3126
3273
  });
3274
+ const open = unanswered.values().next();
3275
+ if (!open.done) throw new TypeError(`model history Tool call ${open.value} has no tool message answering it`);
3276
+ return messages;
3127
3277
  }
3128
- function modelMessages(args) {
3129
- const history = modelHistory(args);
3130
- if (!history.length) return [{ role: "user", content: modelPrompt(args) }];
3278
+ function modelPrompt(args) {
3279
+ return canonicalJson({ objective: args.objective ?? null, context: args.context ?? null, feedback: args.feedback ?? [] });
3280
+ }
3281
+ function turnMessages(args) {
3282
+ const history = modelHistoryMessages(args.history);
3283
+ if (!history.length) return { messages: [{ role: "user", content: modelPrompt(args) }], lastHistory: null };
3131
3284
  const feedback = args.feedback ?? [];
3132
- return [
3133
- { role: "user", content: canonicalJson({ objective: args.objective ?? null, context: args.context ?? null }) },
3134
- ...history,
3135
- ...feedback.length ? [{ role: "user", content: canonicalJson({ feedback }) }] : []
3136
- ];
3285
+ const prompt = args.objective == null && args.context == null && history[0].role === "user" ? [] : [{ role: "user", content: canonicalJson({ objective: args.objective ?? null, context: args.context ?? null }) }];
3286
+ return {
3287
+ messages: [...prompt, ...history, ...feedback.length ? [{ role: "user", content: canonicalJson({ feedback }) }] : []],
3288
+ lastHistory: prompt.length + history.length - 1
3289
+ };
3290
+ }
3291
+ function modelMessages(args) {
3292
+ return turnMessages(args).messages;
3293
+ }
3294
+ function anthropicBlocks(content2) {
3295
+ return typeof content2 !== "string" ? content2 : content2 ? [{ type: "text", text: content2 }] : [];
3296
+ }
3297
+ function anthropicMessage(message2) {
3298
+ if (message2.role === "tool") return { role: "user", content: [{
3299
+ type: "tool_result",
3300
+ tool_use_id: message2.toolCallId,
3301
+ content: message2.content,
3302
+ ...message2.isError ? { is_error: true } : {}
3303
+ }] };
3304
+ if (message2.role === "assistant" && message2.toolCalls) return { role: "assistant", content: [
3305
+ ...anthropicBlocks(message2.content),
3306
+ ...message2.toolCalls.map((call) => {
3307
+ const args = JSON.parse(canonicalJson(call.args));
3308
+ return { type: "tool_use", id: call.id, name: call.name, input: record7(args) ?? { value: args } };
3309
+ })
3310
+ ] };
3311
+ return { role: message2.role, content: message2.content };
3137
3312
  }
3138
3313
  function alternating(messages) {
3139
3314
  const merged = [];
3140
3315
  for (const message2 of messages) {
3141
3316
  const last = merged.at(-1);
3142
- if (last && last.role === message2.role) last.content = `${last.content}
3317
+ if (!last || last.role !== message2.role) merged.push({ ...message2 });
3318
+ else if (typeof last.content === "string" && typeof message2.content === "string") last.content = `${last.content}
3143
3319
 
3144
3320
  ${message2.content}`;
3145
- else merged.push({ ...message2 });
3321
+ else last.content = [...anthropicBlocks(last.content), ...anthropicBlocks(message2.content)];
3146
3322
  }
3147
3323
  return merged;
3148
3324
  }
3149
- function modelProtocolRequest(protocol, model, maxOutputTokens, temperature, args) {
3325
+ function openAiMessage(message2, options) {
3326
+ if (message2.role === "tool") return {
3327
+ role: "tool",
3328
+ tool_call_id: message2.toolCallId,
3329
+ content: message2.content,
3330
+ ...options.toolErrorName && message2.isError ? { name: "tool_error" } : {}
3331
+ };
3332
+ if (message2.role === "assistant" && message2.toolCalls) return {
3333
+ role: "assistant",
3334
+ content: message2.content || null,
3335
+ tool_calls: message2.toolCalls.map((call) => ({
3336
+ id: call.id,
3337
+ type: "function",
3338
+ function: { name: call.name, arguments: canonicalJson(call.args) }
3339
+ }))
3340
+ };
3341
+ return { role: message2.role, content: message2.content };
3342
+ }
3343
+ function modelProtocolRequest(protocol, model, maxOutputTokens, temperature, args, options = {}) {
3150
3344
  const { effort } = modelGenerationOptions(args);
3151
3345
  if (args.toolChoice !== void 0 && args.toolChoice !== "auto" && args.toolChoice !== "required") {
3152
3346
  throw new TypeError("model Tool choice is invalid");
@@ -3154,37 +3348,66 @@ function modelProtocolRequest(protocol, model, maxOutputTokens, temperature, arg
3154
3348
  if (args.toolChoice === "required" && !args.tools?.length) {
3155
3349
  throw new TypeError("required model Tool choice needs at least one offered Tool");
3156
3350
  }
3157
- const messages = modelMessages(args);
3158
- if (protocol === "anthropic") return {
3159
- model,
3160
- system: args.system ?? "",
3161
- messages: alternating(messages),
3162
- ...maxOutputTokens === null ? {} : { max_tokens: maxOutputTokens },
3163
- ...effort === void 0 ? {} : { output_config: { effort } },
3164
- ...temperature === null ? {} : { temperature },
3165
- ...args.tools?.length ? { tools: args.tools.map((tool) => ({ name: tool.name, description: tool.description, input_schema: tool.schema })) } : {},
3166
- ...args.toolChoice === void 0 ? {} : { tool_choice: { type: args.toolChoice === "required" ? "any" : "auto" } }
3167
- };
3168
- if (protocol === "openai") return {
3169
- model,
3170
- messages: [
3171
- ...args.system ? [{ role: "developer", content: args.system }] : [],
3172
- ...messages
3173
- ],
3174
- ...maxOutputTokens === null ? {} : { max_completion_tokens: maxOutputTokens },
3175
- ...effort === void 0 ? {} : { reasoning_effort: effort },
3176
- ...temperature === null ? {} : { temperature },
3177
- ...args.tools?.length ? { tools: args.tools.map((tool) => ({
3178
- type: "function",
3179
- function: { name: tool.name, description: tool.description, parameters: tool.schema }
3180
- })) } : {},
3181
- ...args.toolChoice === void 0 ? {} : { tool_choice: args.toolChoice }
3182
- };
3351
+ const cache = modelCacheHint(args.cache);
3352
+ const { messages, lastHistory } = turnMessages(args);
3353
+ const breakpoint = cache ? { type: "ephemeral", ...cache.ttl === void 0 ? {} : { ttl: cache.ttl } } : null;
3354
+ if (protocol === "anthropic") {
3355
+ const anthropic = messages.map(anthropicMessage);
3356
+ const marked = breakpoint && lastHistory !== null ? anthropicBlocks(anthropic[lastHistory].content) : [];
3357
+ if (breakpoint && lastHistory !== null && marked.length) {
3358
+ anthropic[lastHistory] = { ...anthropic[lastHistory], content: [...marked.slice(0, -1), { ...marked.at(-1), cache_control: breakpoint }] };
3359
+ }
3360
+ const tools = args.tools ?? [];
3361
+ return {
3362
+ model,
3363
+ system: breakpoint && args.system ? [{ type: "text", text: args.system, cache_control: breakpoint }] : args.system ?? "",
3364
+ messages: alternating(anthropic),
3365
+ ...maxOutputTokens === null ? {} : { max_tokens: maxOutputTokens },
3366
+ ...effort === void 0 ? {} : { output_config: { effort } },
3367
+ ...temperature === null ? {} : { temperature },
3368
+ ...tools.length ? { tools: tools.map((tool, index) => ({
3369
+ name: tool.name,
3370
+ description: tool.description,
3371
+ input_schema: tool.schema,
3372
+ ...breakpoint && index === tools.length - 1 ? { cache_control: breakpoint } : {}
3373
+ })) } : {},
3374
+ ...args.toolChoice === void 0 ? {} : { tool_choice: { type: args.toolChoice === "required" ? "any" : "auto" } }
3375
+ };
3376
+ }
3377
+ if (protocol === "openai") {
3378
+ const marks = options.contentCacheControl === true ? breakpoint : null;
3379
+ const marked = (text2) => marks && text2 ? [{ type: "text", text: text2, cache_control: marks }] : text2;
3380
+ const openai = messages.map((message2, index) => {
3381
+ const entry2 = openAiMessage(message2, options);
3382
+ return index === lastHistory && typeof entry2.content === "string" ? { ...entry2, content: marked(entry2.content) } : entry2;
3383
+ });
3384
+ return {
3385
+ model,
3386
+ messages: [
3387
+ ...args.system ? [{ role: "developer", content: marked(args.system) }] : [],
3388
+ ...openai
3389
+ ],
3390
+ ...maxOutputTokens === null ? {} : { max_completion_tokens: maxOutputTokens },
3391
+ ...effort === void 0 ? {} : { reasoning_effort: effort },
3392
+ ...temperature === null ? {} : { temperature },
3393
+ ...args.tools?.length ? { tools: args.tools.map((tool) => ({
3394
+ type: "function",
3395
+ function: { name: tool.name, description: tool.description, parameters: tool.schema }
3396
+ })) } : {},
3397
+ ...args.toolChoice === void 0 ? {} : { tool_choice: args.toolChoice },
3398
+ ...cache?.key === void 0 ? {} : { prompt_cache_key: cache.key },
3399
+ ...cache?.retention === void 0 ? {} : { prompt_cache_retention: cache.retention }
3400
+ };
3401
+ }
3183
3402
  throw new TypeError("model gateway protocol is invalid");
3184
3403
  }
3185
3404
  function integer2(value) {
3186
3405
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : 0;
3187
3406
  }
3407
+ function cacheWrite(usage) {
3408
+ const value = usage.cache_creation_input_tokens ?? record7(usage.prompt_tokens_details)?.cache_write_tokens;
3409
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? { cacheWrite: value } : {};
3410
+ }
3188
3411
  function costMetadata(usage) {
3189
3412
  const cost = usage.cost;
3190
3413
  const costUsd = cost === null ? null : typeof cost === "number" && Number.isFinite(cost) && cost >= 0 ? cost : void 0;
@@ -3220,6 +3443,7 @@ function modelProtocolResult(protocol, raw, provider, model) {
3220
3443
  input: integer2(values.input_tokens) + integer2(values.cache_creation_input_tokens) + cached,
3221
3444
  output: integer2(values.output_tokens),
3222
3445
  cached,
3446
+ ...cacheWrite(values),
3223
3447
  ...costMetadata(values)
3224
3448
  };
3225
3449
  } else if (protocol === "openai") {
@@ -3249,6 +3473,7 @@ function modelProtocolResult(protocol, raw, provider, model) {
3249
3473
  input: integer2(values.prompt_tokens),
3250
3474
  output: integer2(values.completion_tokens),
3251
3475
  cached: integer2(record7(values.prompt_tokens_details)?.cached_tokens),
3476
+ ...cacheWrite(values),
3252
3477
  ...costMetadata(values)
3253
3478
  };
3254
3479
  } else throw new TypeError("model gateway protocol is invalid");
@@ -3276,7 +3501,7 @@ function modelCompletionStatus(protocol, raw) {
3276
3501
  async function checkpointArtifactRef(value) {
3277
3502
  return await sha256Hex(canonicalJson(value));
3278
3503
  }
3279
- var SLOT = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
3504
+ var SLOT2 = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
3280
3505
  var HASH3 = /^[a-f0-9]{64}$/u;
3281
3506
  var MODEL_RESOURCE_ID = /^[a-z0-9][a-z0-9-]{0,62}$/u;
3282
3507
  function httpsUrl(value, field2) {
@@ -3296,7 +3521,7 @@ function slotMetadata(value) {
3296
3521
  const output = {};
3297
3522
  for (const [slot, raw] of entries) {
3298
3523
  const item = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : null;
3299
- 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))) {
3524
+ 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))) {
3300
3525
  throw new TypeError("Gateway Credential slots are invalid");
3301
3526
  }
3302
3527
  httpsUrl(item.documentationUrl, "Gateway Credential slot documentation URL");
@@ -3309,7 +3534,7 @@ function configEgressBindings(value) {
3309
3534
  if (!Array.isArray(value)) throw new TypeError("Gateway config egress bindings are invalid");
3310
3535
  return value.map((raw) => {
3311
3536
  const item = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : null;
3312
- 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))) {
3537
+ 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))) {
3313
3538
  throw new TypeError("Gateway config egress bindings are invalid");
3314
3539
  }
3315
3540
  return {
@@ -3322,7 +3547,7 @@ function configEgressBindings(value) {
3322
3547
  function discoverySetup(value) {
3323
3548
  if (value === void 0) return void 0;
3324
3549
  const item = value && typeof value === "object" && !Array.isArray(value) ? value : null;
3325
- 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))) {
3550
+ 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))) {
3326
3551
  throw new TypeError("Gateway discovery setup is invalid");
3327
3552
  }
3328
3553
  return { operation: String(item.operation), resultConfigProperty: String(item.resultConfigProperty) };
@@ -3387,7 +3612,7 @@ function gatewayModelOffer(value) {
3387
3612
  const modalities = (field2) => {
3388
3613
  const values = source[field2];
3389
3614
  if (values === void 0) return void 0;
3390
- if (!Array.isArray(values) || values.length === 0 || values.some((item) => typeof item !== "string" || !SLOT.test(item)) || new Set(values).size !== values.length) {
3615
+ if (!Array.isArray(values) || values.length === 0 || values.some((item) => typeof item !== "string" || !SLOT2.test(item)) || new Set(values).size !== values.length) {
3391
3616
  throw new TypeError("Gateway Model offer is invalid");
3392
3617
  }
3393
3618
  return values;
@@ -4481,6 +4706,7 @@ export {
4481
4706
  ResourceInvalid,
4482
4707
  ResourceUnbound,
4483
4708
  RollbackTargetInvalid,
4709
+ SANDBOX_EGRESS_LIMITS,
4484
4710
  SessionDeleted,
4485
4711
  SpawnCardinality,
4486
4712
  SwallowedYield,
@@ -4573,6 +4799,9 @@ export {
4573
4799
  modelProtocolResult,
4574
4800
  murmur3_32,
4575
4801
  normalizeModelGatewayConfig,
4802
+ normalizeSandboxEgressCredentialRules,
4803
+ normalizeSandboxEgressPolicy,
4804
+ normalizeSandboxLabels,
4576
4805
  normalizeSandboxNetworkPolicy,
4577
4806
  normalizeSandboxWorkspacePath,
4578
4807
  noulDecision,
@@ -4598,6 +4827,8 @@ export {
4598
4827
  resourceSelector,
4599
4828
  resourceTools,
4600
4829
  sandboxControls,
4830
+ sandboxEgressDecision,
4831
+ sandboxEgressHostMatches,
4601
4832
  sandboxLimit,
4602
4833
  scopedBindingKey,
4603
4834
  scopedCredentialRef,