@constal/sdk 6.9.0 → 6.10.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": "6.9.0",
3
+ "version": "6.10.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": "6.9.0",
3
+ "version": "6.10.0",
4
4
  "exports": [
5
5
  "AGENT_UI_DEFAULTS",
6
6
  "Action",
@@ -65,9 +65,14 @@
65
65
  "ChannelDeliveryOutcome",
66
66
  "ChannelDeliveryReport",
67
67
  "ChannelFailure",
68
+ "ChannelFetchRequest",
69
+ "ChannelFetchResult",
68
70
  "ChannelIngressEvent",
69
71
  "ChannelIngressSource",
70
72
  "ChannelMessage",
73
+ "ChannelObject",
74
+ "ChannelPresence",
75
+ "ChannelPresenceReceipt",
71
76
  "ChannelProtocol",
72
77
  "ChannelReceiveResult",
73
78
  "ChannelRequest",
@@ -279,7 +284,9 @@
279
284
  "ModelAdvertisedPricing",
280
285
  "ModelCacheHint",
281
286
  "ModelCompletion",
287
+ "ModelContentPart",
282
288
  "ModelCredentialHeader",
289
+ "ModelFilePart",
283
290
  "ModelGatewayBinding",
284
291
  "ModelGatewayConfig",
285
292
  "ModelGatewayProtocol",
@@ -292,6 +299,7 @@
292
299
  "ModelInvocationResult",
293
300
  "ModelProtocolRequestOptions",
294
301
  "ModelTechnicalCapabilities",
302
+ "ModelTextPart",
295
303
  "ModelTool",
296
304
  "NondeterministicReplay",
297
305
  "NormalizedModelGatewayConfig",
@@ -605,6 +613,7 @@
605
613
  "murmur3_32",
606
614
  "normalizeCredentialDestinations",
607
615
  "normalizeModelGatewayConfig",
616
+ "normalizeSandboxConnectionKeys",
608
617
  "normalizeSandboxEgressPolicy",
609
618
  "normalizeSandboxLabels",
610
619
  "normalizeSandboxNetworkPolicy",
@@ -15,12 +15,32 @@ interface ModelHistoryToolCall {
15
15
  name: string;
16
16
  args: unknown;
17
17
  }
18
+ /** Text a user or tool message carries among its parts. */
19
+ interface ModelTextPart {
20
+ type: "text";
21
+ text: string;
22
+ }
23
+ /**
24
+ * A stored file a user or tool message carries, by its ref: the history and the journal hold only this, and the model's
25
+ * connection sends the file's bytes, or the provider's id of them, when it sends the request.
26
+ */
27
+ interface ModelFilePart {
28
+ type: "file";
29
+ ref: Ref;
30
+ bytes: number;
31
+ mediaType: string;
32
+ name?: string;
33
+ /** The object the value came from, which remembers provider file ids. */
34
+ object?: string;
35
+ }
36
+ type ModelContentPart = ModelTextPart | ModelFilePart;
18
37
  /** One earlier message, oldest first. User and assistant text is as it always was; an assistant message may also carry the
19
- * Tool calls it made, and a tool message returns one call's result to the model. The tool messages right after an
20
- * assistant message answer each of its calls once, before any other message. */
38
+ * Tool calls it made, and a tool message returns one call's result to the model. A user or tool message may carry content
39
+ * parts instead of text: text and stored files, in order. The tool messages right after an assistant message answer each of
40
+ * its calls once, before any other message. */
21
41
  type ModelHistoryMessage = {
22
42
  role: "user";
23
- content: string;
43
+ content: string | ModelContentPart[];
24
44
  } | {
25
45
  role: "assistant";
26
46
  content: string;
@@ -28,7 +48,7 @@ type ModelHistoryMessage = {
28
48
  } | {
29
49
  role: "tool";
30
50
  toolCallId: string;
31
- content: string;
51
+ content: string | ModelContentPart[];
32
52
  isError?: boolean;
33
53
  };
34
54
 
@@ -1,3 +1,5 @@
1
+ /** A sandbox may narrow its owner's connections by binding key. An empty list permits no connection. */
2
+ declare function normalizeSandboxConnectionKeys(value: unknown): string[];
1
3
  /**
2
4
  * A sandbox's own egress settings: an ordered host policy that narrows its pool's network, and labels every egress event
3
5
  * carries. They are provider-neutral declarations; a pool whose provider has no egress gate refuses them rather than
@@ -201,12 +203,32 @@ interface ModelHistoryToolCall {
201
203
  name: string;
202
204
  args: unknown;
203
205
  }
206
+ /** Text a user or tool message carries among its parts. */
207
+ interface ModelTextPart {
208
+ type: "text";
209
+ text: string;
210
+ }
211
+ /**
212
+ * A stored file a user or tool message carries, by its ref: the history and the journal hold only this, and the model's
213
+ * connection sends the file's bytes, or the provider's id of them, when it sends the request.
214
+ */
215
+ interface ModelFilePart {
216
+ type: "file";
217
+ ref: Ref;
218
+ bytes: number;
219
+ mediaType: string;
220
+ name?: string;
221
+ /** The object the value came from, which remembers provider file ids. */
222
+ object?: string;
223
+ }
224
+ type ModelContentPart = ModelTextPart | ModelFilePart;
204
225
  /** One earlier message, oldest first. User and assistant text is as it always was; an assistant message may also carry the
205
- * Tool calls it made, and a tool message returns one call's result to the model. The tool messages right after an
206
- * assistant message answer each of its calls once, before any other message. */
226
+ * Tool calls it made, and a tool message returns one call's result to the model. A user or tool message may carry content
227
+ * parts instead of text: text and stored files, in order. The tool messages right after an assistant message answer each of
228
+ * its calls once, before any other message. */
207
229
  type ModelHistoryMessage = {
208
230
  role: "user";
209
- content: string;
231
+ content: string | ModelContentPart[];
210
232
  } | {
211
233
  role: "assistant";
212
234
  content: string;
@@ -214,7 +236,7 @@ type ModelHistoryMessage = {
214
236
  } | {
215
237
  role: "tool";
216
238
  toolCallId: string;
217
- content: string;
239
+ content: string | ModelContentPart[];
218
240
  isError?: boolean;
219
241
  };
220
242
  /** Opt-in prompt caching. With a hint, an Anthropic-protocol request marks cache breakpoints on its stable prefix (Tools and
@@ -236,6 +258,19 @@ declare function modelPrompt(args: ModelInvocationArgs): string;
236
258
  * assistant message), then each earlier exchange as its own message, then feedback about the previous attempt. Without
237
259
  * history this is the single prompt message it always was. */
238
260
  declare function modelMessages(args: ModelInvocationArgs): ModelHistoryMessage[];
261
+ /**
262
+ * How a model's connection sends one stored file of a request: its bytes inline, the provider's id of the file it already holds,
263
+ * or, when the file cannot be sent to this model, a text part with the reason, so the turn goes on and the model reads why.
264
+ */
265
+ type ResolvedModelFile = {
266
+ kind: "inline";
267
+ } | {
268
+ kind: "provider";
269
+ id: string;
270
+ } | {
271
+ kind: "refused";
272
+ reason: string;
273
+ };
239
274
  /** Choices an OpenAI-protocol request makes for the endpoint it is sent to. Without them the request is plain Chat
240
275
  * Completions, as every OpenAI-compatible endpoint takes it. */
241
276
  interface ModelProtocolRequestOptions {
@@ -245,7 +280,11 @@ interface ModelProtocolRequestOptions {
245
280
  /** Name an error Tool result `tool_error`, which the Constal Gateway sends to Anthropic as `is_error`. */
246
281
  toolErrorName?: boolean;
247
282
  }
248
- declare function modelProtocolRequest(protocol: ModelGatewayProtocol, model: string, maxOutputTokens: number | null, temperature: number | null, args: ModelInvocationArgs, options?: ModelProtocolRequestOptions): Record<string, unknown>;
283
+ /** How each stored file of a request is sent, by its ref (`modelFileParts`); every file part of the request needs one. */
284
+ interface ModelProtocolFiles {
285
+ files?: ReadonlyMap<string, ResolvedModelFile>;
286
+ }
287
+ declare function modelProtocolRequest(protocol: ModelGatewayProtocol, model: string, maxOutputTokens: number | null, temperature: number | null, args: ModelInvocationArgs, options?: ModelProtocolRequestOptions & ModelProtocolFiles): Record<string, unknown>;
249
288
  declare function modelProtocolResult(protocol: ModelGatewayProtocol, raw: unknown, provider: string, model: string): ModelInvocationResult;
250
289
 
251
290
  /**
@@ -1829,7 +1868,7 @@ type PolicyInvocationOrigin = {
1829
1868
  } | {
1830
1869
  kind: "channel";
1831
1870
  channel: CRN;
1832
- phase: "receive" | "respond" | "send" | "failed" | "authorize-subscription";
1871
+ phase: "receive" | "respond" | "send" | "failed" | "authorize-subscription" | "presence" | "fetch";
1833
1872
  } | {
1834
1873
  kind: "sandbox";
1835
1874
  agent: CRN;
@@ -1980,6 +2019,8 @@ declare function normalizeSandboxWorkspacePath(path: string, cwd?: string): stri
1980
2019
  * (CredentialDestination). Nothing here names them.
1981
2020
  */
1982
2021
  interface CreateSandboxOptions {
2022
+ /** Restrict egress credentials to these owner connection keys. Omitted keeps the existing restriction; [] permits none. */
2023
+ connectionKeys?: string[];
1983
2024
  image?: SandboxImage;
1984
2025
  resetImage?: boolean;
1985
2026
  execution?: ContainerImageSelection;
@@ -3306,10 +3347,12 @@ interface BoundResourceCapabilities {
3306
3347
  hash: Hash;
3307
3348
  credentialSlots: string[];
3308
3349
  operations: BoundOperation[];
3350
+ /** `inputModalities`: what the model takes as input (`text`, `image`, `file`, …), when its Resource declares it. */
3309
3351
  model?: {
3310
3352
  id: string;
3311
3353
  contextTokens?: number;
3312
3354
  maxOutputTokens?: number;
3355
+ inputModalities?: string[];
3313
3356
  };
3314
3357
  }
3315
3358
  /** One evaluation of shared state against typed questions through a bound evaluation Model, or a Gateway plus explicit model identifier. */
@@ -3381,6 +3424,12 @@ interface Ctx {
3381
3424
  invokeAsync<T>(resource: CRN, op: string, args: unknown, opts?: InvokeOpts): InvocationHandle<T>;
3382
3425
  request(policy: PolicyCRN, grant: CapabilityGrant): Handle<CapabilityRef>;
3383
3426
  analytics: AnalyticsClient;
3427
+ /**
3428
+ * Declares what this Run's conversation shows once the Run ends: a state its Channel renders (Leonard's Slack Channel:
3429
+ * suspended, processing or active). The last declaration of the Run stands; with none, a Run admitted by an event that
3430
+ * showed working shows idle. "working" is the platform's own and cannot be declared.
3431
+ */
3432
+ presence(state: string): void;
3384
3433
  /** This step's journal at the Agent's current position. Undefined where the platform's runtime predates it. */
3385
3434
  readonly journal?: StepJournal;
3386
3435
  run: RunInfo;
@@ -3508,6 +3557,31 @@ interface CanonicalEvent<T = unknown> {
3508
3557
  occurredAt: number;
3509
3558
  deliver?: DeliveryMode;
3510
3559
  }
3560
+ /** A file an event carries, as the source declared it. */
3561
+ interface ChannelObject {
3562
+ /** The source's own id of the file, unique within this Channel for its customer. */
3563
+ id: string;
3564
+ name?: string;
3565
+ mediaType?: string;
3566
+ /** Its size as the source declared it. */
3567
+ bytes?: number;
3568
+ /** What fetch() needs to reach it again (Slack: the download path). */
3569
+ metadata?: Record<string, string | number | boolean>;
3570
+ }
3571
+ /** A range of a file receive() declared, for fetch() to download with this Channel's own Resources. */
3572
+ interface ChannelFetchRequest {
3573
+ object: ChannelObject;
3574
+ range: {
3575
+ offset: number;
3576
+ length: number;
3577
+ };
3578
+ }
3579
+ /** `gone` says why the source no longer has the file. */
3580
+ type ChannelFetchResult = {
3581
+ fetched: true;
3582
+ } | {
3583
+ gone: string;
3584
+ };
3511
3585
  interface CanonicalEventDraft<T = unknown> {
3512
3586
  id: string;
3513
3587
  type: string;
@@ -3526,6 +3600,31 @@ interface CanonicalEventDraft<T = unknown> {
3526
3600
  replyTo?: string;
3527
3601
  metadata?: Record<string, string | number | boolean>;
3528
3602
  };
3603
+ /** The event's presence: `working` asks the Session to show working when it admits the event (never for a duplicate);
3604
+ * `metadata` reaches presence() for this event's destination. */
3605
+ presence?: {
3606
+ working?: true;
3607
+ metadata?: Record<string, string | number | boolean>;
3608
+ };
3609
+ /** Files the event carries that the platform stores when first read, or in the background from admission. */
3610
+ objects?: ChannelObject[];
3611
+ }
3612
+ /** What a destination shows, as presence() receives it. */
3613
+ interface ChannelPresence {
3614
+ destination: string;
3615
+ replyTo?: string;
3616
+ /** The reply address's metadata, as receive() pinned it. */
3617
+ replyMetadata?: Record<string, string | number | boolean>;
3618
+ /** "working", "idle", or the state a Run declared (ctx.presence). */
3619
+ state: string;
3620
+ /** The presence metadata of the event this destination's presence came from. */
3621
+ metadata: Record<string, string | number | boolean>;
3622
+ /** What this Channel's last presence() for this destination returned; null for the first. */
3623
+ previous: Record<string, string | number | boolean> | null;
3624
+ }
3625
+ /** What presence() returns; the next presence() for the destination receives its metadata as `previous`. */
3626
+ interface ChannelPresenceReceipt {
3627
+ metadata?: Record<string, string | number | boolean>;
3529
3628
  }
3530
3629
  interface IgnoredChannelEvent {
3531
3630
  ignored: true;
@@ -3616,6 +3715,10 @@ interface ChannelProtocol<Input = unknown, Output = unknown, Delivery = Output>
3616
3715
  failed?(failure: ChannelFailure, context: ChannelContext): Promise<void> | void;
3617
3716
  /** Prove external access before a subscriber's Channel, bindings, or routes are installed. */
3618
3717
  authorizeSubscription?(request: ChannelSubscriptionRequest, context: ChannelContext): Promise<boolean> | boolean;
3718
+ /** Shows a destination's presence. Called by the Session's outbox, in order, once per state change. */
3719
+ presence?(presence: ChannelPresence, context: ChannelContext): Promise<ChannelPresenceReceipt> | ChannelPresenceReceipt;
3720
+ /** Fetches a range of a file receive() declared, with this Channel's own Resources; `gone` says why the source no longer has it. */
3721
+ fetch?(request: ChannelFetchRequest, context: ChannelContext): Promise<ChannelFetchResult> | ChannelFetchResult;
3619
3722
  }
3620
3723
  interface Channel<Input = unknown, Output = unknown, Delivery = Output> {
3621
3724
  id: string;
@@ -5539,5 +5642,5 @@ declare function parseLedgerAddress(value: unknown): LedgerAddressParts | null;
5539
5642
  /** Formats ledger address parts; throws when a part breaks its id rule. */
5540
5643
  declare function formatLedgerAddress(parts: LedgerAddressParts): LedgerAddress;
5541
5644
 
5542
- export { AGENT_UI_DEFAULTS, AfterYield, ApiError, CHAT_FORMAT_CAPABILITY, 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, DATA_SHARE_FEE_BPS, DirectNetworkDenied, EVALUATION_LIMITS, EffectCeilingExceeded, EmptyJoin, GENERAL_QUALITY_JUDGE, GateExhausted, IntegrationRequestNotSent, LeaseLost, MCP_CLIENT_CAPABILITY, MCP_PROTOCOL_VERSION, MEMORY_OPERATION_DECLARATIONS, MODEL_CHECKPOINT_IMPORT_CAPABILITY, MODEL_COMPLETION_CAPABILITY, MODEL_EVALUATION_CAPABILITY, McpClient, NondeterministicReplay, NotAppendOnly, OutcomeUnknown, PolicyConstraintFailed, PolicyDecisionFailed, RESOURCE_CREDENTIAL_BINDING_SCHEMA, RESOURCE_KINDS, ResourceDisabled, ResourceInvalid, ResourceUnbound, RollbackTargetInvalid, SANDBOX_EGRESS_LIMITS, SessionDeleted, SpawnCardinality, SwallowedYield, TRAINING_PROVIDER_CAPABILITY, TRAINING_RECIPE_DEFAULTS, 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, chatFormat, chatFormatMetadata, chatFormatPin, chatParseInput, chatParsed, chatRenderInput, chatRenderRequest, chatRendering, checkpointArtifactRef, checkpointDeploymentRequest, checkpointImportMetadata, checkpointImportRequest, codeScorerIR, containerImageReference, containerImageSelection, containerImageSource, credentialEvidence, credentialInteractionAction, credentialInteractionEvent, credentialInteractionResult, credentialName, credentialProvider, credentialProviderConfigSchema, credentialProviderName, credentialProviderSetupMetadata, credentialRotationDefaults, credentialSetupState, customerTenantName, cutBatches, cutPartitions, dataShareEarningMicroUsd, datasetName, evaluateCodeScorer, evaluatePolicyDefinition, evaluationArguments, evaluationProtocolRequest, evaluationProtocolResult, formatLedgerAddress, gateway, gatewayModelOffer, gatewayPackageMetadata, hash, hashValue, immutableContainerImageReference, integrationEgressPolicy, invocationCredentialUses, judgeAgent, labelSelector, matchesAction, matchesLabelSelector, matchesResource, mcpToolDescription, mcpToolResult, memoryStoreBinding, modelAdvertisedPricing, modelControls, modelGatewayBinding, modelGatewayEndpoint, modelGenerationOptions, modelLimit, modelMessages, modelPrompt, modelProtocolRequest, modelProtocolResult, murmur3_32, normalizeCredentialDestinations, normalizeModelGatewayConfig, normalizeSandboxEgressPolicy, normalizeSandboxLabels, normalizeSandboxNetworkPolicy, normalizeSandboxWorkspacePath, noulDecision, opTool, opTools, parseLedgerAddress, parseResourceName, policy, policyName, race, resolveBindingOwner, resolveContainerImageSource, resolveGatewayEgress, resolveResourceDependencyRef, resourceContractRef, resourceCredentialBinding, resourceDependencyRef, resourceLabelMap, resourceName, resourceNeed, resourcePattern, resourceSelector, resourceTools, runLabels, sandboxControls, sandboxEgressDecision, sandboxEgressHostMatches, sandboxLimit, scopedBindingKey, scopedCredentialRef, scopedResourceRef, scoreLevel, scorerDraftHash, scorerName, select, selectableResourceLabels, setupAwait, setupCredentialReceipt, setupPanelProviderIsCrn, setupScreen, setupScreenView, setupSubmission, sha256Hex, shareContributionRequest, shareContributionReview, shareEvaluation, sharePrices, shareRequest, skills, stageOutput, startTrainingRequest, subtask, tableDescribe, tableQuery, trainingCorrection, trainingProvider, trainingProviderMetadata, trainingRecipe, uiAssetContentType, uiBundle, uiBundleManifest, uiLimit, uiName, validateBatchSpec, validateFoldFn, validateJsonSchema, validateJsonSchemaDefinition, validatePartitionFn, validatePartitionSpec, validateStageOutputSpec, validateTool, validateView, webFetch, webSearch };
5543
- 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, ChatFormatDefinition, ChatFormatMetadata, ChatFormatPin, ChatMessage, ChatParseRequest, ChatParsed, ChatRenderRequest, ChatRendering, ChatSpan, ChatTool, 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, CredentialDestination, CredentialDestroyResult, CredentialEvidence, CredentialInteractionAction, CredentialInteractionAdvanceRequest, CredentialInteractionEvent, CredentialInteractionPrimaryAction, CredentialInteractionProof, CredentialInteractionResult, CredentialInteractionStartRequest, CredentialMaterialRequest, CredentialMintRequest, CredentialMintResult, CredentialPresentation, CredentialProviderCRN, CredentialProviderConfigEgressBinding, CredentialProviderContext, CredentialProviderCredentialSlotSetup, CredentialProviderDefinition, CredentialProviderPackage, CredentialProviderPackageMetadata, CredentialProviderSecretInput, CredentialProviderSetupMetadata, CredentialSetupState, CredentialUninstallRequest, CredentialUninstallResult, CredentialVerifyResult, Ctx, CustomerTenantCRN, DataManifest, DataSharingScope, DatasetCRN, DatasetDraft, DatasetRef, DelegatedGrant, DelegationCeiling, DeliveryMode, DeliveryReceipt, DispatchResult, EffectClass, EvalComparison, EvalDivergence, EvalMode, EvalSubject, EvalSubjectSource, EvalSuiteCase, EvalSuiteCasePage, EvalSuiteCaseScore, EvalSuiteCaseState, EvalSuiteScoreState, 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, HistoryPage, HistoryView, HmacVerification, IgnoredChannelEvent, IngressRequest, IngressTarget, IntegrationArtifactEgressRequest, IntegrationArtifactEgressResponse, IntegrationAttachment, IntegrationContext, IntegrationEgressPolicy, IntegrationEgressRequest, IntegrationEgressResponse, IntegrationEgressRule, IntegrationLifecycle, IntegrationReleaseContext, IntegrationSecret, IntegrationState, InvocationCredentialUse, InvocationHandle, InvokableKind, InvokeOpts, JoinOutcome, JsonScalar, JsonValue, JudgeRubric, LabelRequest, LabelSelector, LabelSelectorOperator, LabelSelectorRequirement, LedgerAddress, LedgerAddressParts, LedgerEvent, ListSchedulesOptions, 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, SandboxEgressPolicy, SandboxEgressRule, SandboxExecInput, SandboxFileResult, SandboxGovernanceControls, SandboxGovernanceMeter, SandboxImage, SandboxLabels, SandboxMutationResult, SandboxNetworkMode, SandboxNetworkPolicy, SandboxPool, SandboxProcess, SandboxProcessCredentials, SandboxProcessIoOperation, SandboxProcessOperation, SandboxProcessReadInput, SandboxProcessReadResult, SandboxProcessStatus, SandboxProcessWriteResult, SandboxReadFileOptions, SandboxReadFileResult, SandboxWorkspace, SandboxWorkspaceInspection, SandboxWorkspacePreparation, SandboxWorkspaceReceipt, 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, ScorerDraft, ScorerEvaluation, ScorerKind, ScorerRef, ScorerVerdictIntent, SetEvalBaselineRequest, SetupAction, SetupCredentialCandidate, SetupCredentialInteractionPanel, SetupCredentialReceipt, SetupFormPanel, SetupPanel, SetupProgressPanel, SetupReviewPanel, SetupScreen, SetupStepStatus, SetupStepSummary, SetupSubmission, SetupTerminalPanel, SetupWorkflowStatus, Share, ShareAction, ShareContribution, ShareContributionImport, ShareContributionRequest, ShareContributionReview, ShareContributionReviewRequest, ShareContributionStatus, ShareEvaluation, ShareEvaluationPin, ShareEvaluationRequest, ShareEvaluationVerdict, ShareEvaluationView, ShareHistory, SharePrice, ShareRequest, ShareReviewDecision, SortField, SpawnAttenuation, SpawnBudget, SpawnHandle, SpawnOpts, SqlFold, StageInfo, StageOutputSpec, StartTrainingRequest, SteerEvent, StepJournal, SuiteFact, TableAggregate, TableDescribeArgs, TableFilter, TableFilterOperation, TableOrder, TableQueryArgs, TableQueryPlan, TableQueryResult, TableScalar, TableSnapshotDescription, Task, Tier, Tool, ToolCallRecord, TrainingCorrection, TrainingJobFact, TrainingJobReference, TrainingJobState, TrainingJobStatus, TrainingMethod, TrainingModelOffer, TrainingPreparation, TrainingProviderDefinition, TrainingProviderMetadata, TrainingProviderPin, TrainingRecipe, TrainingResumePoint, TrainingStep, TrainingUsageUnits, TurnDraft, TurnGate, TurnHistoryMessage, TurnRecord, TurnSpec, UiAccess, UiBundle, UiBundleManifest, UiCRN, UiCapability, UiExecution, UiGovernanceMeter, UiHandler, UiResource, UiRuntimeContext, UiSource, UiSqlResult, UiState, UpstreamPayer, Verdict, VerdictSamplingMode, ViewDef, WaitResolvedEvent };
5645
+ export { AGENT_UI_DEFAULTS, AfterYield, ApiError, CHAT_FORMAT_CAPABILITY, 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, DATA_SHARE_FEE_BPS, DirectNetworkDenied, EVALUATION_LIMITS, EffectCeilingExceeded, EmptyJoin, GENERAL_QUALITY_JUDGE, GateExhausted, IntegrationRequestNotSent, LeaseLost, MCP_CLIENT_CAPABILITY, MCP_PROTOCOL_VERSION, MEMORY_OPERATION_DECLARATIONS, MODEL_CHECKPOINT_IMPORT_CAPABILITY, MODEL_COMPLETION_CAPABILITY, MODEL_EVALUATION_CAPABILITY, McpClient, NondeterministicReplay, NotAppendOnly, OutcomeUnknown, PolicyConstraintFailed, PolicyDecisionFailed, RESOURCE_CREDENTIAL_BINDING_SCHEMA, RESOURCE_KINDS, ResourceDisabled, ResourceInvalid, ResourceUnbound, RollbackTargetInvalid, SANDBOX_EGRESS_LIMITS, SessionDeleted, SpawnCardinality, SwallowedYield, TRAINING_PROVIDER_CAPABILITY, TRAINING_RECIPE_DEFAULTS, 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, chatFormat, chatFormatMetadata, chatFormatPin, chatParseInput, chatParsed, chatRenderInput, chatRenderRequest, chatRendering, checkpointArtifactRef, checkpointDeploymentRequest, checkpointImportMetadata, checkpointImportRequest, codeScorerIR, containerImageReference, containerImageSelection, containerImageSource, credentialEvidence, credentialInteractionAction, credentialInteractionEvent, credentialInteractionResult, credentialName, credentialProvider, credentialProviderConfigSchema, credentialProviderName, credentialProviderSetupMetadata, credentialRotationDefaults, credentialSetupState, customerTenantName, cutBatches, cutPartitions, dataShareEarningMicroUsd, datasetName, evaluateCodeScorer, evaluatePolicyDefinition, evaluationArguments, evaluationProtocolRequest, evaluationProtocolResult, formatLedgerAddress, gateway, gatewayModelOffer, gatewayPackageMetadata, hash, hashValue, immutableContainerImageReference, integrationEgressPolicy, invocationCredentialUses, judgeAgent, labelSelector, matchesAction, matchesLabelSelector, matchesResource, mcpToolDescription, mcpToolResult, memoryStoreBinding, modelAdvertisedPricing, modelControls, modelGatewayBinding, modelGatewayEndpoint, modelGenerationOptions, modelLimit, modelMessages, modelPrompt, modelProtocolRequest, modelProtocolResult, murmur3_32, normalizeCredentialDestinations, normalizeModelGatewayConfig, normalizeSandboxConnectionKeys, normalizeSandboxEgressPolicy, normalizeSandboxLabels, normalizeSandboxNetworkPolicy, normalizeSandboxWorkspacePath, noulDecision, opTool, opTools, parseLedgerAddress, parseResourceName, policy, policyName, race, resolveBindingOwner, resolveContainerImageSource, resolveGatewayEgress, resolveResourceDependencyRef, resourceContractRef, resourceCredentialBinding, resourceDependencyRef, resourceLabelMap, resourceName, resourceNeed, resourcePattern, resourceSelector, resourceTools, runLabels, sandboxControls, sandboxEgressDecision, sandboxEgressHostMatches, sandboxLimit, scopedBindingKey, scopedCredentialRef, scopedResourceRef, scoreLevel, scorerDraftHash, scorerName, select, selectableResourceLabels, setupAwait, setupCredentialReceipt, setupPanelProviderIsCrn, setupScreen, setupScreenView, setupSubmission, sha256Hex, shareContributionRequest, shareContributionReview, shareEvaluation, sharePrices, shareRequest, skills, stageOutput, startTrainingRequest, subtask, tableDescribe, tableQuery, trainingCorrection, trainingProvider, trainingProviderMetadata, trainingRecipe, uiAssetContentType, uiBundle, uiBundleManifest, uiLimit, uiName, validateBatchSpec, validateFoldFn, validateJsonSchema, validateJsonSchemaDefinition, validatePartitionFn, validatePartitionSpec, validateStageOutputSpec, validateTool, validateView, webFetch, webSearch };
5646
+ 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, ChannelFetchRequest, ChannelFetchResult, ChannelIngressEvent, ChannelIngressSource, ChannelMessage, ChannelObject, ChannelPresence, ChannelPresenceReceipt, ChannelProtocol, ChannelReceiveResult, ChannelRequest, ChannelResponse, ChannelSourceEvidence, ChannelSubscriptionRequest, ChannelTarget, ChatFormatDefinition, ChatFormatMetadata, ChatFormatPin, ChatMessage, ChatParseRequest, ChatParsed, ChatRenderRequest, ChatRendering, ChatSpan, ChatTool, 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, CredentialDestination, CredentialDestroyResult, CredentialEvidence, CredentialInteractionAction, CredentialInteractionAdvanceRequest, CredentialInteractionEvent, CredentialInteractionPrimaryAction, CredentialInteractionProof, CredentialInteractionResult, CredentialInteractionStartRequest, CredentialMaterialRequest, CredentialMintRequest, CredentialMintResult, CredentialPresentation, CredentialProviderCRN, CredentialProviderConfigEgressBinding, CredentialProviderContext, CredentialProviderCredentialSlotSetup, CredentialProviderDefinition, CredentialProviderPackage, CredentialProviderPackageMetadata, CredentialProviderSecretInput, CredentialProviderSetupMetadata, CredentialSetupState, CredentialUninstallRequest, CredentialUninstallResult, CredentialVerifyResult, Ctx, CustomerTenantCRN, DataManifest, DataSharingScope, DatasetCRN, DatasetDraft, DatasetRef, DelegatedGrant, DelegationCeiling, DeliveryMode, DeliveryReceipt, DispatchResult, EffectClass, EvalComparison, EvalDivergence, EvalMode, EvalSubject, EvalSubjectSource, EvalSuiteCase, EvalSuiteCasePage, EvalSuiteCaseScore, EvalSuiteCaseState, EvalSuiteScoreState, 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, HistoryPage, HistoryView, HmacVerification, IgnoredChannelEvent, IngressRequest, IngressTarget, IntegrationArtifactEgressRequest, IntegrationArtifactEgressResponse, IntegrationAttachment, IntegrationContext, IntegrationEgressPolicy, IntegrationEgressRequest, IntegrationEgressResponse, IntegrationEgressRule, IntegrationLifecycle, IntegrationReleaseContext, IntegrationSecret, IntegrationState, InvocationCredentialUse, InvocationHandle, InvokableKind, InvokeOpts, JoinOutcome, JsonScalar, JsonValue, JudgeRubric, LabelRequest, LabelSelector, LabelSelectorOperator, LabelSelectorRequirement, LedgerAddress, LedgerAddressParts, LedgerEvent, ListSchedulesOptions, LocalResourceRef, ManifestIndexPage, MapFact, MapOpts, McpClientOptions, McpClientState, McpMessageTransport, MemoryDeleteArgs, MemoryGetArgs, MemoryRecord, MemoryRememberArgs, MemorySearchArgs, MemorySearchHit, MemoryStoreBinding, Mode, ModelAdvertisedPricing, ModelCacheHint, ModelCompletion, ModelContentPart, ModelCredentialHeader, ModelFilePart, ModelGatewayBinding, ModelGatewayConfig, ModelGatewayProtocol, ModelGenerationOptions, ModelGovernanceControls, ModelGovernanceMeter, ModelHistoryMessage, ModelHistoryToolCall, ModelInvocationArgs, ModelInvocationResult, ModelProtocolRequestOptions, ModelTechnicalCapabilities, ModelTextPart, 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, SandboxEgressPolicy, SandboxEgressRule, SandboxExecInput, SandboxFileResult, SandboxGovernanceControls, SandboxGovernanceMeter, SandboxImage, SandboxLabels, SandboxMutationResult, SandboxNetworkMode, SandboxNetworkPolicy, SandboxPool, SandboxProcess, SandboxProcessCredentials, SandboxProcessIoOperation, SandboxProcessOperation, SandboxProcessReadInput, SandboxProcessReadResult, SandboxProcessStatus, SandboxProcessWriteResult, SandboxReadFileOptions, SandboxReadFileResult, SandboxWorkspace, SandboxWorkspaceInspection, SandboxWorkspacePreparation, SandboxWorkspaceReceipt, 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, ScorerDraft, ScorerEvaluation, ScorerKind, ScorerRef, ScorerVerdictIntent, SetEvalBaselineRequest, SetupAction, SetupCredentialCandidate, SetupCredentialInteractionPanel, SetupCredentialReceipt, SetupFormPanel, SetupPanel, SetupProgressPanel, SetupReviewPanel, SetupScreen, SetupStepStatus, SetupStepSummary, SetupSubmission, SetupTerminalPanel, SetupWorkflowStatus, Share, ShareAction, ShareContribution, ShareContributionImport, ShareContributionRequest, ShareContributionReview, ShareContributionReviewRequest, ShareContributionStatus, ShareEvaluation, ShareEvaluationPin, ShareEvaluationRequest, ShareEvaluationVerdict, ShareEvaluationView, ShareHistory, SharePrice, ShareRequest, ShareReviewDecision, SortField, SpawnAttenuation, SpawnBudget, SpawnHandle, SpawnOpts, SqlFold, StageInfo, StageOutputSpec, StartTrainingRequest, SteerEvent, StepJournal, SuiteFact, TableAggregate, TableDescribeArgs, TableFilter, TableFilterOperation, TableOrder, TableQueryArgs, TableQueryPlan, TableQueryResult, TableScalar, TableSnapshotDescription, Task, Tier, Tool, ToolCallRecord, TrainingCorrection, TrainingJobFact, TrainingJobReference, TrainingJobState, TrainingJobStatus, TrainingMethod, TrainingModelOffer, TrainingPreparation, TrainingProviderDefinition, TrainingProviderMetadata, TrainingProviderPin, TrainingRecipe, TrainingResumePoint, TrainingStep, 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
@@ -1533,7 +1533,7 @@ function executable(value, path2) {
1533
1533
  function channel(definition) {
1534
1534
  executable(definition, "channel");
1535
1535
  executable(definition.protocol, "channel.protocol");
1536
- if (typeof definition.protocol.receive !== "function" || typeof definition.protocol.respond !== "function" || definition.protocol.send !== void 0 && typeof definition.protocol.send !== "function" || definition.protocol.failed !== void 0 && typeof definition.protocol.failed !== "function" || definition.protocol.authorizeSubscription !== void 0 && typeof definition.protocol.authorizeSubscription !== "function") {
1536
+ if (typeof definition.protocol.receive !== "function" || typeof definition.protocol.respond !== "function" || definition.protocol.send !== void 0 && typeof definition.protocol.send !== "function" || definition.protocol.failed !== void 0 && typeof definition.protocol.failed !== "function" || definition.protocol.authorizeSubscription !== void 0 && typeof definition.protocol.authorizeSubscription !== "function" || definition.protocol.presence !== void 0 && typeof definition.protocol.presence !== "function" || definition.protocol.fetch !== void 0 && typeof definition.protocol.fetch !== "function") {
1537
1537
  throw new TypeError("channel.protocol must define receive and respond; optional handlers must be functions");
1538
1538
  }
1539
1539
  resourceDependencyRef(definition.authProvider, ["auth-provider"]);
@@ -2986,6 +2986,37 @@ function modelCacheHint(value) {
2986
2986
  }
2987
2987
  return hint;
2988
2988
  }
2989
+ var REF = /^[a-f0-9]{64}$/u;
2990
+ var MEDIA_TYPE = /^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]*\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]*$/u;
2991
+ var FILE_PART_FIELDS = ["type", "ref", "bytes", "mediaType", "name", "object"];
2992
+ function modelMessageContent(value, at) {
2993
+ if (typeof value === "string") return value;
2994
+ if (!Array.isArray(value)) throw new TypeError(`${at} content must be text or an array of text and file parts`);
2995
+ return value.map((candidate, index) => {
2996
+ const part = record7(candidate);
2997
+ const where = `${at} content part ${index}`;
2998
+ if (part?.type === "text") {
2999
+ if (typeof part.text !== "string" || Object.keys(part).some((key) => key !== "type" && key !== "text")) {
3000
+ throw new TypeError(`${where} is a text part, which carries its text and nothing else`);
3001
+ }
3002
+ return { type: "text", text: part.text };
3003
+ }
3004
+ if (part?.type !== "file") throw new TypeError(`${where} must be a text or file part`);
3005
+ const unknown = Object.keys(part).find((key) => !FILE_PART_FIELDS.includes(key));
3006
+ if (unknown !== void 0) throw new TypeError(`${where} has an unknown field: ${unknown}`);
3007
+ if (typeof part.ref !== "string" || !REF.test(part.ref) || !Number.isSafeInteger(part.bytes) || Number(part.bytes) < 0 || typeof part.mediaType !== "string" || !MEDIA_TYPE.test(part.mediaType) || part.name !== void 0 && !nonempty(part.name) || part.object !== void 0 && !nonempty(part.object)) {
3008
+ throw new TypeError(`${where} needs a stored value's ref, its size in bytes and its media type`);
3009
+ }
3010
+ return {
3011
+ type: "file",
3012
+ ref: part.ref,
3013
+ bytes: Number(part.bytes),
3014
+ mediaType: part.mediaType,
3015
+ ...part.name === void 0 ? {} : { name: part.name },
3016
+ ...part.object === void 0 ? {} : { object: part.object }
3017
+ };
3018
+ });
3019
+ }
2989
3020
  function modelHistoryMessages(value) {
2990
3021
  if (value === void 0) return [];
2991
3022
  if (!Array.isArray(value)) throw new TypeError("model history must be an array of messages");
@@ -2994,9 +3025,10 @@ function modelHistoryMessages(value) {
2994
3025
  const messages = value.map((candidate, index) => {
2995
3026
  const at = `model history message ${index}`;
2996
3027
  const source = record7(candidate);
2997
- if (!source || typeof source.content !== "string" || source.role !== "user" && source.role !== "assistant" && source.role !== "tool") {
3028
+ if (!source || source.role !== "user" && source.role !== "assistant" && source.role !== "tool" || source.role === "assistant" && typeof source.content !== "string") {
2998
3029
  throw new TypeError(`${at} needs a user, assistant or tool role and text content`);
2999
3030
  }
3031
+ const content2 = modelMessageContent(source.content, at);
3000
3032
  const foreign = source.role === "tool" ? ["toolCalls"] : source.role === "user" ? ["toolCalls", "toolCallId", "isError"] : ["toolCallId", "isError"];
3001
3033
  const misplaced = foreign.find((field2) => source[field2] !== void 0);
3002
3034
  if (misplaced !== void 0) throw new TypeError(`${at} has the ${source.role} role, which cannot carry ${misplaced}`);
@@ -3009,13 +3041,15 @@ function modelHistoryMessages(value) {
3009
3041
  return {
3010
3042
  role: "tool",
3011
3043
  toolCallId: source.toolCallId,
3012
- content: source.content,
3044
+ content: content2,
3013
3045
  ...source.isError === void 0 ? {} : { isError: source.isError }
3014
3046
  };
3015
3047
  }
3016
3048
  const open2 = unanswered.values().next();
3017
3049
  if (!open2.done) throw new TypeError(`model history Tool call ${open2.value} has no tool message answering it before message ${index}`);
3018
- if (source.role === "user" || source.toolCalls === void 0) return { role: source.role, content: source.content };
3050
+ if (source.role === "user") return { role: "user", content: content2 };
3051
+ if (typeof content2 !== "string") throw new TypeError(`${at} needs a user, assistant or tool role and text content`);
3052
+ if (source.toolCalls === void 0) return { role: "assistant", content: content2 };
3019
3053
  if (!Array.isArray(source.toolCalls)) throw new TypeError(`${at} toolCalls must be an array`);
3020
3054
  const toolCalls = source.toolCalls.map((call, position2) => {
3021
3055
  const entry2 = record7(call);
@@ -3030,7 +3064,7 @@ function modelHistoryMessages(value) {
3030
3064
  unanswered.add(entry2.id);
3031
3065
  return { id: entry2.id, name: entry2.name, args: entry2.args };
3032
3066
  });
3033
- return { role: "assistant", content: source.content, ...toolCalls.length ? { toolCalls } : {} };
3067
+ return { role: "assistant", content: content2, ...toolCalls.length ? { toolCalls } : {} };
3034
3068
  });
3035
3069
  const open = unanswered.values().next();
3036
3070
  if (!open.done) throw new TypeError(`model history Tool call ${open.value} has no tool message answering it`);
@@ -3052,14 +3086,50 @@ function turnMessages(args) {
3052
3086
  function modelMessages(args) {
3053
3087
  return turnMessages(args).messages;
3054
3088
  }
3089
+ var InlineModelFile = class {
3090
+ constructor(ref, prefix) {
3091
+ this.ref = ref;
3092
+ this.prefix = prefix;
3093
+ }
3094
+ ref;
3095
+ prefix;
3096
+ toJSON() {
3097
+ throw new TypeError("a request with inline files is sent as modelProtocolBody segments");
3098
+ }
3099
+ };
3100
+ function resolvedFile(part, files) {
3101
+ const file = files?.get(part.ref);
3102
+ if (!file) throw new TypeError(`model file ${part.ref} is not resolved for this request`);
3103
+ return file;
3104
+ }
3105
+ function fileLabel(part) {
3106
+ return part.name ? `The file ${part.name}` : "The file";
3107
+ }
3108
+ function imageFile(part) {
3109
+ return part.mediaType.toLowerCase().startsWith("image/");
3110
+ }
3111
+ function pdfFile(part) {
3112
+ return part.mediaType.toLowerCase() === "application/pdf";
3113
+ }
3055
3114
  function anthropicBlocks(content2) {
3056
3115
  return typeof content2 !== "string" ? content2 : content2 ? [{ type: "text", text: content2 }] : [];
3057
3116
  }
3058
- function anthropicMessage(message2) {
3117
+ function anthropicContent(content2, files) {
3118
+ if (typeof content2 === "string") return content2;
3119
+ return content2.map((part) => {
3120
+ if (part.type === "text") return { type: "text", text: part.text };
3121
+ const file = resolvedFile(part, files);
3122
+ if (file.kind === "refused") return { type: "text", text: file.reason };
3123
+ const type = imageFile(part) ? "image" : pdfFile(part) ? "document" : null;
3124
+ if (type === null) return { type: "text", text: `${fileLabel(part)} is ${part.mediaType}, which this model is not shown.` };
3125
+ return { type, source: file.kind === "provider" ? { type: "file", file_id: file.id } : { type: "base64", media_type: part.mediaType, data: new InlineModelFile(part.ref, "") } };
3126
+ });
3127
+ }
3128
+ function anthropicMessage(message2, files) {
3059
3129
  if (message2.role === "tool") return { role: "user", content: [{
3060
3130
  type: "tool_result",
3061
3131
  tool_use_id: message2.toolCallId,
3062
- content: message2.content,
3132
+ content: anthropicContent(message2.content, files),
3063
3133
  ...message2.isError ? { is_error: true } : {}
3064
3134
  }] };
3065
3135
  if (message2.role === "assistant" && message2.toolCalls) return { role: "assistant", content: [
@@ -3069,7 +3139,7 @@ function anthropicMessage(message2) {
3069
3139
  return { type: "tool_use", id: call.id, name: call.name, input: record7(args) ?? { value: args } };
3070
3140
  })
3071
3141
  ] };
3072
- return { role: message2.role, content: message2.content };
3142
+ return { role: message2.role, content: anthropicContent(message2.content, files) };
3073
3143
  }
3074
3144
  function alternating(messages) {
3075
3145
  const merged = [];
@@ -3083,11 +3153,21 @@ ${message2.content}`;
3083
3153
  }
3084
3154
  return merged;
3085
3155
  }
3156
+ function openAiPart(part, files) {
3157
+ if (part.type === "text") return { type: "text", text: part.text };
3158
+ if (!files) return { ...part };
3159
+ const file = resolvedFile(part, files);
3160
+ if (file.kind === "refused") return { type: "text", text: file.reason };
3161
+ if (file.kind === "provider") return { type: "file", file: { file_id: file.id } };
3162
+ const data = new InlineModelFile(part.ref, `data:${part.mediaType};base64,`);
3163
+ return imageFile(part) ? { type: "image_url", image_url: { url: data } } : { type: "file", file: { filename: part.name ?? "file", file_data: data } };
3164
+ }
3086
3165
  function openAiMessage(message2, options = {}) {
3166
+ const content2 = (value) => typeof value === "string" ? value : value.map((part) => openAiPart(part, options.files));
3087
3167
  if (message2.role === "tool") return {
3088
3168
  role: "tool",
3089
3169
  tool_call_id: message2.toolCallId,
3090
- content: message2.content,
3170
+ content: content2(message2.content),
3091
3171
  ...options.toolErrorName && message2.isError ? { name: "tool_error" } : {}
3092
3172
  };
3093
3173
  if (message2.role === "assistant" && message2.toolCalls) return {
@@ -3099,10 +3179,29 @@ function openAiMessage(message2, options = {}) {
3099
3179
  function: { name: call.name, arguments: canonicalJson(call.args) }
3100
3180
  }))
3101
3181
  };
3102
- return { role: message2.role, content: message2.content };
3182
+ return { role: message2.role, content: content2(message2.content) };
3183
+ }
3184
+ function openAiMessages(messages, options, mark) {
3185
+ const openai = [];
3186
+ let carried = [];
3187
+ const release = () => {
3188
+ if (carried.length) openai.push({ role: "user", content: carried.map((part) => openAiPart(part, options.files)) });
3189
+ carried = [];
3190
+ };
3191
+ messages.forEach((message2, index) => {
3192
+ if (message2.role !== "tool") release();
3193
+ if (message2.role === "tool" && typeof message2.content !== "string") {
3194
+ carried.push(...message2.content.filter((part) => part.type === "file"));
3195
+ const text2 = message2.content.flatMap((part) => part.type === "text" ? [part.text] : []).join("\n");
3196
+ openai.push(mark(openAiMessage({ ...message2, content: text2 }, options), index));
3197
+ } else openai.push(mark(openAiMessage(message2, options), index));
3198
+ });
3199
+ release();
3200
+ return openai;
3103
3201
  }
3104
3202
  function modelProtocolRequest(protocol, model, maxOutputTokens, temperature, args, options = {}) {
3105
3203
  const { effort } = modelGenerationOptions(args);
3204
+ const files = options.files ?? /* @__PURE__ */ new Map();
3106
3205
  if (args.toolChoice !== void 0 && args.toolChoice !== "auto" && args.toolChoice !== "required") {
3107
3206
  throw new TypeError("model Tool choice is invalid");
3108
3207
  }
@@ -3113,7 +3212,7 @@ function modelProtocolRequest(protocol, model, maxOutputTokens, temperature, arg
3113
3212
  const { messages, lastHistory } = turnMessages(args);
3114
3213
  const breakpoint = cache ? { type: "ephemeral", ...cache.ttl === void 0 ? {} : { ttl: cache.ttl } } : null;
3115
3214
  if (protocol === "anthropic") {
3116
- const anthropic = messages.map(anthropicMessage);
3215
+ const anthropic = messages.map((message2) => anthropicMessage(message2, files));
3117
3216
  const marked = breakpoint && lastHistory !== null ? anthropicBlocks(anthropic[lastHistory].content) : [];
3118
3217
  if (breakpoint && lastHistory !== null && marked.length) {
3119
3218
  anthropic[lastHistory] = { ...anthropic[lastHistory], content: [...marked.slice(0, -1), { ...marked.at(-1), cache_control: breakpoint }] };
@@ -3138,9 +3237,11 @@ function modelProtocolRequest(protocol, model, maxOutputTokens, temperature, arg
3138
3237
  if (protocol === "openai") {
3139
3238
  const marks = options.contentCacheControl === true ? breakpoint : null;
3140
3239
  const marked = (text2) => marks && text2 ? [{ type: "text", text: text2, cache_control: marks }] : text2;
3141
- const openai = messages.map((message2, index) => {
3142
- const entry2 = openAiMessage(message2, options);
3143
- return index === lastHistory && typeof entry2.content === "string" ? { ...entry2, content: marked(entry2.content) } : entry2;
3240
+ const openai = openAiMessages(messages, { ...options, files }, (entry2, index) => {
3241
+ if (index !== lastHistory) return entry2;
3242
+ if (typeof entry2.content === "string") return { ...entry2, content: marked(entry2.content) };
3243
+ const parts = Array.isArray(entry2.content) ? entry2.content : [];
3244
+ return marks && parts.at(-1)?.type === "text" ? { ...entry2, content: [...parts.slice(0, -1), { ...parts.at(-1), cache_control: marks }] } : entry2;
3144
3245
  });
3145
3246
  return {
3146
3247
  model,
@@ -3319,7 +3420,8 @@ function toolCall(value, field2) {
3319
3420
  function chatMessage(value, index) {
3320
3421
  const source = record8(value);
3321
3422
  const field2 = `chat message ${index}`;
3322
- if (!source || typeof source.content !== "string") throw new TypeError(`${field2} is invalid`);
3423
+ if (!source || source.role === "assistant" && typeof source.content !== "string") throw new TypeError(`${field2} is invalid`);
3424
+ if (source.role !== "assistant") modelMessageContent(source.content, field2);
3323
3425
  if (source.role === "user" && exactKeys3(source, ["role", "content"])) return source;
3324
3426
  if (source.role === "tool" && typeof source.toolCallId === "string" && source.toolCallId && (source.isError === void 0 || typeof source.isError === "boolean") && exactKeys3(source, ["role", "toolCallId", "content"], ["isError"])) return source;
3325
3427
  if (source.role === "assistant" && exactKeys3(source, ["role", "content"], ["toolCalls", "reasoning"]) && (source.reasoning === void 0 || typeof source.reasoning === "string") && (source.toolCalls === void 0 || Array.isArray(source.toolCalls))) {
@@ -3521,6 +3623,10 @@ async function resolveContainerImageSource(reference, platform, request, authori
3521
3623
  }
3522
3624
 
3523
3625
  // packages/sdk/src/sandbox-egress.ts
3626
+ function normalizeSandboxConnectionKeys(value) {
3627
+ if (!Array.isArray(value)) throw new TypeError("sandbox connection keys must be an array");
3628
+ return [...new Set(value.map((key) => scopedBindingKey(key)))].sort();
3629
+ }
3524
3630
  var SANDBOX_EGRESS_LIMITS = { rules: 64, labels: 16, labelValueLength: 256 };
3525
3631
  var HEADER2 = /^[a-z0-9!#$%&'*+.^_`|~-]+$/u;
3526
3632
  var RESERVED_HEADERS2 = /* @__PURE__ */ new Set([
@@ -5353,6 +5459,7 @@ export {
5353
5459
  murmur3_32,
5354
5460
  normalizeCredentialDestinations,
5355
5461
  normalizeModelGatewayConfig,
5462
+ normalizeSandboxConnectionKeys,
5356
5463
  normalizeSandboxEgressPolicy,
5357
5464
  normalizeSandboxLabels,
5358
5465
  normalizeSandboxNetworkPolicy,