@finalai/agent-provider 0.6.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/HOSTING.md +3 -3
- package/README.md +47 -14
- package/dist/modules/channel.d.mts +102 -40
- package/dist/modules/channel.mjs +29 -1
- package/dist/modules/channel.mjs.map +3 -3
- package/dist/modules/conformance/sandbox-kit.d.mts +1 -0
- package/dist/modules/conformance/sandbox-kit.mjs +174 -0
- package/dist/modules/conformance/sandbox-kit.mjs.map +3 -3
- package/dist/modules/index.d.mts +1 -0
- package/dist/modules/index.mjs +1 -0
- package/dist/modules/index.mjs.map +2 -2
- package/dist/modules/local-channel-context.d.mts +3 -3
- package/dist/modules/local-channel-context.mjs +25 -14
- package/dist/modules/local-channel-context.mjs.map +2 -2
- package/dist/modules/manifest.d.mts +18 -14
- package/dist/modules/manifest.mjs +11 -5
- package/dist/modules/manifest.mjs.map +2 -2
- package/dist/modules/room-surface.d.mts +17 -32
- package/dist/modules/room-surface.mjs +12 -12
- package/dist/modules/room-surface.mjs.map +3 -3
- package/dist/modules/sandbox/client.mjs +108 -27
- package/dist/modules/sandbox/client.mjs.map +3 -3
- package/dist/modules/sandbox/convenience.mjs +1 -1
- package/dist/modules/sandbox/convenience.mjs.map +2 -2
- package/dist/modules/sandbox/execution-guard.d.mts +1 -0
- package/dist/modules/sandbox/execution-guard.mjs +9 -0
- package/dist/modules/sandbox/execution-guard.mjs.map +2 -2
- package/dist/modules/sandbox/memory-sandbox.mjs +8 -0
- package/dist/modules/sandbox/memory-sandbox.mjs.map +2 -2
- package/dist/modules/sandbox/server.mjs +87 -14
- package/dist/modules/sandbox/server.mjs.map +3 -3
- package/dist/modules/sandbox/types.d.mts +21 -1
- package/dist/modules/sandbox/types.mjs +1 -0
- package/dist/modules/sandbox/types.mjs.map +2 -2
- package/dist/modules/sandbox/wire.d.mts +40 -0
- package/dist/modules/sandbox/wire.mjs +32 -2
- package/dist/modules/sandbox/wire.mjs.map +2 -2
- package/package.json +2 -2
package/HOSTING.md
CHANGED
|
@@ -269,6 +269,6 @@ Optional readers preserve source compatibility with existing hosts. Definitions
|
|
|
269
269
|
requesting bindings fail clearly if hosting does not provide them. Installing these
|
|
270
270
|
packages alone does not change Final's deployed service wiring or provision secrets.
|
|
271
271
|
|
|
272
|
-
New compiles emit manifest version 4. Hosts
|
|
273
|
-
|
|
274
|
-
publishing newly compiled agents.
|
|
272
|
+
New compiles emit manifest version 4. Hosts read versions 2 through 4; older
|
|
273
|
+
channel entries default to no credentials and an empty surface. Upgrade hosting
|
|
274
|
+
before publishing newly compiled agents.
|
package/README.md
CHANGED
|
@@ -77,7 +77,7 @@ Confined reads require a trusted system `python3` in `/usr/bin` or `/usr/local/b
|
|
|
77
77
|
|
|
78
78
|
Acquiring a hosted MCP endpoint or channel is foreground work: it may start a server and perform deferred workspace setup. Catalog polling on an acquired channel is background maintenance and does not start setup. Abortable operations pass their signal to admission; cancellation rejects pending admission and prevents dispatch even if a host policy settles later.
|
|
79
79
|
|
|
80
|
-
## Channels
|
|
80
|
+
## Channels
|
|
81
81
|
|
|
82
82
|
`ChannelDefinitionIface<Config, Inbound, State>` describes a provider namespace,
|
|
83
83
|
its application credentials, identity proof, place kinds, routes/listeners,
|
|
@@ -105,15 +105,11 @@ are delivered at least once; channels persist provider reply IDs in `store` for
|
|
|
105
105
|
deduplication. `replies: all` enables `message.posted` mirroring. Raw ACP updates
|
|
106
106
|
belong to harnesses and the separately typed Final room surface.
|
|
107
107
|
|
|
108
|
-
`observe` streams
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
selects a tenant API credential with `app({tenant})`. `appInfo()` never returns an access token.
|
|
114
|
-
`app()` and `appInfo()` are available only in package execution. Isolated code
|
|
115
|
-
uses the host's credential-injecting fetch and explicitly declared project secrets
|
|
116
|
-
through `secret(name)`.
|
|
108
|
+
`observe` streams one turn's events, from its start, and accepts a cancellation signal. Use `events` to hear a conversation over time. HTTP and binary WebSocket routes receive the same capabilities; listeners additionally receive an abort signal. Events a host receives for an installed app arrive unchanged at the channel's `POST /webhook` route, signature headers included, so a channel verifies them like any other request. Speech providers and audio processing belong to application code, using its declared credentials and ordinary HTTP/socket requests.
|
|
109
|
+
Installed app credentials stay with the host in every execution mode. `credentials.client()` exposes only the public client ID; `verify()` checks signed payloads without returning the signing key. `exchange()` returns an opaque, short-lived OAuth credential handle. Select that handle or the installed app with `credentials.fetch`'s `credential` option; requests default to no credential. `credentials.connect()` supports host-injected credentials in outgoing JSON socket frames. Hosts enforce the same destination and grant checks for all these operations. Only explicitly declared project secrets can be read through `secret(name)`. Sockets accept bounded caller-owned headers for provider handshakes. Installed app credentials remain opaque and can be injected into JSON frames. Exchange handles are invocation-scoped and expire; they do not provide durable person-token storage or automatic refresh. An application's authorization callback must use provider APIs that can establish the current person's access.
|
|
110
|
+
|
|
111
|
+
`binding.url` is the host's canonical binding base URL for callbacks and routes. Channels compile into their authored bundle; naming an installed implementation does not grant additional authority. `resources.resolve` maps an application URL to a canonical provider place; the required companion `resources.authorize` checks the linked person's current provider access. Hosts repeat that authorization for later observation access. `places.follow` and `unfollow` manage observation under a linked person's authority, while `places.observers` enumerates authorized deliveries.
|
|
112
|
+
|
|
117
113
|
A host must fail ambiguous tenant selection rather than choosing an arbitrary
|
|
118
114
|
credential. Tenant-wide `people.revoke` with reason `uninstalled` or
|
|
119
115
|
`provider-revoked` and no principal also disconnects that tenant's places. Omitting
|
|
@@ -121,7 +117,44 @@ the tenant applies this lifecycle change to the binding's namespace. A socket ha
|
|
|
121
117
|
cleanup grace after disconnect; every other operation is revoked immediately, and all
|
|
122
118
|
capabilities end when the handler returns. Attachment authorization still applies.
|
|
123
119
|
|
|
124
|
-
|
|
125
|
-
The `roomSurface` field describes `channels/final.ts
|
|
126
|
-
|
|
127
|
-
|
|
120
|
+
Manifests record channel credentials and `surface` routes/listeners/place kinds.
|
|
121
|
+
The `roomSurface` field describes `channels/final.ts`, the customization of the Final
|
|
122
|
+
chat itself, which is typed separately in `@finalai/agent-provider/room-surface`.
|
|
123
|
+
The address, attached-session and handoff channel API is removed. Existing channel
|
|
124
|
+
authors must migrate and republish their definitions.
|
|
125
|
+
|
|
126
|
+
## Durable processes
|
|
127
|
+
|
|
128
|
+
A sandbox that advertises `SandboxCapability.DurableProcesses` (through `sandbox/describe`)
|
|
129
|
+
runs `spawn({ durable: true })` as a process that outlives its handle, so a host whose
|
|
130
|
+
runtime restarts (a Worker deploy resetting a Durable Object) keeps long builds and
|
|
131
|
+
tests. The handle's `ref` is an opaque, provider-encoded string; persist it with the
|
|
132
|
+
number of stdout and stderr bytes already delivered, and call
|
|
133
|
+
`attachProcess({ ref, stdoutOffset, stderrOffset })` to watch it again. The memory
|
|
134
|
+
sandbox does not offer durable processes, and sandboxes without the capability ignore
|
|
135
|
+
`durable` (their `ref` is null).
|
|
136
|
+
|
|
137
|
+
- A durable process ends only on its own exit, `kill`, `timeoutMs` (enforced inside
|
|
138
|
+
the sandbox, never by a provider-side timer) or the sandbox stopping or being
|
|
139
|
+
destroyed. Dropping a handle (the handle RPC connection closing,
|
|
140
|
+
`handle/onRuntimeShutdown`, the spawn or attach `abortSignal`) detaches it: its
|
|
141
|
+
streams fail and `wait` rejects, and the process keeps running. Ordinary processes
|
|
142
|
+
are still killed when their handle goes away.
|
|
143
|
+
- `attachProcess` returns null when the sandbox no longer knows the process (it
|
|
144
|
+
restarted or was deleted, the ref expired, is malformed or belongs to another
|
|
145
|
+
sandbox). Otherwise its streams carry output from the returned `stdoutOffset` and
|
|
146
|
+
`stderrOffset`: the requested offsets, or later ones when the provider no longer
|
|
147
|
+
retains the earlier bytes. Attaching after the process exited still yields its
|
|
148
|
+
retained output and its exit code.
|
|
149
|
+
- Stdin belongs to the spawning handle only. An attached process can be watched,
|
|
150
|
+
waited for and killed, but not written to; detaching neither writes to nor closes
|
|
151
|
+
its stdin. Give a durable process its input up front, or through a file.
|
|
152
|
+
- The provider is the source of truth for output and exit; the contract adds no
|
|
153
|
+
buffering. Each provider documents how much output and for how long it retains.
|
|
154
|
+
|
|
155
|
+
To offer durable processes, a provider implements `attachProcess` on its session (the
|
|
156
|
+
handle RPC server then advertises the capability), returns a versioned `ref` from a
|
|
157
|
+
durable spawn, treats the spawn and attach `abortSignal` as detach rather than kill,
|
|
158
|
+
enforces `timeoutMs` inside the sandbox for durable processes, and returns null for a
|
|
159
|
+
ref it cannot resolve, including another provider's. `runSandboxConformance` runs the
|
|
160
|
+
durable cases on any sandbox with `attachProcess`, directly and through the handle RPC.
|
|
@@ -1,10 +1,7 @@
|
|
|
1
1
|
import type { ContentBlock } from '@agentclientprotocol/sdk/experimental/v2';
|
|
2
2
|
import * as z from 'zod';
|
|
3
3
|
import { type JsonObject, type JsonValue } from "./json.mjs";
|
|
4
|
-
import type { ProviderRef } from "./provider-ref.mjs";
|
|
5
|
-
import type { ChannelSocketIface, ChannelTurnStateIface } from "./room-surface.mjs";
|
|
6
4
|
import type { ChannelSemanticDataByKindIface } from "./semantic-events.mjs";
|
|
7
|
-
export * from "./room-surface.mjs";
|
|
8
5
|
export declare const personHandleSchema: z.core.$ZodBranded<z.ZodString, "ChannelPerson", "out">;
|
|
9
6
|
export declare const conversationHandleSchema: z.core.$ZodBranded<z.ZodString, "ChannelConversation", "out">;
|
|
10
7
|
export type PersonHandle = z.infer<typeof personHandleSchema>;
|
|
@@ -109,25 +106,77 @@ export declare const channelReceiveResultSchema: z.ZodUnion<readonly [z.ZodObjec
|
|
|
109
106
|
ignored: z.ZodLiteral<true>;
|
|
110
107
|
reason: z.ZodString;
|
|
111
108
|
}, z.core.$strip>]>;
|
|
112
|
-
export
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
109
|
+
export declare enum ChannelCredentialKind {
|
|
110
|
+
App = "app",
|
|
111
|
+
OAuth = "oauth",
|
|
112
|
+
None = "none"
|
|
116
113
|
}
|
|
117
|
-
export
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
114
|
+
export declare const channelCredentialHandleSchema: z.core.$ZodBranded<z.ZodString, "ChannelCredential", "out">;
|
|
115
|
+
export type ChannelCredentialHandle = z.infer<typeof channelCredentialHandleSchema>;
|
|
116
|
+
export type ChannelCredentialRef = {
|
|
117
|
+
kind: ChannelCredentialKind.App;
|
|
118
|
+
tenant?: string;
|
|
119
|
+
} | {
|
|
120
|
+
kind: ChannelCredentialKind.OAuth;
|
|
121
|
+
handle: ChannelCredentialHandle;
|
|
122
|
+
} | {
|
|
123
|
+
kind: ChannelCredentialKind.None;
|
|
124
|
+
};
|
|
125
|
+
export declare enum ChannelSigningAlgorithm {
|
|
126
|
+
HmacSha256 = "hmac-sha256",
|
|
127
|
+
HmacSha1 = "hmac-sha1",
|
|
128
|
+
Ed25519 = "ed25519"
|
|
129
|
+
}
|
|
130
|
+
export declare enum ChannelSignatureEncoding {
|
|
131
|
+
Hex = "hex",
|
|
132
|
+
Base64 = "base64"
|
|
133
|
+
}
|
|
134
|
+
export declare enum ChannelOAuthClientAuthentication {
|
|
135
|
+
Body = "body",
|
|
136
|
+
Basic = "basic",
|
|
137
|
+
None = "none"
|
|
138
|
+
}
|
|
139
|
+
export interface ChannelCredentialRequestInitIface extends RequestInit {
|
|
140
|
+
credential?: ChannelCredentialRef;
|
|
141
|
+
}
|
|
142
|
+
export interface ChannelVerifyOptionsIface {
|
|
143
|
+
algorithm: ChannelSigningAlgorithm;
|
|
144
|
+
encoding: ChannelSignatureEncoding;
|
|
145
|
+
data: string;
|
|
146
|
+
signature: string;
|
|
147
|
+
}
|
|
148
|
+
export interface ChannelOAuthExchangeOptionsIface {
|
|
149
|
+
url: string;
|
|
150
|
+
parameters: Record<string, string>;
|
|
151
|
+
authentication: ChannelOAuthClientAuthentication;
|
|
152
|
+
clientId?: string;
|
|
153
|
+
signal?: AbortSignal;
|
|
154
|
+
}
|
|
155
|
+
export interface ChannelCredentialConnectOptionsIface {
|
|
156
|
+
url: string;
|
|
157
|
+
signal?: AbortSignal;
|
|
158
|
+
}
|
|
159
|
+
export interface ChannelCredentialInjectionIface {
|
|
160
|
+
path: string[];
|
|
161
|
+
credential: ChannelCredentialRef;
|
|
162
|
+
}
|
|
163
|
+
export interface ChannelCredentialSocketIface {
|
|
164
|
+
messages: AsyncIterable<string | Uint8Array>;
|
|
165
|
+
send(data: string | Uint8Array, options?: {
|
|
166
|
+
inject?: ChannelCredentialInjectionIface[];
|
|
167
|
+
}): Promise<void>;
|
|
168
|
+
close(code?: number, reason?: string): Promise<void>;
|
|
169
|
+
closeCode(): number | null;
|
|
123
170
|
}
|
|
124
171
|
export interface ChannelCredentialsIface {
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
172
|
+
client(): Promise<{
|
|
173
|
+
clientId: string;
|
|
174
|
+
}>;
|
|
175
|
+
verify(args: ChannelVerifyOptionsIface): Promise<boolean>;
|
|
176
|
+
exchange(args: ChannelOAuthExchangeOptionsIface): Promise<ChannelCredentialHandle>;
|
|
177
|
+
fetch(input: RequestInfo | URL, init?: ChannelCredentialRequestInitIface): Promise<Response>;
|
|
178
|
+
connect(args: ChannelCredentialConnectOptionsIface): Promise<ChannelCredentialSocketIface>;
|
|
129
179
|
secret(name: string): Promise<string | null>;
|
|
130
|
-
fetch: typeof fetch;
|
|
131
180
|
}
|
|
132
181
|
export interface ChannelPostArgsIface {
|
|
133
182
|
from: PersonHandle;
|
|
@@ -202,6 +251,7 @@ export type SemanticEvent = {
|
|
|
202
251
|
export interface ChannelReceiveContextIface<Config = JsonObject> {
|
|
203
252
|
binding: {
|
|
204
253
|
id: string;
|
|
254
|
+
url: string;
|
|
205
255
|
owner: {
|
|
206
256
|
kind: 'agent';
|
|
207
257
|
definitionId: string;
|
|
@@ -236,30 +286,21 @@ export interface ChannelReceiveContextIface<Config = JsonObject> {
|
|
|
236
286
|
create?: ChannelCreate | `${ChannelCreate}`;
|
|
237
287
|
}): Promise<ConversationHandle>;
|
|
238
288
|
disconnect(place: PlaceRef, by: PersonHandle): Promise<void>;
|
|
289
|
+
follow(place: PlaceRef, args: {
|
|
290
|
+
by: PersonHandle;
|
|
291
|
+
conversation: ConversationHandle;
|
|
292
|
+
ttlSeconds?: number;
|
|
293
|
+
}): Promise<void>;
|
|
294
|
+
unfollow(place: PlaceRef, args: {
|
|
295
|
+
by: PersonHandle;
|
|
296
|
+
conversation: ConversationHandle;
|
|
297
|
+
}): Promise<void>;
|
|
239
298
|
};
|
|
240
299
|
conversation(handle: ConversationHandle): ChannelConversationIface;
|
|
241
|
-
observe(handle: ConversationHandle, args
|
|
242
|
-
turnId
|
|
300
|
+
observe(handle: ConversationHandle, args: {
|
|
301
|
+
turnId: string;
|
|
243
302
|
signal?: AbortSignal;
|
|
244
303
|
}): AsyncIterable<SemanticEvent>;
|
|
245
|
-
media: {
|
|
246
|
-
transcribe(audio: AsyncIterable<Uint8Array>, options: {
|
|
247
|
-
encoding: string;
|
|
248
|
-
sampleRate: number;
|
|
249
|
-
language?: string;
|
|
250
|
-
endpointing?: boolean;
|
|
251
|
-
signal?: AbortSignal;
|
|
252
|
-
}): AsyncIterable<{
|
|
253
|
-
text: string;
|
|
254
|
-
final: boolean;
|
|
255
|
-
}>;
|
|
256
|
-
synthesize(text: AsyncIterable<string>, options: {
|
|
257
|
-
voice?: string;
|
|
258
|
-
encoding: string;
|
|
259
|
-
sampleRate: number;
|
|
260
|
-
signal?: AbortSignal;
|
|
261
|
-
}): AsyncIterable<Uint8Array>;
|
|
262
|
-
};
|
|
263
304
|
decisions: {
|
|
264
305
|
resolve(args: {
|
|
265
306
|
decisionId: string;
|
|
@@ -286,6 +327,19 @@ export interface ChannelReceiveContextIface<Config = JsonObject> {
|
|
|
286
327
|
};
|
|
287
328
|
log(message: string, details?: JsonObject): void;
|
|
288
329
|
}
|
|
330
|
+
export interface ChannelSocketIface {
|
|
331
|
+
readonly signal: AbortSignal;
|
|
332
|
+
readonly messages: AsyncIterable<string | Uint8Array>;
|
|
333
|
+
accept(options?: {
|
|
334
|
+
protocol?: string;
|
|
335
|
+
}): void;
|
|
336
|
+
send(data: string | Uint8Array): void;
|
|
337
|
+
close(code?: number, reason?: string): void;
|
|
338
|
+
}
|
|
339
|
+
export interface ChannelTurnStateIface<State> {
|
|
340
|
+
get(): State | null;
|
|
341
|
+
set(state: State | null): void;
|
|
342
|
+
}
|
|
289
343
|
export interface ChannelEventContextIface<Config = JsonObject, State = JsonValue> extends Pick<ChannelReceiveContextIface<Config>, 'binding' | 'config' | 'credentials' | 'store' | 'log'> {
|
|
290
344
|
origin: OriginIface;
|
|
291
345
|
conversation: ConversationHandle;
|
|
@@ -299,7 +353,6 @@ export interface ChannelEventContextIface<Config = JsonObject, State = JsonValue
|
|
|
299
353
|
}
|
|
300
354
|
export interface ChannelRouteContextIface<Config = JsonObject> extends ChannelReceiveContextIface<Config> {
|
|
301
355
|
request: Request;
|
|
302
|
-
authenticatedPrincipal?: PrincipalRef;
|
|
303
356
|
receive(input: JsonValue): Promise<ChannelReceiveResult>;
|
|
304
357
|
}
|
|
305
358
|
export interface HttpChannelRouteDefinitionIface<Config = JsonObject> {
|
|
@@ -322,7 +375,6 @@ export type ChannelEventKind = keyof ChannelSemanticDataByKindIface;
|
|
|
322
375
|
export interface ChannelDefinitionIface<Config = JsonObject, Inbound = JsonValue, State = JsonValue> {
|
|
323
376
|
name: string;
|
|
324
377
|
config?: Config;
|
|
325
|
-
installed?: ProviderRef;
|
|
326
378
|
configure?(config: Config): ChannelDefinitionIface<Config, Inbound, State>;
|
|
327
379
|
credentials: {
|
|
328
380
|
app: string | null;
|
|
@@ -347,6 +399,16 @@ export interface ChannelDefinitionIface<Config = JsonObject, Inbound = JsonValue
|
|
|
347
399
|
kinds: readonly string[];
|
|
348
400
|
defaults?(place: PlaceRef): PlaceDefaultsIface | null;
|
|
349
401
|
};
|
|
402
|
+
resources?: {
|
|
403
|
+
authorize(args: {
|
|
404
|
+
place: PlaceRef;
|
|
405
|
+
principal: PrincipalRef;
|
|
406
|
+
}, ctx: ChannelReceiveContextIface<Config>): Promise<boolean>;
|
|
407
|
+
resolve(args: {
|
|
408
|
+
url: string;
|
|
409
|
+
principal: PrincipalRef;
|
|
410
|
+
}, ctx: ChannelReceiveContextIface<Config>): Promise<PlaceRef | null>;
|
|
411
|
+
};
|
|
350
412
|
routes?: RouteDefinitionIface<Config>[];
|
|
351
413
|
listeners?: {
|
|
352
414
|
key: string;
|
package/dist/modules/channel.mjs
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import * as z from "zod";
|
|
2
2
|
import { jsonObjectSchema } from "./json.mjs";
|
|
3
|
-
export * from "./room-surface.mjs";
|
|
4
3
|
const personHandleSchema = z.string().min(1).brand();
|
|
5
4
|
const conversationHandleSchema = z.string().min(1).brand();
|
|
6
5
|
const principalRefSchema = z.object({
|
|
@@ -53,11 +52,40 @@ const channelReceiveResultSchema = z.union([
|
|
|
53
52
|
z.object({ accepted: z.literal(false), refusal: refusalSchema }),
|
|
54
53
|
z.object({ ignored: z.literal(true), reason: z.string() })
|
|
55
54
|
]);
|
|
55
|
+
var ChannelCredentialKind = /* @__PURE__ */ ((ChannelCredentialKind2) => {
|
|
56
|
+
ChannelCredentialKind2["App"] = "app";
|
|
57
|
+
ChannelCredentialKind2["OAuth"] = "oauth";
|
|
58
|
+
ChannelCredentialKind2["None"] = "none";
|
|
59
|
+
return ChannelCredentialKind2;
|
|
60
|
+
})(ChannelCredentialKind || {});
|
|
61
|
+
const channelCredentialHandleSchema = z.string().min(1).brand();
|
|
62
|
+
var ChannelSigningAlgorithm = /* @__PURE__ */ ((ChannelSigningAlgorithm2) => {
|
|
63
|
+
ChannelSigningAlgorithm2["HmacSha256"] = "hmac-sha256";
|
|
64
|
+
ChannelSigningAlgorithm2["HmacSha1"] = "hmac-sha1";
|
|
65
|
+
ChannelSigningAlgorithm2["Ed25519"] = "ed25519";
|
|
66
|
+
return ChannelSigningAlgorithm2;
|
|
67
|
+
})(ChannelSigningAlgorithm || {});
|
|
68
|
+
var ChannelSignatureEncoding = /* @__PURE__ */ ((ChannelSignatureEncoding2) => {
|
|
69
|
+
ChannelSignatureEncoding2["Hex"] = "hex";
|
|
70
|
+
ChannelSignatureEncoding2["Base64"] = "base64";
|
|
71
|
+
return ChannelSignatureEncoding2;
|
|
72
|
+
})(ChannelSignatureEncoding || {});
|
|
73
|
+
var ChannelOAuthClientAuthentication = /* @__PURE__ */ ((ChannelOAuthClientAuthentication2) => {
|
|
74
|
+
ChannelOAuthClientAuthentication2["Body"] = "body";
|
|
75
|
+
ChannelOAuthClientAuthentication2["Basic"] = "basic";
|
|
76
|
+
ChannelOAuthClientAuthentication2["None"] = "none";
|
|
77
|
+
return ChannelOAuthClientAuthentication2;
|
|
78
|
+
})(ChannelOAuthClientAuthentication || {});
|
|
56
79
|
const defineChannel = (definition) => definition;
|
|
57
80
|
export {
|
|
58
81
|
ChannelAudience,
|
|
59
82
|
ChannelCreate,
|
|
83
|
+
ChannelCredentialKind,
|
|
84
|
+
ChannelOAuthClientAuthentication,
|
|
60
85
|
ChannelReplies,
|
|
86
|
+
ChannelSignatureEncoding,
|
|
87
|
+
ChannelSigningAlgorithm,
|
|
88
|
+
channelCredentialHandleSchema,
|
|
61
89
|
channelReceiveResultSchema,
|
|
62
90
|
conversationHandleSchema,
|
|
63
91
|
defineChannel,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/channel.ts"],
|
|
4
|
-
"sourcesContent": ["import type { ContentBlock } from '@agentclientprotocol/sdk/experimental/v2';\nimport * as z from 'zod';\nimport { jsonObjectSchema, type JsonObject, type JsonValue } from \"./json.mjs\";\nimport type { ProviderRef } from \"./provider-ref.mjs\";\nimport type { ChannelSocketIface, ChannelTurnStateIface } from \"./room-surface.mjs\";\nimport type { ChannelSemanticDataByKindIface } from \"./semantic-events.mjs\";\n\nexport * from \"./room-surface.mjs\";\n\n// Handles carry no authority until the platform validates their binding and invocation signature.\nexport const personHandleSchema = z.string().min(1).brand<'ChannelPerson'>();\nexport const conversationHandleSchema = z.string().min(1).brand<'ChannelConversation'>();\nexport type PersonHandle = z.infer<typeof personHandleSchema>;\nexport type ConversationHandle = z.infer<typeof conversationHandleSchema>;\n\nexport const principalRefSchema = z.object({\n id: z.string().min(1),\n tenant: z.string().min(1).optional(),\n displayName: z.string().optional(),\n});\nexport type PrincipalRef = z.infer<typeof principalRefSchema>;\nexport interface PlaceRef {\n kind: string;\n id: string;\n tenant?: string;\n parent?: PlaceRef;\n title?: string;\n}\nexport const placeRefSchema: z.ZodType<PlaceRef> = z.lazy(() =>\n z.object({\n kind: z.string().min(1),\n id: z.string().min(1),\n tenant: z.string().min(1).optional(),\n parent: placeRefSchema.optional(),\n title: z.string().optional(),\n }),\n);\nexport interface OriginIface {\n place: PlaceRef;\n ref?: JsonObject;\n}\nexport const originSchema = z.object({ place: placeRefSchema, ref: jsonObjectSchema.optional() });\n\nexport type PersonResolution =\n | { kind: 'member'; person: PersonHandle; displayName: string }\n | { kind: 'unlinked'; linkUrl: string }\n | { kind: 'blocked'; reason: 'not-in-organization' | 'suspended' };\nexport enum ChannelReplies {\n Origin = 'origin',\n All = 'all',\n}\nexport enum ChannelAudience {\n Members = 'members',\n Anyone = 'anyone',\n}\nexport enum ChannelCreate {\n DirectWithAgent = 'direct-with-agent',\n Group = 'group',\n}\nexport const placePolicySchema = z.object({\n replies: z.nativeEnum(ChannelReplies),\n audience: z.nativeEnum(ChannelAudience),\n});\nexport interface PlacePolicy {\n replies: ChannelReplies | `${ChannelReplies}`;\n audience: ChannelAudience | `${ChannelAudience}`;\n}\nexport interface PlaceDefaultsIface extends PlacePolicy {\n create: ChannelCreate | `${ChannelCreate}`;\n}\nexport type PlaceResolution =\n | { kind: 'connected'; conversation: ConversationHandle; policy: PlacePolicy }\n | { kind: 'unconnected'; connectUrl: string; defaults: PlaceDefaultsIface | null };\nexport interface Refusal {\n refused: 'unlinked' | 'no-access' | 'unconnected' | 'not-audience';\n linkUrl?: string;\n connectUrl?: string;\n message: string;\n}\nexport type ChannelReceiveResult =\n | { accepted: true }\n | { accepted: false; refusal: Refusal }\n | { ignored: true; reason: string };\nexport const refusalSchema = z.object({\n refused: z.union([\n z.literal('unlinked'),\n z.literal('no-access'),\n z.literal('unconnected'),\n z.literal('not-audience'),\n ]),\n linkUrl: z.string().optional(),\n connectUrl: z.string().optional(),\n message: z.string(),\n});\nexport const channelReceiveResultSchema = z.union([\n z.object({ accepted: z.literal(true) }),\n z.object({ accepted: z.literal(false), refusal: refusalSchema }),\n z.object({ ignored: z.literal(true), reason: z.string() }),\n]);\nexport interface InstalledAppInfoIface {\n clientId: string;\n clientSecret: string;\n signingSecret?: string;\n}\nexport interface InstalledAppCredential extends InstalledAppInfoIface {\n accessToken: string;\n tenantId?: string;\n externalId?: string;\n expiresAt?: string | null;\n customHeaders?: Record<string, string>;\n}\nexport interface ChannelCredentialsIface {\n // Installed app credentials and metadata are package-only; isolates use token-injecting fetch.\n appInfo(): Promise<InstalledAppInfoIface>;\n app(options?: { tenant?: string }): Promise<InstalledAppCredential>;\n // Explicitly declared project secrets are available in both execution modes.\n secret(name: string): Promise<string | null>;\n fetch: typeof fetch;\n}\nexport interface ChannelPostArgsIface {\n from: PersonHandle;\n content: ContentBlock[];\n context?: string[];\n origin: OriginIface;\n idempotencyKey: string;\n waitForAcceptance?: boolean;\n}\nexport interface ChannelConversationIface {\n post(args: ChannelPostArgsIface): Promise<{ messageId: string; turnId?: string } | Refusal>;\n input(args: {\n label: string;\n principal?: PrincipalRef;\n content: ContentBlock[];\n context?: string[];\n origin: OriginIface;\n idempotencyKey: string;\n waitForAcceptance?: boolean;\n }): Promise<{ inputId: string; turnId?: string } | Refusal>;\n attach(args: {\n origin: OriginIface;\n content: ContentBlock[];\n label: string;\n idempotencyKey: string;\n from?: PersonHandle;\n }): Promise<{ messageId: string } | Refusal>;\n edit(args: {\n externalKey: string;\n by: PersonHandle;\n content: ContentBlock[];\n }): Promise<{ messageId: string } | Refusal>;\n remove(args: { externalKey: string; by: PersonHandle }): Promise<{ removed: boolean } | Refusal>;\n react(args: {\n target: { externalKey: string } | { replyOf: { externalKey: string; turnId: string } };\n emoji: string;\n by: PersonHandle;\n op: 'add' | 'remove';\n }): Promise<{ ok: true } | Refusal>;\n}\nexport type SemanticEvent = {\n [Kind in keyof ChannelSemanticDataByKindIface]: {\n type: Kind;\n data: ChannelSemanticDataByKindIface[Kind];\n seq: number;\n };\n}[keyof ChannelSemanticDataByKindIface];\nexport interface ChannelReceiveContextIface<Config = JsonObject> {\n binding: {\n id: string;\n owner: { kind: 'agent'; definitionId: string } | { kind: 'install'; installId: string };\n };\n config: Config;\n credentials: ChannelCredentialsIface;\n people: {\n resolve(principal: PrincipalRef): Promise<PersonResolution>;\n identify(person: PersonHandle): Promise<PrincipalRef | null>;\n // Tenant-wide uninstall/revocation also disconnects that tenant's places.\n revoke(args: {\n principal?: PrincipalRef;\n tenant?: string;\n reason: 'deactivated' | 'uninstalled' | 'provider-revoked';\n }): Promise<void>;\n confirm(args: { ticket: string; principal: PrincipalRef }): Promise<{ linked: true } | Refusal>;\n };\n places: {\n // Explicit anyone/group defaults may create a Shared chat while resolving a new place.\n resolve(place: PlaceRef): Promise<PlaceResolution>;\n observers(place: PlaceRef): Promise<ConversationHandle[]>;\n connect(\n place: PlaceRef,\n to: {\n by: PersonHandle;\n conversation?: ConversationHandle;\n create?: ChannelCreate | `${ChannelCreate}`;\n },\n ): Promise<ConversationHandle>;\n disconnect(place: PlaceRef, by: PersonHandle): Promise<void>;\n };\n conversation(handle: ConversationHandle): ChannelConversationIface;\n observe(\n handle: ConversationHandle,\n args?: { turnId?: string; signal?: AbortSignal },\n ): AsyncIterable<SemanticEvent>;\n media: {\n transcribe(\n audio: AsyncIterable<Uint8Array>,\n options: {\n encoding: string;\n sampleRate: number;\n language?: string;\n endpointing?: boolean;\n signal?: AbortSignal;\n },\n ): AsyncIterable<{ text: string; final: boolean }>;\n synthesize(\n text: AsyncIterable<string>,\n options: { voice?: string; encoding: string; sampleRate: number; signal?: AbortSignal },\n ): AsyncIterable<Uint8Array>;\n };\n decisions: {\n resolve(args: {\n decisionId: string;\n outcome: JsonValue;\n by: PersonHandle;\n }): Promise<{ resolved: boolean } | Refusal>;\n };\n turns: {\n cancel(args: {\n conversation: ConversationHandle;\n by?: PersonHandle;\n turnId?: string;\n }): Promise<{ accepted: boolean } | Refusal>;\n };\n store: {\n get(key: string): Promise<JsonValue | null>;\n set(key: string, value: JsonValue | null, options?: { ttlSeconds?: number }): Promise<void>;\n };\n log(message: string, details?: JsonObject): void;\n}\nexport interface ChannelEventContextIface<Config = JsonObject, State = JsonValue> extends Pick<\n ChannelReceiveContextIface<Config>,\n 'binding' | 'config' | 'credentials' | 'store' | 'log'\n> {\n origin: OriginIface;\n conversation: ConversationHandle;\n turn: { id: string; agent: { displayName: string } };\n state: ChannelTurnStateIface<State>;\n}\nexport interface ChannelRouteContextIface<\n Config = JsonObject,\n> extends ChannelReceiveContextIface<Config> {\n request: Request;\n authenticatedPrincipal?: PrincipalRef;\n receive(input: JsonValue): Promise<ChannelReceiveResult>;\n}\nexport interface HttpChannelRouteDefinitionIface<Config = JsonObject> {\n method: 'GET' | 'POST' | 'PUT' | 'DELETE';\n path: string;\n handler(args: ChannelRouteContextIface<Config>): Promise<Response>;\n}\nexport interface WebSocketChannelRouteDefinitionIface<Config = JsonObject> {\n method: 'WS';\n path: string;\n handler(\n args: ChannelRouteContextIface<Config> & { socket: ChannelSocketIface },\n ): Promise<Response | void>;\n}\nexport type RouteDefinitionIface<Config = JsonObject> =\n | HttpChannelRouteDefinitionIface<Config>\n | WebSocketChannelRouteDefinitionIface<Config>;\nexport type ChannelEventHandlersIface<Config, State> = {\n [Kind in keyof ChannelSemanticDataByKindIface]?: (\n data: ChannelSemanticDataByKindIface[Kind],\n ctx: ChannelEventContextIface<Config, State>,\n ) => Promise<void>;\n};\nexport type ChannelEventKind = keyof ChannelSemanticDataByKindIface;\nexport interface ChannelDefinitionIface<\n Config = JsonObject,\n Inbound = JsonValue,\n State = JsonValue,\n> {\n name: string;\n config?: Config;\n installed?: ProviderRef;\n configure?(config: Config): ChannelDefinitionIface<Config, Inbound, State>;\n credentials: { app: string | null; secrets?: string[] };\n identity:\n | {\n kind: 'redirect';\n start(\n args: { ticket: string; principal: PrincipalRef },\n ctx: ChannelReceiveContextIface<Config>,\n ): Promise<URL>;\n }\n | {\n kind: 'challenge';\n deliver(\n args: { principal: PrincipalRef; code: string },\n ctx: ChannelReceiveContextIface<Config>,\n ): Promise<void>;\n }\n | { kind: 'none' };\n places: { kinds: readonly string[]; defaults?(place: PlaceRef): PlaceDefaultsIface | null };\n routes?: RouteDefinitionIface<Config>[];\n listeners?: {\n key: string;\n run(ctx: ChannelReceiveContextIface<Config> & { signal: AbortSignal }): Promise<void>;\n }[];\n receive(input: Inbound, ctx: ChannelReceiveContextIface<Config>): Promise<ChannelReceiveResult>;\n events?: ChannelEventHandlersIface<Config, State>;\n}\nexport const defineChannel = <Config = JsonObject, Inbound = JsonValue, State = JsonValue>(\n definition: ChannelDefinitionIface<Config, Inbound, State>,\n): ChannelDefinitionIface<Config, Inbound, State> => definition;\n"],
|
|
5
|
-
"mappings": "AACA,YAAY,OAAO;AACnB,SAAS,wBAAyD;
|
|
6
|
-
"names": ["ChannelReplies", "ChannelAudience", "ChannelCreate"]
|
|
4
|
+
"sourcesContent": ["import type { ContentBlock } from '@agentclientprotocol/sdk/experimental/v2';\nimport * as z from 'zod';\nimport { jsonObjectSchema, type JsonObject, type JsonValue } from \"./json.mjs\";\nimport type { ChannelSemanticDataByKindIface } from \"./semantic-events.mjs\";\n\n// Handles carry no authority until the platform validates their binding and invocation signature.\nexport const personHandleSchema = z.string().min(1).brand<'ChannelPerson'>();\nexport const conversationHandleSchema = z.string().min(1).brand<'ChannelConversation'>();\nexport type PersonHandle = z.infer<typeof personHandleSchema>;\nexport type ConversationHandle = z.infer<typeof conversationHandleSchema>;\n\nexport const principalRefSchema = z.object({\n id: z.string().min(1),\n tenant: z.string().min(1).optional(),\n displayName: z.string().optional(),\n});\nexport type PrincipalRef = z.infer<typeof principalRefSchema>;\nexport interface PlaceRef {\n kind: string;\n id: string;\n tenant?: string;\n parent?: PlaceRef;\n title?: string;\n}\nexport const placeRefSchema: z.ZodType<PlaceRef> = z.lazy(() =>\n z.object({\n kind: z.string().min(1),\n id: z.string().min(1),\n tenant: z.string().min(1).optional(),\n parent: placeRefSchema.optional(),\n title: z.string().optional(),\n }),\n);\nexport interface OriginIface {\n place: PlaceRef;\n ref?: JsonObject;\n}\nexport const originSchema = z.object({ place: placeRefSchema, ref: jsonObjectSchema.optional() });\n\nexport type PersonResolution =\n | { kind: 'member'; person: PersonHandle; displayName: string }\n | { kind: 'unlinked'; linkUrl: string }\n | { kind: 'blocked'; reason: 'not-in-organization' | 'suspended' };\nexport enum ChannelReplies {\n Origin = 'origin',\n All = 'all',\n}\nexport enum ChannelAudience {\n Members = 'members',\n Anyone = 'anyone',\n}\nexport enum ChannelCreate {\n DirectWithAgent = 'direct-with-agent',\n Group = 'group',\n}\nexport const placePolicySchema = z.object({\n replies: z.nativeEnum(ChannelReplies),\n audience: z.nativeEnum(ChannelAudience),\n});\nexport interface PlacePolicy {\n replies: ChannelReplies | `${ChannelReplies}`;\n audience: ChannelAudience | `${ChannelAudience}`;\n}\nexport interface PlaceDefaultsIface extends PlacePolicy {\n create: ChannelCreate | `${ChannelCreate}`;\n}\nexport type PlaceResolution =\n | { kind: 'connected'; conversation: ConversationHandle; policy: PlacePolicy }\n | { kind: 'unconnected'; connectUrl: string; defaults: PlaceDefaultsIface | null };\nexport interface Refusal {\n refused: 'unlinked' | 'no-access' | 'unconnected' | 'not-audience';\n linkUrl?: string;\n connectUrl?: string;\n message: string;\n}\nexport type ChannelReceiveResult =\n | { accepted: true }\n | { accepted: false; refusal: Refusal }\n | { ignored: true; reason: string };\nexport const refusalSchema = z.object({\n refused: z.union([\n z.literal('unlinked'),\n z.literal('no-access'),\n z.literal('unconnected'),\n z.literal('not-audience'),\n ]),\n linkUrl: z.string().optional(),\n connectUrl: z.string().optional(),\n message: z.string(),\n});\nexport const channelReceiveResultSchema = z.union([\n z.object({ accepted: z.literal(true) }),\n z.object({ accepted: z.literal(false), refusal: refusalSchema }),\n z.object({ ignored: z.literal(true), reason: z.string() }),\n]);\nexport enum ChannelCredentialKind {\n App = 'app',\n OAuth = 'oauth',\n None = 'none',\n}\nexport const channelCredentialHandleSchema = z.string().min(1).brand<'ChannelCredential'>();\nexport type ChannelCredentialHandle = z.infer<typeof channelCredentialHandleSchema>;\nexport type ChannelCredentialRef =\n | { kind: ChannelCredentialKind.App; tenant?: string }\n | { kind: ChannelCredentialKind.OAuth; handle: ChannelCredentialHandle }\n | { kind: ChannelCredentialKind.None };\nexport enum ChannelSigningAlgorithm {\n HmacSha256 = 'hmac-sha256',\n HmacSha1 = 'hmac-sha1',\n Ed25519 = 'ed25519',\n}\nexport enum ChannelSignatureEncoding {\n Hex = 'hex',\n Base64 = 'base64',\n}\nexport enum ChannelOAuthClientAuthentication {\n Body = 'body',\n Basic = 'basic',\n None = 'none',\n}\nexport interface ChannelCredentialRequestInitIface extends RequestInit {\n credential?: ChannelCredentialRef;\n}\nexport interface ChannelVerifyOptionsIface {\n algorithm: ChannelSigningAlgorithm;\n encoding: ChannelSignatureEncoding;\n data: string;\n signature: string;\n}\nexport interface ChannelOAuthExchangeOptionsIface {\n url: string;\n parameters: Record<string, string>;\n authentication: ChannelOAuthClientAuthentication;\n clientId?: string;\n signal?: AbortSignal;\n}\nexport interface ChannelCredentialConnectOptionsIface {\n url: string;\n signal?: AbortSignal;\n}\nexport interface ChannelCredentialInjectionIface {\n path: string[];\n credential: ChannelCredentialRef;\n}\nexport interface ChannelCredentialSocketIface {\n messages: AsyncIterable<string | Uint8Array>;\n send(\n data: string | Uint8Array,\n options?: { inject?: ChannelCredentialInjectionIface[] },\n ): Promise<void>;\n close(code?: number, reason?: string): Promise<void>;\n closeCode(): number | null;\n}\nexport interface ChannelCredentialsIface {\n // Installed credentials stay with the host in every execution mode.\n client(): Promise<{ clientId: string }>;\n verify(args: ChannelVerifyOptionsIface): Promise<boolean>;\n exchange(args: ChannelOAuthExchangeOptionsIface): Promise<ChannelCredentialHandle>;\n // Requests without an explicit credential are unauthenticated.\n fetch(input: RequestInfo | URL, init?: ChannelCredentialRequestInitIface): Promise<Response>;\n connect(args: ChannelCredentialConnectOptionsIface): Promise<ChannelCredentialSocketIface>;\n // Only explicitly declared project secrets can be read by authored code.\n secret(name: string): Promise<string | null>;\n}\nexport interface ChannelPostArgsIface {\n from: PersonHandle;\n content: ContentBlock[];\n context?: string[];\n origin: OriginIface;\n idempotencyKey: string;\n waitForAcceptance?: boolean;\n}\nexport interface ChannelConversationIface {\n post(args: ChannelPostArgsIface): Promise<{ messageId: string; turnId?: string } | Refusal>;\n input(args: {\n label: string;\n principal?: PrincipalRef;\n content: ContentBlock[];\n context?: string[];\n origin: OriginIface;\n idempotencyKey: string;\n waitForAcceptance?: boolean;\n }): Promise<{ inputId: string; turnId?: string } | Refusal>;\n attach(args: {\n origin: OriginIface;\n content: ContentBlock[];\n label: string;\n idempotencyKey: string;\n from?: PersonHandle;\n }): Promise<{ messageId: string } | Refusal>;\n edit(args: {\n externalKey: string;\n by: PersonHandle;\n content: ContentBlock[];\n }): Promise<{ messageId: string } | Refusal>;\n remove(args: { externalKey: string; by: PersonHandle }): Promise<{ removed: boolean } | Refusal>;\n react(args: {\n target: { externalKey: string } | { replyOf: { externalKey: string; turnId: string } };\n emoji: string;\n by: PersonHandle;\n op: 'add' | 'remove';\n }): Promise<{ ok: true } | Refusal>;\n}\nexport type SemanticEvent = {\n [Kind in keyof ChannelSemanticDataByKindIface]: {\n type: Kind;\n data: ChannelSemanticDataByKindIface[Kind];\n seq: number;\n };\n}[keyof ChannelSemanticDataByKindIface];\nexport interface ChannelReceiveContextIface<Config = JsonObject> {\n binding: {\n id: string;\n url: string;\n owner: { kind: 'agent'; definitionId: string } | { kind: 'install'; installId: string };\n };\n config: Config;\n credentials: ChannelCredentialsIface;\n people: {\n resolve(principal: PrincipalRef): Promise<PersonResolution>;\n identify(person: PersonHandle): Promise<PrincipalRef | null>;\n // Tenant-wide uninstall/revocation also disconnects that tenant's places.\n revoke(args: {\n principal?: PrincipalRef;\n tenant?: string;\n reason: 'deactivated' | 'uninstalled' | 'provider-revoked';\n }): Promise<void>;\n confirm(args: { ticket: string; principal: PrincipalRef }): Promise<{ linked: true } | Refusal>;\n };\n places: {\n // Explicit anyone/group defaults may create a Shared chat while resolving a new place.\n resolve(place: PlaceRef): Promise<PlaceResolution>;\n observers(place: PlaceRef): Promise<ConversationHandle[]>;\n connect(\n place: PlaceRef,\n to: {\n by: PersonHandle;\n conversation?: ConversationHandle;\n create?: ChannelCreate | `${ChannelCreate}`;\n },\n ): Promise<ConversationHandle>;\n disconnect(place: PlaceRef, by: PersonHandle): Promise<void>;\n follow(\n place: PlaceRef,\n args: { by: PersonHandle; conversation: ConversationHandle; ttlSeconds?: number },\n ): Promise<void>;\n unfollow(\n place: PlaceRef,\n args: { by: PersonHandle; conversation: ConversationHandle },\n ): Promise<void>;\n };\n conversation(handle: ConversationHandle): ChannelConversationIface;\n observe(\n handle: ConversationHandle,\n args: { turnId: string; signal?: AbortSignal },\n ): AsyncIterable<SemanticEvent>;\n decisions: {\n resolve(args: {\n decisionId: string;\n outcome: JsonValue;\n by: PersonHandle;\n }): Promise<{ resolved: boolean } | Refusal>;\n };\n turns: {\n cancel(args: {\n conversation: ConversationHandle;\n by?: PersonHandle;\n turnId?: string;\n }): Promise<{ accepted: boolean } | Refusal>;\n };\n store: {\n get(key: string): Promise<JsonValue | null>;\n set(key: string, value: JsonValue | null, options?: { ttlSeconds?: number }): Promise<void>;\n };\n log(message: string, details?: JsonObject): void;\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// State starts null and persists for the callbacks of one turn.\nexport interface ChannelTurnStateIface<State> {\n get(): State | null;\n set(state: State | null): void;\n}\nexport interface ChannelEventContextIface<Config = JsonObject, State = JsonValue> extends Pick<\n ChannelReceiveContextIface<Config>,\n 'binding' | 'config' | 'credentials' | 'store' | 'log'\n> {\n origin: OriginIface;\n conversation: ConversationHandle;\n turn: { id: string; agent: { displayName: string } };\n state: ChannelTurnStateIface<State>;\n}\nexport interface ChannelRouteContextIface<\n Config = JsonObject,\n> extends ChannelReceiveContextIface<Config> {\n request: Request;\n receive(input: JsonValue): Promise<ChannelReceiveResult>;\n}\nexport interface HttpChannelRouteDefinitionIface<Config = JsonObject> {\n method: 'GET' | 'POST' | 'PUT' | 'DELETE';\n path: string;\n handler(args: ChannelRouteContextIface<Config>): Promise<Response>;\n}\nexport interface WebSocketChannelRouteDefinitionIface<Config = JsonObject> {\n method: 'WS';\n path: string;\n handler(\n args: ChannelRouteContextIface<Config> & { socket: ChannelSocketIface },\n ): Promise<Response | void>;\n}\nexport type RouteDefinitionIface<Config = JsonObject> =\n | HttpChannelRouteDefinitionIface<Config>\n | WebSocketChannelRouteDefinitionIface<Config>;\nexport type ChannelEventHandlersIface<Config, State> = {\n [Kind in keyof ChannelSemanticDataByKindIface]?: (\n data: ChannelSemanticDataByKindIface[Kind],\n ctx: ChannelEventContextIface<Config, State>,\n ) => Promise<void>;\n};\nexport type ChannelEventKind = keyof ChannelSemanticDataByKindIface;\nexport interface ChannelDefinitionIface<\n Config = JsonObject,\n Inbound = JsonValue,\n State = JsonValue,\n> {\n name: string;\n config?: Config;\n configure?(config: Config): ChannelDefinitionIface<Config, Inbound, State>;\n credentials: { app: string | null; secrets?: string[] };\n identity:\n | {\n kind: 'redirect';\n start(\n args: { ticket: string; principal: PrincipalRef },\n ctx: ChannelReceiveContextIface<Config>,\n ): Promise<URL>;\n }\n | {\n kind: 'challenge';\n deliver(\n args: { principal: PrincipalRef; code: string },\n ctx: ChannelReceiveContextIface<Config>,\n ): Promise<void>;\n }\n | { kind: 'none' };\n places: { kinds: readonly string[]; defaults?(place: PlaceRef): PlaceDefaultsIface | null };\n resources?: {\n authorize(\n args: { place: PlaceRef; principal: PrincipalRef },\n ctx: ChannelReceiveContextIface<Config>,\n ): Promise<boolean>;\n resolve(\n args: { url: string; principal: PrincipalRef },\n ctx: ChannelReceiveContextIface<Config>,\n ): Promise<PlaceRef | null>;\n };\n routes?: RouteDefinitionIface<Config>[];\n listeners?: {\n key: string;\n run(ctx: ChannelReceiveContextIface<Config> & { signal: AbortSignal }): Promise<void>;\n }[];\n receive(input: Inbound, ctx: ChannelReceiveContextIface<Config>): Promise<ChannelReceiveResult>;\n events?: ChannelEventHandlersIface<Config, State>;\n}\nexport const defineChannel = <Config = JsonObject, Inbound = JsonValue, State = JsonValue>(\n definition: ChannelDefinitionIface<Config, Inbound, State>,\n): ChannelDefinitionIface<Config, Inbound, State> => definition;\n"],
|
|
5
|
+
"mappings": "AACA,YAAY,OAAO;AACnB,SAAS,wBAAyD;AAI3D,MAAM,qBAAqB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,MAAuB;AACpE,MAAM,2BAA2B,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,MAA6B;AAIhF,MAAM,qBAAqB,EAAE,OAAO;AAAA,EACzC,IAAI,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACpB,QAAQ,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AAAA,EACnC,aAAa,EAAE,OAAO,EAAE,SAAS;AACnC,CAAC;AASM,MAAM,iBAAsC,EAAE;AAAA,EAAK,MACxD,EAAE,OAAO;AAAA,IACP,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,IACtB,IAAI,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,IACpB,QAAQ,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AAAA,IACnC,QAAQ,eAAe,SAAS;AAAA,IAChC,OAAO,EAAE,OAAO,EAAE,SAAS;AAAA,EAC7B,CAAC;AACH;AAKO,MAAM,eAAe,EAAE,OAAO,EAAE,OAAO,gBAAgB,KAAK,iBAAiB,SAAS,EAAE,CAAC;AAMzF,IAAK,iBAAL,kBAAKA,oBAAL;AACL,EAAAA,gBAAA,YAAS;AACT,EAAAA,gBAAA,SAAM;AAFI,SAAAA;AAAA,GAAA;AAIL,IAAK,kBAAL,kBAAKC,qBAAL;AACL,EAAAA,iBAAA,aAAU;AACV,EAAAA,iBAAA,YAAS;AAFC,SAAAA;AAAA,GAAA;AAIL,IAAK,gBAAL,kBAAKC,mBAAL;AACL,EAAAA,eAAA,qBAAkB;AAClB,EAAAA,eAAA,WAAQ;AAFE,SAAAA;AAAA,GAAA;AAIL,MAAM,oBAAoB,EAAE,OAAO;AAAA,EACxC,SAAS,EAAE,WAAW,cAAc;AAAA,EACpC,UAAU,EAAE,WAAW,eAAe;AACxC,CAAC;AAqBM,MAAM,gBAAgB,EAAE,OAAO;AAAA,EACpC,SAAS,EAAE,MAAM;AAAA,IACf,EAAE,QAAQ,UAAU;AAAA,IACpB,EAAE,QAAQ,WAAW;AAAA,IACrB,EAAE,QAAQ,aAAa;AAAA,IACvB,EAAE,QAAQ,cAAc;AAAA,EAC1B,CAAC;AAAA,EACD,SAAS,EAAE,OAAO,EAAE,SAAS;AAAA,EAC7B,YAAY,EAAE,OAAO,EAAE,SAAS;AAAA,EAChC,SAAS,EAAE,OAAO;AACpB,CAAC;AACM,MAAM,6BAA6B,EAAE,MAAM;AAAA,EAChD,EAAE,OAAO,EAAE,UAAU,EAAE,QAAQ,IAAI,EAAE,CAAC;AAAA,EACtC,EAAE,OAAO,EAAE,UAAU,EAAE,QAAQ,KAAK,GAAG,SAAS,cAAc,CAAC;AAAA,EAC/D,EAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,IAAI,GAAG,QAAQ,EAAE,OAAO,EAAE,CAAC;AAC3D,CAAC;AACM,IAAK,wBAAL,kBAAKC,2BAAL;AACL,EAAAA,uBAAA,SAAM;AACN,EAAAA,uBAAA,WAAQ;AACR,EAAAA,uBAAA,UAAO;AAHG,SAAAA;AAAA,GAAA;AAKL,MAAM,gCAAgC,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,MAA2B;AAMnF,IAAK,0BAAL,kBAAKC,6BAAL;AACL,EAAAA,yBAAA,gBAAa;AACb,EAAAA,yBAAA,cAAW;AACX,EAAAA,yBAAA,aAAU;AAHA,SAAAA;AAAA,GAAA;AAKL,IAAK,2BAAL,kBAAKC,8BAAL;AACL,EAAAA,0BAAA,SAAM;AACN,EAAAA,0BAAA,YAAS;AAFC,SAAAA;AAAA,GAAA;AAIL,IAAK,mCAAL,kBAAKC,sCAAL;AACL,EAAAA,kCAAA,UAAO;AACP,EAAAA,kCAAA,WAAQ;AACR,EAAAA,kCAAA,UAAO;AAHG,SAAAA;AAAA,GAAA;AA+PL,MAAM,gBAAgB,CAC3B,eACmD;",
|
|
6
|
+
"names": ["ChannelReplies", "ChannelAudience", "ChannelCreate", "ChannelCredentialKind", "ChannelSigningAlgorithm", "ChannelSignatureEncoding", "ChannelOAuthClientAuthentication"]
|
|
7
7
|
}
|
|
@@ -24,4 +24,5 @@ export interface SandboxConformanceReportIface {
|
|
|
24
24
|
passed: boolean;
|
|
25
25
|
cases: ConformanceCaseResultIface[];
|
|
26
26
|
}
|
|
27
|
+
export declare const DURABLE_CONFORMANCE_SCRIPT = "echo one; echo err-one >&2; sleep 2; echo two; echo err-two >&2; exit 7";
|
|
27
28
|
export declare const runSandboxConformance: (args: RunSandboxConformanceArgsIface) => Promise<SandboxConformanceReportIface>;
|
|
@@ -183,6 +183,136 @@ const sandboxCases = (largeFileBytes) => [
|
|
|
183
183
|
}
|
|
184
184
|
}
|
|
185
185
|
];
|
|
186
|
+
const DURABLE_CONFORMANCE_SCRIPT = "echo one; echo err-one >&2; sleep 2; echo two; echo err-two >&2; exit 7";
|
|
187
|
+
const textOf = (chunks) => new TextDecoder().decode(concatChunks(chunks));
|
|
188
|
+
const concatChunks = (chunks) => {
|
|
189
|
+
const out = new Uint8Array(chunks.reduce((sum, chunk) => sum + chunk.byteLength, 0));
|
|
190
|
+
let offset = 0;
|
|
191
|
+
for (const chunk of chunks) {
|
|
192
|
+
out.set(chunk, offset);
|
|
193
|
+
offset += chunk.byteLength;
|
|
194
|
+
}
|
|
195
|
+
return out;
|
|
196
|
+
};
|
|
197
|
+
const readThrough = async (stream, text) => {
|
|
198
|
+
const reader = stream.getReader();
|
|
199
|
+
const chunks = [];
|
|
200
|
+
while (!textOf(chunks).includes(text)) {
|
|
201
|
+
const next = await reader.read();
|
|
202
|
+
if (next.done) throw new Error(`stream ended before ${JSON.stringify(text)}`);
|
|
203
|
+
chunks.push(next.value);
|
|
204
|
+
}
|
|
205
|
+
return concatChunks(chunks);
|
|
206
|
+
};
|
|
207
|
+
const DURABLE_STDOUT = "one\ntwo\n";
|
|
208
|
+
const DURABLE_STDERR = "err-one\nerr-two\n";
|
|
209
|
+
const after = (text, offset) => text.slice(offset);
|
|
210
|
+
const attachOrFail = async (sandbox, options) => {
|
|
211
|
+
check(sandbox.attachProcess != null, "attachProcess is missing");
|
|
212
|
+
const attached = await sandbox.attachProcess?.(options);
|
|
213
|
+
if (attached == null) throw new Error("attachProcess found no process for a durable ref");
|
|
214
|
+
return attached;
|
|
215
|
+
};
|
|
216
|
+
const durableCases = async (targets, record, prefix) => {
|
|
217
|
+
const state = {
|
|
218
|
+
spawned: null
|
|
219
|
+
};
|
|
220
|
+
await record(
|
|
221
|
+
`${prefix}durable processes: re-attach resumes at the delivered offsets`,
|
|
222
|
+
async () => {
|
|
223
|
+
const controller = new AbortController();
|
|
224
|
+
const sandbox = await targets.spawnOn();
|
|
225
|
+
const process = await sandbox.spawn({
|
|
226
|
+
command: DURABLE_CONFORMANCE_SCRIPT,
|
|
227
|
+
shell: true,
|
|
228
|
+
durable: true,
|
|
229
|
+
abortSignal: controller.signal
|
|
230
|
+
});
|
|
231
|
+
const ref = process.ref;
|
|
232
|
+
check(typeof ref === "string" && ref.length > 0, "a durable process has no ref");
|
|
233
|
+
if (ref == null) return;
|
|
234
|
+
const [stdout, stderr] = await Promise.all([
|
|
235
|
+
readThrough(process.stdout, "one\n"),
|
|
236
|
+
readThrough(process.stderr, "err-one\n")
|
|
237
|
+
]);
|
|
238
|
+
targets.drop({ controller, sandbox });
|
|
239
|
+
const options = { ref, stdoutOffset: stdout.byteLength, stderrOffset: stderr.byteLength };
|
|
240
|
+
const attached = await attachOrFail(await targets.attachOn(), options);
|
|
241
|
+
check(
|
|
242
|
+
attached.stdoutOffset === options.stdoutOffset && attached.stderrOffset === options.stderrOffset,
|
|
243
|
+
`attached at ${attached.stdoutOffset}/${attached.stderrOffset}, asked ${options.stdoutOffset}/${options.stderrOffset}`
|
|
244
|
+
);
|
|
245
|
+
const [restOut, restErr, exit] = await Promise.all([
|
|
246
|
+
streamToString(attached.stdout),
|
|
247
|
+
streamToString(attached.stderr),
|
|
248
|
+
attached.wait()
|
|
249
|
+
]);
|
|
250
|
+
const out = textOf([stdout]) + restOut;
|
|
251
|
+
const err = textOf([stderr]) + restErr;
|
|
252
|
+
check(out === DURABLE_STDOUT, `stdout across the re-attach: ${JSON.stringify(out)}`);
|
|
253
|
+
check(err === DURABLE_STDERR, `stderr across the re-attach: ${JSON.stringify(err)}`);
|
|
254
|
+
check(exit.exitCode === 7, `exit code ${exit.exitCode}`);
|
|
255
|
+
state.spawned = options;
|
|
256
|
+
}
|
|
257
|
+
);
|
|
258
|
+
await record(
|
|
259
|
+
`${prefix}durable processes: attach after exit keeps output and exit code`,
|
|
260
|
+
async () => {
|
|
261
|
+
const options = state.spawned;
|
|
262
|
+
if (options == null) throw new Error("the re-attach case failed");
|
|
263
|
+
const attached = await attachOrFail(await targets.attachOn(), options);
|
|
264
|
+
const [out, err, exit] = await Promise.all([
|
|
265
|
+
streamToString(attached.stdout),
|
|
266
|
+
streamToString(attached.stderr),
|
|
267
|
+
attached.wait()
|
|
268
|
+
]);
|
|
269
|
+
check(
|
|
270
|
+
out === after(DURABLE_STDOUT, options.stdoutOffset) && err === after(DURABLE_STDERR, options.stderrOffset),
|
|
271
|
+
`after exit: ${JSON.stringify([out, err])}`
|
|
272
|
+
);
|
|
273
|
+
check(exit.exitCode === 7, `exit code after exit ${exit.exitCode}`);
|
|
274
|
+
}
|
|
275
|
+
);
|
|
276
|
+
await record(`${prefix}durable processes: kill through an attached handle`, async () => {
|
|
277
|
+
const controller = new AbortController();
|
|
278
|
+
const sandbox = await targets.spawnOn();
|
|
279
|
+
const process = await sandbox.spawn({
|
|
280
|
+
command: "sleep 30",
|
|
281
|
+
shell: true,
|
|
282
|
+
durable: true,
|
|
283
|
+
abortSignal: controller.signal
|
|
284
|
+
});
|
|
285
|
+
const ref = process.ref;
|
|
286
|
+
if (ref == null) throw new Error("a durable process has no ref");
|
|
287
|
+
targets.drop({ controller, sandbox });
|
|
288
|
+
const attached = await attachOrFail(await targets.attachOn(), {
|
|
289
|
+
ref,
|
|
290
|
+
stdoutOffset: 0,
|
|
291
|
+
stderrOffset: 0
|
|
292
|
+
});
|
|
293
|
+
void streamToString(attached.stdout).catch(() => void 0);
|
|
294
|
+
void streamToString(attached.stderr).catch(() => void 0);
|
|
295
|
+
await attached.kill();
|
|
296
|
+
const result = await withTimeout(attached.wait(), 1e4, "wait after kill");
|
|
297
|
+
check(result.exitCode !== 0, "killed process exited 0");
|
|
298
|
+
});
|
|
299
|
+
await record(`${prefix}durable processes: unknown refs and ordinary processes`, async () => {
|
|
300
|
+
const sandbox = await targets.attachOn();
|
|
301
|
+
const unknown = await sandbox.attachProcess?.({
|
|
302
|
+
ref: "conformance-unknown-ref",
|
|
303
|
+
stdoutOffset: 0,
|
|
304
|
+
stderrOffset: 0
|
|
305
|
+
});
|
|
306
|
+
check(unknown === null, "an unknown ref attached to a process");
|
|
307
|
+
const ordinary = await (await targets.spawnOn()).spawn({ command: "echo", args: ["ordinary"] });
|
|
308
|
+
check(ordinary.ref == null, "an ordinary process has a ref");
|
|
309
|
+
await Promise.all([
|
|
310
|
+
streamToString(ordinary.stdout),
|
|
311
|
+
streamToString(ordinary.stderr),
|
|
312
|
+
ordinary.wait()
|
|
313
|
+
]);
|
|
314
|
+
});
|
|
315
|
+
};
|
|
186
316
|
const startFromProvider = async (args, provider, overrides = {}) => {
|
|
187
317
|
const implementation = provider.definition.environment(
|
|
188
318
|
overrides.environmentOptions ?? args.environmentOptions
|
|
@@ -461,6 +591,25 @@ const runSandboxConformance = async (args) => {
|
|
|
461
591
|
const root = target.resolvePath(`conformance-${crypto.randomUUID().slice(0, 8)}`);
|
|
462
592
|
const list = sandboxCases(args.largeFileBytes ?? 5 * 1024 * 1024);
|
|
463
593
|
for (const entry of list) await record(entry.name, () => entry.run(target, root));
|
|
594
|
+
const durable = target.attachProcess != null;
|
|
595
|
+
if (durable)
|
|
596
|
+
await durableCases(
|
|
597
|
+
{
|
|
598
|
+
spawnOn: async () => target,
|
|
599
|
+
attachOn: async () => target,
|
|
600
|
+
drop: ({ controller }) => controller.abort()
|
|
601
|
+
},
|
|
602
|
+
record,
|
|
603
|
+
""
|
|
604
|
+
);
|
|
605
|
+
else
|
|
606
|
+
cases.push({
|
|
607
|
+
name: "durable processes",
|
|
608
|
+
status: ConformanceCaseStatus.Skipped,
|
|
609
|
+
durationMs: 0,
|
|
610
|
+
error: null,
|
|
611
|
+
detail: "the sandbox has no attachProcess"
|
|
612
|
+
});
|
|
464
613
|
if (args.viaWire !== false) {
|
|
465
614
|
const network = createInMemoryHandleNetwork();
|
|
466
615
|
network.serve({ url: "mem://conformance", sandbox: target });
|
|
@@ -512,6 +661,30 @@ const runSandboxConformance = async (args) => {
|
|
|
512
661
|
readOnly.close();
|
|
513
662
|
}
|
|
514
663
|
});
|
|
664
|
+
if (durable) {
|
|
665
|
+
const connections = [];
|
|
666
|
+
const open = async () => {
|
|
667
|
+
const connection = await network.connect({
|
|
668
|
+
url: "mem://conformance",
|
|
669
|
+
token: "conformance"
|
|
670
|
+
});
|
|
671
|
+
connections.push(connection);
|
|
672
|
+
return connection;
|
|
673
|
+
};
|
|
674
|
+
try {
|
|
675
|
+
await durableCases(
|
|
676
|
+
{
|
|
677
|
+
spawnOn: open,
|
|
678
|
+
attachOn: open,
|
|
679
|
+
drop: ({ sandbox: sandbox2 }) => connections.find((entry) => entry === sandbox2)?.close()
|
|
680
|
+
},
|
|
681
|
+
record,
|
|
682
|
+
"handle rpc: "
|
|
683
|
+
);
|
|
684
|
+
} finally {
|
|
685
|
+
for (const connection of connections) connection.close();
|
|
686
|
+
}
|
|
687
|
+
}
|
|
515
688
|
} finally {
|
|
516
689
|
client.close();
|
|
517
690
|
await target.removePath({ path: `${root}-wire`, recursive: true, force: true }).catch(() => void 0);
|
|
@@ -537,6 +710,7 @@ const runSandboxConformance = async (args) => {
|
|
|
537
710
|
return { passed: cases.every((entry) => entry.status !== ConformanceCaseStatus.Failed), cases };
|
|
538
711
|
};
|
|
539
712
|
export {
|
|
713
|
+
DURABLE_CONFORMANCE_SCRIPT,
|
|
540
714
|
runSandboxConformance
|
|
541
715
|
};
|
|
542
716
|
//# sourceMappingURL=sandbox-kit.mjs.map
|