@constal/sdk 5.0.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/package.json +1 -1
- package/publish/api.json +19 -1
- package/publish/index.d.ts +222 -15
- package/publish/index.js +282 -56
package/package.json
CHANGED
package/publish/api.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"package": "@constal/sdk",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.1.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",
|
package/publish/index.d.ts
CHANGED
|
@@ -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
|
-
|
|
702
|
-
|
|
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";
|
|
703
722
|
content: string;
|
|
723
|
+
toolCalls?: ModelHistoryToolCall[];
|
|
724
|
+
} | {
|
|
725
|
+
role: "tool";
|
|
726
|
+
toolCallId: string;
|
|
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
|
|
709
|
-
*
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
2448
|
-
|
|
2449
|
-
|
|
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;
|
|
@@ -4663,5 +4870,5 @@ declare function parseLedgerAddress(value: unknown): LedgerAddressParts | null;
|
|
|
4663
4870
|
/** Formats ledger address parts; throws when a part breaks its id rule. */
|
|
4664
4871
|
declare function formatLedgerAddress(parts: LedgerAddressParts): LedgerAddress;
|
|
4665
4872
|
|
|
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 };
|
|
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
|
|
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) => {
|
|
@@ -2851,6 +2854,93 @@ async function resolveContainerImageSource(reference, platform, request, authori
|
|
|
2851
2854
|
});
|
|
2852
2855
|
}
|
|
2853
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
|
+
|
|
2854
2944
|
// packages/sdk/src/sandbox-pool.ts
|
|
2855
2945
|
var WORKSPACE_ROOT = "/workspace";
|
|
2856
2946
|
function absoluteSandboxPath(value) {
|
|
@@ -3053,15 +3143,15 @@ function modelGenerationOptions(source) {
|
|
|
3053
3143
|
};
|
|
3054
3144
|
}
|
|
3055
3145
|
var NAME4 = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
|
|
3056
|
-
var
|
|
3057
|
-
var
|
|
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"]);
|
|
3058
3148
|
function record7(value) {
|
|
3059
3149
|
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
3060
3150
|
}
|
|
3061
3151
|
function credentialHeader(value, name) {
|
|
3062
3152
|
if (value === null || value === void 0) return null;
|
|
3063
3153
|
const source = record7(value);
|
|
3064
|
-
if (!source || typeof source.slot !== "string" || !NAME4.test(source.slot) || typeof source.header !== "string" || !
|
|
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`);
|
|
3065
3155
|
return { slot: source.slot, header: source.header.toLowerCase(), scheme: source.scheme };
|
|
3066
3156
|
}
|
|
3067
3157
|
function normalizeModelGatewayConfig(value) {
|
|
@@ -3111,42 +3201,141 @@ function modelGatewayEndpoint(config) {
|
|
|
3111
3201
|
endpoint.pathname = `${endpoint.pathname.replace(/\/+$/u, "")}/${suffix}`.replace(/^\/+/u, "/");
|
|
3112
3202
|
return endpoint;
|
|
3113
3203
|
}
|
|
3114
|
-
|
|
3115
|
-
|
|
3204
|
+
var CACHE_HINT_FIELDS = ["key", "retention", "ttl"];
|
|
3205
|
+
function nonempty(value) {
|
|
3206
|
+
return typeof value === "string" && value.trim().length > 0;
|
|
3116
3207
|
}
|
|
3117
|
-
function
|
|
3118
|
-
|
|
3119
|
-
|
|
3120
|
-
|
|
3121
|
-
|
|
3122
|
-
|
|
3123
|
-
|
|
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`);
|
|
3124
3233
|
}
|
|
3125
|
-
|
|
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 } : {} };
|
|
3126
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;
|
|
3127
3272
|
}
|
|
3128
|
-
function
|
|
3129
|
-
|
|
3130
|
-
|
|
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 };
|
|
3131
3279
|
const feedback = args.feedback ?? [];
|
|
3132
|
-
|
|
3133
|
-
|
|
3134
|
-
...history,
|
|
3135
|
-
|
|
3136
|
-
|
|
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 };
|
|
3137
3307
|
}
|
|
3138
3308
|
function alternating(messages) {
|
|
3139
3309
|
const merged = [];
|
|
3140
3310
|
for (const message2 of messages) {
|
|
3141
3311
|
const last = merged.at(-1);
|
|
3142
|
-
if (last
|
|
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}
|
|
3143
3314
|
|
|
3144
3315
|
${message2.content}`;
|
|
3145
|
-
else
|
|
3316
|
+
else last.content = [...anthropicBlocks(last.content), ...anthropicBlocks(message2.content)];
|
|
3146
3317
|
}
|
|
3147
3318
|
return merged;
|
|
3148
3319
|
}
|
|
3149
|
-
function
|
|
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 = {}) {
|
|
3150
3339
|
const { effort } = modelGenerationOptions(args);
|
|
3151
3340
|
if (args.toolChoice !== void 0 && args.toolChoice !== "auto" && args.toolChoice !== "required") {
|
|
3152
3341
|
throw new TypeError("model Tool choice is invalid");
|
|
@@ -3154,37 +3343,66 @@ function modelProtocolRequest(protocol, model, maxOutputTokens, temperature, arg
|
|
|
3154
3343
|
if (args.toolChoice === "required" && !args.tools?.length) {
|
|
3155
3344
|
throw new TypeError("required model Tool choice needs at least one offered Tool");
|
|
3156
3345
|
}
|
|
3157
|
-
const
|
|
3158
|
-
|
|
3159
|
-
|
|
3160
|
-
|
|
3161
|
-
messages
|
|
3162
|
-
|
|
3163
|
-
|
|
3164
|
-
|
|
3165
|
-
|
|
3166
|
-
|
|
3167
|
-
|
|
3168
|
-
|
|
3169
|
-
|
|
3170
|
-
|
|
3171
|
-
...
|
|
3172
|
-
...
|
|
3173
|
-
|
|
3174
|
-
|
|
3175
|
-
|
|
3176
|
-
|
|
3177
|
-
|
|
3178
|
-
|
|
3179
|
-
|
|
3180
|
-
|
|
3181
|
-
|
|
3182
|
-
}
|
|
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
|
+
}
|
|
3183
3397
|
throw new TypeError("model gateway protocol is invalid");
|
|
3184
3398
|
}
|
|
3185
3399
|
function integer2(value) {
|
|
3186
3400
|
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : 0;
|
|
3187
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
|
+
}
|
|
3188
3406
|
function costMetadata(usage) {
|
|
3189
3407
|
const cost = usage.cost;
|
|
3190
3408
|
const costUsd = cost === null ? null : typeof cost === "number" && Number.isFinite(cost) && cost >= 0 ? cost : void 0;
|
|
@@ -3220,6 +3438,7 @@ function modelProtocolResult(protocol, raw, provider, model) {
|
|
|
3220
3438
|
input: integer2(values.input_tokens) + integer2(values.cache_creation_input_tokens) + cached,
|
|
3221
3439
|
output: integer2(values.output_tokens),
|
|
3222
3440
|
cached,
|
|
3441
|
+
...cacheWrite(values),
|
|
3223
3442
|
...costMetadata(values)
|
|
3224
3443
|
};
|
|
3225
3444
|
} else if (protocol === "openai") {
|
|
@@ -3249,6 +3468,7 @@ function modelProtocolResult(protocol, raw, provider, model) {
|
|
|
3249
3468
|
input: integer2(values.prompt_tokens),
|
|
3250
3469
|
output: integer2(values.completion_tokens),
|
|
3251
3470
|
cached: integer2(record7(values.prompt_tokens_details)?.cached_tokens),
|
|
3471
|
+
...cacheWrite(values),
|
|
3252
3472
|
...costMetadata(values)
|
|
3253
3473
|
};
|
|
3254
3474
|
} else throw new TypeError("model gateway protocol is invalid");
|
|
@@ -3276,7 +3496,7 @@ function modelCompletionStatus(protocol, raw) {
|
|
|
3276
3496
|
async function checkpointArtifactRef(value) {
|
|
3277
3497
|
return await sha256Hex(canonicalJson(value));
|
|
3278
3498
|
}
|
|
3279
|
-
var
|
|
3499
|
+
var SLOT2 = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
|
|
3280
3500
|
var HASH3 = /^[a-f0-9]{64}$/u;
|
|
3281
3501
|
var MODEL_RESOURCE_ID = /^[a-z0-9][a-z0-9-]{0,62}$/u;
|
|
3282
3502
|
function httpsUrl(value, field2) {
|
|
@@ -3296,7 +3516,7 @@ function slotMetadata(value) {
|
|
|
3296
3516
|
const output = {};
|
|
3297
3517
|
for (const [slot, raw] of entries) {
|
|
3298
3518
|
const item = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : null;
|
|
3299
|
-
if (!
|
|
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))) {
|
|
3300
3520
|
throw new TypeError("Gateway Credential slots are invalid");
|
|
3301
3521
|
}
|
|
3302
3522
|
httpsUrl(item.documentationUrl, "Gateway Credential slot documentation URL");
|
|
@@ -3309,7 +3529,7 @@ function configEgressBindings(value) {
|
|
|
3309
3529
|
if (!Array.isArray(value)) throw new TypeError("Gateway config egress bindings are invalid");
|
|
3310
3530
|
return value.map((raw) => {
|
|
3311
3531
|
const item = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : null;
|
|
3312
|
-
if (!item || !
|
|
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))) {
|
|
3313
3533
|
throw new TypeError("Gateway config egress bindings are invalid");
|
|
3314
3534
|
}
|
|
3315
3535
|
return {
|
|
@@ -3322,7 +3542,7 @@ function configEgressBindings(value) {
|
|
|
3322
3542
|
function discoverySetup(value) {
|
|
3323
3543
|
if (value === void 0) return void 0;
|
|
3324
3544
|
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 ?? "")) || !
|
|
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))) {
|
|
3326
3546
|
throw new TypeError("Gateway discovery setup is invalid");
|
|
3327
3547
|
}
|
|
3328
3548
|
return { operation: String(item.operation), resultConfigProperty: String(item.resultConfigProperty) };
|
|
@@ -3387,7 +3607,7 @@ function gatewayModelOffer(value) {
|
|
|
3387
3607
|
const modalities = (field2) => {
|
|
3388
3608
|
const values = source[field2];
|
|
3389
3609
|
if (values === void 0) return void 0;
|
|
3390
|
-
if (!Array.isArray(values) || values.length === 0 || values.some((item) => typeof item !== "string" || !
|
|
3610
|
+
if (!Array.isArray(values) || values.length === 0 || values.some((item) => typeof item !== "string" || !SLOT2.test(item)) || new Set(values).size !== values.length) {
|
|
3391
3611
|
throw new TypeError("Gateway Model offer is invalid");
|
|
3392
3612
|
}
|
|
3393
3613
|
return values;
|
|
@@ -4481,6 +4701,7 @@ export {
|
|
|
4481
4701
|
ResourceInvalid,
|
|
4482
4702
|
ResourceUnbound,
|
|
4483
4703
|
RollbackTargetInvalid,
|
|
4704
|
+
SANDBOX_EGRESS_LIMITS,
|
|
4484
4705
|
SessionDeleted,
|
|
4485
4706
|
SpawnCardinality,
|
|
4486
4707
|
SwallowedYield,
|
|
@@ -4573,6 +4794,9 @@ export {
|
|
|
4573
4794
|
modelProtocolResult,
|
|
4574
4795
|
murmur3_32,
|
|
4575
4796
|
normalizeModelGatewayConfig,
|
|
4797
|
+
normalizeSandboxEgressCredentialRules,
|
|
4798
|
+
normalizeSandboxEgressPolicy,
|
|
4799
|
+
normalizeSandboxLabels,
|
|
4576
4800
|
normalizeSandboxNetworkPolicy,
|
|
4577
4801
|
normalizeSandboxWorkspacePath,
|
|
4578
4802
|
noulDecision,
|
|
@@ -4598,6 +4822,8 @@ export {
|
|
|
4598
4822
|
resourceSelector,
|
|
4599
4823
|
resourceTools,
|
|
4600
4824
|
sandboxControls,
|
|
4825
|
+
sandboxEgressDecision,
|
|
4826
|
+
sandboxEgressHostMatches,
|
|
4601
4827
|
sandboxLimit,
|
|
4602
4828
|
scopedBindingKey,
|
|
4603
4829
|
scopedCredentialRef,
|