@finalai/agent-provider 0.1.2 → 0.1.3

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/HOSTING.md ADDED
@@ -0,0 +1,165 @@
1
+ # Portable agent definitions and hosted bindings
2
+
3
+ An agent declares behavior and logical resources. Hosting supplies endpoints,
4
+ resource identifiers, and credential references. The same compiled source can
5
+ resolve against dev and production configuration without source edits.
6
+
7
+ ## Selecting a deployment
8
+
9
+ ```sh
10
+ export FINAL_API_HOST=https://agent-session.primary-dev.final.ai/api
11
+ export FINAL_API_KEY=<dev-organization-key>
12
+ pnpm exec final-agents build ./agent
13
+ pnpm exec final-agents publish ./agent --agent my-agent
14
+ ```
15
+
16
+ Choose production by changing the host and organization key. `--host` overrides
17
+ `FINAL_API_HOST`; without either, the existing production default remains. Build
18
+ compiles locally and optionally checks installed-harness compatibility. Publish
19
+ compiles again and sends source/release requests to the selected deployment.
20
+ Neither rewrites authored URLs. A GitHub-backed definition uses remote source;
21
+ push edits before explicitly publishing a ref. Caller API keys never become agent
22
+ credentials merely because they were used to publish.
23
+
24
+ ## Hosted connections
25
+
26
+ ```ts
27
+ import { defineHostedConnection } from '@finalai/agents';
28
+
29
+ export default defineHostedConnection({
30
+ binding: 'issue-tracker',
31
+ tools: { allow: ['read_issue'], deny: ['delete_issue'] },
32
+ });
33
+ ```
34
+
35
+ `issue-tracker` is an example configuration name, not a built-in service.
36
+ Hosting configures it with non-secret JSON:
37
+
38
+ ```json
39
+ {
40
+ "url": "https://issues.dev.example/mcp",
41
+ "auth": { "secretKey": "ISSUE_TRACKER_TOKEN", "headerName": null },
42
+ "headers": { "X-Workspace": "development" }
43
+ }
44
+ ```
45
+
46
+ Production supplies another value under the same name. The helper uses an ordinary
47
+ `defineDynamic` connection at `session.started`, then the usual HTTP MCP lowering,
48
+ validation, permissions, and credential broker. Hosting supplies transport settings,
49
+ not tool policies. URL, authentication references, transport headers belong to hosting; the hosted helper does
50
+ not accept authored overrides for these fields. Referenced secrets still need the agent's secret allowlist and normal
51
+ authorization. Actual tokens must not be returned in configuration headers.
52
+
53
+ Final uses the same generic helper:
54
+
55
+ ```ts
56
+ import { defineFinalConnection } from '@finalai/agents';
57
+
58
+ export default defineFinalConnection({
59
+ tools: { deny: ['create_agent_session'] },
60
+ });
61
+ ```
62
+
63
+ This resolves the `final` binding. Hosting supplies its URL and
64
+ `auth: { kind: 'final-session' }`, just as it supplies authentication for any
65
+ other hosted connection. `binding`
66
+ selects another name. Existing explicit `url` calls remain static and compatible;
67
+ they always point at that URL. There is no Final-specific compiler rewrite.
68
+
69
+ ## Resources and provider packages
70
+
71
+ `HostedBindingsIface` is the shared `@finalai/agent-provider` contract. Hosting
72
+ implements `get(name)` to return scoped JSON or null. `requireHostedBinding` rejects
73
+ missing hosting, absent names, and invalid JSON without an environment fallback.
74
+ Names are configuration keys, not global permissions or inferred URLs.
75
+
76
+ Tools, hooks, dynamic resolvers, sandbox selectors, and harness/sandbox/channel
77
+ provider contexts expose an optional `bindings` reader. A third-party resolver can
78
+ use the same reader for model or resource configuration:
79
+
80
+ ```ts
81
+ import { defineDynamic, requireHostedBinding } from '@finalai/agents';
82
+
83
+ export const model = defineDynamic({
84
+ requiredBindings: [{ name: 'primary-model', schema: { type: 'string', minLength: 1 } }],
85
+ description: 'The deployment model',
86
+ preview: 'Resolved from primary-model',
87
+ events: {
88
+ 'session.started': async (_event, ctx) =>
89
+ requireHostedBinding({ bindings: ctx.bindings, name: 'primary-model' }),
90
+ },
91
+ });
92
+ ```
93
+
94
+ Use that value in a harness configuration supporting dynamic models. A resource
95
+ binding can similarly contain a repository, guide slug, device ID, or non-secret
96
+ SDK base URL; the consumer validates the resource-specific schema. Literal IDs,
97
+ custom URLs, and external credential choices are never silently rewritten.
98
+
99
+ Installed providers already accept factory configuration injected by hosting.
100
+ Keep supplying deployment service URLs there. Computer/WebSocket clients retain
101
+ explicit configuration; a hosted provider can obtain it through this shared reader.
102
+ Package versions stay pinned. Packages do not read a global DEV/PROD flag.
103
+
104
+ ## Declared requirements and user experience
105
+
106
+ `defineHostedConnection` declares its binding name and JSON configuration schema
107
+ in the compiled dynamic slot automatically. Other dynamic consumers declare
108
+ `requiredBindings` as in the model example. Hosts can inspect these requirements
109
+ without running authored resolvers. Repeated names must satisfy every declared
110
+ schema; names are looked up once per preflight.
111
+
112
+ Before accepting a release, hosting calls
113
+ `validateHostedBindings({ manifest, bindings })` with a reader scoped to the
114
+ selected deployment, organization, and agent. Hosts compiling source can instead
115
+ pass `hostedBindings` to `compile`; failed preflight returns error diagnostics and
116
+ no manifest or bundle. An offline build can still compile and expose requirements
117
+ without accessing deployment configuration. The CLI does not yet fetch binding
118
+ configuration itself: server-side publication must enable this preflight.
119
+
120
+ When dev is selected, lookups use only dev configuration. A missing dev binding
121
+ fails even if production has the same name; never retry against production or
122
+ substitute a production default. Changing the CLI host selects where to publish;
123
+ the runtime reader comes from that deployment, not from the author's environment.
124
+ Explicit authored URLs retain their literal destination.
125
+
126
+ Authors keep one source definition. Operators configure its named connections
127
+ and resources once in each deployment. End users start the agent as usual; an
128
+ unconfigured required resource produces a configuration failure instead of a
129
+ session silently missing tools. Dynamic handlers validate declared requirements
130
+ before running. Shared manifest resolution rejects null results for required slots,
131
+ even if a host catches a resolver exception and returns null. Hosts must propagate
132
+ that failure to startup. Session-started values stay pinned across turns and resume.
133
+
134
+ This PR adds no configuration UI. A host can use the compiled requirements to show
135
+ which names need configuration and return an actionable deployment-specific error.
136
+
137
+ ## Host integration
138
+
139
+ These packages implement contracts and authored runtime behavior, not a deployment
140
+ configuration store or RPC service. Existing hosting needs to:
141
+
142
+ 1. Resolve names within the authorized deployment, organization, and agent; never
143
+ expose the process environment or an unrestricted cross-tenant registry.
144
+ 2. Inject `bindings` into lifecycle resolution and the tool/hook/selector/provider
145
+ contexts using it. Dynamic approval evaluation and tool reconstruction after
146
+ isolate eviction need the same reader. Readers and tokens are not persisted in
147
+ boundary snapshots.
148
+ 3. Configure `final` with that deployment's approved MCP endpoint. The ordinary
149
+ broker continues restricting `final-session` grants to that endpoint.
150
+ 4. Return non-secret configuration and credential references, with normal provider,
151
+ secret, resource, and organization authorization.
152
+ 5. Run the release preflight above and validate again before starting a new
153
+ session. Treat failed required-binding resolution as a startup/configuration error, not
154
+ an omitted connection or a fallback to production. Preserve existing runtime
155
+ revisions when publication fails.
156
+ 6. Retain session-started resolved values across turns/resume; resolve new sessions
157
+ against their own deployment.
158
+
159
+ Optional readers preserve source compatibility with existing hosts. Definitions
160
+ requesting bindings fail clearly if hosting does not provide them. Installing these
161
+ packages alone does not change Final's deployed service wiring or provision secrets.
162
+
163
+ New compiles emit manifest version 3, so older hosts reject them rather than
164
+ stripping required-binding metadata. Updated readers still accept persisted
165
+ version 2 revisions. Upgrade hosting before publishing newly compiled agents.
@@ -1,3 +1,4 @@
1
+ import type { HostedBindingsIface } from "./hosted-bindings.mjs";
1
2
  import type { ContentBlock, SessionUpdate } from '@agentclientprotocol/sdk/experimental/v2';
2
3
  import * as z from 'zod';
3
4
  import type { ChannelSessionOperationsIface } from "./channel-context.mjs";
@@ -265,6 +266,7 @@ export interface ChannelInputResponseIface {
265
266
  apiKeyId: string | null;
266
267
  }
267
268
  export interface ChannelReceiveContextIface {
269
+ bindings?: HostedBindingsIface;
268
270
  platform: ChannelPlatformIface;
269
271
  organizationId: string;
270
272
  definitionId: string | null;
@@ -284,6 +286,7 @@ export interface ChannelReceiveContextIface {
284
286
  requestedDelivery?: Delivery;
285
287
  }
286
288
  export interface ChannelRouteContextIface {
289
+ bindings?: HostedBindingsIface;
287
290
  request: Request;
288
291
  secrets: {
289
292
  get(name: string): Promise<string | null>;
@@ -317,6 +320,7 @@ export interface ChannelTurnStateIface<State> {
317
320
  set(state: State | null): void;
318
321
  }
319
322
  export interface ProjectionContextIface<State = JsonValue> {
323
+ bindings?: HostedBindingsIface;
320
324
  sessionId?: string;
321
325
  platform: ChannelPlatformIface;
322
326
  conversation: ConversationIface | null;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/channel.ts"],
4
- "sourcesContent": ["import type { ContentBlock, SessionUpdate } from '@agentclientprotocol/sdk/experimental/v2';\nimport * as z from 'zod';\nimport type { ChannelSessionOperationsIface } from \"./channel-context.mjs\";\nimport { jsonObjectSchema, jsonValueSchema, type JsonObject, type JsonValue } from \"./json.mjs\";\nimport type { ProviderRef } from \"./provider-ref.mjs\";\nimport type { SemanticChannelEventKind } from \"./semantic-events.mjs\";\n\n// Channels. Messaging has no orchestrator: a channel\n// receives input, inserts it into the conversation, routes it to agent\n// participants as ACP prompt or observe, and projects ACP updates back into\n// visible messages and cards. The built-in messaging channels implement this\n// contract with no private hooks into the session service; the session\n// service hands every channel the same ChannelPlatformIface.\n\nexport enum ConversationKind {\n Direct = 'direct',\n Group = 'group',\n}\n\nexport enum ParticipantKind {\n User = 'user',\n Agent = 'agent',\n System = 'system',\n}\n\nexport enum SystemParticipantKind {\n Schedule = 'schedule',\n Webhook = 'webhook',\n Goal = 'goal',\n Tool = 'tool',\n ApiKey = 'api-key',\n}\n\nexport enum RoutingMode {\n Mention = 'mention',\n All = 'all',\n Default = 'default',\n}\n\nexport enum TurnPolicy {\n Steer = 'steer',\n Queue = 'queue',\n}\n\nexport enum Delivery {\n Prompt = 'prompt',\n Observe = 'observe',\n}\n\nexport enum MessageKind {\n Message = 'message',\n System = 'system',\n Card = 'card',\n}\n\nexport enum CardKind {\n Elicitation = 'elicitation',\n Permission = 'permission',\n Notice = 'notice',\n}\n\nexport interface ParticipantIface {\n id: string;\n kind: ParticipantKind;\n displayName: string;\n userId: string | null;\n servicePrincipalId?: string | null;\n definitionId: string | null;\n systemKind: SystemParticipantKind | null;\n routingMode: RoutingMode | null;\n sessionId: string | null;\n // Whether the agent's harness supports _final/session/observe and renders\n // _meta[\"final.ai\"].author; null for non-agents.\n supportsObserve: boolean | null;\n rendersAuthorMeta: boolean | null;\n left: boolean;\n}\n\nexport const channelReceiveResultSchema = z.union([\n z.object({ conversationId: z.string().min(1) }),\n z.object({ sessionId: z.string().min(1) }),\n z.null(),\n]);\nexport type ChannelReceiveResult = z.infer<typeof channelReceiveResultSchema>;\n\nexport interface ConversationRefIface {\n conversationId: string;\n}\n\nexport interface ConversationIface extends ConversationRefIface {\n organizationId: string;\n kind: ConversationKind;\n title: string | null;\n isHome: boolean;\n turnPolicy: TurnPolicy;\n}\n\nexport interface MessageRefIface {\n messageId: string;\n seq: number;\n}\n\nexport interface ConversationMessageIface extends MessageRefIface {\n conversationId: string;\n authorParticipantId: string;\n kind: MessageKind;\n body: string;\n content: ContentBlock[];\n replyToMessageId: string | null;\n threadRootId: string | null;\n // Earlier messages of the conversation the author quoted, in order.\n quotedMessageIds: string[];\n // Agent participant ids explicitly mentioned in the message.\n mentionedParticipantIds: string[];\n // Number of agent-authored hops that led to this message (0 for humans).\n hopDepth: number;\n // The originating agent for a tool-posted message, including linked conversations.\n agentAuthorDefinitionId?: string | null;\n createdAt: string;\n}\n\nexport interface RouteArgsIface {\n conversation: ConversationIface;\n message: ConversationMessageIface;\n participants: ParticipantIface[];\n agentParticipantId?: string;\n}\n\nexport interface RouteDecisionIface {\n participantId: string;\n delivery: Delivery;\n}\n\nexport interface PostMessageArgsIface {\n conversationId: string;\n authorParticipantId: string;\n kind?: MessageKind;\n content: ContentBlock[];\n replyToMessageId?: string | null;\n threadRootId?: string | null;\n quotedMessageIds?: string[];\n clientMessageId?: string | null;\n mentionedParticipantIds?: string[];\n attachmentIds?: string[];\n hopDepth?: number;\n // A tool or linked-conversation event carries the turn that produced it.\n originTurnId?: string | null;\n // Projection provenance for agent replies.\n source?: { turnId: string; fromSeq: number; toSeq: number } | null;\n}\n\nexport const channelMessageInputSchema = z.object({\n conversationId: z.string().min(1),\n authorParticipantId: z.string().min(1),\n kind: z.nativeEnum(MessageKind).default(MessageKind.Message),\n content: z.array(jsonObjectSchema).min(1),\n clientMessageId: z.string().min(1).nullish(),\n replyToMessageId: z.string().min(1).nullish(),\n threadRootId: z.string().min(1).nullish(),\n quotedMessageIds: z.array(z.string().min(1)).default([]),\n mentionedParticipantIds: z.array(z.string().min(1)).default([]),\n});\n\nexport interface CardArgsIface {\n conversationId: string;\n authorParticipantId: string;\n kind: CardKind;\n pendingRequestId: string | null;\n // Generic cards only: a title, body, options, and entity links (a Goal is an\n // entity link, not a card kind).\n state: JsonObject;\n entityLinks: {\n kind: string;\n id: string;\n title?: string;\n url?: string;\n description?: string;\n imageUrl?: string;\n }[];\n}\n\nexport interface PromptArgsIface {\n waitForAcceptance?: boolean;\n channelBinding?: { id: string; revisionId: string };\n auth?: JsonObject | null;\n title?: string;\n participantId: string;\n content: ContentBlock[];\n turnPolicy: TurnPolicy;\n replyExpected: boolean;\n idempotencyKey: string;\n // Who prompted (for payer resolution and pending-request audience).\n authorParticipantId: string;\n audienceParticipantIds: string[];\n sourceMessageId: string;\n}\n\nexport interface ObserveArgsIface {\n participantId: string;\n content: ContentBlock[];\n idempotencyKey: string;\n}\n\n// What the session service lets a channel do. Implemented once, handed to\n// built-in and custom channels alike.\nexport interface ChannelPlatformIface {\n channelSessions?: ChannelSessionOperationsIface;\n conversations: {\n get(conversationId: string): Promise<ConversationIface | null>;\n createAttachmentUpload?(args: {\n conversationId: string;\n name: string;\n contentType: string;\n sizeBytes: number;\n }): Promise<{\n attachmentId: string;\n uploadUrl: string;\n method: string;\n headers: Record<string, string>;\n expiresAt: string;\n }>;\n getAttachmentUrl?(args: {\n conversationId: string;\n attachmentId: string;\n }): Promise<{ attachmentId: string; url: string; expiresAt: string }>;\n // Dispatch a stored reply to each recipient's binding; each channel owns routing.\n dispatchMessage?(args: {\n conversationId: string;\n messageId: string;\n participantId?: string;\n requestedDelivery?: Delivery;\n }): Promise<void>;\n findOrCreateDirect(args: {\n organizationId: string;\n userId: string;\n definitionId: string;\n }): Promise<ConversationIface>;\n // The conversation a channel binding is attached to.\n boundTo(bindingId: string): Promise<ConversationIface | null>;\n participants(conversationId: string): Promise<ParticipantIface[]>;\n systemParticipant(args: {\n conversationId: string;\n systemKind: SystemParticipantKind;\n displayName: string;\n sourceRef: string;\n }): Promise<ParticipantIface>;\n postMessage(args: PostMessageArgsIface): Promise<ConversationMessageIface>;\n updateMessage(args: {\n messageId: string;\n content: ContentBlock[];\n final: boolean;\n }): Promise<void>;\n postCard(args: CardArgsIface): Promise<ConversationMessageIface>;\n updateCard(args: { messageId: string; state: JsonObject }): Promise<void>;\n recentMessages(args: {\n conversationId: string;\n limit: number;\n beforeSeq?: number;\n afterSeq?: number;\n }): Promise<ConversationMessageIface[]>;\n // Messages of the conversation by id, however old (reply, thread and quote\n // context outside the recent window); unknown and deleted ones are absent.\n getMessages(args: {\n conversationId: string;\n messageIds: string[];\n }): Promise<ConversationMessageIface[]>;\n };\n sessions: {\n prompt(\n args: PromptArgsIface,\n ): Promise<{ messageId: string; sessionId?: string; turnId?: string }>;\n observe(args: ObserveArgsIface): Promise<void>;\n cancel(args: {\n participantId: string;\n reason?: string;\n throughMessageSeq?: number;\n }): Promise<void>;\n respond?(args: ChannelInputResponseIface): Promise<{ resolved: boolean }>;\n };\n log(message: string, details?: Record<string, JsonValue>): void;\n}\n\nexport interface ChannelInputResponseIface {\n channelBinding?: { id: string; revisionId: string };\n auth?: JsonObject | null;\n participantId: string;\n pendingId: string;\n outcome: JsonValue;\n actorParticipantId: string;\n userId: string | null;\n apiKeyId: string | null;\n}\n\nexport interface ChannelReceiveContextIface {\n platform: ChannelPlatformIface;\n organizationId: string;\n definitionId: string | null;\n bindingId: string | null;\n config: JsonObject;\n secrets: { get(name: string): Promise<string | null> };\n // A stored, authenticated delivery to one agent in a shared conversation.\n agentParticipantId?: string;\n message?: ConversationMessageIface;\n conversation?: ConversationIface;\n participants?: readonly ParticipantIface[];\n response?: ChannelInputResponseIface;\n conversationId?: string;\n cancelReason?: string;\n // Preserve this boundary when forwarding a retryable conversation Stop.\n cancelThroughMessageSeq?: number;\n requestedDelivery?: Delivery;\n}\n\n// An HTTP route a channel serves (webhooks), mounted by the front door at\n// /api/events/webhooks/:bindingId<path> and the per-agent aliases.\nexport interface ChannelRouteContextIface {\n request: Request;\n secrets: { get(name: string): Promise<string | null> };\n receive: (input: JsonValue) => Promise<ChannelReceiveResult>;\n}\n\nexport interface ChannelSocketIface {\n readonly signal: AbortSignal;\n readonly messages: AsyncIterable<string | Uint8Array>;\n // Authenticate the request before accepting. The selected protocol must have been offered.\n accept(options?: { protocol?: string }): void;\n send(data: string | Uint8Array): void;\n close(code?: number, reason?: string): void;\n}\n\nexport interface HttpChannelRouteDefinitionIface {\n method: 'GET' | 'POST' | 'PUT' | 'DELETE';\n path: string;\n handler: (args: ChannelRouteContextIface) => Promise<Response>;\n}\n\nexport interface WebSocketChannelRouteDefinitionIface {\n method: 'WS';\n path: string;\n // Returning an HTTP response before accept rejects the handshake. The handler lives until close.\n handler: (\n args: ChannelRouteContextIface & { socket: ChannelSocketIface },\n ) => Promise<Response | void>;\n}\n\nexport type RouteDefinitionIface =\n | HttpChannelRouteDefinitionIface\n | WebSocketChannelRouteDefinitionIface;\n\n// The per-turn value a channel keeps between its project and event calls of\n// one turn (the definition's `State`). The platform holds it, so a channel\n// running in a Worker isolate keeps nothing in memory; it starts null each turn\n// and is discarded when the turn's projection finishes.\nexport interface ChannelTurnStateIface<State> {\n get(): State | null;\n set(state: State | null): void;\n}\n\nexport interface ProjectionContextIface<State = JsonValue> {\n sessionId?: string;\n platform: ChannelPlatformIface;\n conversation: ConversationIface | null;\n agentParticipant: ParticipantIface | null;\n turn: { id: string; promptMessageId: string | null; authorParticipantId: string | null };\n seq: number;\n state: ChannelTurnStateIface<State>;\n}\n\nexport enum PendingEventKind {\n Created = 'pending.created',\n Resolved = 'pending.resolved',\n}\n\nexport type AcpUpdateKind = SessionUpdate['sessionUpdate'];\n\nexport type ChannelEventKind =\n | AcpUpdateKind\n | `${PendingEventKind}`\n | `${SemanticChannelEventKind}`;\n\nexport interface ChannelEventIface {\n type: string;\n data: JsonValue;\n seq: number;\n}\n\nexport type ChannelEventHandler<State = JsonValue> = (\n event: ChannelEventIface,\n ctx: ProjectionContextIface<State>,\n) => Promise<void>;\n\nexport enum PendingKind {\n Permission = 'permission',\n Elicitation = 'elicitation',\n}\n\n// `data` of a pending.created event: an ACP session/request_permission or\n// elicitation/create request awaiting its audience.\nexport const pendingCreatedDataSchema = z.object({\n pendingRequestId: z.string().min(1),\n kind: z.nativeEnum(PendingKind),\n audienceParticipantIds: z.array(z.string()),\n request: jsonValueSchema,\n});\n\nexport type PendingCreatedDataIface = z.infer<typeof pendingCreatedDataSchema>;\n\n// `data` of a pending.resolved event: the answer (or cancellation) as recorded.\nexport const pendingResolvedDataSchema = z.object({\n pendingRequestId: z.string().min(1),\n outcome: jsonValueSchema,\n});\n\nexport type PendingResolvedDataIface = z.infer<typeof pendingResolvedDataSchema>;\n\n// The visible-output updates `project` receives. After them, the\n// turn's projection ends with one ACP v2 idle `state_update` (turnEndUpdate).\n// Thought, tool, plan and every other update, other state updates included,\n// reach a channel only through an `events` handler for its kind.\nexport const PROJECTED_UPDATE_KINDS: ReadonlySet<AcpUpdateKind> = new Set<AcpUpdateKind>([\n 'agent_message_chunk',\n 'agent_message',\n]);\n\nconst turnEndSchema = z.looseObject({\n sessionUpdate: z.literal('state_update'),\n state: z.literal('idle'),\n stopReason: z.string().nullish(),\n _meta: z\n .looseObject({ 'final.ai': z.looseObject({ stopReason: z.string().nullish() }).nullish() })\n .nullish(),\n});\n\n// The stop reason when the update ends the turn (an idle state_update); null otherwise.\nexport const turnEndOf = (update: SessionUpdate): { stopReason: string | null } | null => {\n const parsed = turnEndSchema.safeParse(update);\n if (!parsed.success) return null;\n return {\n stopReason: parsed.data.stopReason ?? parsed.data._meta?.['final.ai']?.stopReason ?? null,\n };\n};\n\n// The idle state_update that ends a turn, as `project` receives it. A stop\n// reason outside ACP's known set rides in `_meta[\"final.ai\"]` (the SDK types\n// only received values as unknown variants).\nexport const turnEndUpdate = (stopReason: string | null): SessionUpdate => {\n switch (stopReason) {\n case null:\n return { sessionUpdate: 'state_update', state: 'idle' };\n case 'end_turn':\n return { sessionUpdate: 'state_update', state: 'idle', stopReason: 'end_turn' };\n case 'max_tokens':\n return { sessionUpdate: 'state_update', state: 'idle', stopReason: 'max_tokens' };\n case 'max_turn_requests':\n return { sessionUpdate: 'state_update', state: 'idle', stopReason: 'max_turn_requests' };\n case 'refusal':\n return { sessionUpdate: 'state_update', state: 'idle', stopReason: 'refusal' };\n case 'cancelled':\n return { sessionUpdate: 'state_update', state: 'idle', stopReason: 'cancelled' };\n default:\n return {\n sessionUpdate: 'state_update',\n state: 'idle',\n _meta: { 'final.ai': { stopReason } },\n };\n }\n};\n\n// Built-in and custom (bundle) channels implement exactly this; the\n// session service calls nothing else on a channel.\nexport interface ChannelDefinitionIface<Inbound, State = undefined> {\n config?: JsonObject;\n // Installed execution is an optimization for an uncustomized definition.\n installed?: ProviderRef;\n configure?: (config: JsonObject) => ChannelDefinitionIface<Inbound, State>;\n routes?: RouteDefinitionIface[];\n respond?(\n input: ChannelInputResponseIface,\n ctx: ChannelReceiveContextIface,\n ): Promise<{ resolved: boolean }>;\n cancel?(ctx: ChannelReceiveContextIface): Promise<{ accepted: boolean }>;\n // Inserts the input into its conversation and routes it. Returns where it went.\n receive(input: Inbound, ctx: ChannelReceiveContextIface): Promise<ChannelReceiveResult>;\n // Pure: who gets this message, and how. The channel applies it\n // to what it posts, from receive and project.\n route(args: RouteArgsIface): RouteDecisionIface[] | Promise<RouteDecisionIface[]>;\n turnPolicy: TurnPolicy;\n // ACP update \u2192 visible message / card. Called with a turn's\n // PROJECTED_UPDATE_KINDS updates in seq order, then its idle state_update.\n project(update: SessionUpdate, ctx: ProjectionContextIface<State>): Promise<void>;\n events?: Partial<Record<ChannelEventKind, ChannelEventHandler<State>>>;\n}\n\nexport const defineChannel = <Inbound, State = undefined>(\n definition: ChannelDefinitionIface<Inbound, State>,\n): ChannelDefinitionIface<Inbound, State> => definition;\n"],
5
- "mappings": "AACA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A2BO,MAAM,gBAAgB,CAC3B,eAC2C;",
4
+ "sourcesContent": ["import type { HostedBindingsIface } from \"./hosted-bindings.mjs\";\nimport type { ContentBlock, SessionUpdate } from '@agentclientprotocol/sdk/experimental/v2';\nimport * as z from 'zod';\nimport type { ChannelSessionOperationsIface } from \"./channel-context.mjs\";\nimport { jsonObjectSchema, jsonValueSchema, type JsonObject, type JsonValue } from \"./json.mjs\";\nimport type { ProviderRef } from \"./provider-ref.mjs\";\nimport type { SemanticChannelEventKind } from \"./semantic-events.mjs\";\n\n// Channels. Messaging has no orchestrator: a channel\n// receives input, inserts it into the conversation, routes it to agent\n// participants as ACP prompt or observe, and projects ACP updates back into\n// visible messages and cards. The built-in messaging channels implement this\n// contract with no private hooks into the session service; the session\n// service hands every channel the same ChannelPlatformIface.\n\nexport enum ConversationKind {\n Direct = 'direct',\n Group = 'group',\n}\n\nexport enum ParticipantKind {\n User = 'user',\n Agent = 'agent',\n System = 'system',\n}\n\nexport enum SystemParticipantKind {\n Schedule = 'schedule',\n Webhook = 'webhook',\n Goal = 'goal',\n Tool = 'tool',\n ApiKey = 'api-key',\n}\n\nexport enum RoutingMode {\n Mention = 'mention',\n All = 'all',\n Default = 'default',\n}\n\nexport enum TurnPolicy {\n Steer = 'steer',\n Queue = 'queue',\n}\n\nexport enum Delivery {\n Prompt = 'prompt',\n Observe = 'observe',\n}\n\nexport enum MessageKind {\n Message = 'message',\n System = 'system',\n Card = 'card',\n}\n\nexport enum CardKind {\n Elicitation = 'elicitation',\n Permission = 'permission',\n Notice = 'notice',\n}\n\nexport interface ParticipantIface {\n id: string;\n kind: ParticipantKind;\n displayName: string;\n userId: string | null;\n servicePrincipalId?: string | null;\n definitionId: string | null;\n systemKind: SystemParticipantKind | null;\n routingMode: RoutingMode | null;\n sessionId: string | null;\n // Whether the agent's harness supports _final/session/observe and renders\n // _meta[\"final.ai\"].author; null for non-agents.\n supportsObserve: boolean | null;\n rendersAuthorMeta: boolean | null;\n left: boolean;\n}\n\nexport const channelReceiveResultSchema = z.union([\n z.object({ conversationId: z.string().min(1) }),\n z.object({ sessionId: z.string().min(1) }),\n z.null(),\n]);\nexport type ChannelReceiveResult = z.infer<typeof channelReceiveResultSchema>;\n\nexport interface ConversationRefIface {\n conversationId: string;\n}\n\nexport interface ConversationIface extends ConversationRefIface {\n organizationId: string;\n kind: ConversationKind;\n title: string | null;\n isHome: boolean;\n turnPolicy: TurnPolicy;\n}\n\nexport interface MessageRefIface {\n messageId: string;\n seq: number;\n}\n\nexport interface ConversationMessageIface extends MessageRefIface {\n conversationId: string;\n authorParticipantId: string;\n kind: MessageKind;\n body: string;\n content: ContentBlock[];\n replyToMessageId: string | null;\n threadRootId: string | null;\n // Earlier messages of the conversation the author quoted, in order.\n quotedMessageIds: string[];\n // Agent participant ids explicitly mentioned in the message.\n mentionedParticipantIds: string[];\n // Number of agent-authored hops that led to this message (0 for humans).\n hopDepth: number;\n // The originating agent for a tool-posted message, including linked conversations.\n agentAuthorDefinitionId?: string | null;\n createdAt: string;\n}\n\nexport interface RouteArgsIface {\n conversation: ConversationIface;\n message: ConversationMessageIface;\n participants: ParticipantIface[];\n agentParticipantId?: string;\n}\n\nexport interface RouteDecisionIface {\n participantId: string;\n delivery: Delivery;\n}\n\nexport interface PostMessageArgsIface {\n conversationId: string;\n authorParticipantId: string;\n kind?: MessageKind;\n content: ContentBlock[];\n replyToMessageId?: string | null;\n threadRootId?: string | null;\n quotedMessageIds?: string[];\n clientMessageId?: string | null;\n mentionedParticipantIds?: string[];\n attachmentIds?: string[];\n hopDepth?: number;\n // A tool or linked-conversation event carries the turn that produced it.\n originTurnId?: string | null;\n // Projection provenance for agent replies.\n source?: { turnId: string; fromSeq: number; toSeq: number } | null;\n}\n\nexport const channelMessageInputSchema = z.object({\n conversationId: z.string().min(1),\n authorParticipantId: z.string().min(1),\n kind: z.nativeEnum(MessageKind).default(MessageKind.Message),\n content: z.array(jsonObjectSchema).min(1),\n clientMessageId: z.string().min(1).nullish(),\n replyToMessageId: z.string().min(1).nullish(),\n threadRootId: z.string().min(1).nullish(),\n quotedMessageIds: z.array(z.string().min(1)).default([]),\n mentionedParticipantIds: z.array(z.string().min(1)).default([]),\n});\n\nexport interface CardArgsIface {\n conversationId: string;\n authorParticipantId: string;\n kind: CardKind;\n pendingRequestId: string | null;\n // Generic cards only: a title, body, options, and entity links (a Goal is an\n // entity link, not a card kind).\n state: JsonObject;\n entityLinks: {\n kind: string;\n id: string;\n title?: string;\n url?: string;\n description?: string;\n imageUrl?: string;\n }[];\n}\n\nexport interface PromptArgsIface {\n waitForAcceptance?: boolean;\n channelBinding?: { id: string; revisionId: string };\n auth?: JsonObject | null;\n title?: string;\n participantId: string;\n content: ContentBlock[];\n turnPolicy: TurnPolicy;\n replyExpected: boolean;\n idempotencyKey: string;\n // Who prompted (for payer resolution and pending-request audience).\n authorParticipantId: string;\n audienceParticipantIds: string[];\n sourceMessageId: string;\n}\n\nexport interface ObserveArgsIface {\n participantId: string;\n content: ContentBlock[];\n idempotencyKey: string;\n}\n\n// What the session service lets a channel do. Implemented once, handed to\n// built-in and custom channels alike.\nexport interface ChannelPlatformIface {\n channelSessions?: ChannelSessionOperationsIface;\n conversations: {\n get(conversationId: string): Promise<ConversationIface | null>;\n createAttachmentUpload?(args: {\n conversationId: string;\n name: string;\n contentType: string;\n sizeBytes: number;\n }): Promise<{\n attachmentId: string;\n uploadUrl: string;\n method: string;\n headers: Record<string, string>;\n expiresAt: string;\n }>;\n getAttachmentUrl?(args: {\n conversationId: string;\n attachmentId: string;\n }): Promise<{ attachmentId: string; url: string; expiresAt: string }>;\n // Dispatch a stored reply to each recipient's binding; each channel owns routing.\n dispatchMessage?(args: {\n conversationId: string;\n messageId: string;\n participantId?: string;\n requestedDelivery?: Delivery;\n }): Promise<void>;\n findOrCreateDirect(args: {\n organizationId: string;\n userId: string;\n definitionId: string;\n }): Promise<ConversationIface>;\n // The conversation a channel binding is attached to.\n boundTo(bindingId: string): Promise<ConversationIface | null>;\n participants(conversationId: string): Promise<ParticipantIface[]>;\n systemParticipant(args: {\n conversationId: string;\n systemKind: SystemParticipantKind;\n displayName: string;\n sourceRef: string;\n }): Promise<ParticipantIface>;\n postMessage(args: PostMessageArgsIface): Promise<ConversationMessageIface>;\n updateMessage(args: {\n messageId: string;\n content: ContentBlock[];\n final: boolean;\n }): Promise<void>;\n postCard(args: CardArgsIface): Promise<ConversationMessageIface>;\n updateCard(args: { messageId: string; state: JsonObject }): Promise<void>;\n recentMessages(args: {\n conversationId: string;\n limit: number;\n beforeSeq?: number;\n afterSeq?: number;\n }): Promise<ConversationMessageIface[]>;\n // Messages of the conversation by id, however old (reply, thread and quote\n // context outside the recent window); unknown and deleted ones are absent.\n getMessages(args: {\n conversationId: string;\n messageIds: string[];\n }): Promise<ConversationMessageIface[]>;\n };\n sessions: {\n prompt(\n args: PromptArgsIface,\n ): Promise<{ messageId: string; sessionId?: string; turnId?: string }>;\n observe(args: ObserveArgsIface): Promise<void>;\n cancel(args: {\n participantId: string;\n reason?: string;\n throughMessageSeq?: number;\n }): Promise<void>;\n respond?(args: ChannelInputResponseIface): Promise<{ resolved: boolean }>;\n };\n log(message: string, details?: Record<string, JsonValue>): void;\n}\n\nexport interface ChannelInputResponseIface {\n channelBinding?: { id: string; revisionId: string };\n auth?: JsonObject | null;\n participantId: string;\n pendingId: string;\n outcome: JsonValue;\n actorParticipantId: string;\n userId: string | null;\n apiKeyId: string | null;\n}\n\nexport interface ChannelReceiveContextIface {\n bindings?: HostedBindingsIface;\n platform: ChannelPlatformIface;\n organizationId: string;\n definitionId: string | null;\n bindingId: string | null;\n config: JsonObject;\n secrets: { get(name: string): Promise<string | null> };\n // A stored, authenticated delivery to one agent in a shared conversation.\n agentParticipantId?: string;\n message?: ConversationMessageIface;\n conversation?: ConversationIface;\n participants?: readonly ParticipantIface[];\n response?: ChannelInputResponseIface;\n conversationId?: string;\n cancelReason?: string;\n // Preserve this boundary when forwarding a retryable conversation Stop.\n cancelThroughMessageSeq?: number;\n requestedDelivery?: Delivery;\n}\n\n// An HTTP route a channel serves (webhooks), mounted by the front door at\n// /api/events/webhooks/:bindingId<path> and the per-agent aliases.\nexport interface ChannelRouteContextIface {\n bindings?: HostedBindingsIface;\n request: Request;\n secrets: { get(name: string): Promise<string | null> };\n receive: (input: JsonValue) => Promise<ChannelReceiveResult>;\n}\n\nexport interface ChannelSocketIface {\n readonly signal: AbortSignal;\n readonly messages: AsyncIterable<string | Uint8Array>;\n // Authenticate the request before accepting. The selected protocol must have been offered.\n accept(options?: { protocol?: string }): void;\n send(data: string | Uint8Array): void;\n close(code?: number, reason?: string): void;\n}\n\nexport interface HttpChannelRouteDefinitionIface {\n method: 'GET' | 'POST' | 'PUT' | 'DELETE';\n path: string;\n handler: (args: ChannelRouteContextIface) => Promise<Response>;\n}\n\nexport interface WebSocketChannelRouteDefinitionIface {\n method: 'WS';\n path: string;\n // Returning an HTTP response before accept rejects the handshake. The handler lives until close.\n handler: (\n args: ChannelRouteContextIface & { socket: ChannelSocketIface },\n ) => Promise<Response | void>;\n}\n\nexport type RouteDefinitionIface =\n | HttpChannelRouteDefinitionIface\n | WebSocketChannelRouteDefinitionIface;\n\n// The per-turn value a channel keeps between its project and event calls of\n// one turn (the definition's `State`). The platform holds it, so a channel\n// running in a Worker isolate keeps nothing in memory; it starts null each turn\n// and is discarded when the turn's projection finishes.\nexport interface ChannelTurnStateIface<State> {\n get(): State | null;\n set(state: State | null): void;\n}\n\nexport interface ProjectionContextIface<State = JsonValue> {\n bindings?: HostedBindingsIface;\n sessionId?: string;\n platform: ChannelPlatformIface;\n conversation: ConversationIface | null;\n agentParticipant: ParticipantIface | null;\n turn: { id: string; promptMessageId: string | null; authorParticipantId: string | null };\n seq: number;\n state: ChannelTurnStateIface<State>;\n}\n\nexport enum PendingEventKind {\n Created = 'pending.created',\n Resolved = 'pending.resolved',\n}\n\nexport type AcpUpdateKind = SessionUpdate['sessionUpdate'];\n\nexport type ChannelEventKind =\n | AcpUpdateKind\n | `${PendingEventKind}`\n | `${SemanticChannelEventKind}`;\n\nexport interface ChannelEventIface {\n type: string;\n data: JsonValue;\n seq: number;\n}\n\nexport type ChannelEventHandler<State = JsonValue> = (\n event: ChannelEventIface,\n ctx: ProjectionContextIface<State>,\n) => Promise<void>;\n\nexport enum PendingKind {\n Permission = 'permission',\n Elicitation = 'elicitation',\n}\n\n// `data` of a pending.created event: an ACP session/request_permission or\n// elicitation/create request awaiting its audience.\nexport const pendingCreatedDataSchema = z.object({\n pendingRequestId: z.string().min(1),\n kind: z.nativeEnum(PendingKind),\n audienceParticipantIds: z.array(z.string()),\n request: jsonValueSchema,\n});\n\nexport type PendingCreatedDataIface = z.infer<typeof pendingCreatedDataSchema>;\n\n// `data` of a pending.resolved event: the answer (or cancellation) as recorded.\nexport const pendingResolvedDataSchema = z.object({\n pendingRequestId: z.string().min(1),\n outcome: jsonValueSchema,\n});\n\nexport type PendingResolvedDataIface = z.infer<typeof pendingResolvedDataSchema>;\n\n// The visible-output updates `project` receives. After them, the\n// turn's projection ends with one ACP v2 idle `state_update` (turnEndUpdate).\n// Thought, tool, plan and every other update, other state updates included,\n// reach a channel only through an `events` handler for its kind.\nexport const PROJECTED_UPDATE_KINDS: ReadonlySet<AcpUpdateKind> = new Set<AcpUpdateKind>([\n 'agent_message_chunk',\n 'agent_message',\n]);\n\nconst turnEndSchema = z.looseObject({\n sessionUpdate: z.literal('state_update'),\n state: z.literal('idle'),\n stopReason: z.string().nullish(),\n _meta: z\n .looseObject({ 'final.ai': z.looseObject({ stopReason: z.string().nullish() }).nullish() })\n .nullish(),\n});\n\n// The stop reason when the update ends the turn (an idle state_update); null otherwise.\nexport const turnEndOf = (update: SessionUpdate): { stopReason: string | null } | null => {\n const parsed = turnEndSchema.safeParse(update);\n if (!parsed.success) return null;\n return {\n stopReason: parsed.data.stopReason ?? parsed.data._meta?.['final.ai']?.stopReason ?? null,\n };\n};\n\n// The idle state_update that ends a turn, as `project` receives it. A stop\n// reason outside ACP's known set rides in `_meta[\"final.ai\"]` (the SDK types\n// only received values as unknown variants).\nexport const turnEndUpdate = (stopReason: string | null): SessionUpdate => {\n switch (stopReason) {\n case null:\n return { sessionUpdate: 'state_update', state: 'idle' };\n case 'end_turn':\n return { sessionUpdate: 'state_update', state: 'idle', stopReason: 'end_turn' };\n case 'max_tokens':\n return { sessionUpdate: 'state_update', state: 'idle', stopReason: 'max_tokens' };\n case 'max_turn_requests':\n return { sessionUpdate: 'state_update', state: 'idle', stopReason: 'max_turn_requests' };\n case 'refusal':\n return { sessionUpdate: 'state_update', state: 'idle', stopReason: 'refusal' };\n case 'cancelled':\n return { sessionUpdate: 'state_update', state: 'idle', stopReason: 'cancelled' };\n default:\n return {\n sessionUpdate: 'state_update',\n state: 'idle',\n _meta: { 'final.ai': { stopReason } },\n };\n }\n};\n\n// Built-in and custom (bundle) channels implement exactly this; the\n// session service calls nothing else on a channel.\nexport interface ChannelDefinitionIface<Inbound, State = undefined> {\n config?: JsonObject;\n // Installed execution is an optimization for an uncustomized definition.\n installed?: ProviderRef;\n configure?: (config: JsonObject) => ChannelDefinitionIface<Inbound, State>;\n routes?: RouteDefinitionIface[];\n respond?(\n input: ChannelInputResponseIface,\n ctx: ChannelReceiveContextIface,\n ): Promise<{ resolved: boolean }>;\n cancel?(ctx: ChannelReceiveContextIface): Promise<{ accepted: boolean }>;\n // Inserts the input into its conversation and routes it. Returns where it went.\n receive(input: Inbound, ctx: ChannelReceiveContextIface): Promise<ChannelReceiveResult>;\n // Pure: who gets this message, and how. The channel applies it\n // to what it posts, from receive and project.\n route(args: RouteArgsIface): RouteDecisionIface[] | Promise<RouteDecisionIface[]>;\n turnPolicy: TurnPolicy;\n // ACP update \u2192 visible message / card. Called with a turn's\n // PROJECTED_UPDATE_KINDS updates in seq order, then its idle state_update.\n project(update: SessionUpdate, ctx: ProjectionContextIface<State>): Promise<void>;\n events?: Partial<Record<ChannelEventKind, ChannelEventHandler<State>>>;\n}\n\nexport const defineChannel = <Inbound, State = undefined>(\n definition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O;AAAA,QACP,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE;AAAA,MACtC;AAAA,EACJ;AACF;AA2BO,MAAM,gBAAgB,CAC3B,eAC2C;",
6
6
  "names": ["ConversationKind", "ParticipantKind", "SystemParticipantKind", "RoutingMode", "TurnPolicy", "Delivery", "MessageKind", "CardKind", "PendingEventKind", "PendingKind"]
7
7
  }
@@ -10,6 +10,10 @@ export declare const dynamicSlotSchema: z.ZodObject<{
10
10
  events: z.ZodArray<z.ZodEnum<typeof DynamicEvent>>;
11
11
  description: z.ZodOptional<z.ZodString>;
12
12
  preview: z.ZodOptional<z.ZodString>;
13
+ requiredBindings: z.ZodOptional<z.ZodArray<z.ZodObject<{
14
+ name: z.ZodString;
15
+ schema: z.ZodType<import("./json.mjs").JsonObject, unknown, z.core.$ZodTypeInternals<import("./json.mjs").JsonObject, unknown>>;
16
+ }, z.core.$strip>>>;
13
17
  }, z.core.$strip>;
14
18
  }, z.core.$strip>;
15
19
  export type DynamicSlotIface = z.infer<typeof dynamicSlotSchema>;
@@ -21,6 +25,10 @@ export declare const maybeDynamic: <T extends z.ZodType>(schema: T) => z.ZodUnio
21
25
  events: z.ZodArray<z.ZodEnum<typeof DynamicEvent>>;
22
26
  description: z.ZodOptional<z.ZodString>;
23
27
  preview: z.ZodOptional<z.ZodString>;
28
+ requiredBindings: z.ZodOptional<z.ZodArray<z.ZodObject<{
29
+ name: z.ZodString;
30
+ schema: z.ZodType<import("./json.mjs").JsonObject, unknown, z.core.$ZodTypeInternals<import("./json.mjs").JsonObject, unknown>>;
31
+ }, z.core.$strip>>>;
24
32
  }, z.core.$strip>;
25
33
  }, z.core.$strip>, T]>;
26
34
  export interface DynamicSlotLocationIface {
@@ -1,4 +1,5 @@
1
1
  import * as z from "zod";
2
+ import { hostedBindingRequirementSchema } from "./hosted-bindings.mjs";
2
3
  var DynamicEvent = /* @__PURE__ */ ((DynamicEvent2) => {
3
4
  DynamicEvent2["SessionStarted"] = "session.started";
4
5
  DynamicEvent2["TurnStarted"] = "turn.started";
@@ -11,7 +12,8 @@ const dynamicSlotSchema = z.object({
11
12
  events: z.array(z.nativeEnum(DynamicEvent)).min(1),
12
13
  // Final additions so Build can render a slot without resolving it.
13
14
  description: z.string().optional(),
14
- preview: z.string().optional()
15
+ preview: z.string().optional(),
16
+ requiredBindings: z.array(hostedBindingRequirementSchema).optional()
15
17
  })
16
18
  });
17
19
  const isDynamicSlot = (value) => dynamicSlotSchema.safeParse(value).success;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/dynamic.ts"],
4
- "sourcesContent": ["import * as z from 'zod';\nimport type { JsonValue } from \"./json.mjs\";\n\n// Lifecycle boundaries a dynamic slot may resolve at.\n// The harness owns steps, so `step.started` is not supported.\nexport enum DynamicEvent {\n SessionStarted = 'session.started',\n TurnStarted = 'turn.started',\n}\n\nexport const dynamicSlotSchema = z.object({\n $dynamic: z.object({\n // Bundle export that implements the resolver ('instructions/org-context').\n resolver: z.string().min(1),\n events: z.array(z.nativeEnum(DynamicEvent)).min(1),\n // Final additions so Build can render a slot without resolving it.\n description: z.string().optional(),\n preview: z.string().optional(),\n }),\n});\n\nexport type DynamicSlotIface = z.infer<typeof dynamicSlotSchema>;\nexport type Dynamic<_T> = DynamicSlotIface;\n\nexport const isDynamicSlot = <T>(value: T): value is T & DynamicSlotIface =>\n dynamicSlotSchema.safeParse(value).success;\n\nconst slotOf = <T>(value: T): DynamicSlotIface | null => {\n const parsed = dynamicSlotSchema.safeParse(value);\n return parsed.success ? parsed.data : null;\n};\n\nconst listSchema = z.array(z.json());\nconst objectSchema = z.record(z.string(), z.json());\nconst looseListSchema = z.array(z.unknown());\nconst looseObjectSchema = z.record(z.string(), z.unknown());\n\nexport const maybeDynamic = <T extends z.ZodType>(schema: T) =>\n z.union([dynamicSlotSchema, schema]);\n\n// A dynamic slot found while walking a JSON document, addressed by a stable\n// path ('harness.config.instructions[1]') that the manifest's bundle.resolvers\n// map keys by.\nexport interface DynamicSlotLocationIface {\n path: string;\n slot: DynamicSlotIface;\n}\n\nconst indexPath = (parent: string, index: number): string => `${parent}[${index}]`;\nconst keyPath = (parent: string, key: string): string =>\n parent.length === 0 ? key : `${parent}.${key}`;\n\nexport const findDynamicSlots = <T>(value: T, path = ''): DynamicSlotLocationIface[] => {\n const slot = slotOf(value);\n if (slot != null) return [{ path, slot }];\n const list = looseListSchema.safeParse(value);\n if (list.success) {\n return list.data.flatMap((item, index) => findDynamicSlots(item, indexPath(path, index)));\n }\n const object = looseObjectSchema.safeParse(value);\n if (object.success) {\n return Object.entries(object.data).flatMap(([key, item]) =>\n findDynamicSlots(item, keyPath(path, key)),\n );\n }\n return [];\n};\n\nexport const containsDynamicSlot = <T>(value: T): boolean => findDynamicSlots(value).length > 0;\n\n// Replaces each slot with the resolver output for its path. A resolver that\n// returned null removes an array entry and leaves an object field as null.\nexport const replaceDynamicSlots = (\n value: JsonValue,\n resolved: Record<string, JsonValue | null>,\n path = '',\n): JsonValue => {\n if (isDynamicSlot(value)) return resolved[path] ?? null;\n const list = listSchema.safeParse(value);\n if (list.success) {\n const out: JsonValue[] = [];\n list.data.forEach((item, index) => {\n const itemPath = indexPath(path, index);\n if (isDynamicSlot(item) && resolved[itemPath] == null) return;\n out.push(replaceDynamicSlots(item, resolved, itemPath));\n });\n return out;\n }\n const object = objectSchema.safeParse(value);\n if (object.success) {\n return Object.fromEntries(\n Object.entries(object.data).map(([key, item]) => [\n key,\n replaceDynamicSlots(item, resolved, keyPath(path, key)),\n ]),\n );\n }\n return value;\n};\n"],
5
- "mappings": "AAAA,YAAY,OAAO;AAKZ,IAAK,eAAL,kBAAKA,kBAAL;AACL,EAAAA,cAAA,oBAAiB;AACjB,EAAAA,cAAA,iBAAc;AAFJ,SAAAA;AAAA,GAAA;AAKL,MAAM,oBAAoB,EAAE,OAAO;AAAA,EACxC,UAAU,EAAE,OAAO;AAAA;AAAA,IAEjB,UAAU,EAAE,OAAO,EAAE,IAAI,C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O,IAAI,EAAE;AAAA,MAAQ,CAAC,CAAC,KAAK,IAAI,MACpD,iBAAiB,MAAM,QAAQ,MAAM,GAAG,CAAC;AAAA,IAC3C;AAAA,EACF;AACA,SAAO,CAAC;AACV;AAEO,MAAM,sBAAsB,CAAI,UAAsB,iBAAiB,KAAK,EAAE,SAAS;AAIvF,MAAM,sBAAsB,CACjC,OACA,UACA,OAAO,OACO;AACd,MAAI,cAAc,KAAK,EAAG,QAAO,SAAS,IAAI,KAAK;AACnD,QAAM,OAAO,WAAW,UAAU,KAAK;AACvC,MAAI,KAAK,SAAS;AAChB,UAAM,MAAmB,CAAC;AAC1B,SAAK,KAAK,QAAQ,CAAC,MAAM,UAAU;AACjC,YAAM,WAAW,UAAU,MAAM,KAAK;AACtC,UAAI,cAAc,IAAI,KAAK,SAAS,QAAQ,KAAK,KAAM;AACvD,UAAI,KAAK,oBAAoB,MAAM,UAAU,QAAQ,CAAC;AAAA,IACxD,CAAC;AACD,WAAO;AAAA,EACT;AACA,QAAM,SAAS,aAAa,UAAU,KAAK;AAC3C,MAAI,OAAO,SAAS;AAClB,WAAO,OAAO;AAAA,MACZ,OAAO,QAAQ,OAAO,IAAI,EAAE,IAAI,CAAC,CAAC,KAAK,IAAI,MAAM;AAAA,QAC/C;AAAA,QACA,oBAAoB,MAAM,UAAU,QAAQ,MAAM,GAAG,CAAC;AAAA,MACxD,CAAC;AAAA,IACH;AAAA,EACF;AACA,SAAO;AACT;",
4
+ "sourcesContent": ["import * as z from 'zod';\nimport type { JsonValue } from \"./json.mjs\";\nimport { hostedBindingRequirementSchema } from \"./hosted-bindings.mjs\";\n\n// Lifecycle boundaries a dynamic slot may resolve at.\n// The harness owns steps, so `step.started` is not supported.\nexport enum DynamicEvent {\n SessionStarted = 'session.started',\n TurnStarted = 'turn.started',\n}\n\nexport const dynamicSlotSchema = z.object({\n $dynamic: z.object({\n // Bundle export that implements the resolver ('instructions/org-context').\n resolver: z.string().min(1),\n events: z.array(z.nativeEnum(DynamicEvent)).min(1),\n // Final additions so Build can render a slot without resolving it.\n description: z.string().optional(),\n preview: z.string().optional(),\n requiredBindings: z.array(hostedBindingRequirementSchema).optional(),\n }),\n});\n\nexport type DynamicSlotIface = z.infer<typeof dynamicSlotSchema>;\nexport type Dynamic<_T> = DynamicSlotIface;\n\nexport const isDynamicSlot = <T>(value: T): value is T & DynamicSlotIface =>\n dynamicSlotSchema.safeParse(value).success;\n\nconst slotOf = <T>(value: T): DynamicSlotIface | null => {\n const parsed = dynamicSlotSchema.safeParse(value);\n return parsed.success ? parsed.data : null;\n};\n\nconst listSchema = z.array(z.json());\nconst objectSchema = z.record(z.string(), z.json());\nconst looseListSchema = z.array(z.unknown());\nconst looseObjectSchema = z.record(z.string(), z.unknown());\n\nexport const maybeDynamic = <T extends z.ZodType>(schema: T) =>\n z.union([dynamicSlotSchema, schema]);\n\n// A dynamic slot found while walking a JSON document, addressed by a stable\n// path ('harness.config.instructions[1]') that the manifest's bundle.resolvers\n// map keys by.\nexport interface DynamicSlotLocationIface {\n path: string;\n slot: DynamicSlotIface;\n}\n\nconst indexPath = (parent: string, index: number): string => `${parent}[${index}]`;\nconst keyPath = (parent: string, key: string): string =>\n parent.length === 0 ? key : `${parent}.${key}`;\n\nexport const findDynamicSlots = <T>(value: T, path = ''): DynamicSlotLocationIface[] => {\n const slot = slotOf(value);\n if (slot != null) return [{ path, slot }];\n const list = looseListSchema.safeParse(value);\n if (list.success) {\n return list.data.flatMap((item, index) => findDynamicSlots(item, indexPath(path, index)));\n }\n const object = looseObjectSchema.safeParse(value);\n if (object.success) {\n return Object.entries(object.data).flatMap(([key, item]) =>\n findDynamicSlots(item, keyPath(path, key)),\n );\n }\n return [];\n};\n\nexport const containsDynamicSlot = <T>(value: T): boolean => findDynamicSlots(value).length > 0;\n\n// Replaces each slot with the resolver output for its path. A resolver that\n// returned null removes an array entry and leaves an object field as null.\nexport const replaceDynamicSlots = (\n value: JsonValue,\n resolved: Record<string, JsonValue | null>,\n path = '',\n): JsonValue => {\n if (isDynamicSlot(value)) return resolved[path] ?? null;\n const list = listSchema.safeParse(value);\n if (list.success) {\n const out: JsonValue[] = [];\n list.data.forEach((item, index) => {\n const itemPath = indexPath(path, index);\n if (isDynamicSlot(item) && resolved[itemPath] == null) return;\n out.push(replaceDynamicSlots(item, resolved, itemPath));\n });\n return out;\n }\n const object = objectSchema.safeParse(value);\n if (object.success) {\n return Object.fromEntries(\n Object.entries(object.data).map(([key, item]) => [\n key,\n replaceDynamicSlots(item, resolved, keyPath(path, key)),\n ]),\n );\n }\n return value;\n};\n"],
5
+ "mappings": "AAAA,YAAY,OAAO;AAEnB,SAAS,sCAAsC;AAIxC,IAAK,eAAL,kBAAKA,kBAAL;AACL,EAAAA,cAAA,oBAAiB;AACjB,EAAAA,cAAA,iBAAc;AAFJ,SAAAA;AAAA,GAAA;AAKL,MAAM,oBAAoB,EAAE,OAAO;AAAA,EACxC,UAAU,EAAE,OAAO;AAAA;AAAA,IAEjB,UAAU,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,IAC1B,QAAQ,EAAE,MAAM,EAAE,WAAW,YAAY,CAAC,EAAE,IAAI,CAAC;AAAA;AAAA,IAEjD,aAAa,EAAE,OAAO,EAAE,SAAS;AAAA,IACjC,SAAS,EAAE,OAAO,EAAE,SAAS;AAAA,IAC7B,kBAAkB,EAAE,MAAM,8BAA8B,EAAE,SAAS;AAAA,EACrE,CAAC;AACH,CAAC;AAKM,MAAM,gBAAgB,CAAI,UAC/B,kBAAkB,UAAU,KAAK,EAAE;AAErC,MAAM,SAAS,CAAI,UAAsC;AACvD,QAAM,SAAS,kBAAkB,UAAU,KAAK;AAChD,SAAO,OAAO,UAAU,OAAO,OAAO;AACxC;AAEA,MAAM,aAAa,EAAE,MAAM,EAAE,KAAK,CAAC;AACnC,MAAM,eAAe,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,KAAK,CAAC;AAClD,MAAM,kBAAkB,EAAE,MAAM,EAAE,QAAQ,CAAC;AAC3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oBAAoB,MAAM,UAAU,QAAQ,CAAC;AAAA,IACxD,CAAC;AACD,WAAO;AAAA,EACT;AACA,QAAM,SAAS,aAAa,UAAU,KAAK;AAC3C,MAAI,OAAO,SAAS;AAClB,WAAO,OAAO;AAAA,MACZ,OAAO,QAAQ,OAAO,IAAI,EAAE,IAAI,CAAC,CAAC,KAAK,IAAI,MAAM;AAAA,QAC/C;AAAA,QACA,oBAAoB,MAAM,UAAU,QAAQ,MAAM,GAAG,CAAC;AAAA,MACxD,CAAC;AAAA,IACH;AAAA,EACF;AACA,SAAO;AACT;",
6
6
  "names": ["DynamicEvent"]
7
7
  }
@@ -3,6 +3,7 @@ import * as z from 'zod';
3
3
  import { CredentialRoute, type RouteGrantIface } from "./credential-routes.mjs";
4
4
  import { CredentialDelivery, InferenceCredentialKind } from "./credentials.mjs";
5
5
  import type { JsonSchema, JsonValue } from "./json.mjs";
6
+ import type { HostedBindingsIface } from "./hosted-bindings.mjs";
6
7
  import { BaseCapability, type ResolvedAgentManifestIface } from "./manifest.mjs";
7
8
  import { type ProviderRef } from "./provider-ref.mjs";
8
9
  export declare const PENDING_BUNDLE_EXPORT = "<pending>";
@@ -267,6 +268,7 @@ export interface SandboxTargetEndpointIface {
267
268
  } | null;
268
269
  }
269
270
  export interface HarnessSessionContextIface {
271
+ bindings?: HostedBindingsIface;
270
272
  sessionId: string;
271
273
  organizationId: string;
272
274
  definitionId: string;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/harness.ts"],
4
- "sourcesContent": ["import type { McpServer } from '@agentclientprotocol/sdk/experimental/v2';\nimport * as z from 'zod';\nimport { CredentialRoute, routeGrantSchema, type RouteGrantIface } from \"./credential-routes.mjs\";\nimport { CredentialDelivery, InferenceCredentialKind } from \"./credentials.mjs\";\nimport type { JsonSchema, JsonValue } from \"./json.mjs\";\nimport { jsonObjectSchema, jsonSchemaSchema } from \"./json.mjs\";\nimport { BaseCapability, InstructionRole, type ResolvedAgentManifestIface } from \"./manifest.mjs\";\nimport { bundleRef, providerRefSchema, type ProviderRef } from \"./provider-ref.mjs\";\nimport { referencedSharedSchemas, SCHEMA_IDS } from \"./schemas.mjs\";\n\n// Placeholder export name the compiler replaces with the defining module's path.\nexport const PENDING_BUNDLE_EXPORT = '<pending>';\n\n// A harness is a specific ACP agent program together with how to reach it. Hosting is part of what a harness is, so there is no\n// engine parameter: \"Pi on Final's serverless runtime\" and \"Pi on a server you\n// run\" are two harnesses. The hosting half is deliberately small; everything\n// about what the agent does goes over ACP v2.\n\nexport enum AcpTransport {\n Relay = 'relay',\n Ws = 'ws',\n Http = 'http',\n Stdio = 'stdio',\n}\n\nexport enum McpTransportKind {\n Acp = 'acp',\n Http = 'http',\n Stdio = 'stdio',\n}\n\n// How a harness provides one base capability.\nexport enum BaseToolProvision {\n // Routed to the declared sandbox target.\n Bound = 'bound',\n // Native on the harness's host and switchable through its own allow-lists.\n HostDisableable = 'host-disableable',\n // Native on the harness's host and not switchable.\n HostFixed = 'host-fixed',\n}\n\n// SDK wires a harness speaks to reach a bound sandbox target.\nexport enum SandboxWire {\n HandleRpc = 'handle-rpc',\n Mcp = 'mcp',\n}\n\nexport enum UserInstructionDelivery {\n History = 'history',\n System = 'system',\n}\n\n// Who operates the place a harness's credentials land. Every\n// harness, Final's included, gets the same grant forms; a subscription goes to\n// a third-party harness only when its owner allowed third-party harnesses.\n// Only installed provider packages may declare first-party; a bundle-declared\n// harness is third-party whatever it declares.\nexport enum HarnessTrustClass {\n // The provider operates the harness on infrastructure it runs (Final's serverless harnesses).\n FirstParty = 'first-party',\n // Someone else's host or program (remote hosts, external ACP agents, local processes).\n ThirdParty = 'third-party',\n}\n\n// What an accepted session/prompt does while the session is running. Both are valid; refusing one is a conformance failure.\nexport enum PromptWhileRunning {\n // Joins the running work: the model sees it at its next step.\n Inject = 'inject',\n // Runs after the current work goes idle; dropped by session/cancel if not started.\n Queue = 'queue',\n}\n\n// Defaults for a description that does not declare the hosting contract's\n// newer fields (bundle harnesses, older registrations): the session service\n// then assumes nothing survives a dropped connection and that a prompt while\n// running waits for idle.\nexport const DEFAULT_PROMPT_WHILE_RUNNING = PromptWhileRunning.Queue;\nexport const DEFAULT_SESSION_SURVIVES_DISCONNECT = false;\n\nexport const baseToolDeclarationSchema = z.object({\n provision: z.nativeEnum(BaseToolProvision),\n nativeTools: z.array(z.string()),\n});\n\nexport const harnessDescriptionSchema = z.object({\n // Everything configurable about this harness (model, reasoning, credentials,\n // permission mode, instructions, skills, cwd, ...). JSON Schema so Build can\n // render it; may $ref the shared final://schemas/* fragments.\n configSchema: jsonSchemaSchema,\n // Absent: user fragments enter history. System-only programs declare their conversion.\n userInstructionDelivery: z.nativeEnum(UserInstructionDelivery).optional(),\n acp: z.object({\n transports: z.array(z.nativeEnum(AcpTransport)).min(1),\n mcp: z.array(z.nativeEnum(McpTransportKind)),\n }),\n // A capability missing here is unavailable on this harness.\n baseTools: z.partialRecord(z.nativeEnum(BaseCapability), baseToolDeclarationSchema),\n consumes: z.array(z.nativeEnum(SandboxWire)),\n inference: z.object({\n vendors: z.array(z.string()),\n kinds: z.array(z.nativeEnum(InferenceCredentialKind)),\n delivery: z.nativeEnum(CredentialDelivery),\n }),\n // Absent: third-party.\n trust: z.nativeEnum(HarnessTrustClass).optional(),\n supports: z.object({\n observe: z.boolean(),\n resumeReplay: z.boolean(),\n fork: z.boolean(),\n // Renders _meta[\"final.ai\"].author itself; otherwise the channel prepends\n // the author's name to the text.\n authorMeta: z.boolean(),\n // Explicit false: native toolPolicy cannot be enforced by this adapter's public surface.\n nativeToolPolicy: z.boolean().optional(),\n }),\n promptWhileRunning: z.nativeEnum(PromptWhileRunning).default(DEFAULT_PROMPT_WHILE_RUNNING),\n // Keeps the session, its running work and its open requests across a dropped\n // connection, buffers updates for replay, and re-raises the open requests\n // with the same JSON-RPC ids on the next session/resume. False:\n // open turns end `harness_state_lost` after a reconnect.\n sessionSurvivesDisconnect: z.boolean().default(DEFAULT_SESSION_SURVIVES_DISCONNECT),\n});\n\nexport type BaseToolDeclarationIface = z.infer<typeof baseToolDeclarationSchema>;\nexport type HarnessDescriptionIface = z.infer<typeof harnessDescriptionSchema>;\n\nexport const deliveredHarnessConfig = (args: {\n config: JsonValue;\n description: HarnessDescriptionIface;\n}): JsonValue => {\n if (args.description.userInstructionDelivery !== UserInstructionDelivery.System)\n return args.config;\n const config = jsonObjectSchema.safeParse(args.config);\n if (!config.success) return args.config;\n const fields = referencedSharedSchemas(args.description.configSchema);\n const field =\n Object.entries(fields).find(([, schema]) => schema === SCHEMA_IDS.instructions)?.[0] ??\n 'instructions';\n const instructions = config.data[field];\n if (!Array.isArray(instructions)) return args.config;\n return {\n ...config.data,\n [field]: instructions.map((value) => {\n const fragment = jsonObjectSchema.safeParse(value);\n return fragment.success && fragment.data['role'] === InstructionRole.User\n ? { ...fragment.data, role: InstructionRole.System }\n : value;\n }),\n };\n};\n\nexport const harnessSessionRefSchema = z.object({\n harness: providerRefSchema,\n // Opaque to the session service; the harness's own id for the session.\n harnessSessionRef: z.string().min(1),\n // Bumped whenever the harness loses state; a mismatch on resume means the\n // session service must re-seed with session/new.\n generation: z.number().int().nonnegative(),\n});\n\nexport type HarnessSessionRefIface = z.infer<typeof harnessSessionRefSchema>;\n\n// Route-scoped, short-lived grants: credential-routes.ts.\nexport {\n credentialRefreshRequestSchema,\n CredentialRoute,\n routeGrantSchema,\n type CredentialRefreshRequestIface,\n type RouteGrantIface,\n} from \"./credential-routes.mjs\";\n\nexport interface CredentialGrantIface {\n // Base URL of the broker routes (`<base>/model`, `<base>/refresh`, ...).\n brokerUrl: string;\n grants: RouteGrantIface[];\n // What the model grant resolved to, for harnesses that hand credentials over\n // at open (delivery 'at-open'). Null for per-request harnesses.\n atOpen: AtOpenModelCredentialIface | null;\n // How to renew this grant; null only when it carries no route grant.\n refresh: CredentialGrantRefreshIface | null;\n}\n\n// Renewal is pulled, never pushed. Per-request harnesses fetch\n// `<brokerUrl>/model` on every request. At-open harnesses (or their host)\n// POST `url` with `authorization: Bearer <token>` and a\n// `credentialRefreshRequestSchema` body before `expiresAt` and once after a\n// vendor 401; the answer is the grant's next generation (a\n// `credentialRefreshResultSchema` body with its own `refresh`), which replaces\n// this one. The broker resolves the policy again for it, so a disconnected\n// credential falls through; a revoked grant (every open revokes the previous\n// open's grants) or a closed harness session is refused (401).\nexport interface CredentialGrantRefreshIface {\n // `<brokerUrl>/refresh`.\n url: string;\n // One of this grant's own route grants (the model route's).\n token: string;\n harnessSessionId: string;\n // When `token` expires; a refresh after it is refused.\n expiresAt: string;\n}\n\nexport interface AtOpenModelCredentialIface {\n vendor: string;\n kind: InferenceCredentialKind;\n // Base URL and bearer for an OpenAI- or Anthropic-compatible endpoint (the\n // platform proxy, a corporate gateway) or the vendor itself.\n baseUrl: string | null;\n apiKey: string | null;\n // Subscription material for Final-managed harnesses only (Claude setup token,\n // Codex app-server chatgptAuthTokens); renewed through the grant's refresh route.\n subscription: { format: 'claude-setup-token' | 'chatgpt-auth-tokens'; value: string } | null;\n fingerprint: string;\n}\n\nexport const atOpenModelCredentialSchema = z.object({\n vendor: z.string(),\n kind: z.nativeEnum(InferenceCredentialKind),\n baseUrl: z.string().min(1).nullable(),\n apiKey: z.string().min(1).nullable(),\n subscription: z\n .object({\n format: z.union([z.literal('claude-setup-token'), z.literal('chatgpt-auth-tokens')]),\n value: z.string().min(1),\n })\n .nullable(),\n fingerprint: z.string(),\n}) satisfies z.ZodType<AtOpenModelCredentialIface>;\n\nexport const credentialGrantRefreshSchema = z.object({\n url: z.string().min(1),\n token: z.string().min(1),\n harnessSessionId: z.string().min(1),\n expiresAt: z.string(),\n}) satisfies z.ZodType<CredentialGrantRefreshIface>;\n\nexport const credentialGrantSchema = z.object({\n brokerUrl: z.string().min(1),\n grants: z.array(routeGrantSchema),\n atOpen: atOpenModelCredentialSchema.nullable(),\n refresh: credentialGrantRefreshSchema.nullable(),\n}) satisfies z.ZodType<CredentialGrantIface>;\n\n// An `http` MCP server entry the harness was handed in `session/new`\n// (`mcpServers`), with fresh headers. Same name and url; the harness swaps the\n// headers of the entry with that url.\nexport interface RenewedMcpServerIface {\n name: string;\n url: string;\n headers: { name: string; value: string }[];\n}\n\n// What a refresh answers: the grant's next generation, plus fresh copies of the\n// other short-lived material the harness was handed at open. Renewing the\n// `mcp` route renews the session's `http` MCP server headers; renewing\n// `sandbox` renews the bound sandbox targets' endpoint tokens.\nexport interface CredentialRefreshResultIface extends CredentialGrantIface {\n mcpServers: RenewedMcpServerIface[];\n sandboxes: Record<string, SandboxTargetEndpointIface>;\n}\n\nconst endpointTokenSchema = z.object({\n url: z.string().min(1),\n token: z.string(),\n expiresAt: z.string(),\n});\n\nexport const sandboxTargetEndpointSchema = z.object({\n target: z.string().min(1),\n bindingId: z.string().min(1),\n capabilities: z.array(z.string()),\n rpc: endpointTokenSchema.nullable(),\n mcp: endpointTokenSchema.nullable(),\n}) satisfies z.ZodType<SandboxTargetEndpointIface>;\n\nexport const renewedMcpServerSchema = z.object({\n name: z.string().min(1),\n url: z.string().min(1),\n headers: z.array(z.object({ name: z.string().min(1), value: z.string() })),\n}) satisfies z.ZodType<RenewedMcpServerIface>;\n\n// Absent renewals parse as none, so an answer without them still parses.\nexport const credentialRefreshResultSchema = credentialGrantSchema.extend({\n mcpServers: z.array(renewedMcpServerSchema).default([]),\n sandboxes: z.record(z.string(), sandboxTargetEndpointSchema).default({}),\n}) satisfies z.ZodType<CredentialRefreshResultIface, unknown>;\n\n// The refresh descriptor for a set of route grants: authenticated by the model\n// grant (else the first), due when that token expires.\nexport const grantRefreshFor = (args: {\n brokerUrl: string;\n harnessSessionId: string;\n grants: readonly RouteGrantIface[];\n}): CredentialGrantRefreshIface | null => {\n const grant =\n args.grants.find((candidate) => candidate.route === CredentialRoute.Model) ?? args.grants[0];\n if (grant == null) return null;\n return {\n url: `${args.brokerUrl.replace(/\\/+$/, '')}/refresh`,\n token: grant.token,\n harnessSessionId: args.harnessSessionId,\n expiresAt: grant.expiresAt,\n };\n};\n\nexport interface SecretReaderIface {\n get(name: string): Promise<string | null>;\n}\n\nexport interface TraceContextIface {\n traceparent: string | null;\n tracestate: string | null;\n}\n\n// A bound sandbox target as the session service hands it to a harness: a stable\n// per-binding address that starts the sandbox on the first tool call. Never a lease, a data-plane token for a live VM, or provider code.\nexport interface SandboxTargetEndpointIface {\n target: string;\n bindingId: string;\n capabilities: string[];\n rpc: { url: string; token: string; expiresAt: string } | null;\n mcp: { url: string; token: string; expiresAt: string } | null;\n}\n\nexport interface HarnessSessionContextIface {\n sessionId: string;\n organizationId: string;\n definitionId: string;\n revisionId: string;\n // Public base URL of the session service for this session (MCP over HTTP,\n // sandbox endpoints, the broker).\n sessionServiceUrl: string;\n // The region of the session service serving the session and its sandbox\n // bindings, so a harness can run near it; null when unknown.\n sessionServiceRegion?: string | null;\n}\n\n// Lifecycle signals a harness implementation may report about the runtime\n// hosting a session (invocations, metering, traces). Informational: the\n// session service records them (agent.harness_invocations, Tinybird) and never\n// depends on them for correctness.\nexport interface HarnessObserverIface {\n // The runtime accepted the invocation request (its response began).\n invocationAccepted?(event: { invocationRef: string; at: string }): void;\n invocationStarted?(event: {\n invocationRef: string;\n at: string;\n bootMs: number | null;\n // The runtime's deployed version (Workers version id, commit), for rollouts.\n versionId?: string | null;\n commitSha?: string | null;\n }): void;\n invocationKeepalive?(event: { invocationRef: string; at: string; activeWork: number }): void;\n invocationEnded?(event: {\n invocationRef: string;\n at: string;\n reason: string;\n error: string | null;\n metering: Record<string, number>;\n }): void;\n trace?(event: { name: string; at: string; fields: Record<string, JsonValue> }): void;\n}\n\nexport interface OpenHarnessSessionArgsIface {\n session: HarnessSessionContextIface;\n // The session service's id for this harness session (agent.harness_sessions);\n // implementations key their runtime state and route grants by it.\n harnessSessionId: string;\n // Hosting may authorize the child endpoint to fork this source through ACP.\n forkSource?: { ref: HarnessSessionRefIface; acpSessionId: string };\n observer?: HarnessObserverIface;\n // The binding's config, validated against configSchema, dynamic slots resolved.\n config: JsonValue;\n manifest: ResolvedAgentManifestIface;\n // Already materialized ACP MCP server entries: authored tools, connections\n // (Final's MCP server among them), sandbox MCP projections where applicable.\n mcpServers: McpServer[];\n // Declared base capabilities with the target endpoint each is bound to.\n baseTools: Partial<Record<BaseCapability, SandboxTargetEndpointIface>>;\n sandboxes: Record<string, SandboxTargetEndpointIface>;\n credentials: CredentialGrantIface;\n secrets: SecretReaderIface;\n trace: TraceContextIface;\n}\n\nexport interface ResumeHarnessSessionArgsIface extends OpenHarnessSessionArgsIface {\n ref: HarnessSessionRefIface;\n // Last log seq the session service holds from this harness session; the\n // harness replays anything newer after session/resume.\n lastSeq: number;\n}\n\n// Resolved only in memory; refs/manifests retain secret names, never TLS keys.\nexport interface HarnessClientTlsIface {\n cert: string;\n key: string;\n ca?: string;\n}\n\nexport type HarnessEndpointIface =\n | {\n ref: HarnessSessionRefIface;\n transport: AcpTransport.Ws;\n url: string;\n headers: Record<string, string>;\n resolveHeaders?: () => Promise<Record<string, string>>;\n tls?: HarnessClientTlsIface;\n }\n | {\n ref: HarnessSessionRefIface;\n transport: AcpTransport.Http;\n url: string;\n headers: Record<string, string>;\n resolveHeaders?: () => Promise<Record<string, string>>;\n tls?: HarnessClientTlsIface;\n }\n // websocket-gateway relay channel (Final-managed harnesses).\n | { ref: HarnessSessionRefIface; transport: AcpTransport.Relay; channel: string; token: string }\n // Local development, CI and conformance only.\n | {\n ref: HarnessSessionRefIface;\n transport: AcpTransport.Stdio;\n command: string;\n args: string[];\n env: Record<string, string>;\n };\n\nexport interface HarnessHealthIface {\n ok: boolean;\n detail?: string;\n checkedAt: string;\n}\n\n// The binding a description is asked for: its config (validated against the\n// configSchema of the binding-free description) and the definition's secrets.\nexport interface DescribeHarnessArgsIface {\n config: JsonValue;\n secrets: SecretReaderIface;\n}\n\nexport interface HarnessIface {\n // Without a binding: what Build renders before one exists (configSchema,\n // declared capabilities). With one: the description of that binding, which a\n // harness reaching an arbitrary agent derives from the agent itself (e.g. its\n // `initialize`). Every harness implements both; most ignore the binding.\n describe(binding?: DescribeHarnessArgsIface): Promise<HarnessDescriptionIface>;\n open(args: OpenHarnessSessionArgsIface): Promise<HarnessEndpointIface>;\n resume(args: ResumeHarnessSessionArgsIface): Promise<HarnessEndpointIface>;\n park(ref: HarnessSessionRefIface): Promise<void>;\n // Graceful by default: the program's state is durable (resumable) before it\n // stops, bounded by the implementation's timeout, then forced. `force` skips\n // the wait; the session service passes it when the program did not settle\n // ACP `session/close` within its bound.\n close(ref: HarnessSessionRefIface, opts?: CloseHarnessSessionOptsIface): Promise<void>;\n health(\n ref: HarnessSessionRefIface,\n context?: DescribeHarnessArgsIface,\n ): Promise<HarnessHealthIface>;\n}\n\nexport interface CloseHarnessSessionOptsIface {\n force?: boolean;\n // As with health, retained refs can resolve current client TLS without storing keys in the ref.\n context?: DescribeHarnessArgsIface;\n}\n\n// What an installed harness module exports: the implementation plus an\n// authoring helper that builds the manifest binding.\nexport interface HarnessModuleIface<Config> {\n ref: ProviderRef;\n harness: HarnessIface;\n binding: (config: Config) => { harness: ProviderRef; config: JsonValue };\n}\n\n// Custom harnesses in a definition's bundle. Calling the result\n// with a config yields the manifest binding; the implementation is resolved\n// from the bundle by export name.\nexport interface DefinedHarnessBindingIface {\n harness: ProviderRef;\n config: JsonValue;\n definedHarness: true;\n}\n\nexport interface DefinedHarnessIface<Config> extends HarnessIface {\n (config: Config): DefinedHarnessBindingIface;\n}\n\nexport const defineHarness = <Config extends JsonValue = JsonValue>(\n implementation: HarnessIface,\n): DefinedHarnessIface<Config> => {\n // The export name is unknown here; the compiler rewrites `bundle:<pending>`\n // to the module path that exported this harness.\n const binding = (config: Config): DefinedHarnessBindingIface => ({\n harness: bundleRef(PENDING_BUNDLE_EXPORT),\n config,\n definedHarness: true,\n });\n return Object.assign(binding, implementation);\n};\n\nexport const describeConfigSchema = (description: HarnessDescriptionIface): JsonSchema =>\n description.configSchema;\n"],
5
- "mappings": "AACA,YAAY,OAAO;AACnB,SAAS,iBAAiB,wB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,EACtD,WAAW,EAAE,OAAO,EAAE,OAAO,GAAG,2BAA2B,EAAE,QAAQ,CAAC,CAAC;AACzE,CAAC;AAIM,MAAM,kBAAkB,CAAC,SAIU;AACxC,QAAM,QACJ,KAAK,OAAO,KAAK,CAAC,cAAc,UAAU,UAAU,gBAAgB,KAAK,KAAK,KAAK,OAAO,CAAC;AAC7F,MAAI,SAAS,KAAM,QAAO;AAC1B,SAAO;AAAA,IACL,KAAK,GAAG,KAAK,UAAU,QAAQ,QAAQ,EAAE,CAAC;AAAA,IAC1C,OAAO,MAAM;AAAA,IACb,kBAAkB,KAAK;AAAA,IACvB,WAAW,MAAM;AAAA,EACnB;AACF;AAwLO,MAAM,gBAAgB,CAC3B,mBACgC;AAGhC,QAAM,UAAU,CAAC,YAAgD;AAAA,IAC/D,SAAS,UAAU,qBAAqB;AAAA,IACxC;AAAA,IACA,gBAAgB;AAAA,EAClB;AACA,SAAO,OAAO,OAAO,SAAS,cAAc;AAC9C;AAEO,MAAM,uBAAuB,CAAC,gBACnC,YAAY;",
4
+ "sourcesContent": ["import type { McpServer } from '@agentclientprotocol/sdk/experimental/v2';\nimport * as z from 'zod';\nimport { CredentialRoute, routeGrantSchema, type RouteGrantIface } from \"./credential-routes.mjs\";\nimport { CredentialDelivery, InferenceCredentialKind } from \"./credentials.mjs\";\nimport type { JsonSchema, JsonValue } from \"./json.mjs\";\nimport type { HostedBindingsIface } from \"./hosted-bindings.mjs\";\nimport { jsonObjectSchema, jsonSchemaSchema } from \"./json.mjs\";\nimport { BaseCapability, InstructionRole, type ResolvedAgentManifestIface } from \"./manifest.mjs\";\nimport { bundleRef, providerRefSchema, type ProviderRef } from \"./provider-ref.mjs\";\nimport { referencedSharedSchemas, SCHEMA_IDS } from \"./schemas.mjs\";\n\n// Placeholder export name the compiler replaces with the defining module's path.\nexport const PENDING_BUNDLE_EXPORT = '<pending>';\n\n// A harness is a specific ACP agent program together with how to reach it. Hosting is part of what a harness is, so there is no\n// engine parameter: \"Pi on Final's serverless runtime\" and \"Pi on a server you\n// run\" are two harnesses. The hosting half is deliberately small; everything\n// about what the agent does goes over ACP v2.\n\nexport enum AcpTransport {\n Relay = 'relay',\n Ws = 'ws',\n Http = 'http',\n Stdio = 'stdio',\n}\n\nexport enum McpTransportKind {\n Acp = 'acp',\n Http = 'http',\n Stdio = 'stdio',\n}\n\n// How a harness provides one base capability.\nexport enum BaseToolProvision {\n // Routed to the declared sandbox target.\n Bound = 'bound',\n // Native on the harness's host and switchable through its own allow-lists.\n HostDisableable = 'host-disableable',\n // Native on the harness's host and not switchable.\n HostFixed = 'host-fixed',\n}\n\n// SDK wires a harness speaks to reach a bound sandbox target.\nexport enum SandboxWire {\n HandleRpc = 'handle-rpc',\n Mcp = 'mcp',\n}\n\nexport enum UserInstructionDelivery {\n History = 'history',\n System = 'system',\n}\n\n// Who operates the place a harness's credentials land. Every\n// harness, Final's included, gets the same grant forms; a subscription goes to\n// a third-party harness only when its owner allowed third-party harnesses.\n// Only installed provider packages may declare first-party; a bundle-declared\n// harness is third-party whatever it declares.\nexport enum HarnessTrustClass {\n // The provider operates the harness on infrastructure it runs (Final's serverless harnesses).\n FirstParty = 'first-party',\n // Someone else's host or program (remote hosts, external ACP agents, local processes).\n ThirdParty = 'third-party',\n}\n\n// What an accepted session/prompt does while the session is running. Both are valid; refusing one is a conformance failure.\nexport enum PromptWhileRunning {\n // Joins the running work: the model sees it at its next step.\n Inject = 'inject',\n // Runs after the current work goes idle; dropped by session/cancel if not started.\n Queue = 'queue',\n}\n\n// Defaults for a description that does not declare the hosting contract's\n// newer fields (bundle harnesses, older registrations): the session service\n// then assumes nothing survives a dropped connection and that a prompt while\n// running waits for idle.\nexport const DEFAULT_PROMPT_WHILE_RUNNING = PromptWhileRunning.Queue;\nexport const DEFAULT_SESSION_SURVIVES_DISCONNECT = false;\n\nexport const baseToolDeclarationSchema = z.object({\n provision: z.nativeEnum(BaseToolProvision),\n nativeTools: z.array(z.string()),\n});\n\nexport const harnessDescriptionSchema = z.object({\n // Everything configurable about this harness (model, reasoning, credentials,\n // permission mode, instructions, skills, cwd, ...). JSON Schema so Build can\n // render it; may $ref the shared final://schemas/* fragments.\n configSchema: jsonSchemaSchema,\n // Absent: user fragments enter history. System-only programs declare their conversion.\n userInstructionDelivery: z.nativeEnum(UserInstructionDelivery).optional(),\n acp: z.object({\n transports: z.array(z.nativeEnum(AcpTransport)).min(1),\n mcp: z.array(z.nativeEnum(McpTransportKind)),\n }),\n // A capability missing here is unavailable on this harness.\n baseTools: z.partialRecord(z.nativeEnum(BaseCapability), baseToolDeclarationSchema),\n consumes: z.array(z.nativeEnum(SandboxWire)),\n inference: z.object({\n vendors: z.array(z.string()),\n kinds: z.array(z.nativeEnum(InferenceCredentialKind)),\n delivery: z.nativeEnum(CredentialDelivery),\n }),\n // Absent: third-party.\n trust: z.nativeEnum(HarnessTrustClass).optional(),\n supports: z.object({\n observe: z.boolean(),\n resumeReplay: z.boolean(),\n fork: z.boolean(),\n // Renders _meta[\"final.ai\"].author itself; otherwise the channel prepends\n // the author's name to the text.\n authorMeta: z.boolean(),\n // Explicit false: native toolPolicy cannot be enforced by this adapter's public surface.\n nativeToolPolicy: z.boolean().optional(),\n }),\n promptWhileRunning: z.nativeEnum(PromptWhileRunning).default(DEFAULT_PROMPT_WHILE_RUNNING),\n // Keeps the session, its running work and its open requests across a dropped\n // connection, buffers updates for replay, and re-raises the open requests\n // with the same JSON-RPC ids on the next session/resume. False:\n // open turns end `harness_state_lost` after a reconnect.\n sessionSurvivesDisconnect: z.boolean().default(DEFAULT_SESSION_SURVIVES_DISCONNECT),\n});\n\nexport type BaseToolDeclarationIface = z.infer<typeof baseToolDeclarationSchema>;\nexport type HarnessDescriptionIface = z.infer<typeof harnessDescriptionSchema>;\n\nexport const deliveredHarnessConfig = (args: {\n config: JsonValue;\n description: HarnessDescriptionIface;\n}): JsonValue => {\n if (args.description.userInstructionDelivery !== UserInstructionDelivery.System)\n return args.config;\n const config = jsonObjectSchema.safeParse(args.config);\n if (!config.success) return args.config;\n const fields = referencedSharedSchemas(args.description.configSchema);\n const field =\n Object.entries(fields).find(([, schema]) => schema === SCHEMA_IDS.instructions)?.[0] ??\n 'instructions';\n const instructions = config.data[field];\n if (!Array.isArray(instructions)) return args.config;\n return {\n ...config.data,\n [field]: instructions.map((value) => {\n const fragment = jsonObjectSchema.safeParse(value);\n return fragment.success && fragment.data['role'] === InstructionRole.User\n ? { ...fragment.data, role: InstructionRole.System }\n : value;\n }),\n };\n};\n\nexport const harnessSessionRefSchema = z.object({\n harness: providerRefSchema,\n // Opaque to the session service; the harness's own id for the session.\n harnessSessionRef: z.string().min(1),\n // Bumped whenever the harness loses state; a mismatch on resume means the\n // session service must re-seed with session/new.\n generation: z.number().int().nonnegative(),\n});\n\nexport type HarnessSessionRefIface = z.infer<typeof harnessSessionRefSchema>;\n\n// Route-scoped, short-lived grants: credential-routes.ts.\nexport {\n credentialRefreshRequestSchema,\n CredentialRoute,\n routeGrantSchema,\n type CredentialRefreshRequestIface,\n type RouteGrantIface,\n} from \"./credential-routes.mjs\";\n\nexport interface CredentialGrantIface {\n // Base URL of the broker routes (`<base>/model`, `<base>/refresh`, ...).\n brokerUrl: string;\n grants: RouteGrantIface[];\n // What the model grant resolved to, for harnesses that hand credentials over\n // at open (delivery 'at-open'). Null for per-request harnesses.\n atOpen: AtOpenModelCredentialIface | null;\n // How to renew this grant; null only when it carries no route grant.\n refresh: CredentialGrantRefreshIface | null;\n}\n\n// Renewal is pulled, never pushed. Per-request harnesses fetch\n// `<brokerUrl>/model` on every request. At-open harnesses (or their host)\n// POST `url` with `authorization: Bearer <token>` and a\n// `credentialRefreshRequestSchema` body before `expiresAt` and once after a\n// vendor 401; the answer is the grant's next generation (a\n// `credentialRefreshResultSchema` body with its own `refresh`), which replaces\n// this one. The broker resolves the policy again for it, so a disconnected\n// credential falls through; a revoked grant (every open revokes the previous\n// open's grants) or a closed harness session is refused (401).\nexport interface CredentialGrantRefreshIface {\n // `<brokerUrl>/refresh`.\n url: string;\n // One of this grant's own route grants (the model route's).\n token: string;\n harnessSessionId: string;\n // When `token` expires; a refresh after it is refused.\n expiresAt: string;\n}\n\nexport interface AtOpenModelCredentialIface {\n vendor: string;\n kind: InferenceCredentialKind;\n // Base URL and bearer for an OpenAI- or Anthropic-compatible endpoint (the\n // platform proxy, a corporate gateway) or the vendor itself.\n baseUrl: string | null;\n apiKey: string | null;\n // Subscription material for Final-managed harnesses only (Claude setup token,\n // Codex app-server chatgptAuthTokens); renewed through the grant's refresh route.\n subscription: { format: 'claude-setup-token' | 'chatgpt-auth-tokens'; value: string } | null;\n fingerprint: string;\n}\n\nexport const atOpenModelCredentialSchema = z.object({\n vendor: z.string(),\n kind: z.nativeEnum(InferenceCredentialKind),\n baseUrl: z.string().min(1).nullable(),\n apiKey: z.string().min(1).nullable(),\n subscription: z\n .object({\n format: z.union([z.literal('claude-setup-token'), z.literal('chatgpt-auth-tokens')]),\n value: z.string().min(1),\n })\n .nullable(),\n fingerprint: z.string(),\n}) satisfies z.ZodType<AtOpenModelCredentialIface>;\n\nexport const credentialGrantRefreshSchema = z.object({\n url: z.string().min(1),\n token: z.string().min(1),\n harnessSessionId: z.string().min(1),\n expiresAt: z.string(),\n}) satisfies z.ZodType<CredentialGrantRefreshIface>;\n\nexport const credentialGrantSchema = z.object({\n brokerUrl: z.string().min(1),\n grants: z.array(routeGrantSchema),\n atOpen: atOpenModelCredentialSchema.nullable(),\n refresh: credentialGrantRefreshSchema.nullable(),\n}) satisfies z.ZodType<CredentialGrantIface>;\n\n// An `http` MCP server entry the harness was handed in `session/new`\n// (`mcpServers`), with fresh headers. Same name and url; the harness swaps the\n// headers of the entry with that url.\nexport interface RenewedMcpServerIface {\n name: string;\n url: string;\n headers: { name: string; value: string }[];\n}\n\n// What a refresh answers: the grant's next generation, plus fresh copies of the\n// other short-lived material the harness was handed at open. Renewing the\n// `mcp` route renews the session's `http` MCP server headers; renewing\n// `sandbox` renews the bound sandbox targets' endpoint tokens.\nexport interface CredentialRefreshResultIface extends CredentialGrantIface {\n mcpServers: RenewedMcpServerIface[];\n sandboxes: Record<string, SandboxTargetEndpointIface>;\n}\n\nconst endpointTokenSchema = z.object({\n url: z.string().min(1),\n token: z.string(),\n expiresAt: z.string(),\n});\n\nexport const sandboxTargetEndpointSchema = z.object({\n target: z.string().min(1),\n bindingId: z.string().min(1),\n capabilities: z.array(z.string()),\n rpc: endpointTokenSchema.nullable(),\n mcp: endpointTokenSchema.nullable(),\n}) satisfies z.ZodType<SandboxTargetEndpointIface>;\n\nexport const renewedMcpServerSchema = z.object({\n name: z.string().min(1),\n url: z.string().min(1),\n headers: z.array(z.object({ name: z.string().min(1), value: z.string() })),\n}) satisfies z.ZodType<RenewedMcpServerIface>;\n\n// Absent renewals parse as none, so an answer without them still parses.\nexport const credentialRefreshResultSchema = credentialGrantSchema.extend({\n mcpServers: z.array(renewedMcpServerSchema).default([]),\n sandboxes: z.record(z.string(), sandboxTargetEndpointSchema).default({}),\n}) satisfies z.ZodType<CredentialRefreshResultIface, unknown>;\n\n// The refresh descriptor for a set of route grants: authenticated by the model\n// grant (else the first), due when that token expires.\nexport const grantRefreshFor = (args: {\n brokerUrl: string;\n harnessSessionId: string;\n grants: readonly RouteGrantIface[];\n}): CredentialGrantRefreshIface | null => {\n const grant =\n args.grants.find((candidate) => candidate.route === CredentialRoute.Model) ?? args.grants[0];\n if (grant == null) return null;\n return {\n url: `${args.brokerUrl.replace(/\\/+$/, '')}/refresh`,\n token: grant.token,\n harnessSessionId: args.harnessSessionId,\n expiresAt: grant.expiresAt,\n };\n};\n\nexport interface SecretReaderIface {\n get(name: string): Promise<string | null>;\n}\n\nexport interface TraceContextIface {\n traceparent: string | null;\n tracestate: string | null;\n}\n\n// A bound sandbox target as the session service hands it to a harness: a stable\n// per-binding address that starts the sandbox on the first tool call. Never a lease, a data-plane token for a live VM, or provider code.\nexport interface SandboxTargetEndpointIface {\n target: string;\n bindingId: string;\n capabilities: string[];\n rpc: { url: string; token: string; expiresAt: string } | null;\n mcp: { url: string; token: string; expiresAt: string } | null;\n}\n\nexport interface HarnessSessionContextIface {\n bindings?: HostedBindingsIface;\n sessionId: string;\n organizationId: string;\n definitionId: string;\n revisionId: string;\n // Public base URL of the session service for this session (MCP over HTTP,\n // sandbox endpoints, the broker).\n sessionServiceUrl: string;\n // The region of the session service serving the session and its sandbox\n // bindings, so a harness can run near it; null when unknown.\n sessionServiceRegion?: string | null;\n}\n\n// Lifecycle signals a harness implementation may report about the runtime\n// hosting a session (invocations, metering, traces). Informational: the\n// session service records them (agent.harness_invocations, Tinybird) and never\n// depends on them for correctness.\nexport interface HarnessObserverIface {\n // The runtime accepted the invocation request (its response began).\n invocationAccepted?(event: { invocationRef: string; at: string }): void;\n invocationStarted?(event: {\n invocationRef: string;\n at: string;\n bootMs: number | null;\n // The runtime's deployed version (Workers version id, commit), for rollouts.\n versionId?: string | null;\n commitSha?: string | null;\n }): void;\n invocationKeepalive?(event: { invocationRef: string; at: string; activeWork: number }): void;\n invocationEnded?(event: {\n invocationRef: string;\n at: string;\n reason: string;\n error: string | null;\n metering: Record<string, number>;\n }): void;\n trace?(event: { name: string; at: string; fields: Record<string, JsonValue> }): void;\n}\n\nexport interface OpenHarnessSessionArgsIface {\n session: HarnessSessionContextIface;\n // The session service's id for this harness session (agent.harness_sessions);\n // implementations key their runtime state and route grants by it.\n harnessSessionId: string;\n // Hosting may authorize the child endpoint to fork this source through ACP.\n forkSource?: { ref: HarnessSessionRefIface; acpSessionId: string };\n observer?: HarnessObserverIface;\n // The binding's config, validated against configSchema, dynamic slots resolved.\n config: JsonValue;\n manifest: ResolvedAgentManifestIface;\n // Already materialized ACP MCP server entries: authored tools, connections\n // (Final's MCP server among them), sandbox MCP projections where applicable.\n mcpServers: McpServer[];\n // Declared base capabilities with the target endpoint each is bound to.\n baseTools: Partial<Record<BaseCapability, SandboxTargetEndpointIface>>;\n sandboxes: Record<string, SandboxTargetEndpointIface>;\n credentials: CredentialGrantIface;\n secrets: SecretReaderIface;\n trace: TraceContextIface;\n}\n\nexport interface ResumeHarnessSessionArgsIface extends OpenHarnessSessionArgsIface {\n ref: HarnessSessionRefIface;\n // Last log seq the session service holds from this harness session; the\n // harness replays anything newer after session/resume.\n lastSeq: number;\n}\n\n// Resolved only in memory; refs/manifests retain secret names, never TLS keys.\nexport interface HarnessClientTlsIface {\n cert: string;\n key: string;\n ca?: string;\n}\n\nexport type HarnessEndpointIface =\n | {\n ref: HarnessSessionRefIface;\n transport: AcpTransport.Ws;\n url: string;\n headers: Record<string, string>;\n resolveHeaders?: () => Promise<Record<string, string>>;\n tls?: HarnessClientTlsIface;\n }\n | {\n ref: HarnessSessionRefIface;\n transport: AcpTransport.Http;\n url: string;\n headers: Record<string, string>;\n resolveHeaders?: () => Promise<Record<string, string>>;\n tls?: HarnessClientTlsIface;\n }\n // websocket-gateway relay channel (Final-managed harnesses).\n | { ref: HarnessSessionRefIface; transport: AcpTransport.Relay; channel: string; token: string }\n // Local development, CI and conformance only.\n | {\n ref: HarnessSessionRefIface;\n transport: AcpTransport.Stdio;\n command: string;\n args: string[];\n env: Record<string, string>;\n };\n\nexport interface HarnessHealthIface {\n ok: boolean;\n detail?: string;\n checkedAt: string;\n}\n\n// The binding a description is asked for: its config (validated against the\n// configSchema of the binding-free description) and the definition's secrets.\nexport interface DescribeHarnessArgsIface {\n config: JsonValue;\n secrets: SecretReaderIface;\n}\n\nexport interface HarnessIface {\n // Without a binding: what Build renders before one exists (configSchema,\n // declared capabilities). With one: the description of that binding, which a\n // harness reaching an arbitrary agent derives from the agent itself (e.g. its\n // `initialize`). Every harness implements both; most ignore the binding.\n describe(binding?: DescribeHarnessArgsIface): Promise<HarnessDescriptionIface>;\n open(args: OpenHarnessSessionArgsIface): Promise<HarnessEndpointIface>;\n resume(args: ResumeHarnessSessionArgsIface): Promise<HarnessEndpointIface>;\n park(ref: HarnessSessionRefIface): Promise<void>;\n // Graceful by default: the program's state is durable (resumable) before it\n // stops, bounded by the implementation's timeout, then forced. `force` skips\n // the wait; the session service passes it when the program did not settle\n // ACP `session/close` within its bound.\n close(ref: HarnessSessionRefIface, opts?: CloseHarnessSessionOptsIface): Promise<void>;\n health(\n ref: HarnessSessionRefIface,\n context?: DescribeHarnessArgsIface,\n ): Promise<HarnessHealthIface>;\n}\n\nexport interface CloseHarnessSessionOptsIface {\n force?: boolean;\n // As with health, retained refs can resolve current client TLS without storing keys in the ref.\n context?: DescribeHarnessArgsIface;\n}\n\n// What an installed harness module exports: the implementation plus an\n// authoring helper that builds the manifest binding.\nexport interface HarnessModuleIface<Config> {\n ref: ProviderRef;\n harness: HarnessIface;\n binding: (config: Config) => { harness: ProviderRef; config: JsonValue };\n}\n\n// Custom harnesses in a definition's bundle. Calling the result\n// with a config yields the manifest binding; the implementation is resolved\n// from the bundle by export name.\nexport interface DefinedHarnessBindingIface {\n harness: ProviderRef;\n config: JsonValue;\n definedHarness: true;\n}\n\nexport interface DefinedHarnessIface<Config> extends HarnessIface {\n (config: Config): DefinedHarnessBindingIface;\n}\n\nexport const defineHarness = <Config extends JsonValue = JsonValue>(\n implementation: HarnessIface,\n): DefinedHarnessIface<Config> => {\n // The export name is unknown here; the compiler rewrites `bundle:<pending>`\n // to the module path that exported this harness.\n const binding = (config: Config): DefinedHarnessBindingIface => ({\n harness: bundleRef(PENDING_BUNDLE_EXPORT),\n config,\n definedHarness: true,\n });\n return Object.assign(binding, implementation);\n};\n\nexport const describeConfigSchema = (description: HarnessDescriptionIface): JsonSchema =>\n description.configSchema;\n"],
5
+ "mappings": "AACA,YAAY,OAAO;AACnB,SAAS,iBAAiB,wBAA8C;AACxE,SAAS,oBAAoB,+BAA+B;AAG5D,SAAS,kBAAkB,wBAAwB;AACnD,SAAS,gBAAgB,uBAAwD;AACjF,SAAS,WAAW,yBAA2C;AAC/D,SAAS,yBAAyB,kBAAkB;AAG7C,MAAM,wBAAwB;AAO9B,IAAK,eAAL,kBAAKA,kBAAL;AACL,EAAAA,cAAA,WAAQ;AACR,EA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KAAM,QAAO;AAC1B,SAAO;AAAA,IACL,KAAK,GAAG,KAAK,UAAU,QAAQ,QAAQ,EAAE,CAAC;AAAA,IAC1C,OAAO,MAAM;AAAA,IACb,kBAAkB,KAAK;AAAA,IACvB,WAAW,MAAM;AAAA,EACnB;AACF;AAyLO,MAAM,gBAAgB,CAC3B,mBACgC;AAGhC,QAAM,UAAU,CAAC,YAAgD;AAAA,IAC/D,SAAS,UAAU,qBAAqB;AAAA,IACxC;AAAA,IACA,gBAAgB;AAAA,EAClB;AACA,SAAO,OAAO,OAAO,SAAS,cAAc;AAC9C;AAEO,MAAM,uBAAuB,CAAC,gBACnC,YAAY;",
6
6
  "names": ["AcpTransport", "McpTransportKind", "BaseToolProvision", "SandboxWire", "UserInstructionDelivery", "HarnessTrustClass", "PromptWhileRunning", "CredentialRoute", "routeGrantSchema"]
7
7
  }
@@ -0,0 +1,15 @@
1
+ import * as z from 'zod';
2
+ import { type JsonValue } from "./json.mjs";
3
+ export interface HostedBindingsIface {
4
+ get(name: string): Promise<JsonValue | null>;
5
+ }
6
+ export interface HostedBindingOptionsIface {
7
+ bindings?: HostedBindingsIface;
8
+ name: string;
9
+ }
10
+ export declare const requireHostedBinding: (options: HostedBindingOptionsIface) => Promise<JsonValue>;
11
+ export declare const hostedBindingRequirementSchema: z.ZodObject<{
12
+ name: z.ZodString;
13
+ schema: z.ZodType<import("./json.mjs").JsonObject, unknown, z.core.$ZodTypeInternals<import("./json.mjs").JsonObject, unknown>>;
14
+ }, z.core.$strip>;
15
+ export type HostedBindingRequirementIface = z.infer<typeof hostedBindingRequirementSchema>;
@@ -0,0 +1,21 @@
1
+ import * as z from "zod";
2
+ import { jsonSchemaSchema, jsonValueSchema } from "./json.mjs";
3
+ const requireHostedBinding = async (options) => {
4
+ if (options.name.trim().length === 0) throw new Error("Hosted binding name must not be empty");
5
+ if (options.bindings == null)
6
+ throw new Error(`Hosting does not supply bindings required by ${options.name}`);
7
+ const value = await options.bindings.get(options.name);
8
+ if (value == null) throw new Error(`Hosted binding ${options.name} is not configured`);
9
+ const parsed = jsonValueSchema.safeParse(value);
10
+ if (!parsed.success) throw new Error(`Hosted binding ${options.name} is not JSON configuration`);
11
+ return parsed.data;
12
+ };
13
+ const hostedBindingRequirementSchema = z.object({
14
+ name: z.string().trim().min(1),
15
+ schema: jsonSchemaSchema
16
+ });
17
+ export {
18
+ hostedBindingRequirementSchema,
19
+ requireHostedBinding
20
+ };
21
+ //# sourceMappingURL=hosted-bindings.mjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/hosted-bindings.ts"],
4
+ "sourcesContent": ["import * as z from 'zod';\nimport { jsonSchemaSchema, jsonValueSchema, type JsonValue } from \"./json.mjs\";\n\n// Hosting scopes this reader to the deployment, organization and agent. Values\n// contain configuration and credential references, never resolved credentials.\nexport interface HostedBindingsIface {\n get(name: string): Promise<JsonValue | null>;\n}\n\nexport interface HostedBindingOptionsIface {\n bindings?: HostedBindingsIface;\n name: string;\n}\n\nexport const requireHostedBinding = async (\n options: HostedBindingOptionsIface,\n): Promise<JsonValue> => {\n if (options.name.trim().length === 0) throw new Error('Hosted binding name must not be empty');\n if (options.bindings == null)\n throw new Error(`Hosting does not supply bindings required by ${options.name}`);\n const value = await options.bindings.get(options.name);\n if (value == null) throw new Error(`Hosted binding ${options.name} is not configured`);\n const parsed = jsonValueSchema.safeParse(value);\n if (!parsed.success) throw new Error(`Hosted binding ${options.name} is not JSON configuration`);\n return parsed.data;\n};\n\nexport const hostedBindingRequirementSchema = z.object({\n name: z.string().trim().min(1),\n schema: jsonSchemaSchema,\n});\n\nexport type HostedBindingRequirementIface = z.infer<typeof hostedBindingRequirementSchema>;\n"],
5
+ "mappings": "AAAA,YAAY,OAAO;AACnB,SAAS,kBAAkB,uBAAuC;AAa3D,MAAM,uBAAuB,OAClC,YACuB;AACvB,MAAI,QAAQ,KAAK,KAAK,EAAE,WAAW,EAAG,OAAM,IAAI,MAAM,uCAAuC;AAC7F,MAAI,QAAQ,YAAY;AACtB,UAAM,IAAI,MAAM,gDAAgD,QAAQ,IAAI,EAAE;AAChF,QAAM,QAAQ,MAAM,QAAQ,SAAS,IAAI,QAAQ,IAAI;AACrD,MAAI,SAAS,KAAM,OAAM,IAAI,MAAM,kBAAkB,QAAQ,IAAI,oBAAoB;AACrF,QAAM,SAAS,gBAAgB,UAAU,KAAK;AAC9C,MAAI,CAAC,OAAO,QAAS,OAAM,IAAI,MAAM,kBAAkB,QAAQ,IAAI,4BAA4B;AAC/F,SAAO,OAAO;AAChB;AAEO,MAAM,iCAAiC,EAAE,OAAO;AAAA,EACrD,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC;AAAA,EAC7B,QAAQ;AACV,CAAC;",
6
+ "names": []
7
+ }
@@ -3,6 +3,7 @@ export * from "./channel.mjs";
3
3
  export * from "./credentials.mjs";
4
4
  export * from "./dynamic.mjs";
5
5
  export * from "./harness.mjs";
6
+ export * from "./hosted-bindings.mjs";
6
7
  export * from "./json.mjs";
7
8
  export * from "./manifest.mjs";
8
9
  export * from "./provider-ref.mjs";
@@ -10,6 +10,7 @@ export * from "./channel.mjs";
10
10
  export * from "./credentials.mjs";
11
11
  export * from "./dynamic.mjs";
12
12
  export * from "./harness.mjs";
13
+ export * from "./hosted-bindings.mjs";
13
14
  export * from "./json.mjs";
14
15
  export * from "./manifest.mjs";
15
16
  export * from "./provider-ref.mjs";
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/index.ts"],
4
- "sourcesContent": ["export {\n ProcessInspectionOperation,\n inspectedProcessSchema,\n processInspectionDetailSchema,\n processInspectionPageSchema,\n processInspectionRequestSchema,\n processInspectionResultSchema,\n type InspectedProcessIface,\n type ProcessInspectionDetailIface,\n type ProcessInspectionPageIface,\n type ProcessInspectionRequestIface,\n type ProcessInspectionResultIface,\n} from '@finalai/agent-protocol/process-inspection';\nexport * from \"./channel.mjs\";\nexport * from \"./credentials.mjs\";\nexport * from \"./dynamic.mjs\";\nexport * from \"./harness.mjs\";\nexport * from \"./json.mjs\";\nexport * from \"./manifest.mjs\";\nexport * from \"./provider-ref.mjs\";\nexport * from \"./sandbox/open-scope.mjs\";\nexport * from \"./sandbox/types.mjs\";\nexport * from \"./schemas.mjs\";\n\nexport * from \"./channel-context.mjs\";\n\nexport * from \"./semantic-events.mjs\";\n\nexport * from \"./sandbox/snapshots.mjs\";\n\nexport {\n SandboxEditorOperation,\n sandboxEditorRequestSchema,\n sandboxEditorResultSchema,\n sandboxEditorSessionSchema,\n type SandboxEditorRequestIface,\n type SandboxEditorResultIface,\n type SandboxEditorSessionIface,\n} from \"./sandbox/editor.mjs\";\n"],
5
- "mappings": "AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAMK;AACP,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AAEd,cAAc;AAEd,cAAc;AAEd,cAAc;AAEd;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIK;",
4
+ "sourcesContent": ["export {\n ProcessInspectionOperation,\n inspectedProcessSchema,\n processInspectionDetailSchema,\n processInspectionPageSchema,\n processInspectionRequestSchema,\n processInspectionResultSchema,\n type InspectedProcessIface,\n type ProcessInspectionDetailIface,\n type ProcessInspectionPageIface,\n type ProcessInspectionRequestIface,\n type ProcessInspectionResultIface,\n} from '@finalai/agent-protocol/process-inspection';\nexport * from \"./channel.mjs\";\nexport * from \"./credentials.mjs\";\nexport * from \"./dynamic.mjs\";\nexport * from \"./harness.mjs\";\nexport * from \"./hosted-bindings.mjs\";\nexport * from \"./json.mjs\";\nexport * from \"./manifest.mjs\";\nexport * from \"./provider-ref.mjs\";\nexport * from \"./sandbox/open-scope.mjs\";\nexport * from \"./sandbox/types.mjs\";\nexport * from \"./schemas.mjs\";\n\nexport * from \"./channel-context.mjs\";\n\nexport * from \"./semantic-events.mjs\";\n\nexport * from \"./sandbox/snapshots.mjs\";\n\nexport {\n SandboxEditorOperation,\n sandboxEditorRequestSchema,\n sandboxEditorResultSchema,\n sandboxEditorSessionSchema,\n type SandboxEditorRequestIface,\n type SandboxEditorResultIface,\n type SandboxEditorSessionIface,\n} from \"./sandbox/editor.mjs\";\n"],
5
+ "mappings": "AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAMK;AACP,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AAEd,cAAc;AAEd,cAAc;AAEd,cAAc;AAEd;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIK;",
6
6
  "names": []
7
7
  }
@@ -1,6 +1,6 @@
1
1
  import * as z from 'zod';
2
2
  import { DynamicEvent } from "./dynamic.mjs";
3
- export declare const MANIFEST_VERSION = 2;
3
+ export declare const MANIFEST_VERSION = 3;
4
4
  export declare enum BaseCapability {
5
5
  Shell = "shell",
6
6
  Files = "files",
@@ -186,6 +186,10 @@ export declare const sandboxBindingSchema: z.ZodObject<{
186
186
  events: z.ZodArray<z.ZodEnum<typeof DynamicEvent>>;
187
187
  description: z.ZodOptional<z.ZodString>;
188
188
  preview: z.ZodOptional<z.ZodString>;
189
+ requiredBindings: z.ZodOptional<z.ZodArray<z.ZodObject<{
190
+ name: z.ZodString;
191
+ schema: z.ZodType<import("./json.mjs").JsonObject, unknown, z.core.$ZodTypeInternals<import("./json.mjs").JsonObject, unknown>>;
192
+ }, z.core.$strip>>>;
189
193
  }, z.core.$strip>;
190
194
  }, z.core.$strip>, z.ZodType<import("./json.mjs").JsonValue, unknown, z.core.$ZodTypeInternals<import("./json.mjs").JsonValue, unknown>>]>;
191
195
  access: z.ZodDefault<z.ZodEnum<typeof SandboxAccess>>;
@@ -243,11 +247,15 @@ export declare const harnessBindingSchema: z.ZodObject<{
243
247
  events: z.ZodArray<z.ZodEnum<typeof DynamicEvent>>;
244
248
  description: z.ZodOptional<z.ZodString>;
245
249
  preview: z.ZodOptional<z.ZodString>;
250
+ requiredBindings: z.ZodOptional<z.ZodArray<z.ZodObject<{
251
+ name: z.ZodString;
252
+ schema: z.ZodType<import("./json.mjs").JsonObject, unknown, z.core.$ZodTypeInternals<import("./json.mjs").JsonObject, unknown>>;
253
+ }, z.core.$strip>>>;
246
254
  }, z.core.$strip>;
247
255
  }, z.core.$strip>, z.ZodType<import("./json.mjs").JsonValue, unknown, z.core.$ZodTypeInternals<import("./json.mjs").JsonValue, unknown>>]>;
248
256
  }, z.core.$strip>;
249
257
  export declare const agentManifestSchema: z.ZodObject<{
250
- version: z.ZodLiteral<2>;
258
+ version: z.ZodUnion<readonly [z.ZodLiteral<2>, z.ZodLiteral<3>]>;
251
259
  identity: z.ZodObject<{
252
260
  name: z.ZodString;
253
261
  description: z.ZodNullable<z.ZodString>;
@@ -267,6 +275,10 @@ export declare const agentManifestSchema: z.ZodObject<{
267
275
  events: z.ZodArray<z.ZodEnum<typeof DynamicEvent>>;
268
276
  description: z.ZodOptional<z.ZodString>;
269
277
  preview: z.ZodOptional<z.ZodString>;
278
+ requiredBindings: z.ZodOptional<z.ZodArray<z.ZodObject<{
279
+ name: z.ZodString;
280
+ schema: z.ZodType<import("./json.mjs").JsonObject, unknown, z.core.$ZodTypeInternals<import("./json.mjs").JsonObject, unknown>>;
281
+ }, z.core.$strip>>>;
270
282
  }, z.core.$strip>;
271
283
  }, z.core.$strip>, z.ZodType<import("./json.mjs").JsonValue, unknown, z.core.$ZodTypeInternals<import("./json.mjs").JsonValue, unknown>>]>;
272
284
  }, z.core.$strip>;
@@ -276,6 +288,10 @@ export declare const agentManifestSchema: z.ZodObject<{
276
288
  events: z.ZodArray<z.ZodEnum<typeof DynamicEvent>>;
277
289
  description: z.ZodOptional<z.ZodString>;
278
290
  preview: z.ZodOptional<z.ZodString>;
291
+ requiredBindings: z.ZodOptional<z.ZodArray<z.ZodObject<{
292
+ name: z.ZodString;
293
+ schema: z.ZodType<import("./json.mjs").JsonObject, unknown, z.core.$ZodTypeInternals<import("./json.mjs").JsonObject, unknown>>;
294
+ }, z.core.$strip>>>;
279
295
  }, z.core.$strip>;
280
296
  }, z.core.$strip>, z.ZodArray<z.ZodDiscriminatedUnion<[z.ZodObject<{
281
297
  key: z.ZodString;
@@ -329,6 +345,10 @@ export declare const agentManifestSchema: z.ZodObject<{
329
345
  events: z.ZodArray<z.ZodEnum<typeof DynamicEvent>>;
330
346
  description: z.ZodOptional<z.ZodString>;
331
347
  preview: z.ZodOptional<z.ZodString>;
348
+ requiredBindings: z.ZodOptional<z.ZodArray<z.ZodObject<{
349
+ name: z.ZodString;
350
+ schema: z.ZodType<import("./json.mjs").JsonObject, unknown, z.core.$ZodTypeInternals<import("./json.mjs").JsonObject, unknown>>;
351
+ }, z.core.$strip>>>;
332
352
  }, z.core.$strip>;
333
353
  }, z.core.$strip>, z.ZodRecord<z.ZodString, z.ZodObject<{
334
354
  provider: z.ZodDiscriminatedUnion<[z.ZodObject<{
@@ -344,6 +364,10 @@ export declare const agentManifestSchema: z.ZodObject<{
344
364
  events: z.ZodArray<z.ZodEnum<typeof DynamicEvent>>;
345
365
  description: z.ZodOptional<z.ZodString>;
346
366
  preview: z.ZodOptional<z.ZodString>;
367
+ requiredBindings: z.ZodOptional<z.ZodArray<z.ZodObject<{
368
+ name: z.ZodString;
369
+ schema: z.ZodType<import("./json.mjs").JsonObject, unknown, z.core.$ZodTypeInternals<import("./json.mjs").JsonObject, unknown>>;
370
+ }, z.core.$strip>>>;
347
371
  }, z.core.$strip>;
348
372
  }, z.core.$strip>, z.ZodType<import("./json.mjs").JsonValue, unknown, z.core.$ZodTypeInternals<import("./json.mjs").JsonValue, unknown>>]>;
349
373
  access: z.ZodDefault<z.ZodEnum<typeof SandboxAccess>>;
@@ -396,7 +420,7 @@ export declare const agentManifestSchema: z.ZodObject<{
396
420
  }, z.core.$strip>>;
397
421
  }, z.core.$strip>;
398
422
  export declare const resolvedAgentManifestSchema: z.ZodObject<{
399
- version: z.ZodLiteral<2>;
423
+ version: z.ZodUnion<readonly [z.ZodLiteral<2>, z.ZodLiteral<3>]>;
400
424
  identity: z.ZodObject<{
401
425
  name: z.ZodString;
402
426
  description: z.ZodNullable<z.ZodString>;
@@ -2,7 +2,7 @@ import * as z from "zod";
2
2
  import { containsDynamicSlot, DynamicEvent, maybeDynamic } from "./dynamic.mjs";
3
3
  import { jsonObjectSchema, jsonSchemaSchema, jsonValueSchema } from "./json.mjs";
4
4
  import { packageRef, providerRefSchema } from "./provider-ref.mjs";
5
- const MANIFEST_VERSION = 2;
5
+ const MANIFEST_VERSION = 3;
6
6
  var BaseCapability = /* @__PURE__ */ ((BaseCapability2) => {
7
7
  BaseCapability2["Shell"] = "shell";
8
8
  BaseCapability2["Files"] = "files";
@@ -166,7 +166,8 @@ const harnessBindingSchema = z.object({
166
166
  config: maybeDynamic(jsonValueSchema)
167
167
  });
168
168
  const agentManifestSchema = z.object({
169
- version: z.literal(MANIFEST_VERSION),
169
+ // Read persisted v2 revisions; v3 writers require hosts enforcing hosted bindings.
170
+ version: z.union([z.literal(2), z.literal(MANIFEST_VERSION)]),
170
171
  identity: identitySchema,
171
172
  harness: harnessBindingSchema,
172
173
  mcpServers: maybeDynamic(z.array(mcpServerBindingSchema)),
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/manifest.ts"],
4
- "sourcesContent": ["import * as z from 'zod';\nimport { containsDynamicSlot, DynamicEvent, maybeDynamic } from \"./dynamic.mjs\";\nimport { jsonObjectSchema, jsonSchemaSchema, jsonValueSchema } from \"./json.mjs\";\nimport { packageRef, providerRefSchema } from \"./provider-ref.mjs\";\n\n// The Agent Manifest. It lives in the provider contract\n// package because it is what harnesses, sandboxes and channels receive;\n// @finalai/agent-definition compiles directories into it and re-exports it.\n//\n// A harness owns its loop, native tools, prompt assembly, models, permission\n// modes, memory and compaction: all of that is `harness.config`, typed by the\n// harness's own configSchema. What ACP standardizes (MCP servers, prompts,\n// permissions, cancellation) is session input, identical for every harness.\n\nexport const MANIFEST_VERSION = 2;\n\n// Base tool capability classes, one to one with sandbox handle capabilities.\nexport enum BaseCapability {\n Shell = 'shell',\n Files = 'files',\n Process = 'process',\n Ports = 'ports',\n Browser = 'browser',\n ComputerUse = 'computerUse',\n}\n\nexport enum ToolApproval {\n Allow = 'allow',\n Ask = 'ask',\n}\n\n// What a session may do on a sandbox target: read files; also run\n// processes (execute, without file writes); or everything (write).\nexport enum SandboxAccess {\n Read = 'read',\n Execute = 'execute',\n Write = 'write',\n}\n\nconst SANDBOX_ACCESS_RANK = {\n [SandboxAccess.Read]: 0,\n [SandboxAccess.Execute]: 1,\n [SandboxAccess.Write]: 2,\n} satisfies Record<SandboxAccess, number>;\n\n// Each access includes the ones before it: read < execute < write.\nexport const sandboxAccessAtLeast = (access: SandboxAccess, floor: SandboxAccess): boolean =>\n SANDBOX_ACCESS_RANK[access] >= SANDBOX_ACCESS_RANK[floor];\n\nexport const narrowerSandboxAccess = (a: SandboxAccess, b: SandboxAccess): SandboxAccess =>\n SANDBOX_ACCESS_RANK[a] <= SANDBOX_ACCESS_RANK[b] ? a : b;\n\nexport enum SandboxAttach {\n Lazy = 'lazy',\n OnPrompt = 'on-prompt',\n}\n\nexport enum McpServerBindingKind {\n // Authored tools, served from the agent's Worker isolate behind the MCP host.\n Worker = 'worker',\n Http = 'http',\n}\n\nexport enum ScheduleTarget {\n OwnerDirect = 'owner-direct',\n BoundConversation = 'bound-conversation',\n}\n\n// Whether a schedule's firing must get a visible reply. Values match the schedules API.\nexport enum ScheduleDelivery {\n Always = 'always',\n // The agent replies only when there is something to say; an empty turn posts nothing.\n IfNeeded = 'if_needed',\n}\n\nexport const identitySchema = z.object({\n name: z.string().min(1).max(120),\n description: z.string().max(2000).nullable(),\n avatarUrl: z.string().url().nullable(),\n});\n\nexport enum InputApprovalKind {\n Tool = 'tool',\n Connection = 'connection',\n}\n\nexport const inputApprovalSchema = z.object({\n kind: z.nativeEnum(InputApprovalKind),\n export: z.string().min(1),\n // Connection default when absent; otherwise tools.approval[policyKey].\n policyKey: z.string().min(1).optional(),\n dynamic: jsonObjectSchema.optional(),\n});\nexport type InputApprovalIface = z.infer<typeof inputApprovalSchema>;\n\n// Tool descriptors are stored statically so `tools/list` never needs the isolate.\nexport const toolDescriptorSchema = z.object({\n name: z.string().min(1),\n description: z.string(),\n inputSchema: jsonSchemaSchema,\n outputSchema: jsonSchemaSchema.optional(),\n annotations: z\n .object({\n title: z.string().optional(),\n readOnlyHint: z.boolean().optional(),\n destructiveHint: z.boolean().optional(),\n idempotentHint: z.boolean().optional(),\n openWorldHint: z.boolean().optional(),\n })\n .optional(),\n // Bundle export implementing it ('tools/lookup_release_notes').\n export: z.string().min(1).optional(),\n // Boundary snapshot used to reconstruct dynamic tools after isolate eviction.\n dynamic: jsonObjectSchema.optional(),\n inputApproval: inputApprovalSchema.optional(),\n});\n\nexport const mcpAuthSchema = z.union([\n z.object({ secretKey: z.string().min(1), headerName: z.string().min(1).nullable() }),\n // Resolved by the broker to a session-scoped grant (Final's own MCP server).\n z.object({ kind: z.literal('final-session') }),\n]);\n\nconst toolApprovalsSchema = z.record(z.string(), z.nativeEnum(ToolApproval)).nullable();\n\nexport const workerMcpServerBindingSchema = z.object({\n key: z.string().min(1),\n kind: z.literal(McpServerBindingKind.Worker),\n tools: z.array(toolDescriptorSchema),\n approvals: toolApprovalsSchema,\n});\n\nexport const httpMcpServerBindingSchema = z.object({\n key: z.string().min(1),\n kind: z.literal(McpServerBindingKind.Http),\n url: z.string().url(),\n auth: mcpAuthSchema.nullable(),\n headers: z.record(z.string(), z.string()).default({}),\n // Null allows every tool the server lists, each with the default approval.\n approvals: toolApprovalsSchema,\n // Tools hidden even when `approvals` would expose them.\n deny: z.array(z.string().min(1)).optional(),\n // The authored resolver that produced this connection, for retained boundary values.\n dynamicResolver: z.string().min(1).optional(),\n inputApprovals: z.record(z.string(), inputApprovalSchema).optional(),\n});\n\nexport const mcpServerBindingSchema = z.discriminatedUnion('kind', [\n workerMcpServerBindingSchema,\n httpMcpServerBindingSchema,\n]);\n\nexport const sandboxBindingSchema = z.object({\n provider: providerRefSchema,\n // Provider-defined environment options (`computer`: a setup guide reference or\n // inline guide plus start-time parameters). Validated by the provider.\n environment: maybeDynamic(jsonValueSchema),\n access: z.nativeEnum(SandboxAccess).default(SandboxAccess.Write),\n attach: z.nativeEnum(SandboxAttach).default(SandboxAttach.Lazy),\n});\n\nexport const baseToolsSchema = z.object({\n base: z.partialRecord(z.nativeEnum(BaseCapability), z.object({ target: z.string().min(1) })),\n // Capabilities declared on the harness's own host with no sandbox target\n // (`baseTools({ shell: harnessHost })`): only a harness that\n // provides them natively (host-disableable, host-fixed) can serve them.\n host: z.array(z.nativeEnum(BaseCapability)).optional(),\n});\n\nexport const channelBindingSchema = z.object({\n // Stable within the definition; publish maps it to a binding id.\n key: z.string().min(1),\n channel: providerRefSchema,\n config: jsonObjectSchema.default({}),\n source: z.string().optional(),\n});\n\nexport const hookBindingSchema = z.object({\n slug: z.string().min(1),\n export: z.string().min(1),\n events: z.array(z.string().min(1)).min(1),\n});\n\nexport const scheduleDefinitionSchema = z.object({\n key: z.string().min(1),\n cron: z.string().min(1),\n timezone: z.string().min(1),\n prompt: z.string().min(1),\n target: z.nativeEnum(ScheduleTarget),\n});\n\nexport const bundleSchema = z.object({\n // Absent on historical revisions: the host must inspect their resources.\n hasPreparationFiles: z.boolean().optional(),\n hash: z.string().min(1),\n // Dynamic slot path \u2192 resolver export and events.\n resolvers: z.record(\n z.string(),\n z.object({ export: z.string().min(1), events: z.array(z.nativeEnum(DynamicEvent)).min(1) }),\n ),\n});\n\nexport const harnessBindingSchema = z.object({\n harness: providerRefSchema,\n // Validated against the harness's configSchema; may contain dynamic slots at\n // any depth (an instruction fragment, the model).\n config: maybeDynamic(jsonValueSchema),\n});\n\nexport const agentManifestSchema = z.object({\n version: z.literal(MANIFEST_VERSION),\n identity: identitySchema,\n harness: harnessBindingSchema,\n mcpServers: maybeDynamic(z.array(mcpServerBindingSchema)),\n sandboxes: maybeDynamic(z.record(z.string(), sandboxBindingSchema)),\n tools: baseToolsSchema,\n toolPolicy: z.record(z.string(), z.nativeEnum(ToolApproval)),\n // Organization secrets this agent may read, by name (`secrets.get`,\n // MCP `secretKey`, `apiKey({ secret })`). Nothing else is readable;\n // binding organization secrets requires an organization admin at publish.\n secrets: z.array(z.string().min(1)).default([]),\n channels: z.array(channelBindingSchema),\n channelSources: z\n .record(z.string(), z.object({ path: z.string(), source: z.string(), disabled: z.boolean() }))\n .optional(),\n hooks: z.array(hookBindingSchema),\n schedules: z.array(scheduleDefinitionSchema),\n bundle: bundleSchema.nullable(),\n});\n\n// What one session actually got: every dynamic slot replaced by its resolved\n// value (stored in agent.session_manifests).\nexport const resolvedAgentManifestSchema = agentManifestSchema\n .extend({\n harness: z.object({ harness: providerRefSchema, config: jsonValueSchema }),\n mcpServers: z.array(mcpServerBindingSchema),\n sandboxes: z.record(z.string(), sandboxBindingSchema.extend({ environment: jsonValueSchema })),\n })\n .superRefine((manifest, ctx) => {\n if (containsDynamicSlot(manifest)) {\n ctx.addIssue({\n code: 'custom',\n message: 'a resolved manifest must not contain dynamic slots',\n });\n }\n });\n\nexport type IdentityIface = z.infer<typeof identitySchema>;\nexport type ToolDescriptorIface = z.infer<typeof toolDescriptorSchema>;\nexport type McpAuth = z.infer<typeof mcpAuthSchema>;\nexport type WorkerMcpServerBindingIface = z.infer<typeof workerMcpServerBindingSchema>;\nexport type HttpMcpServerBindingIface = z.infer<typeof httpMcpServerBindingSchema>;\nexport type McpServerBinding = z.infer<typeof mcpServerBindingSchema>;\nexport type SandboxBindingIface = z.infer<typeof sandboxBindingSchema>;\nexport type BaseToolsIface = z.infer<typeof baseToolsSchema>;\nexport type ChannelBindingIface = z.infer<typeof channelBindingSchema>;\nexport type HookBindingIface = z.infer<typeof hookBindingSchema>;\nexport type ScheduleDefinitionIface = z.infer<typeof scheduleDefinitionSchema>;\nexport type BundleIface = z.infer<typeof bundleSchema>;\nexport type HarnessBindingIface = z.infer<typeof harnessBindingSchema>;\nexport type AgentManifestIface = z.infer<typeof agentManifestSchema>;\nexport type ResolvedAgentManifestIface = z.infer<typeof resolvedAgentManifestSchema>;\nexport type ResolvedSandboxBindingIface = ResolvedAgentManifestIface['sandboxes'][string];\n\n// The fields of a harness config the platform itself reads through the shared\n// schema fragments; everything else is opaque to the platform.\nexport enum InstructionRole {\n System = 'system',\n User = 'user',\n}\n\nexport const instructionFragmentSchema = z.object({\n role: z.nativeEnum(InstructionRole),\n content: z.string(),\n // Source file, for the compatibility report and Build.\n source: z.string().optional(),\n});\n\nexport const skillFileSchema = z.object({ path: z.string().min(1), content: z.string() });\nexport const skillBundleSchema = z.object({\n key: z.string().min(1),\n description: z.string().optional(),\n files: z.array(skillFileSchema),\n});\n\nexport type InstructionFragmentIface = z.infer<typeof instructionFragmentSchema>;\nexport type SkillBundleIface = z.infer<typeof skillBundleSchema>;\n\nexport const emptyManifest = (name: string): AgentManifestIface => ({\n version: MANIFEST_VERSION,\n identity: { name, description: null, avatarUrl: null },\n harness: {\n harness: packageRef('@finalai/final-agent-provider/harnesses/serverless-final'),\n config: {},\n },\n mcpServers: [],\n sandboxes: {},\n tools: { base: {} },\n toolPolicy: {},\n secrets: [],\n channels: [],\n hooks: [],\n schedules: [],\n bundle: null,\n});\n"],
5
- "mappings": "AAAA,YAAY,OAAO;AACnB,SAAS,qBAAqB,cAAc,oBAAoB;AAChE,SAAS,kBAAkB,kBAAkB,uBAAuB;AACpE,SAAS,YAAY,yBAAyB;AAWvC,MAAM,mBAAmB;AAGzB,IAAK,iBAAL,kBAAKA,oBAAL;AACL,EAAAA,gBAAA,WAAQ;AACR,EAAAA,gBAAA,WAAQ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AI,SAAS;AAAA,MACX,MAAM;AAAA,MACN,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AACF,CAAC;AAqBI,IAAK,kBAAL,kBAAKC,qBAAL;AACL,EAAAA,iBAAA,YAAS;AACT,EAAAA,iBAAA,UAAO;AAFG,SAAAA;AAAA,GAAA;AAKL,MAAM,4BAA4B,EAAE,OAAO;AAAA,EAChD,MAAM,EAAE,WAAW,eAAe;AAAA,EAClC,SAAS,EAAE,OAAO;AAAA;AAAA,EAElB,QAAQ,EAAE,OAAO,EAAE,SAAS;AAC9B,CAAC;AAEM,MAAM,kBAAkB,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,GAAG,SAAS,EAAE,OAAO,EAAE,CAAC;AACjF,MAAM,oBAAoB,EAAE,OAAO;AAAA,EACxC,KAAK,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACrB,aAAa,EAAE,OAAO,EAAE,SAAS;AAAA,EACjC,OAAO,EAAE,MAAM,eAAe;AAChC,CAAC;AAKM,MAAM,gBAAgB,CAAC,UAAsC;AAAA,EAClE,SAAS;AAAA,EACT,UAAU,EAAE,MAAM,aAAa,MAAM,WAAW,KAAK;AAAA,EACrD,SAAS;AAAA,IACP,SAAS,WAAW,0DAA0D;AAAA,IAC9E,QAAQ,CAAC;AAAA,EACX;AAAA,EACA,YAAY,CAAC;AAAA,EACb,WAAW,CAAC;AAAA,EACZ,OAAO,EAAE,MAAM,CAAC,EAAE;AAAA,EAClB,YAAY,CAAC;AAAA,EACb,SAAS,CAAC;AAAA,EACV,UAAU,CAAC;AAAA,EACX,OAAO,CAAC;AAAA,EACR,WAAW,CAAC;AAAA,EACZ,QAAQ;AACV;",
4
+ "sourcesContent": ["import * as z from 'zod';\nimport { containsDynamicSlot, DynamicEvent, maybeDynamic } from \"./dynamic.mjs\";\nimport { jsonObjectSchema, jsonSchemaSchema, jsonValueSchema } from \"./json.mjs\";\nimport { packageRef, providerRefSchema } from \"./provider-ref.mjs\";\n\n// The Agent Manifest. It lives in the provider contract\n// package because it is what harnesses, sandboxes and channels receive;\n// @finalai/agent-definition compiles directories into it and re-exports it.\n//\n// A harness owns its loop, native tools, prompt assembly, models, permission\n// modes, memory and compaction: all of that is `harness.config`, typed by the\n// harness's own configSchema. What ACP standardizes (MCP servers, prompts,\n// permissions, cancellation) is session input, identical for every harness.\n\nexport const MANIFEST_VERSION = 3;\n\n// Base tool capability classes, one to one with sandbox handle capabilities.\nexport enum BaseCapability {\n Shell = 'shell',\n Files = 'files',\n Process = 'process',\n Ports = 'ports',\n Browser = 'browser',\n ComputerUse = 'computerUse',\n}\n\nexport enum ToolApproval {\n Allow = 'allow',\n Ask = 'ask',\n}\n\n// What a session may do on a sandbox target: read files; also run\n// processes (execute, without file writes); or everything (write).\nexport enum SandboxAccess {\n Read = 'read',\n Execute = 'execute',\n Write = 'write',\n}\n\nconst SANDBOX_ACCESS_RANK = {\n [SandboxAccess.Read]: 0,\n [SandboxAccess.Execute]: 1,\n [SandboxAccess.Write]: 2,\n} satisfies Record<SandboxAccess, number>;\n\n// Each access includes the ones before it: read < execute < write.\nexport const sandboxAccessAtLeast = (access: SandboxAccess, floor: SandboxAccess): boolean =>\n SANDBOX_ACCESS_RANK[access] >= SANDBOX_ACCESS_RANK[floor];\n\nexport const narrowerSandboxAccess = (a: SandboxAccess, b: SandboxAccess): SandboxAccess =>\n SANDBOX_ACCESS_RANK[a] <= SANDBOX_ACCESS_RANK[b] ? a : b;\n\nexport enum SandboxAttach {\n Lazy = 'lazy',\n OnPrompt = 'on-prompt',\n}\n\nexport enum McpServerBindingKind {\n // Authored tools, served from the agent's Worker isolate behind the MCP host.\n Worker = 'worker',\n Http = 'http',\n}\n\nexport enum ScheduleTarget {\n OwnerDirect = 'owner-direct',\n BoundConversation = 'bound-conversation',\n}\n\n// Whether a schedule's firing must get a visible reply. Values match the schedules API.\nexport enum ScheduleDelivery {\n Always = 'always',\n // The agent replies only when there is something to say; an empty turn posts nothing.\n IfNeeded = 'if_needed',\n}\n\nexport const identitySchema = z.object({\n name: z.string().min(1).max(120),\n description: z.string().max(2000).nullable(),\n avatarUrl: z.string().url().nullable(),\n});\n\nexport enum InputApprovalKind {\n Tool = 'tool',\n Connection = 'connection',\n}\n\nexport const inputApprovalSchema = z.object({\n kind: z.nativeEnum(InputApprovalKind),\n export: z.string().min(1),\n // Connection default when absent; otherwise tools.approval[policyKey].\n policyKey: z.string().min(1).optional(),\n dynamic: jsonObjectSchema.optional(),\n});\nexport type InputApprovalIface = z.infer<typeof inputApprovalSchema>;\n\n// Tool descriptors are stored statically so `tools/list` never needs the isolate.\nexport const toolDescriptorSchema = z.object({\n name: z.string().min(1),\n description: z.string(),\n inputSchema: jsonSchemaSchema,\n outputSchema: jsonSchemaSchema.optional(),\n annotations: z\n .object({\n title: z.string().optional(),\n readOnlyHint: z.boolean().optional(),\n destructiveHint: z.boolean().optional(),\n idempotentHint: z.boolean().optional(),\n openWorldHint: z.boolean().optional(),\n })\n .optional(),\n // Bundle export implementing it ('tools/lookup_release_notes').\n export: z.string().min(1).optional(),\n // Boundary snapshot used to reconstruct dynamic tools after isolate eviction.\n dynamic: jsonObjectSchema.optional(),\n inputApproval: inputApprovalSchema.optional(),\n});\n\nexport const mcpAuthSchema = z.union([\n z.object({ secretKey: z.string().min(1), headerName: z.string().min(1).nullable() }),\n // Resolved by the broker to a session-scoped grant (Final's own MCP server).\n z.object({ kind: z.literal('final-session') }),\n]);\n\nconst toolApprovalsSchema = z.record(z.string(), z.nativeEnum(ToolApproval)).nullable();\n\nexport const workerMcpServerBindingSchema = z.object({\n key: z.string().min(1),\n kind: z.literal(McpServerBindingKind.Worker),\n tools: z.array(toolDescriptorSchema),\n approvals: toolApprovalsSchema,\n});\n\nexport const httpMcpServerBindingSchema = z.object({\n key: z.string().min(1),\n kind: z.literal(McpServerBindingKind.Http),\n url: z.string().url(),\n auth: mcpAuthSchema.nullable(),\n headers: z.record(z.string(), z.string()).default({}),\n // Null allows every tool the server lists, each with the default approval.\n approvals: toolApprovalsSchema,\n // Tools hidden even when `approvals` would expose them.\n deny: z.array(z.string().min(1)).optional(),\n // The authored resolver that produced this connection, for retained boundary values.\n dynamicResolver: z.string().min(1).optional(),\n inputApprovals: z.record(z.string(), inputApprovalSchema).optional(),\n});\n\nexport const mcpServerBindingSchema = z.discriminatedUnion('kind', [\n workerMcpServerBindingSchema,\n httpMcpServerBindingSchema,\n]);\n\nexport const sandboxBindingSchema = z.object({\n provider: providerRefSchema,\n // Provider-defined environment options (`computer`: a setup guide reference or\n // inline guide plus start-time parameters). Validated by the provider.\n environment: maybeDynamic(jsonValueSchema),\n access: z.nativeEnum(SandboxAccess).default(SandboxAccess.Write),\n attach: z.nativeEnum(SandboxAttach).default(SandboxAttach.Lazy),\n});\n\nexport const baseToolsSchema = z.object({\n base: z.partialRecord(z.nativeEnum(BaseCapability), z.object({ target: z.string().min(1) })),\n // Capabilities declared on the harness's own host with no sandbox target\n // (`baseTools({ shell: harnessHost })`): only a harness that\n // provides them natively (host-disableable, host-fixed) can serve them.\n host: z.array(z.nativeEnum(BaseCapability)).optional(),\n});\n\nexport const channelBindingSchema = z.object({\n // Stable within the definition; publish maps it to a binding id.\n key: z.string().min(1),\n channel: providerRefSchema,\n config: jsonObjectSchema.default({}),\n source: z.string().optional(),\n});\n\nexport const hookBindingSchema = z.object({\n slug: z.string().min(1),\n export: z.string().min(1),\n events: z.array(z.string().min(1)).min(1),\n});\n\nexport const scheduleDefinitionSchema = z.object({\n key: z.string().min(1),\n cron: z.string().min(1),\n timezone: z.string().min(1),\n prompt: z.string().min(1),\n target: z.nativeEnum(ScheduleTarget),\n});\n\nexport const bundleSchema = z.object({\n // Absent on historical revisions: the host must inspect their resources.\n hasPreparationFiles: z.boolean().optional(),\n hash: z.string().min(1),\n // Dynamic slot path \u2192 resolver export and events.\n resolvers: z.record(\n z.string(),\n z.object({ export: z.string().min(1), events: z.array(z.nativeEnum(DynamicEvent)).min(1) }),\n ),\n});\n\nexport const harnessBindingSchema = z.object({\n harness: providerRefSchema,\n // Validated against the harness's configSchema; may contain dynamic slots at\n // any depth (an instruction fragment, the model).\n config: maybeDynamic(jsonValueSchema),\n});\n\nexport const agentManifestSchema = z.object({\n // Read persisted v2 revisions; v3 writers require hosts enforcing hosted bindings.\n version: z.union([z.literal(2), z.literal(MANIFEST_VERSION)]),\n identity: identitySchema,\n harness: harnessBindingSchema,\n mcpServers: maybeDynamic(z.array(mcpServerBindingSchema)),\n sandboxes: maybeDynamic(z.record(z.string(), sandboxBindingSchema)),\n tools: baseToolsSchema,\n toolPolicy: z.record(z.string(), z.nativeEnum(ToolApproval)),\n // Organization secrets this agent may read, by name (`secrets.get`,\n // MCP `secretKey`, `apiKey({ secret })`). Nothing else is readable;\n // binding organization secrets requires an organization admin at publish.\n secrets: z.array(z.string().min(1)).default([]),\n channels: z.array(channelBindingSchema),\n channelSources: z\n .record(z.string(), z.object({ path: z.string(), source: z.string(), disabled: z.boolean() }))\n .optional(),\n hooks: z.array(hookBindingSchema),\n schedules: z.array(scheduleDefinitionSchema),\n bundle: bundleSchema.nullable(),\n});\n\n// What one session actually got: every dynamic slot replaced by its resolved\n// value (stored in agent.session_manifests).\nexport const resolvedAgentManifestSchema = agentManifestSchema\n .extend({\n harness: z.object({ harness: providerRefSchema, config: jsonValueSchema }),\n mcpServers: z.array(mcpServerBindingSchema),\n sandboxes: z.record(z.string(), sandboxBindingSchema.extend({ environment: jsonValueSchema })),\n })\n .superRefine((manifest, ctx) => {\n if (containsDynamicSlot(manifest)) {\n ctx.addIssue({\n code: 'custom',\n message: 'a resolved manifest must not contain dynamic slots',\n });\n }\n });\n\nexport type IdentityIface = z.infer<typeof identitySchema>;\nexport type ToolDescriptorIface = z.infer<typeof toolDescriptorSchema>;\nexport type McpAuth = z.infer<typeof mcpAuthSchema>;\nexport type WorkerMcpServerBindingIface = z.infer<typeof workerMcpServerBindingSchema>;\nexport type HttpMcpServerBindingIface = z.infer<typeof httpMcpServerBindingSchema>;\nexport type McpServerBinding = z.infer<typeof mcpServerBindingSchema>;\nexport type SandboxBindingIface = z.infer<typeof sandboxBindingSchema>;\nexport type BaseToolsIface = z.infer<typeof baseToolsSchema>;\nexport type ChannelBindingIface = z.infer<typeof channelBindingSchema>;\nexport type HookBindingIface = z.infer<typeof hookBindingSchema>;\nexport type ScheduleDefinitionIface = z.infer<typeof scheduleDefinitionSchema>;\nexport type BundleIface = z.infer<typeof bundleSchema>;\nexport type HarnessBindingIface = z.infer<typeof harnessBindingSchema>;\nexport type AgentManifestIface = z.infer<typeof agentManifestSchema>;\nexport type ResolvedAgentManifestIface = z.infer<typeof resolvedAgentManifestSchema>;\nexport type ResolvedSandboxBindingIface = ResolvedAgentManifestIface['sandboxes'][string];\n\n// The fields of a harness config the platform itself reads through the shared\n// schema fragments; everything else is opaque to the platform.\nexport enum InstructionRole {\n System = 'system',\n User = 'user',\n}\n\nexport const instructionFragmentSchema = z.object({\n role: z.nativeEnum(InstructionRole),\n content: z.string(),\n // Source file, for the compatibility report and Build.\n source: z.string().optional(),\n});\n\nexport const skillFileSchema = z.object({ path: z.string().min(1), content: z.string() });\nexport const skillBundleSchema = z.object({\n key: z.string().min(1),\n description: z.string().optional(),\n files: z.array(skillFileSchema),\n});\n\nexport type InstructionFragmentIface = z.infer<typeof instructionFragmentSchema>;\nexport type SkillBundleIface = z.infer<typeof skillBundleSchema>;\n\nexport const emptyManifest = (name: string): AgentManifestIface => ({\n version: MANIFEST_VERSION,\n identity: { name, description: null, avatarUrl: null },\n harness: {\n harness: packageRef('@finalai/final-agent-provider/harnesses/serverless-final'),\n config: {},\n },\n mcpServers: [],\n sandboxes: {},\n tools: { base: {} },\n toolPolicy: {},\n secrets: [],\n channels: [],\n hooks: [],\n schedules: [],\n bundle: null,\n});\n"],
5
+ "mappings": "AAAA,YAAY,OAAO;AACnB,SAAS,qBAAqB,cAAc,oBAAoB;AAChE,SAAS,kBAAkB,kBAAkB,uBAAuB;AACpE,SAAS,YAAY,yBAAyB;A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
  "names": ["BaseCapability", "ToolApproval", "SandboxAccess", "SandboxAttach", "McpServerBindingKind", "ScheduleTarget", "ScheduleDelivery", "InputApprovalKind", "InstructionRole"]
7
7
  }
@@ -1,3 +1,4 @@
1
+ import type { HostedBindingsIface } from "../hosted-bindings.mjs";
1
2
  import type { ProcessInspectionRequestIface, ProcessInspectionResultIface } from '@finalai/agent-protocol/process-inspection';
2
3
  import type { JsonValue } from "../json.mjs";
3
4
  import type { ToolDescriptorIface } from "../manifest.mjs";
@@ -239,10 +240,12 @@ export interface SandboxActingUserIface {
239
240
  }
240
241
  export declare const noSandboxActingUser: SandboxActingUserIface;
241
242
  export interface SandboxOfferContextIface {
243
+ bindings?: HostedBindingsIface;
242
244
  organizationId: string;
243
245
  actingUser: SandboxActingUserIface;
244
246
  }
245
247
  export interface SandboxEnvironmentContextIface {
248
+ bindings?: HostedBindingsIface;
246
249
  organizationId: string;
247
250
  guides: SandboxGuidesIface;
248
251
  }
@@ -258,6 +261,7 @@ export interface SandboxPreparationSourceIface {
258
261
  }>;
259
262
  }
260
263
  export interface SandboxPrepareContextIface {
264
+ bindings?: HostedBindingsIface;
261
265
  preparation?: SandboxPreparationSourceIface;
262
266
  artifacts?: SandboxArtifactsIface;
263
267
  files: Record<string, string>;
@@ -270,6 +274,7 @@ export interface SandboxPrepareContextIface {
270
274
  log?: (message: string) => void;
271
275
  }
272
276
  export interface SandboxStartContextIface {
277
+ bindings?: HostedBindingsIface;
273
278
  /** Passive recovery only: never wake, create, seed, or restart backend services. */
274
279
  passive?: boolean;
275
280
  preparation?: SandboxPreparationSourceIface;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/sandbox/types.ts"],
4
- "sourcesContent": ["import type {\n ProcessInspectionRequestIface,\n ProcessInspectionResultIface,\n} from '@finalai/agent-protocol/process-inspection';\nimport type { JsonValue } from \"../json.mjs\";\nimport type { ToolDescriptorIface } from \"../manifest.mjs\";\nimport type { SandboxEditorRequestIface, SandboxEditorResultIface } from \"./editor.mjs\";\nimport { awaitableOpenRequest, type AwaitableSandboxOpenRequestIface } from \"./open-scope.mjs\";\nimport type { SandboxSnapshotRequestIface, SandboxSnapshotResponseIface } from \"./snapshots.mjs\";\n\n// Sandbox providers and consumers share the streaming session contract.\n\nexport interface AbortableIface {\n abortSignal?: AbortSignal;\n}\n\nexport interface SandboxProcessOptionsIface extends AbortableIface {\n command: string;\n args?: string[];\n cwd?: string;\n env?: Record<string, string>;\n // Run through the sandbox's login shell (`bash -lc`) instead of exec'ing.\n shell?: boolean;\n stdin?: ReadableStream<Uint8Array> | string;\n timeoutMs?: number;\n}\n\nexport interface SandboxProcessIface {\n readonly pid: string | null;\n readonly stdout: ReadableStream<Uint8Array>;\n readonly stderr: ReadableStream<Uint8Array>;\n // Writes to the process's stdin; closes stdin when `end` is true.\n write(data: Uint8Array | string, options?: { end?: boolean }): Promise<void>;\n wait(): Promise<{ exitCode: number }>;\n kill(signal?: string): Promise<void>;\n}\n\nexport interface SandboxRunResultIface {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\nexport enum SandboxEntryType {\n File = 'file',\n Directory = 'directory',\n Symlink = 'symlink',\n Other = 'other',\n}\n\nexport interface StatIface {\n path: string;\n type: SandboxEntryType;\n size: number;\n modifiedAt: string | null;\n mode: number | null;\n}\n\nexport interface DirEntryIface {\n name: string;\n path: string;\n type: SandboxEntryType;\n size: number | null;\n}\n\nexport interface ConfinedSandboxFilesIface {\n readFile(\n options: { path: string; root: string } & AbortableIface,\n ): Promise<ReadableStream<Uint8Array> | null>;\n stat(options: { path: string; root: string } & AbortableIface): Promise<StatIface | null>;\n readDir(\n options: { path: string; root: string } & AbortableIface,\n ): Promise<DirEntryIface[] | null>;\n}\n\nexport interface SandboxSessionIface {\n readonly description: string;\n readonly confinedFileReader?: ConfinedSandboxFilesIface;\n // On the RPC surface, root confines viewer reads to this directory, rejects\n // symlink ancestors and requires Python 3 in the sandbox (confinedFiles feature).\n readFile(\n options: { path: string; root?: string } & AbortableIface,\n ): Promise<ReadableStream<Uint8Array> | null>;\n readBinaryFile(options: { path: string } & AbortableIface): Promise<Uint8Array | null>;\n readTextFile(\n options: {\n path: string;\n encoding?: string;\n startLine?: number;\n endLine?: number;\n } & AbortableIface,\n ): Promise<string | null>;\n writeFile(\n options: { path: string; content: ReadableStream<Uint8Array> } & AbortableIface,\n ): Promise<void>;\n writeBinaryFile(options: { path: string; content: Uint8Array } & AbortableIface): Promise<void>;\n writeTextFile(\n options: { path: string; content: string; encoding?: string } & AbortableIface,\n ): Promise<void>;\n spawn(options: SandboxProcessOptionsIface): Promise<SandboxProcessIface>;\n run(options: SandboxProcessOptionsIface): Promise<SandboxRunResultIface>;\n stat(options: { path: string; root?: string } & AbortableIface): Promise<StatIface | null>;\n readDir(options: { path: string; root?: string } & AbortableIface): Promise<DirEntryIface[]>;\n resolvePath(path: string): string;\n removePath(\n options: { path: string; recursive?: boolean; force?: boolean } & AbortableIface,\n ): Promise<void>;\n}\n\nexport enum NetworkPolicy {\n AllowAll = 'allow-all',\n DenyAll = 'deny-all',\n Allowlist = 'allowlist',\n}\n\nexport interface NetworkPolicyIface {\n mode: NetworkPolicy;\n allow?: string[];\n}\n\nexport enum PortProtocol {\n Http = 'http',\n Https = 'https',\n Ws = 'ws',\n}\n\n// An MCP transport the sandbox serves for an optional capability: an HTTP MCP\n// endpoint the harness (or the session service) can dial.\nexport interface McpEndpointIface {\n name: string;\n url: string;\n headers: Record<string, string>;\n}\n\n// A JSON-RPC message channel to an MCP server the sandbox hosts, for backends\n// whose API reaches it some other way than HTTP MCP (a byte pipe, a socket).\n// Messages are JSON-RPC objects, in order.\nexport interface McpChannelIface {\n send(message: JsonValue, options?: AbortableIface): Promise<void>;\n // The messages that arrived since the last call; [] when none did.\n receive(options?: AbortableIface): Promise<JsonValue[]>;\n close(): Promise<void>;\n}\n\n// An MCP server the sandbox hosts, opened in process by whoever runs the handle.\n// It cannot cross the handle RPC wire.\nexport interface McpChannelEndpointIface {\n name: string;\n connect(options?: AbortableIface): Promise<McpChannelIface>;\n}\n\nexport type SandboxMcpEndpoint = McpEndpointIface | McpChannelEndpointIface;\n\n// The tools of a sandbox's hosted MCP servers, as far as they are known without\n// starting it. Null: unknown until the sandbox is attached and asked.\nexport interface SandboxMcpCatalogIface {\n computerUse: ToolDescriptorIface[] | null;\n // Local MCP server name \u2192 its tools.\n localMcp: Record<string, ToolDescriptorIface[]> | null;\n}\n\nexport const isMcpChannelEndpoint = (\n endpoint: SandboxMcpEndpoint,\n): endpoint is McpChannelEndpointIface => 'connect' in endpoint;\n\nexport interface ScreenOptionsIface {\n // View-only by default; explicit input control requires execute access.\n viewOnly?: boolean;\n}\n\nexport interface ScreenSessionIface {\n // A short-lived viewer grant; providers enforce the requested input access.\n url: string;\n token: string;\n expiresAt: string;\n}\n\nexport interface NetworkSandboxSessionIface extends SandboxSessionIface {\n readonly id: string;\n readonly defaultWorkingDirectory: string;\n readonly ports: readonly number[];\n getPortEndpoint(options: {\n port: number;\n protocol?: PortProtocol;\n }): Promise<{ url: string; headers?: Record<string, string> }>;\n getPortUrl(options: { port: number; protocol?: PortProtocol }): Promise<string>;\n stop(): Promise<void>;\n destroy(): Promise<void>;\n setNetworkPolicy?(policy: NetworkPolicyIface): Promise<void>;\n computerUse?(): Promise<SandboxMcpEndpoint>;\n screen?(options?: ScreenOptionsIface): Promise<ScreenSessionIface>;\n localMcp?(): Promise<SandboxMcpEndpoint[]>;\n}\n\n// Capabilities a started sandbox advertises (and the handle RPC exposes).\nexport enum SandboxCapability {\n Files = 'files',\n Process = 'process',\n Ports = 'ports',\n NetworkPolicy = 'networkPolicy',\n ComputerUse = 'computerUse',\n Screen = 'screen',\n LocalMcp = 'localMcp',\n Browser = 'browser',\n}\n\nexport interface SandboxProviderHandleIface<S extends SandboxSessionIface> {\n readonly sandbox: S;\n onSandboxStop(): Promise<void>;\n onSandboxDelete(options?: { reason?: string }): Promise<void>;\n onRuntimeShutdown(): Promise<void>;\n}\n\n// A saved computer setup guide version: Build's versioned build-\n// and start-time inputs for a sandbox, as the session service serves them.\nexport interface SandboxGuideVersionIface {\n guideId: string;\n versionId: string;\n slug: string;\n title: string;\n number: number;\n image: string;\n // `.final/sandbox-template.yaml` v2 as JSON.\n templateConfig: JsonValue;\n // The start-time parameters this version defaults to.\n defaultParameters: JsonValue;\n instructionsMarkdown: string | null;\n // A ready build from the guide's provider, reusable independently of workspace seeds.\n preparedArtifact?: { providerRef: string; key: string; artifact: JsonValue };\n}\n\n// The organization's computer setup guides, read through the session service.\n// Every provider gets the same reader; a provider whose\n// environments name no guide never calls it.\nexport interface SandboxGuidesIface {\n get(args: { ref: string; version: number | 'latest' }): Promise<SandboxGuideVersionIface | null>;\n // The organization's default guide; null when it has none.\n default(): Promise<SandboxGuideVersionIface | null>;\n}\n\n// Where to clone a repository from, with a short-lived read credential that\n// must reach only the clone process (never a repository's git config).\nexport interface SandboxRepositoryCloneSourceIface {\n url: string;\n // Checked out after the clone; null keeps the default branch.\n ref: string | null;\n // An HTTP Authorization header value for the clone, or null.\n authorization: string | null;\n}\n\n// Repository credentials for the repositories an environment names (a Code\n// Storage id, a GitHub owner/name), resolved by the session service for the\n// session's organization only. Null: not a repository it can resolve.\nexport interface SandboxRepositoriesIface {\n cloneSource(args: {\n repository: string;\n ref: string | null;\n }): Promise<SandboxRepositoryCloneSourceIface | null>;\n}\n\n// Reads a named organization variable (managed in Build) for the session's\n// organization. Values are injected into the sandbox only, never stored in a\n// manifest, a state or the log.\nexport interface SandboxVariablesIface {\n get(name: string): Promise<string | null>;\n}\n\nexport const noSandboxGuides: SandboxGuidesIface = {\n get: async () => null,\n default: async () => null,\n};\n\nexport const noSandboxRepositories: SandboxRepositoriesIface = {\n cloneSource: async () => null,\n};\n\nexport const noSandboxVariables: SandboxVariablesIface = { get: async () => null };\n\n// The user a session acts for: the author of its running turn, else its owner,\n// else the user whose Home its conversation is. A call a person makes through\n// the platform's sandbox viewer acts for that person instead. Null when it acts\n// for no user (a turn nobody prompted in a shared conversation) and outside any\n// session (a guide build). Read on each call, because it changes between turns\n// and between callers.\nexport interface SandboxActingUserIface {\n current(): Promise<string | null>;\n}\n\nexport const noSandboxActingUser: SandboxActingUserIface = { current: async () => null };\n\n// What an environment's pre-start reads (capabilities, mcpCatalog) are given.\nexport interface SandboxOfferContextIface {\n organizationId: string;\n actingUser: SandboxActingUserIface;\n}\n\n// What an environment's hooks are given before anything starts.\nexport interface SandboxEnvironmentContextIface {\n organizationId: string;\n guides: SandboxGuidesIface;\n}\n\n// Scoped by the host to this organization and provider. Providers can retain\n// reusable intermediate artifacts independently of a revision's seed files.\nexport interface SandboxArtifactsIface {\n get(key: string): Promise<JsonValue | null>;\n put(key: string, artifact: JsonValue): Promise<void>;\n}\n\nexport interface SandboxPreparationSourceIface {\n sourceRevision: string;\n read(): Promise<{ files: Record<string, string>; resources: Record<string, JsonValue> }>;\n}\n\nexport interface SandboxPrepareContextIface {\n // A host-persisted resource source; artifacts may retain its identity instead of seed contents.\n preparation?: SandboxPreparationSourceIface;\n artifacts?: SandboxArtifactsIface;\n // Agent revisions supply workspace-relative seeds; setup-guide builds supply\n // guide.json and optional instructions.md. Resources name workspace, skills or guide.\n // Model instructions remain harness config.\n files: Record<string, string>;\n resources: Record<string, JsonValue>;\n sourceRevision: string;\n storagePath: string;\n organizationId: string;\n // The guide inputs (build-time) an environment names, resolved by the platform.\n guides: SandboxGuidesIface;\n // Who the session the artifact is prepared for acts for, for environments that\n // name a backend resource relative to that user; the key must then name it.\n actingUser: SandboxActingUserIface;\n log?: (message: string) => void;\n}\n\nexport interface SandboxStartContextIface {\n /** Passive recovery only: never wake, create, seed, or restart backend services. */\n passive?: boolean;\n preparation?: SandboxPreparationSourceIface;\n session: {\n id: string;\n organizationId: string;\n conversationId: string | null;\n definitionId: string;\n bindingId: string;\n target: string;\n };\n storagePath: string;\n // Start-time inputs: guides, the variables to inject, repository credentials.\n guides: SandboxGuidesIface;\n variables: SandboxVariablesIface;\n repositories: SandboxRepositoriesIface;\n actingUser: SandboxActingUserIface;\n}\n\nexport enum SandboxSessionEndReason {\n Completed = 'completed',\n Expired = 'expired',\n Failed = 'failed',\n}\n\n// How long an environment's sandbox outlives a session: `session`\n// keeps it for the session's life; `conversation` gives every session in the\n// conversation one shared sandbox per target, surviving session resets;\n// `ephemeral` discards it when released.\nexport enum SandboxWorkspace {\n Session = 'session',\n Conversation = 'conversation',\n Ephemeral = 'ephemeral',\n}\n\nexport interface SandboxProviderImplementationIface<\n OpenOptions,\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n> {\n // The workspace this environment declares, read before anything starts so the\n // session service knows which sessions share a binding. Absent or null: session.\n workspace?(ctx: SandboxEnvironmentContextIface): Promise<SandboxWorkspace | null>;\n // The capabilities this environment's sandboxes offer, read before anything\n // starts through the backend's own API. Absent or null: unknown\n // until started; local MCP is then not projected.\n capabilities?(ctx: SandboxOfferContextIface): Promise<SandboxCapability[] | null>;\n // The hosted MCP servers' tool catalogs the backend can give without starting\n // a sandbox (from its own records), so the MCP projection lists them from the\n // first `tools/list`. The projection checks a server's catalog against the\n // live server when a call first opens that server (servers a session never\n // uses stay closed) and announces a change with\n // `notifications/tools/list_changed`.\n //\n // Trade-off: a catalog left unknown (absent hook, null, or a null field) can\n // only be learned from the live sandbox, so the first `tools/list` that finds\n // it unknown starts the sandbox in the background, at session start rather\n // than on the first tool call. Otherwise those tools would never be listed,\n // and nothing would ever call them. Providers that can give the catalog keep\n // attach lazy.\n mcpCatalog?(ctx: SandboxOfferContextIface): Promise<SandboxMcpCatalogIface | null>;\n // Reads committed files without starting/resuming a sandbox. Null means the backend\n // is live or offers no snapshot. An unavailable sleeping snapshot must throw,\n // never fall through to a read that wakes it. Pin subsequent ranges by snapshotId.\n readSnapshot?(\n ctx: SandboxOfferContextIface,\n state: State,\n request: SandboxSnapshotRequestIface,\n ): Promise<SandboxSnapshotResponseIface | null>;\n // Inspect retained backend processes without opening, resuming or extending a sandbox.\n // Stop requires execute access; the provider also enforces backend ownership.\n processes?(\n ctx: SandboxOfferContextIface & { bindingId: string },\n state: State,\n request: ProcessInspectionRequestIface,\n ): Promise<ProcessInspectionResultIface>;\n // Browser editor for this provider's existing workspace. The host checks write\n // authorization; this hook never creates or wakes a backend. Credentials stay\n // in the authentication form, never the editor URL or stored provider state.\n editor?(\n ctx: SandboxOfferContextIface,\n state: State,\n request: SandboxEditorRequestIface,\n ): Promise<SandboxEditorResultIface>;\n // Content-addressed by `artifactKey`; the session service caches artifacts in\n // agent.sandbox_artifacts and calls prepare only on a miss.\n artifactKey(ctx: SandboxPrepareContextIface): Promise<string>;\n prepare(ctx: SandboxPrepareContextIface): Promise<Artifact>;\n // `region`: where the backend placed the sandbox (its own region name), so the\n // session service can place the harness near it; null when unknown.\n start(\n ctx: SandboxStartContextIface,\n options: OpenOptions | undefined,\n artifact: Artifact,\n ): Promise<{ handle: SandboxProviderHandleIface<S>; state: State; region?: string | null }>;\n resume(\n ctx: SandboxStartContextIface,\n artifact: Artifact,\n state: State,\n ): Promise<SandboxProviderHandleIface<S>>;\n // Reconnect to an already running backend after host restart for a read-only viewer.\n // Absent: viewers can use a retained live handle but cannot trigger resume.\n resumePassive?(\n ctx: SandboxStartContextIface,\n artifact: Artifact,\n state: State,\n ): Promise<SandboxProviderHandleIface<S>>;\n // Park: pause or stop the sandbox, returning the state resume needs.\n park?(ctx: SandboxStartContextIface, artifact: Artifact, state: State): Promise<State>;\n onSessionEnd?(\n ctx: SandboxStartContextIface,\n artifact: Artifact,\n state: State,\n options: { reason: SandboxSessionEndReason },\n ): Promise<void>;\n}\n\nexport interface SandboxProviderDefinitionIface<\n EnvOptions,\n OpenOptions,\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n> {\n name: string;\n // The version of `State`'s shape. The session service records it with each\n // binding and refuses to resume a state written under another version (the\n // next call starts the sandbox again instead).\n stateProtocolVersion?: number;\n environment(\n options?: EnvOptions,\n ): SandboxProviderImplementationIface<OpenOptions, Artifact, State, S>;\n}\n\n// A defined provider: the definition plus authoring sugar. `environment(opts)`\n// returns an environment whose `.open(openOptions)` records a sandbox binding\n// target when authored, and is what the session service drives at run time.\nexport interface SandboxProviderIface<\n EnvOptions,\n OpenOptions,\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n> {\n readonly definition: SandboxProviderDefinitionIface<EnvOptions, OpenOptions, Artifact, State, S>;\n readonly name: string;\n environment(options?: EnvOptions): AwaitableSandboxEnvironmentIface<EnvOptions, OpenOptions>;\n}\n\nexport interface SandboxEnvironmentIface<EnvOptions, OpenOptions> {\n readonly providerName: string;\n readonly options: EnvOptions | undefined;\n // Provider-authored notices shown by the compiler and Build before publication.\n readonly authoringWarnings?: readonly string[];\n // Authoring: records the open options (access, ...) for this target.\n open(options?: OpenOptions): SandboxOpenRequestIface<EnvOptions, OpenOptions>;\n}\n\n// An environment whose open request a sandbox.ts selector can await to get\n// the live session (open-scope.ts); what defineSandboxProvider and the\n// installed helpers return.\nexport interface AwaitableSandboxEnvironmentIface<\n EnvOptions,\n OpenOptions,\n> extends SandboxEnvironmentIface<EnvOptions, OpenOptions> {\n open(options?: OpenOptions): AwaitableSandboxOpenRequestIface<EnvOptions, OpenOptions>;\n}\n\nexport interface SandboxOpenRequestIface<EnvOptions, OpenOptions> {\n readonly providerName: string;\n readonly environmentOptions: EnvOptions | undefined;\n readonly openOptions: OpenOptions | undefined;\n readonly authoringWarnings?: readonly string[];\n}\n\nexport const defineSandboxProvider = <\n EnvOptions,\n OpenOptions,\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n>(\n definition: SandboxProviderDefinitionIface<EnvOptions, OpenOptions, Artifact, State, S>,\n): SandboxProviderIface<EnvOptions, OpenOptions, Artifact, State, S> => ({\n definition,\n name: definition.name,\n environment: (options) => ({\n providerName: definition.name,\n options,\n open: (openOptions) =>\n awaitableOpenRequest({\n providerName: definition.name,\n environmentOptions: options,\n openOptions,\n }),\n }),\n});\n\n// Erased form the session service stores in its provider registry.\nexport type AnySandboxProviderIface = SandboxProviderIface<\n JsonValue,\n JsonValue,\n JsonValue,\n JsonValue,\n NetworkSandboxSessionIface\n>;\n\n// Events emitted through a sandbox provider's process lifecycle.\nexport enum SandboxEventKind {\n ProcessExited = 'process_exited',\n}\n"],
5
- "mappings": "AAOA,SAAS,4BAAmE;AAoCrE,IAAK,mBAAL,kBAAKA,sBAAL;AACL,EAAAA,kBAAA,UAAO;AACP,EAAAA,kBAAA,eAAY;AACZ,EAAAA,kBAAA,aAAU;AACV,EAAAA,kBAAA,WAAQ;AAJE,SAAAA;AAAA,GAAA;AAkEL,IAAK,gBAAL,kBAAKC,mBAAL;AACL,EAAAA,eAAA,cAAW;AACX,EAAAA,eAAA,aAAU;AACV,EAAAA,eAAA,eAAY;AAHF,SAAAA;AAAA,GAAA;AAWL,IAAK,eAAL,kBAAKC,kBAAL;AACL,EAAAA,cAAA,UAAO;AACP,EAAAA,cAAA,WAAQ;AACR,EAAAA,cAAA,QAAK;AAHK,SAAAA;AAAA,GAAA;AAyCL,MAAM,uBAAuB,CAClC,aACwC,aAAa;AAgChD,IAAK,oBAAL,kBAAKC,uBAAL;AACL,EAAAA,mBAAA,WAAQ;AACR,EAAAA,mBAAA,aAAU;AACV,EAAAA,mBAAA,WAAQ;AACR,EAAAA,mBAAA,mBAAgB;AAChB,EAAAA,mBAAA,iBAAc;AACd,EAAAA,mBAAA,YAAS;AACT,EAAAA,mBAAA,cAAW;AACX,EAAAA,mBAAA,aAAU;AARA,SAAAA;AAAA,GAAA;AAwEL,MAAM,kBAAsC;AAAA,EACjD,KAAK,YAAY;AAAA,EACjB,SAAS,YAAY;AACvB;AAEO,MAAM,wBAAkD;AAAA,EAC7D,aAAa,YAAY;AAC3B;AAEO,MAAM,qBAA4C,EAAE,KAAK,YAAY,KAAK;AAY1E,MAAM,sBAA8C,EAAE,SAAS,YAAY,KAAK;AAkEhF,IAAK,0BAAL,kBAAKC,6BAAL;AACL,EAAAA,yBAAA,eAAY;AACZ,EAAAA,yBAAA,aAAU;AACV,EAAAA,yBAAA,YAAS;AAHC,SAAAA;AAAA,GAAA;AAUL,IAAK,mBAAL,kBAAKC,sBAAL;AACL,EAAAA,kBAAA,aAAU;AACV,EAAAA,kBAAA,kBAAe;AACf,EAAAA,kBAAA,eAAY;AAHF,SAAAA;AAAA,GAAA;AAmJL,MAAM,wBAAwB,CAOnC,gBACuE;AAAA,EACvE;AAAA,EACA,MAAM,WAAW;AAAA,EACjB,aAAa,CAAC,aAAa;AAAA,IACzB,cAAc,WAAW;AAAA,IACzB;AAAA,IACA,MAAM,CAAC,gBACL,qBAAqB;AAAA,MACnB,cAAc,WAAW;AAAA,MACzB,oBAAoB;AAAA,MACpB;AAAA,IACF,CAAC;AAAA,EACL;AACF;AAYO,IAAK,mBAAL,kBAAKC,sBAAL;AACL,EAAAA,kBAAA,mBAAgB;AADN,SAAAA;AAAA,GAAA;",
4
+ "sourcesContent": ["import type { HostedBindingsIface } from \"../hosted-bindings.mjs\";\nimport type {\n ProcessInspectionRequestIface,\n ProcessInspectionResultIface,\n} from '@finalai/agent-protocol/process-inspection';\nimport type { JsonValue } from \"../json.mjs\";\nimport type { ToolDescriptorIface } from \"../manifest.mjs\";\nimport type { SandboxEditorRequestIface, SandboxEditorResultIface } from \"./editor.mjs\";\nimport { awaitableOpenRequest, type AwaitableSandboxOpenRequestIface } from \"./open-scope.mjs\";\nimport type { SandboxSnapshotRequestIface, SandboxSnapshotResponseIface } from \"./snapshots.mjs\";\n\n// Sandbox providers and consumers share the streaming session contract.\n\nexport interface AbortableIface {\n abortSignal?: AbortSignal;\n}\n\nexport interface SandboxProcessOptionsIface extends AbortableIface {\n command: string;\n args?: string[];\n cwd?: string;\n env?: Record<string, string>;\n // Run through the sandbox's login shell (`bash -lc`) instead of exec'ing.\n shell?: boolean;\n stdin?: ReadableStream<Uint8Array> | string;\n timeoutMs?: number;\n}\n\nexport interface SandboxProcessIface {\n readonly pid: string | null;\n readonly stdout: ReadableStream<Uint8Array>;\n readonly stderr: ReadableStream<Uint8Array>;\n // Writes to the process's stdin; closes stdin when `end` is true.\n write(data: Uint8Array | string, options?: { end?: boolean }): Promise<void>;\n wait(): Promise<{ exitCode: number }>;\n kill(signal?: string): Promise<void>;\n}\n\nexport interface SandboxRunResultIface {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\nexport enum SandboxEntryType {\n File = 'file',\n Directory = 'directory',\n Symlink = 'symlink',\n Other = 'other',\n}\n\nexport interface StatIface {\n path: string;\n type: SandboxEntryType;\n size: number;\n modifiedAt: string | null;\n mode: number | null;\n}\n\nexport interface DirEntryIface {\n name: string;\n path: string;\n type: SandboxEntryType;\n size: number | null;\n}\n\nexport interface ConfinedSandboxFilesIface {\n readFile(\n options: { path: string; root: string } & AbortableIface,\n ): Promise<ReadableStream<Uint8Array> | null>;\n stat(options: { path: string; root: string } & AbortableIface): Promise<StatIface | null>;\n readDir(\n options: { path: string; root: string } & AbortableIface,\n ): Promise<DirEntryIface[] | null>;\n}\n\nexport interface SandboxSessionIface {\n readonly description: string;\n readonly confinedFileReader?: ConfinedSandboxFilesIface;\n // On the RPC surface, root confines viewer reads to this directory, rejects\n // symlink ancestors and requires Python 3 in the sandbox (confinedFiles feature).\n readFile(\n options: { path: string; root?: string } & AbortableIface,\n ): Promise<ReadableStream<Uint8Array> | null>;\n readBinaryFile(options: { path: string } & AbortableIface): Promise<Uint8Array | null>;\n readTextFile(\n options: {\n path: string;\n encoding?: string;\n startLine?: number;\n endLine?: number;\n } & AbortableIface,\n ): Promise<string | null>;\n writeFile(\n options: { path: string; content: ReadableStream<Uint8Array> } & AbortableIface,\n ): Promise<void>;\n writeBinaryFile(options: { path: string; content: Uint8Array } & AbortableIface): Promise<void>;\n writeTextFile(\n options: { path: string; content: string; encoding?: string } & AbortableIface,\n ): Promise<void>;\n spawn(options: SandboxProcessOptionsIface): Promise<SandboxProcessIface>;\n run(options: SandboxProcessOptionsIface): Promise<SandboxRunResultIface>;\n stat(options: { path: string; root?: string } & AbortableIface): Promise<StatIface | null>;\n readDir(options: { path: string; root?: string } & AbortableIface): Promise<DirEntryIface[]>;\n resolvePath(path: string): string;\n removePath(\n options: { path: string; recursive?: boolean; force?: boolean } & AbortableIface,\n ): Promise<void>;\n}\n\nexport enum NetworkPolicy {\n AllowAll = 'allow-all',\n DenyAll = 'deny-all',\n Allowlist = 'allowlist',\n}\n\nexport interface NetworkPolicyIface {\n mode: NetworkPolicy;\n allow?: string[];\n}\n\nexport enum PortProtocol {\n Http = 'http',\n Https = 'https',\n Ws = 'ws',\n}\n\n// An MCP transport the sandbox serves for an optional capability: an HTTP MCP\n// endpoint the harness (or the session service) can dial.\nexport interface McpEndpointIface {\n name: string;\n url: string;\n headers: Record<string, string>;\n}\n\n// A JSON-RPC message channel to an MCP server the sandbox hosts, for backends\n// whose API reaches it some other way than HTTP MCP (a byte pipe, a socket).\n// Messages are JSON-RPC objects, in order.\nexport interface McpChannelIface {\n send(message: JsonValue, options?: AbortableIface): Promise<void>;\n // The messages that arrived since the last call; [] when none did.\n receive(options?: AbortableIface): Promise<JsonValue[]>;\n close(): Promise<void>;\n}\n\n// An MCP server the sandbox hosts, opened in process by whoever runs the handle.\n// It cannot cross the handle RPC wire.\nexport interface McpChannelEndpointIface {\n name: string;\n connect(options?: AbortableIface): Promise<McpChannelIface>;\n}\n\nexport type SandboxMcpEndpoint = McpEndpointIface | McpChannelEndpointIface;\n\n// The tools of a sandbox's hosted MCP servers, as far as they are known without\n// starting it. Null: unknown until the sandbox is attached and asked.\nexport interface SandboxMcpCatalogIface {\n computerUse: ToolDescriptorIface[] | null;\n // Local MCP server name \u2192 its tools.\n localMcp: Record<string, ToolDescriptorIface[]> | null;\n}\n\nexport const isMcpChannelEndpoint = (\n endpoint: SandboxMcpEndpoint,\n): endpoint is McpChannelEndpointIface => 'connect' in endpoint;\n\nexport interface ScreenOptionsIface {\n // View-only by default; explicit input control requires execute access.\n viewOnly?: boolean;\n}\n\nexport interface ScreenSessionIface {\n // A short-lived viewer grant; providers enforce the requested input access.\n url: string;\n token: string;\n expiresAt: string;\n}\n\nexport interface NetworkSandboxSessionIface extends SandboxSessionIface {\n readonly id: string;\n readonly defaultWorkingDirectory: string;\n readonly ports: readonly number[];\n getPortEndpoint(options: {\n port: number;\n protocol?: PortProtocol;\n }): Promise<{ url: string; headers?: Record<string, string> }>;\n getPortUrl(options: { port: number; protocol?: PortProtocol }): Promise<string>;\n stop(): Promise<void>;\n destroy(): Promise<void>;\n setNetworkPolicy?(policy: NetworkPolicyIface): Promise<void>;\n computerUse?(): Promise<SandboxMcpEndpoint>;\n screen?(options?: ScreenOptionsIface): Promise<ScreenSessionIface>;\n localMcp?(): Promise<SandboxMcpEndpoint[]>;\n}\n\n// Capabilities a started sandbox advertises (and the handle RPC exposes).\nexport enum SandboxCapability {\n Files = 'files',\n Process = 'process',\n Ports = 'ports',\n NetworkPolicy = 'networkPolicy',\n ComputerUse = 'computerUse',\n Screen = 'screen',\n LocalMcp = 'localMcp',\n Browser = 'browser',\n}\n\nexport interface SandboxProviderHandleIface<S extends SandboxSessionIface> {\n readonly sandbox: S;\n onSandboxStop(): Promise<void>;\n onSandboxDelete(options?: { reason?: string }): Promise<void>;\n onRuntimeShutdown(): Promise<void>;\n}\n\n// A saved computer setup guide version: Build's versioned build-\n// and start-time inputs for a sandbox, as the session service serves them.\nexport interface SandboxGuideVersionIface {\n guideId: string;\n versionId: string;\n slug: string;\n title: string;\n number: number;\n image: string;\n // `.final/sandbox-template.yaml` v2 as JSON.\n templateConfig: JsonValue;\n // The start-time parameters this version defaults to.\n defaultParameters: JsonValue;\n instructionsMarkdown: string | null;\n // A ready build from the guide's provider, reusable independently of workspace seeds.\n preparedArtifact?: { providerRef: string; key: string; artifact: JsonValue };\n}\n\n// The organization's computer setup guides, read through the session service.\n// Every provider gets the same reader; a provider whose\n// environments name no guide never calls it.\nexport interface SandboxGuidesIface {\n get(args: { ref: string; version: number | 'latest' }): Promise<SandboxGuideVersionIface | null>;\n // The organization's default guide; null when it has none.\n default(): Promise<SandboxGuideVersionIface | null>;\n}\n\n// Where to clone a repository from, with a short-lived read credential that\n// must reach only the clone process (never a repository's git config).\nexport interface SandboxRepositoryCloneSourceIface {\n url: string;\n // Checked out after the clone; null keeps the default branch.\n ref: string | null;\n // An HTTP Authorization header value for the clone, or null.\n authorization: string | null;\n}\n\n// Repository credentials for the repositories an environment names (a Code\n// Storage id, a GitHub owner/name), resolved by the session service for the\n// session's organization only. Null: not a repository it can resolve.\nexport interface SandboxRepositoriesIface {\n cloneSource(args: {\n repository: string;\n ref: string | null;\n }): Promise<SandboxRepositoryCloneSourceIface | null>;\n}\n\n// Reads a named organization variable (managed in Build) for the session's\n// organization. Values are injected into the sandbox only, never stored in a\n// manifest, a state or the log.\nexport interface SandboxVariablesIface {\n get(name: string): Promise<string | null>;\n}\n\nexport const noSandboxGuides: SandboxGuidesIface = {\n get: async () => null,\n default: async () => null,\n};\n\nexport const noSandboxRepositories: SandboxRepositoriesIface = {\n cloneSource: async () => null,\n};\n\nexport const noSandboxVariables: SandboxVariablesIface = { get: async () => null };\n\n// The user a session acts for: the author of its running turn, else its owner,\n// else the user whose Home its conversation is. A call a person makes through\n// the platform's sandbox viewer acts for that person instead. Null when it acts\n// for no user (a turn nobody prompted in a shared conversation) and outside any\n// session (a guide build). Read on each call, because it changes between turns\n// and between callers.\nexport interface SandboxActingUserIface {\n current(): Promise<string | null>;\n}\n\nexport const noSandboxActingUser: SandboxActingUserIface = { current: async () => null };\n\n// What an environment's pre-start reads (capabilities, mcpCatalog) are given.\nexport interface SandboxOfferContextIface {\n bindings?: HostedBindingsIface;\n organizationId: string;\n actingUser: SandboxActingUserIface;\n}\n\n// What an environment's hooks are given before anything starts.\nexport interface SandboxEnvironmentContextIface {\n bindings?: HostedBindingsIface;\n organizationId: string;\n guides: SandboxGuidesIface;\n}\n\n// Scoped by the host to this organization and provider. Providers can retain\n// reusable intermediate artifacts independently of a revision's seed files.\nexport interface SandboxArtifactsIface {\n get(key: string): Promise<JsonValue | null>;\n put(key: string, artifact: JsonValue): Promise<void>;\n}\n\nexport interface SandboxPreparationSourceIface {\n sourceRevision: string;\n read(): Promise<{ files: Record<string, string>; resources: Record<string, JsonValue> }>;\n}\n\nexport interface SandboxPrepareContextIface {\n bindings?: HostedBindingsIface;\n // A host-persisted resource source; artifacts may retain its identity instead of seed contents.\n preparation?: SandboxPreparationSourceIface;\n artifacts?: SandboxArtifactsIface;\n // Agent revisions supply workspace-relative seeds; setup-guide builds supply\n // guide.json and optional instructions.md. Resources name workspace, skills or guide.\n // Model instructions remain harness config.\n files: Record<string, string>;\n resources: Record<string, JsonValue>;\n sourceRevision: string;\n storagePath: string;\n organizationId: string;\n // The guide inputs (build-time) an environment names, resolved by the platform.\n guides: SandboxGuidesIface;\n // Who the session the artifact is prepared for acts for, for environments that\n // name a backend resource relative to that user; the key must then name it.\n actingUser: SandboxActingUserIface;\n log?: (message: string) => void;\n}\n\nexport interface SandboxStartContextIface {\n bindings?: HostedBindingsIface;\n /** Passive recovery only: never wake, create, seed, or restart backend services. */\n passive?: boolean;\n preparation?: SandboxPreparationSourceIface;\n session: {\n id: string;\n organizationId: string;\n conversationId: string | null;\n definitionId: string;\n bindingId: string;\n target: string;\n };\n storagePath: string;\n // Start-time inputs: guides, the variables to inject, repository credentials.\n guides: SandboxGuidesIface;\n variables: SandboxVariablesIface;\n repositories: SandboxRepositoriesIface;\n actingUser: SandboxActingUserIface;\n}\n\nexport enum SandboxSessionEndReason {\n Completed = 'completed',\n Expired = 'expired',\n Failed = 'failed',\n}\n\n// How long an environment's sandbox outlives a session: `session`\n// keeps it for the session's life; `conversation` gives every session in the\n// conversation one shared sandbox per target, surviving session resets;\n// `ephemeral` discards it when released.\nexport enum SandboxWorkspace {\n Session = 'session',\n Conversation = 'conversation',\n Ephemeral = 'ephemeral',\n}\n\nexport interface SandboxProviderImplementationIface<\n OpenOptions,\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n> {\n // The workspace this environment declares, read before anything starts so the\n // session service knows which sessions share a binding. Absent or null: session.\n workspace?(ctx: SandboxEnvironmentContextIface): Promise<SandboxWorkspace | null>;\n // The capabilities this environment's sandboxes offer, read before anything\n // starts through the backend's own API. Absent or null: unknown\n // until started; local MCP is then not projected.\n capabilities?(ctx: SandboxOfferContextIface): Promise<SandboxCapability[] | null>;\n // The hosted MCP servers' tool catalogs the backend can give without starting\n // a sandbox (from its own records), so the MCP projection lists them from the\n // first `tools/list`. The projection checks a server's catalog against the\n // live server when a call first opens that server (servers a session never\n // uses stay closed) and announces a change with\n // `notifications/tools/list_changed`.\n //\n // Trade-off: a catalog left unknown (absent hook, null, or a null field) can\n // only be learned from the live sandbox, so the first `tools/list` that finds\n // it unknown starts the sandbox in the background, at session start rather\n // than on the first tool call. Otherwise those tools would never be listed,\n // and nothing would ever call them. Providers that can give the catalog keep\n // attach lazy.\n mcpCatalog?(ctx: SandboxOfferContextIface): Promise<SandboxMcpCatalogIface | null>;\n // Reads committed files without starting/resuming a sandbox. Null means the backend\n // is live or offers no snapshot. An unavailable sleeping snapshot must throw,\n // never fall through to a read that wakes it. Pin subsequent ranges by snapshotId.\n readSnapshot?(\n ctx: SandboxOfferContextIface,\n state: State,\n request: SandboxSnapshotRequestIface,\n ): Promise<SandboxSnapshotResponseIface | null>;\n // Inspect retained backend processes without opening, resuming or extending a sandbox.\n // Stop requires execute access; the provider also enforces backend ownership.\n processes?(\n ctx: SandboxOfferContextIface & { bindingId: string },\n state: State,\n request: ProcessInspectionRequestIface,\n ): Promise<ProcessInspectionResultIface>;\n // Browser editor for this provider's existing workspace. The host checks write\n // authorization; this hook never creates or wakes a backend. Credentials stay\n // in the authentication form, never the editor URL or stored provider state.\n editor?(\n ctx: SandboxOfferContextIface,\n state: State,\n request: SandboxEditorRequestIface,\n ): Promise<SandboxEditorResultIface>;\n // Content-addressed by `artifactKey`; the session service caches artifacts in\n // agent.sandbox_artifacts and calls prepare only on a miss.\n artifactKey(ctx: SandboxPrepareContextIface): Promise<string>;\n prepare(ctx: SandboxPrepareContextIface): Promise<Artifact>;\n // `region`: where the backend placed the sandbox (its own region name), so the\n // session service can place the harness near it; null when unknown.\n start(\n ctx: SandboxStartContextIface,\n options: OpenOptions | undefined,\n artifact: Artifact,\n ): Promise<{ handle: SandboxProviderHandleIface<S>; state: State; region?: string | null }>;\n resume(\n ctx: SandboxStartContextIface,\n artifact: Artifact,\n state: State,\n ): Promise<SandboxProviderHandleIface<S>>;\n // Reconnect to an already running backend after host restart for a read-only viewer.\n // Absent: viewers can use a retained live handle but cannot trigger resume.\n resumePassive?(\n ctx: SandboxStartContextIface,\n artifact: Artifact,\n state: State,\n ): Promise<SandboxProviderHandleIface<S>>;\n // Park: pause or stop the sandbox, returning the state resume needs.\n park?(ctx: SandboxStartContextIface, artifact: Artifact, state: State): Promise<State>;\n onSessionEnd?(\n ctx: SandboxStartContextIface,\n artifact: Artifact,\n state: State,\n options: { reason: SandboxSessionEndReason },\n ): Promise<void>;\n}\n\nexport interface SandboxProviderDefinitionIface<\n EnvOptions,\n OpenOptions,\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n> {\n name: string;\n // The version of `State`'s shape. The session service records it with each\n // binding and refuses to resume a state written under another version (the\n // next call starts the sandbox again instead).\n stateProtocolVersion?: number;\n environment(\n options?: EnvOptions,\n ): SandboxProviderImplementationIface<OpenOptions, Artifact, State, S>;\n}\n\n// A defined provider: the definition plus authoring sugar. `environment(opts)`\n// returns an environment whose `.open(openOptions)` records a sandbox binding\n// target when authored, and is what the session service drives at run time.\nexport interface SandboxProviderIface<\n EnvOptions,\n OpenOptions,\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n> {\n readonly definition: SandboxProviderDefinitionIface<EnvOptions, OpenOptions, Artifact, State, S>;\n readonly name: string;\n environment(options?: EnvOptions): AwaitableSandboxEnvironmentIface<EnvOptions, OpenOptions>;\n}\n\nexport interface SandboxEnvironmentIface<EnvOptions, OpenOptions> {\n readonly providerName: string;\n readonly options: EnvOptions | undefined;\n // Provider-authored notices shown by the compiler and Build before publication.\n readonly authoringWarnings?: readonly string[];\n // Authoring: records the open options (access, ...) for this target.\n open(options?: OpenOptions): SandboxOpenRequestIface<EnvOptions, OpenOptions>;\n}\n\n// An environment whose open request a sandbox.ts selector can await to get\n// the live session (open-scope.ts); what defineSandboxProvider and the\n// installed helpers return.\nexport interface AwaitableSandboxEnvironmentIface<\n EnvOptions,\n OpenOptions,\n> extends SandboxEnvironmentIface<EnvOptions, OpenOptions> {\n open(options?: OpenOptions): AwaitableSandboxOpenRequestIface<EnvOptions, OpenOptions>;\n}\n\nexport interface SandboxOpenRequestIface<EnvOptions, OpenOptions> {\n readonly providerName: string;\n readonly environmentOptions: EnvOptions | undefined;\n readonly openOptions: OpenOptions | undefined;\n readonly authoringWarnings?: readonly string[];\n}\n\nexport const defineSandboxProvider = <\n EnvOptions,\n OpenOptions,\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n>(\n definition: SandboxProviderDefinitionIface<EnvOptions, OpenOptions, Artifact, State, S>,\n): SandboxProviderIface<EnvOptions, OpenOptions, Artifact, State, S> => ({\n definition,\n name: definition.name,\n environment: (options) => ({\n providerName: definition.name,\n options,\n open: (openOptions) =>\n awaitableOpenRequest({\n providerName: definition.name,\n environmentOptions: options,\n openOptions,\n }),\n }),\n});\n\n// Erased form the session service stores in its provider registry.\nexport type AnySandboxProviderIface = SandboxProviderIface<\n JsonValue,\n JsonValue,\n JsonValue,\n JsonValue,\n NetworkSandboxSessionIface\n>;\n\n// Events emitted through a sandbox provider's process lifecycle.\nexport enum SandboxEventKind {\n ProcessExited = 'process_exited',\n}\n"],
5
+ "mappings": "AAQA,SAAS,4BAAmE;AAoCrE,IAAK,mBAAL,kBAAKA,sBAAL;AACL,EAAAA,kBAAA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AA,EACA,MAAM,WAAW;AAAA,EACjB,aAAa,CAAC,aAAa;AAAA,IACzB,cAAc,WAAW;AAAA,IACzB;AAAA,IACA,MAAM,CAAC,gBACL,qBAAqB;AAAA,MACnB,cAAc,WAAW;AAAA,MACzB,oBAAoB;AAAA,MACpB;AAAA,IACF,CAAC;AAAA,EACL;AACF;AAYO,IAAK,mBAAL,kBAAKC,sBAAL;AACL,EAAAA,kBAAA,mBAAgB;AADN,SAAAA;AAAA,GAAA;",
6
6
  "names": ["SandboxEntryType", "NetworkPolicy", "PortProtocol", "SandboxCapability", "SandboxSessionEndReason", "SandboxWorkspace", "SandboxEventKind"]
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@finalai/agent-provider",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "private": false,
5
5
  "description": "Provider contracts for the agent stack: harnesses, sandboxes (handle, wire, MCP projection), channels, credential policies, and the conformance kit.",
6
6
  "license": "Apache-2.0",
@@ -9,6 +9,7 @@
9
9
  "README.md",
10
10
  "LICENSE",
11
11
  "NOTICE",
12
+ "HOSTING.md",
12
13
  "THIRD_PARTY_NOTICES.md"
13
14
  ],
14
15
  "type": "module",
@@ -182,8 +183,8 @@
182
183
  },
183
184
  "dependencies": {
184
185
  "@agentclientprotocol/sdk": "1.8.0",
185
- "@finalai/acp-session": "0.1.2",
186
- "@finalai/agent-protocol": "0.1.2",
186
+ "@finalai/acp-session": "0.1.3",
187
+ "@finalai/agent-protocol": "0.1.3",
187
188
  "@modelcontextprotocol/client": "^2.1.0",
188
189
  "@modelcontextprotocol/core": "^2.1.0",
189
190
  "@modelcontextprotocol/server": "^2.1.0",