@finalai/agent-provider 0.4.3 → 0.5.1
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 +3 -3
- package/README.md +5 -0
- package/dist/modules/channel-context.d.mts +1 -1
- package/dist/modules/channel-context.mjs.map +1 -1
- package/dist/modules/channel.d.mts +14 -14
- package/dist/modules/channel.mjs +19 -19
- package/dist/modules/channel.mjs.map +3 -3
- package/dist/modules/manifest.d.mts +4 -0
- package/dist/modules/manifest.mjs +6 -3
- package/dist/modules/manifest.mjs.map +2 -2
- package/dist/modules/sandbox/networking.mjs +1 -0
- package/dist/modules/sandbox/networking.mjs.map +2 -2
- package/dist/modules/sandbox/types.d.mts +20 -0
- package/dist/modules/sandbox/types.mjs +6 -0
- package/dist/modules/sandbox/types.mjs.map +2 -2
- package/package.json +2 -2
package/HOSTING.md
CHANGED
|
@@ -7,13 +7,13 @@ resolve against dev and production configuration without source edits.
|
|
|
7
7
|
## Selecting a deployment
|
|
8
8
|
|
|
9
9
|
```sh
|
|
10
|
-
export FINAL_API_HOST=https
|
|
11
|
-
export FINAL_API_KEY=<dev-
|
|
10
|
+
export FINAL_API_HOST=https://<dev-agents-api-host>/api
|
|
11
|
+
export FINAL_API_KEY=<dev-api-key>
|
|
12
12
|
pnpm exec final-agents build ./agent
|
|
13
13
|
pnpm exec final-agents publish ./agent --agent my-agent
|
|
14
14
|
```
|
|
15
15
|
|
|
16
|
-
Choose production by changing the host and
|
|
16
|
+
Choose production by changing the host and API key. `--host` overrides
|
|
17
17
|
`FINAL_API_HOST`; without either, the existing production default remains. Build
|
|
18
18
|
compiles locally and optionally checks installed-harness compatibility. Publish
|
|
19
19
|
compiles again and sends source/release requests to the selected deployment.
|
package/README.md
CHANGED
|
@@ -21,6 +21,11 @@ a one-time startup check is insufficient. Custom `attach` implementations own
|
|
|
21
21
|
equivalent admission, deferred setup and failure cleanup. Namespace-only adapters
|
|
22
22
|
must disclose the startup traffic window when their provider cannot fence boot.
|
|
23
23
|
|
|
24
|
+
Hosts pass `credentials` (`SandboxCredentialsIface`) on sandbox contexts:
|
|
25
|
+
`computersAccess()`, `deviceAccess({ actingUserId })` and `secret({ secretRef })`.
|
|
26
|
+
Providers that need a third-party key take `credential: { secretRef }`
|
|
27
|
+
(`sandboxCredentialRefSchema`) in their environment options.
|
|
28
|
+
|
|
24
29
|
Implement the public provider interfaces and use `/conformance` to exercise them.
|
|
25
30
|
Use leaf entrypoints for sandbox wire clients, servers, MCP adapters, and local
|
|
26
31
|
channel sockets. These helpers adapt your integration to the provider contracts.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/channel-context.ts"],
|
|
4
|
-
"sourcesContent": ["import type { ContentBlock } from '@agentclientprotocol/sdk/experimental/v2';\nimport * as z from 'zod';\nimport { type ChannelAuthIface, type ChannelPlatformIface, type TurnPolicy } from \"./channel.mjs\";\nimport type { JsonObject, JsonValue } from \"./json.mjs\";\n\nexport { ChannelPrincipalType, channelAuthSchema, type ChannelAuthIface } from \"./channel.mjs\";\n\n// How a Final room captions the agent's reply to the input (\"After the 9:00\n// schedule\", \"From Dana in #support\"); the platform names the principal when absent.\nexport interface ChannelInputSourceIface {\n label: string;\n}\n\nexport interface ChannelSendInputIface {\n content: ContentBlock[];\n idempotencyKey: string;\n // Required: the platform records the principal of every input.\n auth: ChannelAuthIface;\n context?: string[];\n title?: string;\n turnPolicy?: TurnPolicy | `${TurnPolicy}`;\n // The person the input acts for when its principal is a service: who pays and answers.\n actingUserId?: string;\n // The turn whose work produced the input (a relay or handoff), for loop limits.\n originTurnId?: string;\n source?: ChannelInputSourceIface;\n}\n\nexport interface ChannelResponseInputIface {\n
|
|
4
|
+
"sourcesContent": ["import type { ContentBlock } from '@agentclientprotocol/sdk/experimental/v2';\nimport * as z from 'zod';\nimport { type ChannelAuthIface, type ChannelPlatformIface, type TurnPolicy } from \"./channel.mjs\";\nimport type { JsonObject, JsonValue } from \"./json.mjs\";\n\nexport { ChannelPrincipalType, channelAuthSchema, type ChannelAuthIface } from \"./channel.mjs\";\n\n// How a Final room captions the agent's reply to the input (\"After the 9:00\n// schedule\", \"From Dana in #support\"); the platform names the principal when absent.\nexport interface ChannelInputSourceIface {\n label: string;\n}\n\nexport interface ChannelSendInputIface {\n content: ContentBlock[];\n idempotencyKey: string;\n // Required: the platform records the principal of every input.\n auth: ChannelAuthIface;\n context?: string[];\n title?: string;\n turnPolicy?: TurnPolicy | `${TurnPolicy}`;\n // The person the input acts for when its principal is a service: who pays and answers.\n actingUserId?: string;\n // The turn whose work produced the input (a relay or handoff), for loop limits.\n originTurnId?: string;\n source?: ChannelInputSourceIface;\n}\n\nexport interface ChannelResponseInputIface {\n decisionId: string;\n outcome: JsonValue;\n // Who answered; the channel decides who may (its audience policy) before responding.\n auth: ChannelAuthIface;\n}\n\n// Exactly one of an address (the channel's own), an attached session, or a\n// Final room (`conversationId`, optionally one agent `participantId` in it).\nexport interface ChannelSessionTargetIface {\n address?: string;\n sessionId?: string;\n conversationId?: string;\n participantId?: string;\n}\n\n// `send` accepts the input before any agent runs: the prompt follows, retried\n// by the platform, and the reply arrives through the channel's events.\nexport interface ChannelInputReceiptIface {\n inputId: string;\n sessionId: string;\n}\n\nexport const channelInputReceiptSchema = z.object({\n inputId: z.string().min(1),\n sessionId: z.string().min(1),\n});\n\n// Where a handoff went: a Final room's input, or another channel's own receive\n// (which names a session or nothing).\nexport interface ChannelHandoffReceiptIface {\n inputId: string | null;\n sessionId: string | null;\n}\n\nexport const channelHandoffReceiptSchema = z.object({\n inputId: z.string().min(1).nullable(),\n sessionId: z.string().min(1).nullable(),\n});\n\nexport interface ChannelSessionSnapshotIface {\n sessionId: string;\n conversationId: string | null;\n}\n\nexport interface ChannelCancelInputIface {\n reason?: string;\n throughMessageSeq?: number;\n}\n\nexport interface ChannelSessionOperationsIface {\n inspect(target: ChannelSessionTargetIface): Promise<ChannelSessionSnapshotIface | null>;\n resolve(target: ChannelSessionTargetIface): Promise<string | null>;\n send(\n target: ChannelSessionTargetIface,\n input: ChannelSendInputIface,\n ): Promise<ChannelInputReceiptIface>;\n respond(\n target: ChannelSessionTargetIface,\n input: ChannelResponseInputIface,\n ): Promise<{ resolved: boolean }>;\n cancel(\n target: ChannelSessionTargetIface,\n input?: ChannelCancelInputIface,\n ): Promise<{ accepted: boolean }>;\n close(target: ChannelSessionTargetIface): Promise<void>;\n observe(\n target: ChannelSessionTargetIface,\n input: { content: ContentBlock[]; idempotencyKey: string },\n ): Promise<void>;\n setConfigOption(\n target: ChannelSessionTargetIface,\n input: { configId: string; value: JsonValue },\n ): Promise<void>;\n park(target: ChannelSessionTargetIface): Promise<void>;\n getState(target: ChannelSessionTargetIface): Promise<JsonObject>;\n setState(target: ChannelSessionTargetIface, state: JsonObject): Promise<void>;\n // Input for another of the agent's channels: `final` targets `{ conversationId, participantId? }`.\n handoff(\n channel: string,\n target: JsonValue,\n input: ChannelSendInputIface,\n ): Promise<ChannelHandoffReceiptIface>;\n}\n\nexport interface ChannelSessionHandleIface {\n inspect(): Promise<ChannelSessionSnapshotIface | null>;\n resolveSession(): Promise<string | null>;\n send(input: ChannelSendInputIface): ReturnType<ChannelSessionOperationsIface['send']>;\n respond(input: ChannelResponseInputIface): ReturnType<ChannelSessionOperationsIface['respond']>;\n cancel(input?: ChannelCancelInputIface): ReturnType<ChannelSessionOperationsIface['cancel']>;\n close(): Promise<void>;\n observe(input: { content: ContentBlock[]; idempotencyKey: string }): Promise<void>;\n setConfigOption(input: { configId: string; value: JsonValue }): Promise<void>;\n park(): Promise<void>;\n getState(): Promise<JsonObject>;\n setState(state: JsonObject): Promise<void>;\n}\n\nexport interface ChannelAddressContextIface {\n from(address: string): ChannelSessionHandleIface;\n resolveSession(address: string): Promise<string | null>;\n attachSession(id: string): ChannelSessionHandleIface;\n to(\n channel: string,\n target: JsonValue,\n ): { send(input: ChannelSendInputIface): Promise<ChannelHandoffReceiptIface> };\n}\n\n// Handles resolve at operation time. Only attachSession captures a session ID.\nexport const channelAccessors = (\n platform: Pick<ChannelPlatformIface, 'channelSessions'>,\n): ChannelAddressContextIface => {\n const operations = () => {\n if (platform.channelSessions == null)\n throw new Error('channel session operations are unavailable');\n return platform.channelSessions;\n };\n const handle = (target: ChannelSessionTargetIface): ChannelSessionHandleIface => ({\n inspect: () => operations().inspect(target),\n resolveSession: () => operations().resolve(target),\n send: (input) => operations().send(target, input),\n respond: (input) => operations().respond(target, input),\n cancel: (input) => operations().cancel(target, input),\n close: () => operations().close(target),\n observe: (input) => operations().observe(target, input),\n setConfigOption: (input) => operations().setConfigOption(target, input),\n park: () => operations().park(target),\n getState: () => operations().getState(target),\n setState: (state) => operations().setState(target, state),\n });\n return {\n from: (address) => handle({ address }),\n resolveSession: (address) => operations().resolve({ address }),\n attachSession: (sessionId) => handle({ sessionId }),\n to: (channel, target) => ({ send: (input) => operations().handoff(channel, target, input) }),\n };\n};\n"],
|
|
5
5
|
"mappings": "AACA,YAAY,OAAO;AACnB,eAAkF;AAGlF,SAAS,sBAAsB,yBAAgD;AA8CxE,MAAM,4BAA4B,EAAE,OAAO;AAAA,EAChD,SAAS,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACzB,WAAW,EAAE,OAAO,EAAE,IAAI,CAAC;AAC7B,CAAC;AASM,MAAM,8BAA8B,EAAE,OAAO;AAAA,EAClD,SAAS,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AAAA,EACpC,WAAW,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AACxC,CAAC;AAwEM,MAAM,mBAAmB,CAC9B,aAC+B;AAC/B,QAAM,aAAa,MAAM;AACvB,QAAI,SAAS,mBAAmB;AAC9B,YAAM,IAAI,MAAM,4CAA4C;AAC9D,WAAO,SAAS;AAAA,EAClB;AACA,QAAM,SAAS,CAAC,YAAkE;AAAA,IAChF,SAAS,MAAM,WAAW,EAAE,QAAQ,MAAM;AAAA,IAC1C,gBAAgB,MAAM,WAAW,EAAE,QAAQ,MAAM;AAAA,IACjD,MAAM,CAAC,UAAU,WAAW,EAAE,KAAK,QAAQ,KAAK;AAAA,IAChD,SAAS,CAAC,UAAU,WAAW,EAAE,QAAQ,QAAQ,KAAK;AAAA,IACtD,QAAQ,CAAC,UAAU,WAAW,EAAE,OAAO,QAAQ,KAAK;AAAA,IACpD,OAAO,MAAM,WAAW,EAAE,MAAM,MAAM;AAAA,IACtC,SAAS,CAAC,UAAU,WAAW,EAAE,QAAQ,QAAQ,KAAK;AAAA,IACtD,iBAAiB,CAAC,UAAU,WAAW,EAAE,gBAAgB,QAAQ,KAAK;AAAA,IACtE,MAAM,MAAM,WAAW,EAAE,KAAK,MAAM;AAAA,IACpC,UAAU,MAAM,WAAW,EAAE,SAAS,MAAM;AAAA,IAC5C,UAAU,CAAC,UAAU,WAAW,EAAE,SAAS,QAAQ,KAAK;AAAA,EAC1D;AACA,SAAO;AAAA,IACL,MAAM,CAAC,YAAY,OAAO,EAAE,QAAQ,CAAC;AAAA,IACrC,gBAAgB,CAAC,YAAY,WAAW,EAAE,QAAQ,EAAE,QAAQ,CAAC;AAAA,IAC7D,eAAe,CAAC,cAAc,OAAO,EAAE,UAAU,CAAC;AAAA,IAClD,IAAI,CAAC,SAAS,YAAY,EAAE,MAAM,CAAC,UAAU,WAAW,EAAE,QAAQ,SAAS,QAAQ,KAAK,EAAE;AAAA,EAC5F;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -144,7 +144,7 @@ export interface CardArgsIface {
|
|
|
144
144
|
conversationId: string;
|
|
145
145
|
authorParticipantId: string;
|
|
146
146
|
kind: CardKind;
|
|
147
|
-
|
|
147
|
+
decisionId: string | null;
|
|
148
148
|
state: JsonObject;
|
|
149
149
|
entityLinks: {
|
|
150
150
|
kind: string;
|
|
@@ -262,7 +262,7 @@ export interface ChannelInputResponseIface {
|
|
|
262
262
|
};
|
|
263
263
|
auth?: ChannelAuthIface | null;
|
|
264
264
|
participantId: string;
|
|
265
|
-
|
|
265
|
+
decisionId: string;
|
|
266
266
|
outcome: JsonValue;
|
|
267
267
|
actorParticipantId: string;
|
|
268
268
|
userId: string | null;
|
|
@@ -339,32 +339,32 @@ export interface ProjectionContextIface<State = JsonValue> {
|
|
|
339
339
|
seq: number;
|
|
340
340
|
state: ChannelTurnStateIface<State>;
|
|
341
341
|
}
|
|
342
|
-
export declare enum
|
|
343
|
-
Created = "
|
|
344
|
-
Resolved = "
|
|
342
|
+
export declare enum DecisionEventKind {
|
|
343
|
+
Created = "decision.created",
|
|
344
|
+
Resolved = "decision.resolved"
|
|
345
345
|
}
|
|
346
346
|
export type AcpUpdateKind = SessionUpdate['sessionUpdate'];
|
|
347
347
|
export type KnownAcpUpdateKind = `${SessionUpdateKind}`;
|
|
348
|
-
export type ChannelEventKind = AcpUpdateKind | `${
|
|
348
|
+
export type ChannelEventKind = AcpUpdateKind | `${DecisionEventKind}` | `${SemanticChannelEventKind}`;
|
|
349
349
|
export interface ChannelEventIface {
|
|
350
350
|
type: string;
|
|
351
351
|
data: JsonValue;
|
|
352
352
|
seq: number;
|
|
353
353
|
}
|
|
354
354
|
export type ChannelEventHandler<State = JsonValue> = (event: ChannelEventIface, ctx: ProjectionContextIface<State>) => Promise<void>;
|
|
355
|
-
export declare enum
|
|
355
|
+
export declare enum DecisionKind {
|
|
356
356
|
Permission = "permission",
|
|
357
357
|
Elicitation = "elicitation"
|
|
358
358
|
}
|
|
359
|
-
export declare const
|
|
360
|
-
|
|
361
|
-
kind: z.ZodEnum<typeof
|
|
359
|
+
export declare const decisionCreatedDataSchema: z.ZodObject<{
|
|
360
|
+
decisionId: z.ZodString;
|
|
361
|
+
kind: z.ZodEnum<typeof DecisionKind>;
|
|
362
362
|
audienceParticipantIds: z.ZodArray<z.ZodString>;
|
|
363
363
|
request: z.ZodType<JsonValue, unknown, z.core.$ZodTypeInternals<JsonValue, unknown>>;
|
|
364
364
|
}, z.core.$strip>;
|
|
365
|
-
export type
|
|
366
|
-
export declare const
|
|
367
|
-
|
|
365
|
+
export type DecisionCreatedDataIface = z.infer<typeof decisionCreatedDataSchema>;
|
|
366
|
+
export declare const decisionResolvedDataSchema: z.ZodObject<{
|
|
367
|
+
decisionId: z.ZodString;
|
|
368
368
|
outcome: z.ZodType<JsonValue, unknown, z.core.$ZodTypeInternals<JsonValue, unknown>>;
|
|
369
369
|
respondedBy: z.ZodDefault<z.ZodNullable<z.ZodObject<{
|
|
370
370
|
principalId: z.ZodString;
|
|
@@ -374,7 +374,7 @@ export declare const pendingResolvedDataSchema: z.ZodObject<{
|
|
|
374
374
|
attributes: z.ZodDefault<z.ZodType<JsonObject, unknown, z.core.$ZodTypeInternals<JsonObject, unknown>>>;
|
|
375
375
|
}, z.core.$strip>>>;
|
|
376
376
|
}, z.core.$strip>;
|
|
377
|
-
export type
|
|
377
|
+
export type DecisionResolvedDataIface = z.infer<typeof decisionResolvedDataSchema>;
|
|
378
378
|
export declare const PROJECTED_UPDATE_KINDS: ReadonlySet<AcpUpdateKind>;
|
|
379
379
|
export declare const turnEndOf: (update: SessionUpdate) => {
|
|
380
380
|
stopReason: string | null;
|
package/dist/modules/channel.mjs
CHANGED
|
@@ -70,24 +70,24 @@ const channelMessageInputSchema = z.object({
|
|
|
70
70
|
quotedMessageIds: z.array(z.string().min(1)).default([]),
|
|
71
71
|
mentionedParticipantIds: z.array(z.string().min(1)).default([])
|
|
72
72
|
});
|
|
73
|
-
var
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
return
|
|
77
|
-
})(
|
|
78
|
-
var
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
return
|
|
82
|
-
})(
|
|
83
|
-
const
|
|
84
|
-
|
|
85
|
-
kind: z.nativeEnum(
|
|
73
|
+
var DecisionEventKind = /* @__PURE__ */ ((DecisionEventKind2) => {
|
|
74
|
+
DecisionEventKind2["Created"] = "decision.created";
|
|
75
|
+
DecisionEventKind2["Resolved"] = "decision.resolved";
|
|
76
|
+
return DecisionEventKind2;
|
|
77
|
+
})(DecisionEventKind || {});
|
|
78
|
+
var DecisionKind = /* @__PURE__ */ ((DecisionKind2) => {
|
|
79
|
+
DecisionKind2["Permission"] = "permission";
|
|
80
|
+
DecisionKind2["Elicitation"] = "elicitation";
|
|
81
|
+
return DecisionKind2;
|
|
82
|
+
})(DecisionKind || {});
|
|
83
|
+
const decisionCreatedDataSchema = z.object({
|
|
84
|
+
decisionId: z.string().min(1),
|
|
85
|
+
kind: z.nativeEnum(DecisionKind),
|
|
86
86
|
audienceParticipantIds: z.array(z.string()),
|
|
87
87
|
request: jsonValueSchema
|
|
88
88
|
});
|
|
89
|
-
const
|
|
90
|
-
|
|
89
|
+
const decisionResolvedDataSchema = z.object({
|
|
90
|
+
decisionId: z.string().min(1),
|
|
91
91
|
outcome: jsonValueSchema,
|
|
92
92
|
respondedBy: channelAuthSchema.nullable().default(null)
|
|
93
93
|
});
|
|
@@ -135,20 +135,20 @@ export {
|
|
|
135
135
|
CardKind,
|
|
136
136
|
ChannelPrincipalType,
|
|
137
137
|
ConversationKind,
|
|
138
|
+
DecisionEventKind,
|
|
139
|
+
DecisionKind,
|
|
138
140
|
Delivery,
|
|
139
141
|
MessageKind,
|
|
140
142
|
PROJECTED_UPDATE_KINDS,
|
|
141
143
|
ParticipantKind,
|
|
142
|
-
PendingEventKind,
|
|
143
|
-
PendingKind,
|
|
144
144
|
RoutingMode,
|
|
145
145
|
TurnPolicy,
|
|
146
146
|
channelAuthSchema,
|
|
147
147
|
channelMessageInputSchema,
|
|
148
148
|
channelReceiveResultSchema,
|
|
149
|
+
decisionCreatedDataSchema,
|
|
150
|
+
decisionResolvedDataSchema,
|
|
149
151
|
defineChannel,
|
|
150
|
-
pendingCreatedDataSchema,
|
|
151
|
-
pendingResolvedDataSchema,
|
|
152
152
|
principalDisplayName,
|
|
153
153
|
turnEndOf,
|
|
154
154
|
turnEndUpdate
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/channel.ts"],
|
|
4
|
-
"sourcesContent": ["import type { HostedBindingsIface } from \"./hosted-bindings.mjs\";\nimport type { ContentBlock, SessionUpdate } from '@agentclientprotocol/sdk/experimental/v2';\nimport type { SessionUpdateKind } from '@finalai/acp-session';\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//\n// Members of a conversation are people and agents. Everything else an agent\n// hears (a schedule, a webhook, a Goal, another agent or channel) is channel\n// input from a principal (`ChannelAuthIface`), sent with\n// `channelSessions.send`; it is never a message.\n\nexport enum ChannelPrincipalType {\n User = 'user',\n Service = 'service',\n}\n\n// Who a channel authenticated for an input or a response. Channels vouch for\n// their principals; one principal per authenticator (`slack:<user>`), so\n// the same person on two surfaces is two principals.\nexport interface ChannelAuthIface extends JsonObject {\n principalId: string;\n principalType: ChannelPrincipalType | `${ChannelPrincipalType}`;\n authenticator: string;\n // `displayName` (a string) when the channel names the principal; see principalDisplayName.\n attributes: JsonObject;\n}\n\nexport const channelAuthSchema = z.object({\n principalId: z.string().min(1),\n principalType: z.nativeEnum(ChannelPrincipalType),\n authenticator: z.string().min(1),\n // How the agent and the people reading its reply name the principal.\n displayName: z.string().min(1).max(200).optional(),\n attributes: jsonObjectSchema.default({}),\n});\n\n// How a principal is named to the agent and in captions: its `displayName`, else its id.\nexport const principalDisplayName = (auth: ChannelAuthIface): string => {\n const name = auth['displayName'];\n return typeof name === 'string' && name.length > 0 ? name : auth.principalId;\n};\n\nexport enum ConversationKind {\n Direct = 'direct',\n Group = 'group',\n}\n\nexport enum ParticipantKind {\n User = 'user',\n Agent = 'agent',\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 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 definitionId: string | 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?: ChannelAuthIface | 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 // The person a prompt from no person acts for (payer and audience).\n actingUserId?: string | null;\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 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?: ChannelAuthIface | null;\n participantId: string;\n pendingId: string;\n outcome: JsonValue;\n actorParticipantId: string;\n userId: 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 // The binding's config and the agent's secrets (manifest.secrets), as receive gets them:\n // a channel posts its replies back to its own service with them.\n config: JsonObject;\n secrets: { get(name: string): Promise<string | null> };\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// The update kinds ACP v2 names; AcpUpdateKind also admits any other string.\nexport type KnownAcpUpdateKind = `${SessionUpdateKind}`;\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,\n// and the principal a channel answered as (null for Final rooms and expiries).\nexport const pendingResolvedDataSchema = z.object({\n pendingRequestId: z.string().min(1),\n outcome: jsonValueSchema,\n respondedBy: channelAuthSchema.nullable().default(null),\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": "AAGA,YAAY,OAAO;AAEnB,SAAS,kBAAkB,uBAAwD;AAgB5E,IAAK,uBAAL,kBAAKA,0BAAL;AACL,EAAAA,sBAAA,UAAO;AACP,EAAAA,sBAAA,aAAU;AAFA,SAAAA;AAAA,GAAA;AAgBL,MAAM,oBAAoB,EAAE,OAAO;AAAA,EACxC,aAAa,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EAC7B,eAAe,EAAE,WAAW,oBAAoB;AAAA,EAChD,eAAe,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA;AAAA,EAE/B,aAAa,EAAE,OAAO,EAAE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C;AAAA,EACzC,EAAE,KAAK;AACT,CAAC;AAqEM,MAAM,4BAA4B,EAAE,OAAO;AAAA,EAChD,gBAAgB,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EAChC,qBAAqB,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACrC,MAAM,EAAE,WAAW,WAAW,EAAE,QAAQ,uBAAmB;AAAA,EAC3D,SAAS,EAAE,MAAM,gBAAgB,EAAE,IAAI,CAAC;AAAA,EACxC,iBAAiB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,QAAQ;AAAA,EAC3C,kBAAkB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,QAAQ;AAAA,EAC5C,cAAc,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,QAAQ;AAAA,EACxC,kBAAkB,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAC;AAAA,EACvD,yBAAyB,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAC;AAChE,CAAC;AAiNM,IAAK,
|
|
6
|
-
"names": ["ChannelPrincipalType", "ConversationKind", "ParticipantKind", "RoutingMode", "TurnPolicy", "Delivery", "MessageKind", "CardKind", "
|
|
4
|
+
"sourcesContent": ["import type { HostedBindingsIface } from \"./hosted-bindings.mjs\";\nimport type { ContentBlock, SessionUpdate } from '@agentclientprotocol/sdk/experimental/v2';\nimport type { SessionUpdateKind } from '@finalai/acp-session';\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//\n// Members of a conversation are people and agents. Everything else an agent\n// hears (a schedule, a webhook, a Goal, another agent or channel) is channel\n// input from a principal (`ChannelAuthIface`), sent with\n// `channelSessions.send`; it is never a message.\n\nexport enum ChannelPrincipalType {\n User = 'user',\n Service = 'service',\n}\n\n// Who a channel authenticated for an input or a response. Channels vouch for\n// their principals; one principal per authenticator (`slack:<user>`), so\n// the same person on two surfaces is two principals.\nexport interface ChannelAuthIface extends JsonObject {\n principalId: string;\n principalType: ChannelPrincipalType | `${ChannelPrincipalType}`;\n authenticator: string;\n // `displayName` (a string) when the channel names the principal; see principalDisplayName.\n attributes: JsonObject;\n}\n\nexport const channelAuthSchema = z.object({\n principalId: z.string().min(1),\n principalType: z.nativeEnum(ChannelPrincipalType),\n authenticator: z.string().min(1),\n // How the agent and the people reading its reply name the principal.\n displayName: z.string().min(1).max(200).optional(),\n attributes: jsonObjectSchema.default({}),\n});\n\n// How a principal is named to the agent and in captions: its `displayName`, else its id.\nexport const principalDisplayName = (auth: ChannelAuthIface): string => {\n const name = auth['displayName'];\n return typeof name === 'string' && name.length > 0 ? name : auth.principalId;\n};\n\nexport enum ConversationKind {\n Direct = 'direct',\n Group = 'group',\n}\n\nexport enum ParticipantKind {\n User = 'user',\n Agent = 'agent',\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 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 definitionId: string | 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 decisionId: 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?: ChannelAuthIface | 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 decision audience).\n authorParticipantId: string;\n // The person a prompt from no person acts for (payer and audience).\n actingUserId?: string | null;\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 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?: ChannelAuthIface | null;\n participantId: string;\n decisionId: string;\n outcome: JsonValue;\n actorParticipantId: string;\n userId: 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 // The binding's config and the agent's secrets (manifest.secrets), as receive gets them:\n // a channel posts its replies back to its own service with them.\n config: JsonObject;\n secrets: { get(name: string): Promise<string | null> };\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 DecisionEventKind {\n Created = 'decision.created',\n Resolved = 'decision.resolved',\n}\n\nexport type AcpUpdateKind = SessionUpdate['sessionUpdate'];\n// The update kinds ACP v2 names; AcpUpdateKind also admits any other string.\nexport type KnownAcpUpdateKind = `${SessionUpdateKind}`;\n\nexport type ChannelEventKind =\n | AcpUpdateKind\n | `${DecisionEventKind}`\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 DecisionKind {\n Permission = 'permission',\n Elicitation = 'elicitation',\n}\n\n// `data` of a decision.created event: an ACP session/request_permission or\n// elicitation/create request awaiting its audience.\nexport const decisionCreatedDataSchema = z.object({\n decisionId: z.string().min(1),\n kind: z.nativeEnum(DecisionKind),\n audienceParticipantIds: z.array(z.string()),\n request: jsonValueSchema,\n});\n\nexport type DecisionCreatedDataIface = z.infer<typeof decisionCreatedDataSchema>;\n\n// `data` of a decision.resolved event: the answer (or cancellation) as recorded,\n// and the principal a channel answered as (null for Final rooms and expiries).\nexport const decisionResolvedDataSchema = z.object({\n decisionId: z.string().min(1),\n outcome: jsonValueSchema,\n respondedBy: channelAuthSchema.nullable().default(null),\n});\n\nexport type DecisionResolvedDataIface = z.infer<typeof decisionResolvedDataSchema>;\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": "AAGA,YAAY,OAAO;AAEnB,SAAS,kBAAkB,uBAAwD;AAgB5E,IAAK,uBAAL,kBAAKA,0BAAL;AACL,EAAAA,sBAAA,UAAO;AACP,EAAAA,sBAAA,aAAU;AAFA,SAAAA;AAAA,GAAA;AAgBL,MAAM,oBAAoB,EAAE,OAAO;AAAA,EACxC,aAAa,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EAC7B,eAAe,EAAE,WAAW,oBAAoB;AAAA,EAChD,eAAe,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA;AAAA,EAE/B,aAAa,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG,EAAE,SAAS;AAAA,EACjD,YAAY,iBAAiB,QAAQ,CAAC,CAAC;AACzC,CAAC;AAGM,MAAM,uBAAuB,CAAC,SAAmC;AACtE,QAAM,OAAO,KAAK,aAAa;AAC/B,SAAO,OAAO,SAAS,YAAY,KAAK,SAAS,IAAI,OAAO,KAAK;AACnE;AAEO,IAAK,mBAAL,kBAAKC,sBAAL;AACL,EAAAA,kBAAA,YAAS;AACT,EAAAA,kBAAA,WAAQ;AAFE,SAAAA;AAAA,GAAA;AAKL,IAAK,kBAAL,kBAAKC,qBAAL;AACL,EAAAA,iBAAA,UAAO;AACP,EAAAA,iBAAA,WAAQ;AAFE,SAAAA;AAAA,GAAA;AAKL,IAAK,cAAL,kBAAKC,iBAAL;AACL,EAAAA,aA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AAO;AAC5B,SAAO;AAAA,IACL,YAAY,OAAO,KAAK,cAAc,OAAO,KAAK,QAAQ,UAAU,GAAG,cAAc;AAAA,EACvF;AACF;AAKO,MAAM,gBAAgB,CAAC,eAA6C;AACzE,UAAQ,YAAY;AAAA,IAClB,KAAK;AACH,aAAO,EAAE,eAAe,gBAAgB,OAAO,OAAO;AAAA,IACxD,KAAK;AACH,aAAO,EAAE,eAAe,gBAAgB,OAAO,QAAQ,YAAY,WAAW;AAAA,IAChF,KAAK;AACH,aAAO,EAAE,eAAe,gBAAgB,OAAO,QAAQ,YAAY,aAAa;AAAA,IAClF,KAAK;AACH,aAAO,EAAE,eAAe,gBAAgB,OAAO,QAAQ,YAAY,oBAAoB;AAAA,IACzF,KAAK;AACH,aAAO,EAAE,eAAe,gBAAgB,OAAO,QAAQ,YAAY,UAAU;AAAA,IAC/E,KAAK;AACH,aAAO,EAAE,eAAe,gBAAgB,OAAO,QAAQ,YAAY,YAAY;AAAA,IACjF;AACE,aAAO;AAAA,QACL,eAAe;AAAA,QACf,OAAO;AAAA,QACP,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE;AAAA,MACtC;AAAA,EACJ;AACF;AA2BO,MAAM,gBAAgB,CAC3B,eAC2C;",
|
|
6
|
+
"names": ["ChannelPrincipalType", "ConversationKind", "ParticipantKind", "RoutingMode", "TurnPolicy", "Delivery", "MessageKind", "CardKind", "DecisionEventKind", "DecisionKind"]
|
|
7
7
|
}
|
|
@@ -239,6 +239,10 @@ export declare const mcpServerBindingSchema: z.ZodDiscriminatedUnion<[z.ZodObjec
|
|
|
239
239
|
dynamic: z.ZodOptional<z.ZodType<import("./json.mjs").JsonObject, unknown, z.core.$ZodTypeInternals<import("./json.mjs").JsonObject, unknown>>>;
|
|
240
240
|
}, z.core.$strip>>>;
|
|
241
241
|
}, z.core.$strip>], "kind">;
|
|
242
|
+
export declare const sandboxCredentialRefSchema: z.ZodObject<{
|
|
243
|
+
secretRef: z.ZodString;
|
|
244
|
+
}, z.core.$strict>;
|
|
245
|
+
export type SandboxCredentialRefIface = z.infer<typeof sandboxCredentialRefSchema>;
|
|
242
246
|
export declare const sandboxBindingSchema: z.ZodObject<{
|
|
243
247
|
provider: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
244
248
|
kind: z.ZodLiteral<import("./provider-ref.mjs").ProviderRefKind.Package>;
|
|
@@ -138,6 +138,9 @@ const mcpServerBindingSchema = z.discriminatedUnion("kind", [
|
|
|
138
138
|
workerMcpServerBindingSchema,
|
|
139
139
|
httpMcpServerBindingSchema
|
|
140
140
|
]);
|
|
141
|
+
const sandboxCredentialRefSchema = z.strictObject({
|
|
142
|
+
secretRef: z.string().min(1).max(256)
|
|
143
|
+
});
|
|
141
144
|
const sandboxBindingSchema = z.object({
|
|
142
145
|
provider: providerRefSchema,
|
|
143
146
|
// Provider-defined environment options (`computer`: a setup guide reference or
|
|
@@ -197,9 +200,8 @@ const agentManifestSchema = z.object({
|
|
|
197
200
|
sandboxes: maybeDynamic(z.record(z.string(), sandboxBindingSchema)),
|
|
198
201
|
tools: baseToolsSchema,
|
|
199
202
|
toolPolicy: z.record(z.string(), z.nativeEnum(ToolApproval)),
|
|
200
|
-
//
|
|
201
|
-
//
|
|
202
|
-
// binding organization secrets requires an organization admin at publish.
|
|
203
|
+
// Secrets this agent may read, by name (`secrets.get`, MCP `secretKey`,
|
|
204
|
+
// `apiKey({ secret })`). Nothing else is readable.
|
|
203
205
|
secrets: z.array(z.string().min(1)).default([]),
|
|
204
206
|
channels: z.array(channelBindingSchema),
|
|
205
207
|
channelSources: z.record(z.string(), z.object({ path: z.string(), source: z.string(), disabled: z.boolean() })).optional(),
|
|
@@ -283,6 +285,7 @@ export {
|
|
|
283
285
|
resolvedAgentManifestSchema,
|
|
284
286
|
sandboxAccessAtLeast,
|
|
285
287
|
sandboxBindingSchema,
|
|
288
|
+
sandboxCredentialRefSchema,
|
|
286
289
|
scheduleDefinitionSchema,
|
|
287
290
|
skillBundleSchema,
|
|
288
291
|
skillFileSchema,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/manifest.ts"],
|
|
4
|
-
"sourcesContent": ["import * as z from 'zod';\nimport { agentAvatarSchema } from '@finalai/agent-protocol';\nimport { containsDynamicSlot, DynamicEvent, maybeDynamic } from \"./dynamic.mjs\";\nimport { jsonObjectSchema, jsonSchemaSchema, jsonValueSchema } from \"./json.mjs\";\nimport { packageRef, providerRefSchema } from \"./provider-ref.mjs\";\n\nexport { agentAvatarSchema, avatarMediaSchema } from '@finalai/agent-protocol';\nexport type { AgentAvatarIface, AvatarMedia, AvatarState } from '@finalai/agent-protocol';\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 avatar: agentAvatarSchema.optional(),\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\n// MCP tool annotation hints a connection policy selects on (./tool-annotations.ts).\nexport const toolAnnotationSelectorSchema = z\n .strictObject({\n readOnlyHint: z.boolean().optional(),\n destructiveHint: z.boolean().optional(),\n idempotentHint: z.boolean().optional(),\n openWorldHint: z.boolean().optional(),\n })\n .refine((selector) => Object.keys(selector).length > 0, 'Select at least one annotation');\n\n// Tools exposed because their annotations match, with the approval (and the\n// connection default's input predicate) they run under.\nexport const toolAnnotationRuleSchema = z.object({\n match: toolAnnotationSelectorSchema,\n approval: z.nativeEnum(ToolApproval),\n inputApproval: inputApprovalSchema.optional(),\n});\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 // Keys are tool names or `*` patterns (./tool-patterns.ts); the most\n // specific matching key governs a tool.\n approvals: toolApprovalsSchema,\n // Tool names or `*` patterns hidden even when `approvals` would expose them.\n deny: z.array(z.string().min(1)).optional(),\n // Exposed tools (names or `*` patterns) the harness lists up front. Absent\n // lists every exposed tool; otherwise the host keeps the rest reachable\n // through search (HOSTING.md).\n load: z.array(z.string().min(1)).optional(),\n // Tools also exposed by their MCP annotations; named tools keep `approvals`.\n allowAnnotations: z.array(toolAnnotationRuleSchema).optional(),\n // Tools hidden by their MCP annotations, whatever else exposes them.\n denyAnnotations: z.array(toolAnnotationSelectorSchema).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 ToolAnnotationSelectorIface = z.infer<typeof toolAnnotationSelectorSchema>;\nexport type ToolAnnotationRuleIface = z.infer<typeof toolAnnotationRuleSchema>;\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 },\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,yBAAyB;AAClC,SAAS,qBAAqB,cAAc,oBAAoB;AAChE,SAAS,kBAAkB,kBAAkB,uBAAuB;AACpE,SAAS,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AEX,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC,EAAE,SAAS;AAAA;AAAA;AAAA;AAAA,EAI1C,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC,EAAE,SAAS;AAAA;AAAA,EAE1C,kBAAkB,EAAE,MAAM,wBAAwB,EAAE,SAAS;AAAA;AAAA,EAE7D,iBAAiB,EAAE,MAAM,4BAA4B,EAAE,SAAS;AAAA;AAAA,EAEhE,iBAAiB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AAAA,EAC5C,gBAAgB,EAAE,OAAO,EAAE,OAAO,GAAG,mBAAmB,EAAE,SAAS;AACrE,CAAC;AAEM,MAAM,yBAAyB,EAAE,mBAAmB,QAAQ;AAAA,EACjE;AAAA,EACA;AACF,CAAC;
|
|
4
|
+
"sourcesContent": ["import * as z from 'zod';\nimport { agentAvatarSchema } from '@finalai/agent-protocol';\nimport { containsDynamicSlot, DynamicEvent, maybeDynamic } from \"./dynamic.mjs\";\nimport { jsonObjectSchema, jsonSchemaSchema, jsonValueSchema } from \"./json.mjs\";\nimport { packageRef, providerRefSchema } from \"./provider-ref.mjs\";\n\nexport { agentAvatarSchema, avatarMediaSchema } from '@finalai/agent-protocol';\nexport type { AgentAvatarIface, AvatarMedia, AvatarState } from '@finalai/agent-protocol';\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 avatar: agentAvatarSchema.optional(),\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\n// MCP tool annotation hints a connection policy selects on (./tool-annotations.ts).\nexport const toolAnnotationSelectorSchema = z\n .strictObject({\n readOnlyHint: z.boolean().optional(),\n destructiveHint: z.boolean().optional(),\n idempotentHint: z.boolean().optional(),\n openWorldHint: z.boolean().optional(),\n })\n .refine((selector) => Object.keys(selector).length > 0, 'Select at least one annotation');\n\n// Tools exposed because their annotations match, with the approval (and the\n// connection default's input predicate) they run under.\nexport const toolAnnotationRuleSchema = z.object({\n match: toolAnnotationSelectorSchema,\n approval: z.nativeEnum(ToolApproval),\n inputApproval: inputApprovalSchema.optional(),\n});\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 // Keys are tool names or `*` patterns (./tool-patterns.ts); the most\n // specific matching key governs a tool.\n approvals: toolApprovalsSchema,\n // Tool names or `*` patterns hidden even when `approvals` would expose them.\n deny: z.array(z.string().min(1)).optional(),\n // Exposed tools (names or `*` patterns) the harness lists up front. Absent\n // lists every exposed tool; otherwise the host keeps the rest reachable\n // through search (HOSTING.md).\n load: z.array(z.string().min(1)).optional(),\n // Tools also exposed by their MCP annotations; named tools keep `approvals`.\n allowAnnotations: z.array(toolAnnotationRuleSchema).optional(),\n // Tools hidden by their MCP annotations, whatever else exposes them.\n denyAnnotations: z.array(toolAnnotationSelectorSchema).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\n// A sandbox provider's credential by reference: `secretRef` is the name of a secret,\n// never its value. Providers take it as `credential` in their environment options.\nexport const sandboxCredentialRefSchema = z.strictObject({\n secretRef: z.string().min(1).max(256),\n});\n\nexport type SandboxCredentialRefIface = z.infer<typeof sandboxCredentialRefSchema>;\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 // Secrets this agent may read, by name (`secrets.get`, MCP `secretKey`,\n // `apiKey({ secret })`). Nothing else is readable.\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 ToolAnnotationSelectorIface = z.infer<typeof toolAnnotationSelectorSchema>;\nexport type ToolAnnotationRuleIface = z.infer<typeof toolAnnotationRuleSchema>;\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 },\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,yBAAyB;AAClC,SAAS,qBAAqB,cAAc,oBAAoB;AAChE,SAAS,kBAAkB,kBAAkB,uBAAuB;AACpE,SAAS,YAAY,yBAAyB;AAE9C,SAAS,qBAAAA,oBAAmB,yBAAyB;AAY9C,MAAM,mBAAmB;AAGzB,IAAK,iBAAL,kBAAKC,oBAAL;AACL,EAAAA,gBAAA,WAAQ;AACR,EAAAA,gBAAA,WAAQ;AACR,EAAAA,gBAAA,aAAU;AACV,EAAAA,gBAAA,WAAQ;AACR,EAAAA,gBAAA,aAAU;AACV,EAAAA,gBAAA,iBAAc;AANJ,SAAAA;AAAA,GAAA;AASL,IAAK,eAAL,kBAAKC,kBAAL;AACL,EAAAA,cAAA,WAAQ;AACR,EAAAA,cAAA,SAAM;AAFI,SAAAA;AAAA,GAAA;AAOL,IAAK,gBAAL,kBAAKC,mBAAL;AACL,EAAAA,eAAA,UAAO;AACP,EAAAA,eAAA,aAAU;AACV,EAAAA,eAAA,WAAQ;AAHE,SAAAA;AAAA,GAAA;AAMZ,MAAM,sBAAsB;AAAA,EAC1B,CAAC,iBAAkB,GAAG;AAAA,EACtB,CAAC,uBAAqB,GAAG;AAAA,EACzB,CAAC,mBAAmB,GAAG;AACzB;AAGO,MAAM,uBAAuB,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;AAAA,EACV,UAAU,CAAC;AAAA,EACX,OAAO,CAAC;AAAA,EACR,WAAW,CAAC;AAAA,EACZ,QAAQ;AACV;",
|
|
6
6
|
"names": ["agentAvatarSchema", "BaseCapability", "ToolApproval", "SandboxAccess", "SandboxAttach", "McpServerBindingKind", "ScheduleTarget", "ScheduleDelivery", "InputApprovalKind", "InstructionRole"]
|
|
7
7
|
}
|
|
@@ -93,6 +93,7 @@ const attachSandboxNetworking = async (options) => {
|
|
|
93
93
|
const controller = options.extension.controller({
|
|
94
94
|
ctx: {
|
|
95
95
|
organizationId: options.ctx.session.organizationId,
|
|
96
|
+
credentials: options.ctx.credentials,
|
|
96
97
|
platformEgressHosts: options.ctx.platformEgressHosts,
|
|
97
98
|
platformNetworkPolicy: options.ctx.platformNetworkPolicy,
|
|
98
99
|
actingUser: options.ctx.actingUser,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/sandbox/networking.ts"],
|
|
4
|
-
"sourcesContent": ["import { createSandboxHandle } from \"./handle.mjs\";\nimport type { SandboxExecutionPolicyIface } from \"./handle.mjs\";\nimport { withSandboxOverrides } from \"./overrides.mjs\";\nimport { SandboxAccess } from \"../manifest.mjs\";\nimport { WorkspaceEgressAction } from '@finalai/agent-protocol/device-egress';\nimport { SandboxExecutionOperation, type SandboxExecutionContextIface } from \"./execution-guard.mjs\";\nimport {\n type NetworkPolicyIface,\n type NetworkSandboxSessionIface,\n type SandboxCapability,\n type SandboxOfferContextIface,\n type SandboxProviderHandleIface,\n type SandboxRunResultIface,\n type SandboxStartContextIface,\n} from \"./types.mjs\";\n\nexport interface SandboxNetworkingContextIface {\n access?: SandboxAccess;\n ctx: SandboxOfferContextIface;\n workspaceId: string;\n}\n\nexport interface SandboxNetworkingControllerOptionsIface extends SandboxNetworkingContextIface {\n sandbox: NetworkSandboxSessionIface;\n access: SandboxAccess;\n initialNetworkPolicy: NetworkPolicyIface;\n // Executes inside the sandbox's network namespace with its required privileges.\n privilegedRun?: (request: { source: string; input: string }) => Promise<SandboxRunResultIface>;\n afterGuard: (policy?: NetworkPolicyIface) => Promise<void>;\n afterBlock?: () => Promise<void>;\n namespaceExists?: () => Promise<boolean>;\n onClose?: () => void;\n allowOwnerChange?: boolean;\n log?: (message: string, fields?: Record<string, string | number | boolean | null>) => void;\n}\n\nexport interface SandboxNetworkingControllerIface {\n initialize(): Promise<void>;\n guard(context?: SandboxExecutionContextIface): Promise<void>;\n close(stop?: boolean): Promise<void>;\n closeOnFailure(): Promise<void>;\n // Extensions may expose networking operations; ordinary execution is guarded afterwards.\n extendSandbox<S extends NetworkSandboxSessionIface>(sandbox: S): S;\n authorizeExternalAccess(): Promise<{ expiresAtMs: number | null }>;\n}\n\n// A host composes an opinionated networking implementation with any compatible provider.\nexport interface SandboxNetworkingExtensionIface {\n readonly capabilities: readonly SandboxCapability[];\n readonly fetch?: typeof globalThis.fetch;\n validateWorkspaceId?(workspaceId: string): void;\n enabled(args: SandboxNetworkingContextIface & { teardown?: boolean }): Promise<boolean>;\n // Return the retained logical policy when it differs from the supplied provider snapshot.\n prepare(\n args: SandboxNetworkingContextIface & { policy: NetworkPolicyIface },\n ): Promise<NetworkPolicyIface | void>;\n suspend(args: SandboxNetworkingContextIface): Promise<void>;\n controller(args: SandboxNetworkingControllerOptionsIface): SandboxNetworkingControllerIface;\n // Custom attachment may coordinate provider setup; it owns admission and failure cleanup.\n attach?<S extends NetworkSandboxSessionIface>(\n args: Omit<AttachSandboxNetworkingOptionsIface<S>, 'extension'>,\n ): Promise<SandboxProviderHandleIface<S>>;\n}\n\nconst finishNetworking = async (args: {\n close: () => Promise<void>;\n finish: () => Promise<void>;\n}): Promise<void> => {\n const failures: unknown[] = [];\n try {\n await args.close();\n } catch (cause) {\n failures.push(cause);\n }\n try {\n await args.finish();\n } catch (cause) {\n failures.push(cause);\n }\n if (failures.length === 1) throw failures[0];\n if (failures.length > 1)\n throw new AggregateError(failures, 'Sandbox networking and cleanup failed');\n};\n\nexport interface WithSandboxNetworkingOptionsIface<S extends NetworkSandboxSessionIface> {\n handle: SandboxProviderHandleIface<S>;\n access: SandboxAccess;\n controller?: SandboxNetworkingControllerIface;\n admission?: () => Promise<void>;\n beforeUse?: () => Promise<void>;\n initialized?: boolean;\n fetch?: typeof globalThis.fetch;\n executionPolicy?: SandboxExecutionPolicyIface;\n}\n\nexport const withSandboxNetworking = async <S extends NetworkSandboxSessionIface>(\n options: WithSandboxNetworkingOptionsIface<S>,\n): Promise<SandboxProviderHandleIface<S>> => {\n const { handle, controller } = options;\n if (options.access === SandboxAccess.Read) return handle;\n if (controller != null && options.initialized !== true) {\n try {\n await controller.initialize();\n } catch (cause) {\n await finishNetworking({\n close: () => controller.closeOnFailure(),\n finish: async () => {\n throw cause;\n },\n });\n }\n }\n const source = handle.sandbox;\n const extended = controller?.extendSandbox(source) ?? source;\n const egress = extended.egress?.bind(extended);\n const sandbox =\n options.access === SandboxAccess.Execute && egress != null\n ? withSandboxOverrides(extended, {\n egress: async (request: Parameters<typeof egress>[0]) => {\n if (request.action !== WorkspaceEgressAction.Status)\n throw new Error('Workspace egress configuration requires write access');\n return egress(request);\n },\n })\n : extended;\n return createSandboxHandle({\n executionPolicy: options.executionPolicy,\n handle: withSandboxOverrides(handle, {\n sandbox: withSandboxOverrides(sandbox, {\n stop: () =>\n finishNetworking({\n close: () => controller?.close(true) ?? Promise.resolve(),\n finish: () => source.stop(),\n }),\n destroy: () =>\n finishNetworking({\n close: () => controller?.close(true) ?? Promise.resolve(),\n finish: () => source.destroy(),\n }),\n }),\n executionPolicy: {\n fetch: handle.executionPolicy?.fetch ?? options.fetch ?? options.executionPolicy?.fetch,\n beforeExecution: async (context: SandboxExecutionContextIface) => {\n await handle.executionPolicy?.beforeExecution(context);\n await options.admission?.();\n await controller?.guard(context);\n if (\n !context.background &&\n ![\n SandboxExecutionOperation.SetNetworkPolicy,\n SandboxExecutionOperation.Egress,\n ].includes(context.operation)\n )\n await options.beforeUse?.();\n },\n },\n onRuntimeShutdown: () =>\n finishNetworking({\n close: () => controller?.close(false) ?? Promise.resolve(),\n finish: () => handle.onRuntimeShutdown(),\n }),\n onSandboxStop: () =>\n finishNetworking({\n close: () => controller?.close(true) ?? Promise.resolve(),\n finish: () => handle.onSandboxStop(),\n }),\n onSandboxDelete: (args: Parameters<typeof handle.onSandboxDelete>[0]) =>\n finishNetworking({\n close: () => controller?.close(true) ?? Promise.resolve(),\n finish: () => handle.onSandboxDelete(args),\n }),\n }),\n });\n};\n\nexport interface AttachSandboxNetworkingOptionsIface<S extends NetworkSandboxSessionIface> {\n extension: SandboxNetworkingExtensionIface;\n ctx: SandboxStartContextIface;\n handle: SandboxProviderHandleIface<S>;\n access: SandboxAccess;\n workspaceId: string;\n initialNetworkPolicy: NetworkPolicyIface;\n restoreNetwork: (policy?: NetworkPolicyIface) => Promise<void>;\n blockNetwork?: () => Promise<void>;\n namespaceExists?: () => Promise<boolean>;\n beforeUse: () => Promise<void>;\n log?: SandboxNetworkingControllerOptionsIface['log'];\n}\n\nexport const attachSandboxNetworking = async <S extends NetworkSandboxSessionIface>(\n options: AttachSandboxNetworkingOptionsIface<S>,\n): Promise<SandboxProviderHandleIface<S>> => {\n if (options.access === SandboxAccess.Read) return options.handle;\n if (options.extension.attach != null) return options.extension.attach(options);\n const controller = options.extension.controller({\n ctx: {\n organizationId: options.ctx.session.organizationId,\n platformEgressHosts: options.ctx.platformEgressHosts,\n platformNetworkPolicy: options.ctx.platformNetworkPolicy,\n actingUser: options.ctx.actingUser,\n bindings: options.ctx.bindings,\n },\n sandbox: options.handle.sandbox,\n access: options.access,\n workspaceId: options.workspaceId,\n initialNetworkPolicy: options.initialNetworkPolicy,\n afterGuard: options.restoreNetwork,\n afterBlock: options.blockNetwork,\n namespaceExists: options.namespaceExists,\n log: options.log,\n });\n try {\n await controller.initialize();\n let ready = true;\n try {\n const setupContext = { operation: SandboxExecutionOperation.Run, background: false };\n await options.ctx.executionPolicy?.beforeExecution(setupContext);\n await options.handle.executionPolicy?.beforeExecution(setupContext);\n await controller.guard();\n } catch (cause) {\n ready = false;\n options.log?.('workspace_networking.setup_deferred', {\n workspaceId: options.workspaceId,\n reason: cause instanceof Error ? cause.name : 'UnknownError',\n });\n }\n if (ready) await options.beforeUse();\n return await withSandboxNetworking({\n handle: options.handle,\n controller,\n access: options.access,\n beforeUse: options.beforeUse,\n initialized: true,\n fetch: options.extension.fetch,\n executionPolicy: options.ctx.executionPolicy,\n });\n } catch (cause) {\n await finishNetworking({\n close: () => controller.closeOnFailure(),\n finish: async () => {\n throw cause;\n },\n });\n throw cause;\n }\n};\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,2BAA2B;AAEpC,SAAS,4BAA4B;AACrC,SAAS,qBAAqB;AAC9B,SAAS,6BAA6B;AACtC,SAAS,iCAAoE;AAC7E;AAAA,OAQO;AAkDP,MAAM,mBAAmB,OAAO,SAGX;AACnB,QAAM,WAAsB,CAAC;AAC7B,MAAI;AACF,UAAM,KAAK,MAAM;AAAA,EACnB,SAAS,OAAO;AACd,aAAS,KAAK,KAAK;AAAA,EACrB;AACA,MAAI;AACF,UAAM,KAAK,OAAO;AAAA,EACpB,SAAS,OAAO;AACd,aAAS,KAAK,KAAK;AAAA,EACrB;AACA,MAAI,SAAS,WAAW,EAAG,OAAM,SAAS,CAAC;AAC3C,MAAI,SAAS,SAAS;AACpB,UAAM,IAAI,eAAe,UAAU,uCAAuC;AAC9E;AAaO,MAAM,wBAAwB,OACnC,YAC2C;AAC3C,QAAM,EAAE,QAAQ,WAAW,IAAI;AAC/B,MAAI,QAAQ,WAAW,cAAc,KAAM,QAAO;AAClD,MAAI,cAAc,QAAQ,QAAQ,gBAAgB,MAAM;AACtD,QAAI;AACF,YAAM,WAAW,WAAW;AAAA,IAC9B,SAAS,OAAO;AACd,YAAM,iBAAiB;AAAA,QACrB,OAAO,MAAM,WAAW,eAAe;AAAA,QACvC,QAAQ,YAAY;AAClB,gBAA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nF,YAAM,QAAQ,IAAI,iBAAiB,gBAAgB,YAAY;AAC/D,YAAM,QAAQ,OAAO,iBAAiB,gBAAgB,YAAY;AAClE,YAAM,WAAW,MAAM;AAAA,IACzB,SAAS,OAAO;AACd,cAAQ;AACR,cAAQ,MAAM,uCAAuC;AAAA,QACnD,aAAa,QAAQ;AAAA,QACrB,QAAQ,iBAAiB,QAAQ,MAAM,OAAO;AAAA,MAChD,CAAC;AAAA,IACH;AACA,QAAI,MAAO,OAAM,QAAQ,UAAU;AACnC,WAAO,MAAM,sBAAsB;AAAA,MACjC,QAAQ,QAAQ;AAAA,MAChB;AAAA,MACA,QAAQ,QAAQ;AAAA,MAChB,WAAW,QAAQ;AAAA,MACnB,aAAa;AAAA,MACb,OAAO,QAAQ,UAAU;AAAA,MACzB,iBAAiB,QAAQ,IAAI;AAAA,IAC/B,CAAC;AAAA,EACH,SAAS,OAAO;AACd,UAAM,iBAAiB;AAAA,MACrB,OAAO,MAAM,WAAW,eAAe;AAAA,MACvC,QAAQ,YAAY;AAClB,cAAM;AAAA,MACR;AAAA,IACF,CAAC;AACD,UAAM;AAAA,EACR;AACF;",
|
|
4
|
+
"sourcesContent": ["import { createSandboxHandle } from \"./handle.mjs\";\nimport type { SandboxExecutionPolicyIface } from \"./handle.mjs\";\nimport { withSandboxOverrides } from \"./overrides.mjs\";\nimport { SandboxAccess } from \"../manifest.mjs\";\nimport { WorkspaceEgressAction } from '@finalai/agent-protocol/device-egress';\nimport { SandboxExecutionOperation, type SandboxExecutionContextIface } from \"./execution-guard.mjs\";\nimport {\n type NetworkPolicyIface,\n type NetworkSandboxSessionIface,\n type SandboxCapability,\n type SandboxOfferContextIface,\n type SandboxProviderHandleIface,\n type SandboxRunResultIface,\n type SandboxStartContextIface,\n} from \"./types.mjs\";\n\nexport interface SandboxNetworkingContextIface {\n access?: SandboxAccess;\n ctx: SandboxOfferContextIface;\n workspaceId: string;\n}\n\nexport interface SandboxNetworkingControllerOptionsIface extends SandboxNetworkingContextIface {\n sandbox: NetworkSandboxSessionIface;\n access: SandboxAccess;\n initialNetworkPolicy: NetworkPolicyIface;\n // Executes inside the sandbox's network namespace with its required privileges.\n privilegedRun?: (request: { source: string; input: string }) => Promise<SandboxRunResultIface>;\n afterGuard: (policy?: NetworkPolicyIface) => Promise<void>;\n afterBlock?: () => Promise<void>;\n namespaceExists?: () => Promise<boolean>;\n onClose?: () => void;\n allowOwnerChange?: boolean;\n log?: (message: string, fields?: Record<string, string | number | boolean | null>) => void;\n}\n\nexport interface SandboxNetworkingControllerIface {\n initialize(): Promise<void>;\n guard(context?: SandboxExecutionContextIface): Promise<void>;\n close(stop?: boolean): Promise<void>;\n closeOnFailure(): Promise<void>;\n // Extensions may expose networking operations; ordinary execution is guarded afterwards.\n extendSandbox<S extends NetworkSandboxSessionIface>(sandbox: S): S;\n authorizeExternalAccess(): Promise<{ expiresAtMs: number | null }>;\n}\n\n// A host composes an opinionated networking implementation with any compatible provider.\nexport interface SandboxNetworkingExtensionIface {\n readonly capabilities: readonly SandboxCapability[];\n readonly fetch?: typeof globalThis.fetch;\n validateWorkspaceId?(workspaceId: string): void;\n enabled(args: SandboxNetworkingContextIface & { teardown?: boolean }): Promise<boolean>;\n // Return the retained logical policy when it differs from the supplied provider snapshot.\n prepare(\n args: SandboxNetworkingContextIface & { policy: NetworkPolicyIface },\n ): Promise<NetworkPolicyIface | void>;\n suspend(args: SandboxNetworkingContextIface): Promise<void>;\n controller(args: SandboxNetworkingControllerOptionsIface): SandboxNetworkingControllerIface;\n // Custom attachment may coordinate provider setup; it owns admission and failure cleanup.\n attach?<S extends NetworkSandboxSessionIface>(\n args: Omit<AttachSandboxNetworkingOptionsIface<S>, 'extension'>,\n ): Promise<SandboxProviderHandleIface<S>>;\n}\n\nconst finishNetworking = async (args: {\n close: () => Promise<void>;\n finish: () => Promise<void>;\n}): Promise<void> => {\n const failures: unknown[] = [];\n try {\n await args.close();\n } catch (cause) {\n failures.push(cause);\n }\n try {\n await args.finish();\n } catch (cause) {\n failures.push(cause);\n }\n if (failures.length === 1) throw failures[0];\n if (failures.length > 1)\n throw new AggregateError(failures, 'Sandbox networking and cleanup failed');\n};\n\nexport interface WithSandboxNetworkingOptionsIface<S extends NetworkSandboxSessionIface> {\n handle: SandboxProviderHandleIface<S>;\n access: SandboxAccess;\n controller?: SandboxNetworkingControllerIface;\n admission?: () => Promise<void>;\n beforeUse?: () => Promise<void>;\n initialized?: boolean;\n fetch?: typeof globalThis.fetch;\n executionPolicy?: SandboxExecutionPolicyIface;\n}\n\nexport const withSandboxNetworking = async <S extends NetworkSandboxSessionIface>(\n options: WithSandboxNetworkingOptionsIface<S>,\n): Promise<SandboxProviderHandleIface<S>> => {\n const { handle, controller } = options;\n if (options.access === SandboxAccess.Read) return handle;\n if (controller != null && options.initialized !== true) {\n try {\n await controller.initialize();\n } catch (cause) {\n await finishNetworking({\n close: () => controller.closeOnFailure(),\n finish: async () => {\n throw cause;\n },\n });\n }\n }\n const source = handle.sandbox;\n const extended = controller?.extendSandbox(source) ?? source;\n const egress = extended.egress?.bind(extended);\n const sandbox =\n options.access === SandboxAccess.Execute && egress != null\n ? withSandboxOverrides(extended, {\n egress: async (request: Parameters<typeof egress>[0]) => {\n if (request.action !== WorkspaceEgressAction.Status)\n throw new Error('Workspace egress configuration requires write access');\n return egress(request);\n },\n })\n : extended;\n return createSandboxHandle({\n executionPolicy: options.executionPolicy,\n handle: withSandboxOverrides(handle, {\n sandbox: withSandboxOverrides(sandbox, {\n stop: () =>\n finishNetworking({\n close: () => controller?.close(true) ?? Promise.resolve(),\n finish: () => source.stop(),\n }),\n destroy: () =>\n finishNetworking({\n close: () => controller?.close(true) ?? Promise.resolve(),\n finish: () => source.destroy(),\n }),\n }),\n executionPolicy: {\n fetch: handle.executionPolicy?.fetch ?? options.fetch ?? options.executionPolicy?.fetch,\n beforeExecution: async (context: SandboxExecutionContextIface) => {\n await handle.executionPolicy?.beforeExecution(context);\n await options.admission?.();\n await controller?.guard(context);\n if (\n !context.background &&\n ![\n SandboxExecutionOperation.SetNetworkPolicy,\n SandboxExecutionOperation.Egress,\n ].includes(context.operation)\n )\n await options.beforeUse?.();\n },\n },\n onRuntimeShutdown: () =>\n finishNetworking({\n close: () => controller?.close(false) ?? Promise.resolve(),\n finish: () => handle.onRuntimeShutdown(),\n }),\n onSandboxStop: () =>\n finishNetworking({\n close: () => controller?.close(true) ?? Promise.resolve(),\n finish: () => handle.onSandboxStop(),\n }),\n onSandboxDelete: (args: Parameters<typeof handle.onSandboxDelete>[0]) =>\n finishNetworking({\n close: () => controller?.close(true) ?? Promise.resolve(),\n finish: () => handle.onSandboxDelete(args),\n }),\n }),\n });\n};\n\nexport interface AttachSandboxNetworkingOptionsIface<S extends NetworkSandboxSessionIface> {\n extension: SandboxNetworkingExtensionIface;\n ctx: SandboxStartContextIface;\n handle: SandboxProviderHandleIface<S>;\n access: SandboxAccess;\n workspaceId: string;\n initialNetworkPolicy: NetworkPolicyIface;\n restoreNetwork: (policy?: NetworkPolicyIface) => Promise<void>;\n blockNetwork?: () => Promise<void>;\n namespaceExists?: () => Promise<boolean>;\n beforeUse: () => Promise<void>;\n log?: SandboxNetworkingControllerOptionsIface['log'];\n}\n\nexport const attachSandboxNetworking = async <S extends NetworkSandboxSessionIface>(\n options: AttachSandboxNetworkingOptionsIface<S>,\n): Promise<SandboxProviderHandleIface<S>> => {\n if (options.access === SandboxAccess.Read) return options.handle;\n if (options.extension.attach != null) return options.extension.attach(options);\n const controller = options.extension.controller({\n ctx: {\n organizationId: options.ctx.session.organizationId,\n credentials: options.ctx.credentials,\n platformEgressHosts: options.ctx.platformEgressHosts,\n platformNetworkPolicy: options.ctx.platformNetworkPolicy,\n actingUser: options.ctx.actingUser,\n bindings: options.ctx.bindings,\n },\n sandbox: options.handle.sandbox,\n access: options.access,\n workspaceId: options.workspaceId,\n initialNetworkPolicy: options.initialNetworkPolicy,\n afterGuard: options.restoreNetwork,\n afterBlock: options.blockNetwork,\n namespaceExists: options.namespaceExists,\n log: options.log,\n });\n try {\n await controller.initialize();\n let ready = true;\n try {\n const setupContext = { operation: SandboxExecutionOperation.Run, background: false };\n await options.ctx.executionPolicy?.beforeExecution(setupContext);\n await options.handle.executionPolicy?.beforeExecution(setupContext);\n await controller.guard();\n } catch (cause) {\n ready = false;\n options.log?.('workspace_networking.setup_deferred', {\n workspaceId: options.workspaceId,\n reason: cause instanceof Error ? cause.name : 'UnknownError',\n });\n }\n if (ready) await options.beforeUse();\n return await withSandboxNetworking({\n handle: options.handle,\n controller,\n access: options.access,\n beforeUse: options.beforeUse,\n initialized: true,\n fetch: options.extension.fetch,\n executionPolicy: options.ctx.executionPolicy,\n });\n } catch (cause) {\n await finishNetworking({\n close: () => controller.closeOnFailure(),\n finish: async () => {\n throw cause;\n },\n });\n throw cause;\n }\n};\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,2BAA2B;AAEpC,SAAS,4BAA4B;AACrC,SAAS,qBAAqB;AAC9B,SAAS,6BAA6B;AACtC,SAAS,iCAAoE;AAC7E;AAAA,OAQO;AAkDP,MAAM,mBAAmB,OAAO,SAGX;AACnB,QAAM,WAAsB,CAAC;AAC7B,MAAI;AACF,UAAM,KAAK,MAAM;AAAA,EACnB,SAAS,OAAO;AACd,aAAS,KAAK,KAAK;AAAA,EACrB;AACA,MAAI;AACF,UAAM,KAAK,OAAO;AAAA,EACpB,SAAS,OAAO;AACd,aAAS,KAAK,KAAK;AAAA,EACrB;AACA,MAAI,SAAS,WAAW,EAAG,OAAM,SAAS,CAAC;AAC3C,MAAI,SAAS,SAAS;AACpB,UAAM,IAAI,eAAe,UAAU,uCAAuC;AAC9E;AAaO,MAAM,wBAAwB,OACnC,YAC2C;AAC3C,QAAM,EAAE,QAAQ,WAAW,IAAI;AAC/B,MAAI,QAAQ,WAAW,cAAc,KAAM,QAAO;AAClD,MAAI,cAAc,QAAQ,QAAQ,gBAAgB,MAAM;AACtD,QAAI;AACF,YAAM,WAAW,WAAW;AAAA,IAC9B,SAAS,OA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C;AACD,MAAI;AACF,UAAM,WAAW,WAAW;AAC5B,QAAI,QAAQ;AACZ,QAAI;AACF,YAAM,eAAe,EAAE,WAAW,0BAA0B,KAAK,YAAY,MAAM;AACnF,YAAM,QAAQ,IAAI,iBAAiB,gBAAgB,YAAY;AAC/D,YAAM,QAAQ,OAAO,iBAAiB,gBAAgB,YAAY;AAClE,YAAM,WAAW,MAAM;AAAA,IACzB,SAAS,OAAO;AACd,cAAQ;AACR,cAAQ,MAAM,uCAAuC;AAAA,QACnD,aAAa,QAAQ;AAAA,QACrB,QAAQ,iBAAiB,QAAQ,MAAM,OAAO;AAAA,MAChD,CAAC;AAAA,IACH;AACA,QAAI,MAAO,OAAM,QAAQ,UAAU;AACnC,WAAO,MAAM,sBAAsB;AAAA,MACjC,QAAQ,QAAQ;AAAA,MAChB;AAAA,MACA,QAAQ,QAAQ;AAAA,MAChB,WAAW,QAAQ;AAAA,MACnB,aAAa;AAAA,MACb,OAAO,QAAQ,UAAU;AAAA,MACzB,iBAAiB,QAAQ,IAAI;AAAA,IAC/B,CAAC;AAAA,EACH,SAAS,OAAO;AACd,UAAM,iBAAiB;AAAA,MACrB,OAAO,MAAM,WAAW,eAAe;AAAA,MACvC,QAAQ,YAAY;AAClB,cAAM;AAAA,MACR;AAAA,IACF,CAAC;AACD,UAAM;AAAA,EACR;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -233,6 +233,23 @@ export interface SandboxActingUserIface {
|
|
|
233
233
|
current(): Promise<string | null>;
|
|
234
234
|
}
|
|
235
235
|
export declare const noSandboxActingUser: SandboxActingUserIface;
|
|
236
|
+
export interface FinalPlatformAccessIface {
|
|
237
|
+
baseUrl: string;
|
|
238
|
+
token: string;
|
|
239
|
+
}
|
|
240
|
+
export interface SandboxCredentialsIface {
|
|
241
|
+
computersAccess(args?: {
|
|
242
|
+
refresh?: boolean;
|
|
243
|
+
}): Promise<FinalPlatformAccessIface | null>;
|
|
244
|
+
deviceAccess(args?: {
|
|
245
|
+
actingUserId?: string | null;
|
|
246
|
+
refresh?: boolean;
|
|
247
|
+
}): Promise<FinalPlatformAccessIface | null>;
|
|
248
|
+
secret(args: {
|
|
249
|
+
secretRef: string;
|
|
250
|
+
}): Promise<string | null>;
|
|
251
|
+
}
|
|
252
|
+
export declare const noSandboxCredentials: SandboxCredentialsIface;
|
|
236
253
|
export interface SandboxOfferContextIface {
|
|
237
254
|
executionPolicy?: SandboxExecutionPolicyIface;
|
|
238
255
|
platformNetworkPolicy?: (policy: NetworkPolicyIface) => Promise<void>;
|
|
@@ -240,6 +257,7 @@ export interface SandboxOfferContextIface {
|
|
|
240
257
|
workspaceId?: string;
|
|
241
258
|
bindings?: HostedBindingsIface;
|
|
242
259
|
organizationId: string;
|
|
260
|
+
credentials?: SandboxCredentialsIface;
|
|
243
261
|
actingUser: SandboxActingUserIface;
|
|
244
262
|
}
|
|
245
263
|
export interface SandboxEnvironmentContextIface {
|
|
@@ -267,6 +285,7 @@ export interface SandboxPrepareContextIface {
|
|
|
267
285
|
sourceRevision: string;
|
|
268
286
|
storagePath: string;
|
|
269
287
|
organizationId: string;
|
|
288
|
+
credentials?: SandboxCredentialsIface;
|
|
270
289
|
guides: SandboxGuidesIface;
|
|
271
290
|
actingUser: SandboxActingUserIface;
|
|
272
291
|
log?: (message: string) => void;
|
|
@@ -286,6 +305,7 @@ export interface SandboxStartContextIface {
|
|
|
286
305
|
workspaceId?: string;
|
|
287
306
|
target: string;
|
|
288
307
|
};
|
|
308
|
+
credentials?: SandboxCredentialsIface;
|
|
289
309
|
storagePath: string;
|
|
290
310
|
guides: SandboxGuidesIface;
|
|
291
311
|
variables: SandboxVariablesIface;
|
|
@@ -39,6 +39,11 @@ const noSandboxRepositories = {
|
|
|
39
39
|
};
|
|
40
40
|
const noSandboxVariables = { get: async () => null };
|
|
41
41
|
const noSandboxActingUser = { current: async () => null };
|
|
42
|
+
const noSandboxCredentials = {
|
|
43
|
+
computersAccess: async () => null,
|
|
44
|
+
deviceAccess: async () => null,
|
|
45
|
+
secret: async () => null
|
|
46
|
+
};
|
|
42
47
|
const PLATFORM_ENVIRONMENT_NAMES = /* @__PURE__ */ new Set([
|
|
43
48
|
"HTTPS_PROXY",
|
|
44
49
|
"HTTP_PROXY",
|
|
@@ -151,6 +156,7 @@ export {
|
|
|
151
156
|
defineSandboxProvider,
|
|
152
157
|
isMcpChannelEndpoint,
|
|
153
158
|
noSandboxActingUser,
|
|
159
|
+
noSandboxCredentials,
|
|
154
160
|
noSandboxGuides,
|
|
155
161
|
noSandboxRepositories,
|
|
156
162
|
noSandboxVariables,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/sandbox/types.ts"],
|
|
4
|
-
"sourcesContent": ["import { SandboxEntryType } from \"./file-kind.mjs\";\nexport { SandboxEntryType } from \"./file-kind.mjs\";\nimport type { HostedBindingsIface } from \"../hosted-bindings.mjs\";\nimport { createSandboxHandle, type SandboxExecutionPolicyIface } from \"./handle.mjs\";\nimport { withSandboxOverrides } from \"./overrides.mjs\";\nimport { WorkspaceNetworkPolicy as NetworkPolicy } from '@finalai/agent-protocol/device-egress';\nimport type {\n WorkspaceEgressRequestIface,\n WorkspaceEgressStatusIface,\n WorkspaceNetworkPolicyIface as NetworkPolicyIface,\n} from '@finalai/agent-protocol/device-egress';\nexport {\n WorkspaceNetworkPolicy as NetworkPolicy,\n type WorkspaceNetworkPolicyIface as NetworkPolicyIface,\n} from '@finalai/agent-protocol/device-egress';\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 {\n SandboxEditorOperation,\n type SandboxEditorRequestIface,\n type SandboxEditorResultIface,\n} from \"./editor.mjs\";\nimport { SandboxExecutionOperation } from \"./execution-guard.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 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 // Writes create missing parent directories.\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 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 // Partial discovery retains known tools and must be retried, including after caching.\n localMcpIncomplete?: boolean;\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 egress?(request: WorkspaceEgressRequestIface): Promise<WorkspaceEgressStatusIface>;\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 Egress = 'egress',\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 // Pending policy; the generic handle constructor consumes it before exposing execution.\n readonly executionPolicy?: SandboxExecutionPolicyIface;\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 executionPolicy?: SandboxExecutionPolicyIface;\n platformNetworkPolicy?: (policy: NetworkPolicyIface) => Promise<void>;\n // Retain platform transport access when an extension restores an allowlist.\n platformEgressHosts?: string[];\n // Logical identity when inspecting an existing workspace or opening an execution extension.\n workspaceId?: string;\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 // Host policy composes before the provider's policy, on every exposed execution path.\n executionPolicy?: SandboxExecutionPolicyIface;\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 // Stable logical identity supplied by the host, independent of provider resource names.\n workspaceId?: 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 // Variables the platform sets in every process of this sandbox: the egress\n // proxy, trust for its CA, and one placeholder per bound secret. Evaluated\n // again for every spawn/run, never once per session: a secret bound\n // mid-session must reach the next command. May resolve to {} (no proxy\n // configured, or not ready yet). Platform values override the spec's env.\n platformEnvironment?: () => Promise<Record<string, string>>;\n // Hosts the sandbox must be able to reach for the proxy to work, to append\n // to any allowlist-mode network policy the spec declares.\n platformEgressHosts?: string[];\n // Reports the network policy now in force on the sandbox, exactly as the\n // provider applied it to its backend (after withPlatformEgressHosts). The\n // platform records it so the egress proxy serves only those destinations.\n // Called after awaitRunning and before platformFiles or any command, on start,\n // resume and a reused sandbox; never for a session's own setNetworkPolicy,\n // which the platform records itself. A rejection fails the start or resume.\n platformNetworkPolicy: (policy: NetworkPolicyIface) => Promise<void>;\n // Files the platform needs in the sandbox before any clone, setup step or\n // service runs: written right after the sandbox exists, on start and resume.\n // Paths are absolute; missing parent directories are created.\n platformFiles?: () => Promise<Record<string, string>>;\n}\n\n// The variables `platformEnvironment` owns. A spec that sets one (as a plain\n// value or an organization variable) is refused at start.\nexport const PLATFORM_ENVIRONMENT_NAMES: ReadonlySet<string> = new Set([\n 'HTTPS_PROXY',\n 'HTTP_PROXY',\n 'NO_PROXY',\n 'NODE_USE_ENV_PROXY',\n 'SSL_CERT_FILE',\n 'CURL_CA_BUNDLE',\n 'REQUESTS_CA_BUNDLE',\n 'GIT_SSL_CAINFO',\n 'CARGO_HTTP_CAINFO',\n 'DENO_CERT',\n 'NODE_EXTRA_CA_CERTS',\n 'FINAL_EGRESS_URL',\n 'FINAL_EGRESS_TOKEN',\n 'GH_TOKEN',\n 'GITHUB_TOKEN',\n]);\n\n// A process's base environment: the spec's variables under the platform's,\n// read again on every call.\nexport const platformProcessEnvironment =\n (\n ctx: Pick<SandboxStartContextIface, 'platformEnvironment'>,\n specEnv: Record<string, string>,\n ): (() => Promise<Record<string, string>>) =>\n async () => ({ ...specEnv, ...(await ctx.platformEnvironment?.()) });\n\n// Writes `platformFiles` into a sandbox that now exists, before it runs anything.\n// Relies on writeTextFile creating missing parent directories.\nexport const writePlatformFiles = async (\n ctx: Pick<SandboxStartContextIface, 'platformFiles'>,\n sandbox: Pick<SandboxSessionIface, 'writeTextFile'>,\n): Promise<void> => {\n for (const [path, content] of Object.entries((await ctx.platformFiles?.()) ?? {}))\n await sandbox.writeTextFile({ path, content });\n};\n\n// Reports the policy a provider just applied to its backend: `allow` only for an\n// allowlist, its entries (hosts, `*.suffix` patterns, CIDRs) unchanged.\nexport const reportPlatformNetworkPolicy = async (\n ctx: Pick<SandboxStartContextIface, 'platformNetworkPolicy'>,\n policy: NetworkPolicyIface,\n): Promise<void> =>\n ctx.platformNetworkPolicy(\n policy.mode === NetworkPolicy.Allowlist\n ? { mode: policy.mode, allow: [...(policy.allow ?? [])] }\n : { mode: policy.mode },\n );\n\n// An allowlist policy with the platform's egress hosts appended; any other\n// policy unchanged.\nexport const withPlatformEgressHosts = (\n ctx: Pick<SandboxStartContextIface, 'platformEgressHosts'>,\n policy: NetworkPolicyIface,\n): NetworkPolicyIface => {\n const hosts = ctx.platformEgressHosts ?? [];\n if (policy.mode !== NetworkPolicy.Allowlist || hosts.length === 0) return policy;\n return { ...policy, allow: [...new Set([...(policy.allow ?? []), ...hosts])] };\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 // Known positive offers when the rest of the pre-start capability set is unknown.\n additionalCapabilities?(ctx: SandboxOfferContextIface): Promise<SandboxCapability[]>;\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 // Resolves once the backend sandbox named by `state` is running and will\n // accept a command or a file write; rejects with a clear error after\n // `timeoutMs`. Backend-specific: the provider chooses the readiness signal,\n // the polling cadence and the backoff for its API's rate limits. The\n // platform never polls a backend itself.\n //\n // `start`, `resume` and `resumePassive` call it on the sandbox they just\n // created, started or reused, before anything touches it: create or start \u2192\n // state \u2192 awaitRunning \u2192 platformNetworkPolicy \u2192 platformFiles \u2192 repositories,\n // seeds, setup, services \u2192 handle. On timeout `start` fails and tears down.\n awaitRunning(\n ctx: SandboxStartContextIface,\n state: State,\n options: { timeoutMs: number },\n ): Promise<void>;\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: withSandboxOverrides(definition, {\n environment: (options?: EnvOptions) => {\n const implementation = definition.environment(options);\n if (typeof implementation.awaitRunning !== 'function')\n throw new Error(`sandbox provider ${definition.name} does not implement awaitRunning`);\n const overrides: Partial<typeof implementation> = {\n start: async (ctx, openOptions, artifact) => {\n const started = await implementation.start(ctx, openOptions, artifact);\n return {\n ...started,\n handle: createSandboxHandle({\n handle: started.handle,\n executionPolicy: ctx.executionPolicy,\n }),\n };\n },\n resume: async (ctx, artifact, state) =>\n createSandboxHandle({\n handle: await implementation.resume(ctx, artifact, state),\n executionPolicy: ctx.executionPolicy,\n }),\n };\n if (implementation.editor != null) {\n const editor = implementation.editor.bind(implementation);\n overrides.editor = async (ctx, state, request) => {\n if (\n request.operation === SandboxEditorOperation.Open ||\n request.operation === SandboxEditorOperation.Refresh\n )\n await ctx.executionPolicy?.beforeExecution({\n operation: SandboxExecutionOperation.Editor,\n background: false,\n });\n return editor(ctx, state, request);\n };\n }\n if (implementation.resumePassive != null) {\n const resumePassive = implementation.resumePassive.bind(implementation);\n overrides.resumePassive = async (ctx, artifact, state) =>\n createSandboxHandle({\n handle: await resumePassive(ctx, artifact, state),\n executionPolicy: ctx.executionPolicy,\n });\n }\n return withSandboxOverrides(implementation, overrides);\n },\n }),\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": "AAAA,SAAS,wBAAwB;AACjC,SAAS,oBAAAA,yBAAwB;AAEjC,SAAS,2BAA6D;AACtE,SAAS,4BAA4B;AACrC,SAAS,0BAA0B,qBAAqB;AAMxD;AAAA,EAC4B;AAAA,OAErB;AAOP;AAAA,EACE;AAAA,OAGK;AACP,SAAS,iCAAiC;AAC1C,SAAS,4BAAmE;AAgGrE,IAAK,eAAL,kBAAKC,kBAAL;AACL,EAAAA,cAAA,UAAO;AACP,EAAAA,cAAA,WAAQ;AACR,EAAAA,cAAA,QAAK;AAHK,SAAAA;AAAA,GAAA;AA2CL,MAAM,uBAAuB,CAClC,aACwC,aAAa;AAiChD,IAAK,oBAAL,kBAAKC,uBAAL;AACL,EAAAA,mBAAA,WAAQ;AACR,EAAAA,mBAAA,aAAU;AACV,EAAAA,mBAAA,WAAQ;AACR,EAAAA,mBAAA,mBAAgB;AAChB,EAAAA,mBAAA,YAAS;AACT,EAAAA,mBAAA,iBAAc;AACd,EAAAA,mBAAA,YAAS;AACT,EAAAA,mBAAA,cAAW;AACX,EAAAA,mBAAA,aAAU;AATA,SAAAA;AAAA,GAAA;
|
|
4
|
+
"sourcesContent": ["import { SandboxEntryType } from \"./file-kind.mjs\";\nexport { SandboxEntryType } from \"./file-kind.mjs\";\nimport type { HostedBindingsIface } from \"../hosted-bindings.mjs\";\nimport { createSandboxHandle, type SandboxExecutionPolicyIface } from \"./handle.mjs\";\nimport { withSandboxOverrides } from \"./overrides.mjs\";\nimport { WorkspaceNetworkPolicy as NetworkPolicy } from '@finalai/agent-protocol/device-egress';\nimport type {\n WorkspaceEgressRequestIface,\n WorkspaceEgressStatusIface,\n WorkspaceNetworkPolicyIface as NetworkPolicyIface,\n} from '@finalai/agent-protocol/device-egress';\nexport {\n WorkspaceNetworkPolicy as NetworkPolicy,\n type WorkspaceNetworkPolicyIface as NetworkPolicyIface,\n} from '@finalai/agent-protocol/device-egress';\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 {\n SandboxEditorOperation,\n type SandboxEditorRequestIface,\n type SandboxEditorResultIface,\n} from \"./editor.mjs\";\nimport { SandboxExecutionOperation } from \"./execution-guard.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 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 // Writes create missing parent directories.\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 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 host) 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 // Partial discovery retains known tools and must be retried, including after caching.\n localMcpIncomplete?: boolean;\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 egress?(request: WorkspaceEgressRequestIface): Promise<WorkspaceEgressStatusIface>;\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 Egress = 'egress',\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 // Pending policy; the generic handle constructor consumes it before exposing execution.\n readonly executionPolicy?: SandboxExecutionPolicyIface;\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 host 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 host.\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 Final\n// repository id, a GitHub owner/name), resolved by the host for the session's\n// 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 variable (a secret managed in Build) for the session. Values are\n// injected into the sandbox only, never stored in a 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// Access to a Final API: its origin and a short-lived bearer token. The token\n// determines the organization and project, so requests name neither.\nexport interface FinalPlatformAccessIface {\n // The API origin; requests go to `<baseUrl>/v1/...`.\n baseUrl: string;\n token: string;\n}\n\n// Credentials the host supplies with a sandbox context. Providers read no secrets\n// and name no project themselves.\nexport interface SandboxCredentialsIface {\n // Access to the Computers API (the `computer` sandbox); null when the host grants\n // none. `refresh` asks for a new token after the API rejected the last one.\n computersAccess(args?: { refresh?: boolean }): Promise<FinalPlatformAccessIface | null>;\n // Access to the Device API (the `device` sandbox and workspace Device egress),\n // acting for `actingUserId` when given (null or absent: service access for\n // workspace networking); null when the host grants none.\n deviceAccess(args?: {\n actingUserId?: string | null;\n refresh?: boolean;\n }): Promise<FinalPlatformAccessIface | null>;\n // The value of the secret a provider's `credential.secretRef` names; null when it\n // is not set.\n secret(args: { secretRef: string }): Promise<string | null>;\n}\n\nexport const noSandboxCredentials: SandboxCredentialsIface = {\n computersAccess: async () => null,\n deviceAccess: async () => null,\n secret: async () => null,\n};\n\n// What an environment's pre-start reads (capabilities, mcpCatalog) are given.\nexport interface SandboxOfferContextIface {\n executionPolicy?: SandboxExecutionPolicyIface;\n platformNetworkPolicy?: (policy: NetworkPolicyIface) => Promise<void>;\n // Retain platform transport access when an extension restores an allowlist.\n platformEgressHosts?: string[];\n // Logical identity when inspecting an existing workspace or opening an execution extension.\n workspaceId?: string;\n bindings?: HostedBindingsIface;\n organizationId: string;\n credentials?: SandboxCredentialsIface;\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 credentials?: SandboxCredentialsIface;\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 // Host policy composes before the provider's policy, on every exposed execution path.\n executionPolicy?: SandboxExecutionPolicyIface;\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 // Stable logical identity supplied by the host, independent of provider resource names.\n workspaceId?: string;\n target: string;\n };\n credentials?: SandboxCredentialsIface;\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 // Variables the platform sets in every process of this sandbox: the egress\n // proxy, trust for its CA, and one placeholder per bound secret. Evaluated\n // again for every spawn/run, never once per session: a secret bound\n // mid-session must reach the next command. May resolve to {} (no proxy\n // configured, or not ready yet). Platform values override the spec's env.\n platformEnvironment?: () => Promise<Record<string, string>>;\n // Hosts the sandbox must be able to reach for the proxy to work, to append\n // to any allowlist-mode network policy the spec declares.\n platformEgressHosts?: string[];\n // Reports the network policy now in force on the sandbox, exactly as the\n // provider applied it to its backend (after withPlatformEgressHosts). The\n // platform permits only those destinations.\n // Called after awaitRunning and before platformFiles or any command, on start,\n // resume and a reused sandbox; never for a session's own setNetworkPolicy,\n // which the platform records itself. A rejection fails the start or resume.\n platformNetworkPolicy: (policy: NetworkPolicyIface) => Promise<void>;\n // Files the platform needs in the sandbox before any clone, setup step or\n // service runs: written right after the sandbox exists, on start and resume.\n // Paths are absolute; missing parent directories are created.\n platformFiles?: () => Promise<Record<string, string>>;\n}\n\n// The variables `platformEnvironment` owns. A spec that sets one (as a plain\n// value or a named variable) is refused at start.\nexport const PLATFORM_ENVIRONMENT_NAMES: ReadonlySet<string> = new Set([\n 'HTTPS_PROXY',\n 'HTTP_PROXY',\n 'NO_PROXY',\n 'NODE_USE_ENV_PROXY',\n 'SSL_CERT_FILE',\n 'CURL_CA_BUNDLE',\n 'REQUESTS_CA_BUNDLE',\n 'GIT_SSL_CAINFO',\n 'CARGO_HTTP_CAINFO',\n 'DENO_CERT',\n 'NODE_EXTRA_CA_CERTS',\n 'FINAL_EGRESS_URL',\n 'FINAL_EGRESS_TOKEN',\n 'GH_TOKEN',\n 'GITHUB_TOKEN',\n]);\n\n// A process's base environment: the spec's variables under the platform's,\n// read again on every call.\nexport const platformProcessEnvironment =\n (\n ctx: Pick<SandboxStartContextIface, 'platformEnvironment'>,\n specEnv: Record<string, string>,\n ): (() => Promise<Record<string, string>>) =>\n async () => ({ ...specEnv, ...(await ctx.platformEnvironment?.()) });\n\n// Writes `platformFiles` into a sandbox that now exists, before it runs anything.\n// Relies on writeTextFile creating missing parent directories.\nexport const writePlatformFiles = async (\n ctx: Pick<SandboxStartContextIface, 'platformFiles'>,\n sandbox: Pick<SandboxSessionIface, 'writeTextFile'>,\n): Promise<void> => {\n for (const [path, content] of Object.entries((await ctx.platformFiles?.()) ?? {}))\n await sandbox.writeTextFile({ path, content });\n};\n\n// Reports the policy a provider just applied to its backend: `allow` only for an\n// allowlist, its entries (hosts, `*.suffix` patterns, CIDRs) unchanged.\nexport const reportPlatformNetworkPolicy = async (\n ctx: Pick<SandboxStartContextIface, 'platformNetworkPolicy'>,\n policy: NetworkPolicyIface,\n): Promise<void> =>\n ctx.platformNetworkPolicy(\n policy.mode === NetworkPolicy.Allowlist\n ? { mode: policy.mode, allow: [...(policy.allow ?? [])] }\n : { mode: policy.mode },\n );\n\n// An allowlist policy with the platform's egress hosts appended; any other\n// policy unchanged.\nexport const withPlatformEgressHosts = (\n ctx: Pick<SandboxStartContextIface, 'platformEgressHosts'>,\n policy: NetworkPolicyIface,\n): NetworkPolicyIface => {\n const hosts = ctx.platformEgressHosts ?? [];\n if (policy.mode !== NetworkPolicy.Allowlist || hosts.length === 0) return policy;\n return { ...policy, allow: [...new Set([...(policy.allow ?? []), ...hosts])] };\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 // host 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 // Known positive offers when the rest of the pre-start capability set is unknown.\n additionalCapabilities?(ctx: SandboxOfferContextIface): Promise<SandboxCapability[]>;\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 host caches artifacts and calls\n // prepare only on a miss.\n artifactKey(ctx: SandboxPrepareContextIface): Promise<string>;\n prepare(ctx: SandboxPrepareContextIface): Promise<Artifact>;\n // Resolves once the backend sandbox named by `state` is running and will\n // accept a command or a file write; rejects with a clear error after\n // `timeoutMs`. Backend-specific: the provider chooses the readiness signal,\n // the polling cadence and the backoff for its API's rate limits. The\n // platform never polls a backend itself.\n //\n // `start`, `resume` and `resumePassive` call it on the sandbox they just\n // created, started or reused, before anything touches it: create or start \u2192\n // state \u2192 awaitRunning \u2192 platformNetworkPolicy \u2192 platformFiles \u2192 repositories,\n // seeds, setup, services \u2192 handle. On timeout `start` fails and tears down.\n awaitRunning(\n ctx: SandboxStartContextIface,\n state: State,\n options: { timeoutMs: number },\n ): Promise<void>;\n // `region`: where the backend placed the sandbox (its own region name), so the\n // host 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 host 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 host 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: withSandboxOverrides(definition, {\n environment: (options?: EnvOptions) => {\n const implementation = definition.environment(options);\n if (typeof implementation.awaitRunning !== 'function')\n throw new Error(`sandbox provider ${definition.name} does not implement awaitRunning`);\n const overrides: Partial<typeof implementation> = {\n start: async (ctx, openOptions, artifact) => {\n const started = await implementation.start(ctx, openOptions, artifact);\n return {\n ...started,\n handle: createSandboxHandle({\n handle: started.handle,\n executionPolicy: ctx.executionPolicy,\n }),\n };\n },\n resume: async (ctx, artifact, state) =>\n createSandboxHandle({\n handle: await implementation.resume(ctx, artifact, state),\n executionPolicy: ctx.executionPolicy,\n }),\n };\n if (implementation.editor != null) {\n const editor = implementation.editor.bind(implementation);\n overrides.editor = async (ctx, state, request) => {\n if (\n request.operation === SandboxEditorOperation.Open ||\n request.operation === SandboxEditorOperation.Refresh\n )\n await ctx.executionPolicy?.beforeExecution({\n operation: SandboxExecutionOperation.Editor,\n background: false,\n });\n return editor(ctx, state, request);\n };\n }\n if (implementation.resumePassive != null) {\n const resumePassive = implementation.resumePassive.bind(implementation);\n overrides.resumePassive = async (ctx, artifact, state) =>\n createSandboxHandle({\n handle: await resumePassive(ctx, artifact, state),\n executionPolicy: ctx.executionPolicy,\n });\n }\n return withSandboxOverrides(implementation, overrides);\n },\n }),\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 a host 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": "AAAA,SAAS,wBAAwB;AACjC,SAAS,oBAAAA,yBAAwB;AAEjC,SAAS,2BAA6D;AACtE,SAAS,4BAA4B;AACrC,SAAS,0BAA0B,qBAAqB;AAMxD;AAAA,EAC4B;AAAA,OAErB;AAOP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boxEntryType", "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.
|
|
3
|
+
"version": "0.5.1",
|
|
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",
|
|
@@ -184,7 +184,7 @@
|
|
|
184
184
|
"dependencies": {
|
|
185
185
|
"@agentclientprotocol/sdk": "1.8.0",
|
|
186
186
|
"@finalai/acp-session": "0.1.10",
|
|
187
|
-
"@finalai/agent-protocol": "0.
|
|
187
|
+
"@finalai/agent-protocol": "0.6.0",
|
|
188
188
|
"@modelcontextprotocol/client": "^2.1.0",
|
|
189
189
|
"@modelcontextprotocol/core": "^2.1.0",
|
|
190
190
|
"@modelcontextprotocol/server": "^2.1.0",
|