@finalai/agent-provider 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of @finalai/agent-provider might be problematic. Click here for more details.
- package/README.md +12 -0
- package/dist/modules/channel-context.d.mts +102 -0
- package/dist/modules/channel-context.mjs +52 -0
- package/dist/modules/channel-context.mjs.map +7 -0
- package/dist/modules/channel-socket.d.mts +65 -0
- package/dist/modules/channel-socket.mjs +188 -0
- package/dist/modules/channel-socket.mjs.map +7 -0
- package/dist/modules/channel.d.mts +382 -0
- package/dist/modules/channel.mjs +146 -0
- package/dist/modules/channel.mjs.map +7 -0
- package/dist/modules/conformance/agent.d.mts +20 -0
- package/dist/modules/conformance/agent.mjs +623 -0
- package/dist/modules/conformance/agent.mjs.map +7 -0
- package/dist/modules/conformance/fixtures.d.mts +41 -0
- package/dist/modules/conformance/fixtures.mjs +190 -0
- package/dist/modules/conformance/fixtures.mjs.map +7 -0
- package/dist/modules/conformance/harness-kit.d.mts +82 -0
- package/dist/modules/conformance/harness-kit.mjs +1303 -0
- package/dist/modules/conformance/harness-kit.mjs.map +7 -0
- package/dist/modules/conformance/image.d.mts +2 -0
- package/dist/modules/conformance/image.mjs +79 -0
- package/dist/modules/conformance/image.mjs.map +7 -0
- package/dist/modules/conformance/index.d.mts +8 -0
- package/dist/modules/conformance/index.mjs +12 -0
- package/dist/modules/conformance/index.mjs.map +7 -0
- package/dist/modules/conformance/local-harness.d.mts +25 -0
- package/dist/modules/conformance/local-harness.mjs +108 -0
- package/dist/modules/conformance/local-harness.mjs.map +7 -0
- package/dist/modules/conformance/protocol.d.mts +30 -0
- package/dist/modules/conformance/protocol.mjs +56 -0
- package/dist/modules/conformance/protocol.mjs.map +7 -0
- package/dist/modules/conformance/sandbox-kit.d.mts +19 -0
- package/dist/modules/conformance/sandbox-kit.mjs +320 -0
- package/dist/modules/conformance/sandbox-kit.mjs.map +7 -0
- package/dist/modules/conformance/scripted-model/chat-completions.d.mts +30 -0
- package/dist/modules/conformance/scripted-model/chat-completions.mjs +125 -0
- package/dist/modules/conformance/scripted-model/chat-completions.mjs.map +7 -0
- package/dist/modules/conformance/scripted-model/directives.d.mts +84 -0
- package/dist/modules/conformance/scripted-model/directives.mjs +304 -0
- package/dist/modules/conformance/scripted-model/directives.mjs.map +7 -0
- package/dist/modules/conformance/scripted-model/handler.d.mts +14 -0
- package/dist/modules/conformance/scripted-model/handler.mjs +133 -0
- package/dist/modules/conformance/scripted-model/handler.mjs.map +7 -0
- package/dist/modules/conformance/scripted-model/index.d.mts +6 -0
- package/dist/modules/conformance/scripted-model/index.mjs +7 -0
- package/dist/modules/conformance/scripted-model/index.mjs.map +7 -0
- package/dist/modules/conformance/scripted-model/messages.d.mts +39 -0
- package/dist/modules/conformance/scripted-model/messages.mjs +139 -0
- package/dist/modules/conformance/scripted-model/messages.mjs.map +7 -0
- package/dist/modules/conformance/scripted-model/responses.d.mts +62 -0
- package/dist/modules/conformance/scripted-model/responses.mjs +273 -0
- package/dist/modules/conformance/scripted-model/responses.mjs.map +7 -0
- package/dist/modules/conformance/scripted-model/sse.d.mts +15 -0
- package/dist/modules/conformance/scripted-model/sse.mjs +75 -0
- package/dist/modules/conformance/scripted-model/sse.mjs.map +7 -0
- package/dist/modules/conformance/v1-agent.d.mts +24 -0
- package/dist/modules/conformance/v1-agent.mjs +40 -0
- package/dist/modules/conformance/v1-agent.mjs.map +7 -0
- package/dist/modules/credential-routes.d.mts +24 -0
- package/dist/modules/credential-routes.mjs +25 -0
- package/dist/modules/credential-routes.mjs.map +7 -0
- package/dist/modules/credentials.d.mts +206 -0
- package/dist/modules/credentials.mjs +207 -0
- package/dist/modules/credentials.mjs.map +7 -0
- package/dist/modules/dynamic.d.mts +32 -0
- package/dist/modules/dynamic.mjs +77 -0
- package/dist/modules/dynamic.mjs.map +7 -0
- package/dist/modules/harness.d.mts +397 -0
- package/dist/modules/harness.mjs +213 -0
- package/dist/modules/harness.mjs.map +7 -0
- package/dist/modules/index.d.mts +15 -0
- package/dist/modules/index.mjs +40 -0
- package/dist/modules/index.mjs.map +7 -0
- package/dist/modules/json.d.mts +12 -0
- package/dist/modules/json.mjs +19 -0
- package/dist/modules/json.mjs.map +7 -0
- package/dist/modules/local-channel-socket.d.mts +23 -0
- package/dist/modules/local-channel-socket.mjs +141 -0
- package/dist/modules/local-channel-socket.mjs.map +7 -0
- package/dist/modules/manifest.d.mts +558 -0
- package/dist/modules/manifest.mjs +266 -0
- package/dist/modules/manifest.mjs.map +7 -0
- package/dist/modules/mcp-content.d.mts +21 -0
- package/dist/modules/mcp-content.mjs +86 -0
- package/dist/modules/mcp-content.mjs.map +7 -0
- package/dist/modules/provider-ref.d.mts +29 -0
- package/dist/modules/provider-ref.mjs +55 -0
- package/dist/modules/provider-ref.mjs.map +7 -0
- package/dist/modules/sandbox/bytes.d.mts +9 -0
- package/dist/modules/sandbox/bytes.mjs +154 -0
- package/dist/modules/sandbox/bytes.mjs.map +7 -0
- package/dist/modules/sandbox/client.d.mts +51 -0
- package/dist/modules/sandbox/client.mjs +500 -0
- package/dist/modules/sandbox/client.mjs.map +7 -0
- package/dist/modules/sandbox/confined-files.d.mts +22 -0
- package/dist/modules/sandbox/confined-files.mjs +142 -0
- package/dist/modules/sandbox/confined-files.mjs.map +7 -0
- package/dist/modules/sandbox/convenience.d.mts +10 -0
- package/dist/modules/sandbox/convenience.mjs +116 -0
- package/dist/modules/sandbox/convenience.mjs.map +7 -0
- package/dist/modules/sandbox/editor.d.mts +49 -0
- package/dist/modules/sandbox/editor.mjs +43 -0
- package/dist/modules/sandbox/editor.mjs.map +7 -0
- package/dist/modules/sandbox/frame-channel.d.mts +47 -0
- package/dist/modules/sandbox/frame-channel.mjs +153 -0
- package/dist/modules/sandbox/frame-channel.mjs.map +7 -0
- package/dist/modules/sandbox/index.d.mts +18 -0
- package/dist/modules/sandbox/index.mjs +70 -0
- package/dist/modules/sandbox/index.mjs.map +7 -0
- package/dist/modules/sandbox/mcp-channel.d.mts +9 -0
- package/dist/modules/sandbox/mcp-channel.mjs +77 -0
- package/dist/modules/sandbox/mcp-channel.mjs.map +7 -0
- package/dist/modules/sandbox/mcp-hosted.d.mts +46 -0
- package/dist/modules/sandbox/mcp-hosted.mjs +221 -0
- package/dist/modules/sandbox/mcp-hosted.mjs.map +7 -0
- package/dist/modules/sandbox/mcp-search.d.mts +51 -0
- package/dist/modules/sandbox/mcp-search.mjs +129 -0
- package/dist/modules/sandbox/mcp-search.mjs.map +7 -0
- package/dist/modules/sandbox/mcp-shell.d.mts +21 -0
- package/dist/modules/sandbox/mcp-shell.mjs +205 -0
- package/dist/modules/sandbox/mcp-shell.mjs.map +7 -0
- package/dist/modules/sandbox/mcp-testing.d.mts +11 -0
- package/dist/modules/sandbox/mcp-testing.mjs +33 -0
- package/dist/modules/sandbox/mcp-testing.mjs.map +7 -0
- package/dist/modules/sandbox/mcp.d.mts +83 -0
- package/dist/modules/sandbox/mcp.mjs +971 -0
- package/dist/modules/sandbox/mcp.mjs.map +7 -0
- package/dist/modules/sandbox/memory-sandbox.d.mts +32 -0
- package/dist/modules/sandbox/memory-sandbox.mjs +416 -0
- package/dist/modules/sandbox/memory-sandbox.mjs.map +7 -0
- package/dist/modules/sandbox/memory-shell.d.mts +29 -0
- package/dist/modules/sandbox/memory-shell.mjs +278 -0
- package/dist/modules/sandbox/memory-shell.mjs.map +7 -0
- package/dist/modules/sandbox/open-scope-node.d.mts +4 -0
- package/dist/modules/sandbox/open-scope-node.mjs +19 -0
- package/dist/modules/sandbox/open-scope-node.mjs.map +7 -0
- package/dist/modules/sandbox/open-scope.d.mts +16 -0
- package/dist/modules/sandbox/open-scope.mjs +66 -0
- package/dist/modules/sandbox/open-scope.mjs.map +7 -0
- package/dist/modules/sandbox/paths.d.mts +7 -0
- package/dist/modules/sandbox/paths.mjs +50 -0
- package/dist/modules/sandbox/paths.mjs.map +7 -0
- package/dist/modules/sandbox/rpc-peer.d.mts +35 -0
- package/dist/modules/sandbox/rpc-peer.mjs +224 -0
- package/dist/modules/sandbox/rpc-peer.mjs.map +7 -0
- package/dist/modules/sandbox/seeds.d.mts +26 -0
- package/dist/modules/sandbox/seeds.mjs +228 -0
- package/dist/modules/sandbox/seeds.mjs.map +7 -0
- package/dist/modules/sandbox/server.d.mts +66 -0
- package/dist/modules/sandbox/server.mjs +567 -0
- package/dist/modules/sandbox/server.mjs.map +7 -0
- package/dist/modules/sandbox/snapshots.d.mts +49 -0
- package/dist/modules/sandbox/snapshots.mjs +55 -0
- package/dist/modules/sandbox/snapshots.mjs.map +7 -0
- package/dist/modules/sandbox/stream-mux.d.mts +18 -0
- package/dist/modules/sandbox/stream-mux.mjs +285 -0
- package/dist/modules/sandbox/stream-mux.mjs.map +7 -0
- package/dist/modules/sandbox/testing.d.mts +25 -0
- package/dist/modules/sandbox/testing.mjs +64 -0
- package/dist/modules/sandbox/testing.mjs.map +7 -0
- package/dist/modules/sandbox/types.d.mts +352 -0
- package/dist/modules/sandbox/types.mjs +86 -0
- package/dist/modules/sandbox/types.mjs.map +7 -0
- package/dist/modules/sandbox/wire.d.mts +671 -0
- package/dist/modules/sandbox/wire.mjs +537 -0
- package/dist/modules/sandbox/wire.mjs.map +7 -0
- package/dist/modules/sandbox/workspace-root.d.mts +8 -0
- package/dist/modules/sandbox/workspace-root.mjs +79 -0
- package/dist/modules/sandbox/workspace-root.mjs.map +7 -0
- package/dist/modules/schemas.d.mts +121 -0
- package/dist/modules/schemas.mjs +146 -0
- package/dist/modules/schemas.mjs.map +7 -0
- package/dist/modules/semantic-events.d.mts +31 -0
- package/dist/modules/semantic-events.mjs +23 -0
- package/dist/modules/semantic-events.mjs.map +7 -0
- package/package.json +199 -0
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import * as z from "zod";
|
|
2
|
+
import { CredentialRoute, routeGrantSchema } from "./credential-routes.mjs";
|
|
3
|
+
import { CredentialDelivery, InferenceCredentialKind } from "./credentials.mjs";
|
|
4
|
+
import { jsonObjectSchema, jsonSchemaSchema } from "./json.mjs";
|
|
5
|
+
import { BaseCapability, InstructionRole } from "./manifest.mjs";
|
|
6
|
+
import { bundleRef, providerRefSchema } from "./provider-ref.mjs";
|
|
7
|
+
import { referencedSharedSchemas, SCHEMA_IDS } from "./schemas.mjs";
|
|
8
|
+
const PENDING_BUNDLE_EXPORT = "<pending>";
|
|
9
|
+
var AcpTransport = /* @__PURE__ */ ((AcpTransport2) => {
|
|
10
|
+
AcpTransport2["Relay"] = "relay";
|
|
11
|
+
AcpTransport2["Ws"] = "ws";
|
|
12
|
+
AcpTransport2["Http"] = "http";
|
|
13
|
+
AcpTransport2["Stdio"] = "stdio";
|
|
14
|
+
return AcpTransport2;
|
|
15
|
+
})(AcpTransport || {});
|
|
16
|
+
var McpTransportKind = /* @__PURE__ */ ((McpTransportKind2) => {
|
|
17
|
+
McpTransportKind2["Acp"] = "acp";
|
|
18
|
+
McpTransportKind2["Http"] = "http";
|
|
19
|
+
McpTransportKind2["Stdio"] = "stdio";
|
|
20
|
+
return McpTransportKind2;
|
|
21
|
+
})(McpTransportKind || {});
|
|
22
|
+
var BaseToolProvision = /* @__PURE__ */ ((BaseToolProvision2) => {
|
|
23
|
+
BaseToolProvision2["Bound"] = "bound";
|
|
24
|
+
BaseToolProvision2["HostDisableable"] = "host-disableable";
|
|
25
|
+
BaseToolProvision2["HostFixed"] = "host-fixed";
|
|
26
|
+
return BaseToolProvision2;
|
|
27
|
+
})(BaseToolProvision || {});
|
|
28
|
+
var SandboxWire = /* @__PURE__ */ ((SandboxWire2) => {
|
|
29
|
+
SandboxWire2["HandleRpc"] = "handle-rpc";
|
|
30
|
+
SandboxWire2["Mcp"] = "mcp";
|
|
31
|
+
return SandboxWire2;
|
|
32
|
+
})(SandboxWire || {});
|
|
33
|
+
var UserInstructionDelivery = /* @__PURE__ */ ((UserInstructionDelivery2) => {
|
|
34
|
+
UserInstructionDelivery2["History"] = "history";
|
|
35
|
+
UserInstructionDelivery2["System"] = "system";
|
|
36
|
+
return UserInstructionDelivery2;
|
|
37
|
+
})(UserInstructionDelivery || {});
|
|
38
|
+
var HarnessTrustClass = /* @__PURE__ */ ((HarnessTrustClass2) => {
|
|
39
|
+
HarnessTrustClass2["FirstParty"] = "first-party";
|
|
40
|
+
HarnessTrustClass2["ThirdParty"] = "third-party";
|
|
41
|
+
return HarnessTrustClass2;
|
|
42
|
+
})(HarnessTrustClass || {});
|
|
43
|
+
var PromptWhileRunning = /* @__PURE__ */ ((PromptWhileRunning2) => {
|
|
44
|
+
PromptWhileRunning2["Inject"] = "inject";
|
|
45
|
+
PromptWhileRunning2["Queue"] = "queue";
|
|
46
|
+
return PromptWhileRunning2;
|
|
47
|
+
})(PromptWhileRunning || {});
|
|
48
|
+
const DEFAULT_PROMPT_WHILE_RUNNING = "queue" /* Queue */;
|
|
49
|
+
const DEFAULT_SESSION_SURVIVES_DISCONNECT = false;
|
|
50
|
+
const baseToolDeclarationSchema = z.object({
|
|
51
|
+
provision: z.nativeEnum(BaseToolProvision),
|
|
52
|
+
nativeTools: z.array(z.string())
|
|
53
|
+
});
|
|
54
|
+
const harnessDescriptionSchema = z.object({
|
|
55
|
+
// Everything configurable about this harness (model, reasoning, credentials,
|
|
56
|
+
// permission mode, instructions, skills, cwd, ...). JSON Schema so Build can
|
|
57
|
+
// render it; may $ref the shared final://schemas/* fragments.
|
|
58
|
+
configSchema: jsonSchemaSchema,
|
|
59
|
+
// Absent: user fragments enter history. System-only programs declare their conversion.
|
|
60
|
+
userInstructionDelivery: z.nativeEnum(UserInstructionDelivery).optional(),
|
|
61
|
+
acp: z.object({
|
|
62
|
+
transports: z.array(z.nativeEnum(AcpTransport)).min(1),
|
|
63
|
+
mcp: z.array(z.nativeEnum(McpTransportKind))
|
|
64
|
+
}),
|
|
65
|
+
// A capability missing here is unavailable on this harness.
|
|
66
|
+
baseTools: z.partialRecord(z.nativeEnum(BaseCapability), baseToolDeclarationSchema),
|
|
67
|
+
consumes: z.array(z.nativeEnum(SandboxWire)),
|
|
68
|
+
inference: z.object({
|
|
69
|
+
vendors: z.array(z.string()),
|
|
70
|
+
kinds: z.array(z.nativeEnum(InferenceCredentialKind)),
|
|
71
|
+
delivery: z.nativeEnum(CredentialDelivery)
|
|
72
|
+
}),
|
|
73
|
+
// Absent: third-party.
|
|
74
|
+
trust: z.nativeEnum(HarnessTrustClass).optional(),
|
|
75
|
+
supports: z.object({
|
|
76
|
+
observe: z.boolean(),
|
|
77
|
+
resumeReplay: z.boolean(),
|
|
78
|
+
fork: z.boolean(),
|
|
79
|
+
// Renders _meta["final.ai"].author itself; otherwise the channel prepends
|
|
80
|
+
// the author's name to the text.
|
|
81
|
+
authorMeta: z.boolean(),
|
|
82
|
+
// Explicit false: native toolPolicy cannot be enforced by this adapter's public surface.
|
|
83
|
+
nativeToolPolicy: z.boolean().optional()
|
|
84
|
+
}),
|
|
85
|
+
promptWhileRunning: z.nativeEnum(PromptWhileRunning).default(DEFAULT_PROMPT_WHILE_RUNNING),
|
|
86
|
+
// Keeps the session, its running work and its open requests across a dropped
|
|
87
|
+
// connection, buffers updates for replay, and re-raises the open requests
|
|
88
|
+
// with the same JSON-RPC ids on the next session/resume. False:
|
|
89
|
+
// open turns end `harness_state_lost` after a reconnect.
|
|
90
|
+
sessionSurvivesDisconnect: z.boolean().default(DEFAULT_SESSION_SURVIVES_DISCONNECT)
|
|
91
|
+
});
|
|
92
|
+
const deliveredHarnessConfig = (args) => {
|
|
93
|
+
if (args.description.userInstructionDelivery !== "system" /* System */)
|
|
94
|
+
return args.config;
|
|
95
|
+
const config = jsonObjectSchema.safeParse(args.config);
|
|
96
|
+
if (!config.success) return args.config;
|
|
97
|
+
const fields = referencedSharedSchemas(args.description.configSchema);
|
|
98
|
+
const field = Object.entries(fields).find(([, schema]) => schema === SCHEMA_IDS.instructions)?.[0] ?? "instructions";
|
|
99
|
+
const instructions = config.data[field];
|
|
100
|
+
if (!Array.isArray(instructions)) return args.config;
|
|
101
|
+
return {
|
|
102
|
+
...config.data,
|
|
103
|
+
[field]: instructions.map((value) => {
|
|
104
|
+
const fragment = jsonObjectSchema.safeParse(value);
|
|
105
|
+
return fragment.success && fragment.data["role"] === InstructionRole.User ? { ...fragment.data, role: InstructionRole.System } : value;
|
|
106
|
+
})
|
|
107
|
+
};
|
|
108
|
+
};
|
|
109
|
+
const harnessSessionRefSchema = z.object({
|
|
110
|
+
harness: providerRefSchema,
|
|
111
|
+
// Opaque to the session service; the harness's own id for the session.
|
|
112
|
+
harnessSessionRef: z.string().min(1),
|
|
113
|
+
// Bumped whenever the harness loses state; a mismatch on resume means the
|
|
114
|
+
// session service must re-seed with session/new.
|
|
115
|
+
generation: z.number().int().nonnegative()
|
|
116
|
+
});
|
|
117
|
+
import {
|
|
118
|
+
credentialRefreshRequestSchema,
|
|
119
|
+
CredentialRoute as CredentialRoute2,
|
|
120
|
+
routeGrantSchema as routeGrantSchema2
|
|
121
|
+
} from "./credential-routes.mjs";
|
|
122
|
+
const atOpenModelCredentialSchema = z.object({
|
|
123
|
+
vendor: z.string(),
|
|
124
|
+
kind: z.nativeEnum(InferenceCredentialKind),
|
|
125
|
+
baseUrl: z.string().min(1).nullable(),
|
|
126
|
+
apiKey: z.string().min(1).nullable(),
|
|
127
|
+
subscription: z.object({
|
|
128
|
+
format: z.union([z.literal("claude-setup-token"), z.literal("chatgpt-auth-tokens")]),
|
|
129
|
+
value: z.string().min(1)
|
|
130
|
+
}).nullable(),
|
|
131
|
+
fingerprint: z.string()
|
|
132
|
+
});
|
|
133
|
+
const credentialGrantRefreshSchema = z.object({
|
|
134
|
+
url: z.string().min(1),
|
|
135
|
+
token: z.string().min(1),
|
|
136
|
+
harnessSessionId: z.string().min(1),
|
|
137
|
+
expiresAt: z.string()
|
|
138
|
+
});
|
|
139
|
+
const credentialGrantSchema = z.object({
|
|
140
|
+
brokerUrl: z.string().min(1),
|
|
141
|
+
grants: z.array(routeGrantSchema),
|
|
142
|
+
atOpen: atOpenModelCredentialSchema.nullable(),
|
|
143
|
+
refresh: credentialGrantRefreshSchema.nullable()
|
|
144
|
+
});
|
|
145
|
+
const endpointTokenSchema = z.object({
|
|
146
|
+
url: z.string().min(1),
|
|
147
|
+
token: z.string(),
|
|
148
|
+
expiresAt: z.string()
|
|
149
|
+
});
|
|
150
|
+
const sandboxTargetEndpointSchema = z.object({
|
|
151
|
+
target: z.string().min(1),
|
|
152
|
+
bindingId: z.string().min(1),
|
|
153
|
+
capabilities: z.array(z.string()),
|
|
154
|
+
rpc: endpointTokenSchema.nullable(),
|
|
155
|
+
mcp: endpointTokenSchema.nullable()
|
|
156
|
+
});
|
|
157
|
+
const renewedMcpServerSchema = z.object({
|
|
158
|
+
name: z.string().min(1),
|
|
159
|
+
url: z.string().min(1),
|
|
160
|
+
headers: z.array(z.object({ name: z.string().min(1), value: z.string() }))
|
|
161
|
+
});
|
|
162
|
+
const credentialRefreshResultSchema = credentialGrantSchema.extend({
|
|
163
|
+
mcpServers: z.array(renewedMcpServerSchema).default([]),
|
|
164
|
+
sandboxes: z.record(z.string(), sandboxTargetEndpointSchema).default({})
|
|
165
|
+
});
|
|
166
|
+
const grantRefreshFor = (args) => {
|
|
167
|
+
const grant = args.grants.find((candidate) => candidate.route === CredentialRoute.Model) ?? args.grants[0];
|
|
168
|
+
if (grant == null) return null;
|
|
169
|
+
return {
|
|
170
|
+
url: `${args.brokerUrl.replace(/\/+$/, "")}/refresh`,
|
|
171
|
+
token: grant.token,
|
|
172
|
+
harnessSessionId: args.harnessSessionId,
|
|
173
|
+
expiresAt: grant.expiresAt
|
|
174
|
+
};
|
|
175
|
+
};
|
|
176
|
+
const defineHarness = (implementation) => {
|
|
177
|
+
const binding = (config) => ({
|
|
178
|
+
harness: bundleRef(PENDING_BUNDLE_EXPORT),
|
|
179
|
+
config,
|
|
180
|
+
definedHarness: true
|
|
181
|
+
});
|
|
182
|
+
return Object.assign(binding, implementation);
|
|
183
|
+
};
|
|
184
|
+
const describeConfigSchema = (description) => description.configSchema;
|
|
185
|
+
export {
|
|
186
|
+
AcpTransport,
|
|
187
|
+
BaseToolProvision,
|
|
188
|
+
CredentialRoute2 as CredentialRoute,
|
|
189
|
+
DEFAULT_PROMPT_WHILE_RUNNING,
|
|
190
|
+
DEFAULT_SESSION_SURVIVES_DISCONNECT,
|
|
191
|
+
HarnessTrustClass,
|
|
192
|
+
McpTransportKind,
|
|
193
|
+
PENDING_BUNDLE_EXPORT,
|
|
194
|
+
PromptWhileRunning,
|
|
195
|
+
SandboxWire,
|
|
196
|
+
UserInstructionDelivery,
|
|
197
|
+
atOpenModelCredentialSchema,
|
|
198
|
+
baseToolDeclarationSchema,
|
|
199
|
+
credentialGrantRefreshSchema,
|
|
200
|
+
credentialGrantSchema,
|
|
201
|
+
credentialRefreshRequestSchema,
|
|
202
|
+
credentialRefreshResultSchema,
|
|
203
|
+
defineHarness,
|
|
204
|
+
deliveredHarnessConfig,
|
|
205
|
+
describeConfigSchema,
|
|
206
|
+
grantRefreshFor,
|
|
207
|
+
harnessDescriptionSchema,
|
|
208
|
+
harnessSessionRefSchema,
|
|
209
|
+
renewedMcpServerSchema,
|
|
210
|
+
routeGrantSchema2 as routeGrantSchema,
|
|
211
|
+
sandboxTargetEndpointSchema
|
|
212
|
+
};
|
|
213
|
+
//# sourceMappingURL=harness.mjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../src/harness.ts"],
|
|
4
|
+
"sourcesContent": ["import type { McpServer } from '@agentclientprotocol/sdk/experimental/v2';\nimport * as z from 'zod';\nimport { CredentialRoute, routeGrantSchema, type RouteGrantIface } from \"./credential-routes.mjs\";\nimport { CredentialDelivery, InferenceCredentialKind } from \"./credentials.mjs\";\nimport type { JsonSchema, JsonValue } from \"./json.mjs\";\nimport { jsonObjectSchema, jsonSchemaSchema } from \"./json.mjs\";\nimport { BaseCapability, InstructionRole, type ResolvedAgentManifestIface } from \"./manifest.mjs\";\nimport { bundleRef, providerRefSchema, type ProviderRef } from \"./provider-ref.mjs\";\nimport { referencedSharedSchemas, SCHEMA_IDS } from \"./schemas.mjs\";\n\n// Placeholder export name the compiler replaces with the defining module's path.\nexport const PENDING_BUNDLE_EXPORT = '<pending>';\n\n// A harness is a specific ACP agent program together with how to reach it. Hosting is part of what a harness is, so there is no\n// engine parameter: \"Pi on Final's serverless runtime\" and \"Pi on a server you\n// run\" are two harnesses. The hosting half is deliberately small; everything\n// about what the agent does goes over ACP v2.\n\nexport enum AcpTransport {\n Relay = 'relay',\n Ws = 'ws',\n Http = 'http',\n Stdio = 'stdio',\n}\n\nexport enum McpTransportKind {\n Acp = 'acp',\n Http = 'http',\n Stdio = 'stdio',\n}\n\n// How a harness provides one base capability.\nexport enum BaseToolProvision {\n // Routed to the declared sandbox target.\n Bound = 'bound',\n // Native on the harness's host and switchable through its own allow-lists.\n HostDisableable = 'host-disableable',\n // Native on the harness's host and not switchable.\n HostFixed = 'host-fixed',\n}\n\n// SDK wires a harness speaks to reach a bound sandbox target.\nexport enum SandboxWire {\n HandleRpc = 'handle-rpc',\n Mcp = 'mcp',\n}\n\nexport enum UserInstructionDelivery {\n History = 'history',\n System = 'system',\n}\n\n// Who operates the place a harness's credentials land. Every\n// harness, Final's included, gets the same grant forms; a subscription goes to\n// a third-party harness only when its owner allowed third-party harnesses.\n// Only installed provider packages may declare first-party; a bundle-declared\n// harness is third-party whatever it declares.\nexport enum HarnessTrustClass {\n // The provider operates the harness on infrastructure it runs (Final's serverless harnesses).\n FirstParty = 'first-party',\n // Someone else's host or program (remote hosts, external ACP agents, local processes).\n ThirdParty = 'third-party',\n}\n\n// What an accepted session/prompt does while the session is running. Both are valid; refusing one is a conformance failure.\nexport enum PromptWhileRunning {\n // Joins the running work: the model sees it at its next step.\n Inject = 'inject',\n // Runs after the current work goes idle; dropped by session/cancel if not started.\n Queue = 'queue',\n}\n\n// Defaults for a description that does not declare the hosting contract's\n// newer fields (bundle harnesses, older registrations): the session service\n// then assumes nothing survives a dropped connection and that a prompt while\n// running waits for idle.\nexport const DEFAULT_PROMPT_WHILE_RUNNING = PromptWhileRunning.Queue;\nexport const DEFAULT_SESSION_SURVIVES_DISCONNECT = false;\n\nexport const baseToolDeclarationSchema = z.object({\n provision: z.nativeEnum(BaseToolProvision),\n nativeTools: z.array(z.string()),\n});\n\nexport const harnessDescriptionSchema = z.object({\n // Everything configurable about this harness (model, reasoning, credentials,\n // permission mode, instructions, skills, cwd, ...). JSON Schema so Build can\n // render it; may $ref the shared final://schemas/* fragments.\n configSchema: jsonSchemaSchema,\n // Absent: user fragments enter history. System-only programs declare their conversion.\n userInstructionDelivery: z.nativeEnum(UserInstructionDelivery).optional(),\n acp: z.object({\n transports: z.array(z.nativeEnum(AcpTransport)).min(1),\n mcp: z.array(z.nativeEnum(McpTransportKind)),\n }),\n // A capability missing here is unavailable on this harness.\n baseTools: z.partialRecord(z.nativeEnum(BaseCapability), baseToolDeclarationSchema),\n consumes: z.array(z.nativeEnum(SandboxWire)),\n inference: z.object({\n vendors: z.array(z.string()),\n kinds: z.array(z.nativeEnum(InferenceCredentialKind)),\n delivery: z.nativeEnum(CredentialDelivery),\n }),\n // Absent: third-party.\n trust: z.nativeEnum(HarnessTrustClass).optional(),\n supports: z.object({\n observe: z.boolean(),\n resumeReplay: z.boolean(),\n fork: z.boolean(),\n // Renders _meta[\"final.ai\"].author itself; otherwise the channel prepends\n // the author's name to the text.\n authorMeta: z.boolean(),\n // Explicit false: native toolPolicy cannot be enforced by this adapter's public surface.\n nativeToolPolicy: z.boolean().optional(),\n }),\n promptWhileRunning: z.nativeEnum(PromptWhileRunning).default(DEFAULT_PROMPT_WHILE_RUNNING),\n // Keeps the session, its running work and its open requests across a dropped\n // connection, buffers updates for replay, and re-raises the open requests\n // with the same JSON-RPC ids on the next session/resume. False:\n // open turns end `harness_state_lost` after a reconnect.\n sessionSurvivesDisconnect: z.boolean().default(DEFAULT_SESSION_SURVIVES_DISCONNECT),\n});\n\nexport type BaseToolDeclarationIface = z.infer<typeof baseToolDeclarationSchema>;\nexport type HarnessDescriptionIface = z.infer<typeof harnessDescriptionSchema>;\n\nexport const deliveredHarnessConfig = (args: {\n config: JsonValue;\n description: HarnessDescriptionIface;\n}): JsonValue => {\n if (args.description.userInstructionDelivery !== UserInstructionDelivery.System)\n return args.config;\n const config = jsonObjectSchema.safeParse(args.config);\n if (!config.success) return args.config;\n const fields = referencedSharedSchemas(args.description.configSchema);\n const field =\n Object.entries(fields).find(([, schema]) => schema === SCHEMA_IDS.instructions)?.[0] ??\n 'instructions';\n const instructions = config.data[field];\n if (!Array.isArray(instructions)) return args.config;\n return {\n ...config.data,\n [field]: instructions.map((value) => {\n const fragment = jsonObjectSchema.safeParse(value);\n return fragment.success && fragment.data['role'] === InstructionRole.User\n ? { ...fragment.data, role: InstructionRole.System }\n : value;\n }),\n };\n};\n\nexport const harnessSessionRefSchema = z.object({\n harness: providerRefSchema,\n // Opaque to the session service; the harness's own id for the session.\n harnessSessionRef: z.string().min(1),\n // Bumped whenever the harness loses state; a mismatch on resume means the\n // session service must re-seed with session/new.\n generation: z.number().int().nonnegative(),\n});\n\nexport type HarnessSessionRefIface = z.infer<typeof harnessSessionRefSchema>;\n\n// Route-scoped, short-lived grants: credential-routes.ts.\nexport {\n credentialRefreshRequestSchema,\n CredentialRoute,\n routeGrantSchema,\n type CredentialRefreshRequestIface,\n type RouteGrantIface,\n} from \"./credential-routes.mjs\";\n\nexport interface CredentialGrantIface {\n // Base URL of the broker routes (`<base>/model`, `<base>/refresh`, ...).\n brokerUrl: string;\n grants: RouteGrantIface[];\n // What the model grant resolved to, for harnesses that hand credentials over\n // at open (delivery 'at-open'). Null for per-request harnesses.\n atOpen: AtOpenModelCredentialIface | null;\n // How to renew this grant; null only when it carries no route grant.\n refresh: CredentialGrantRefreshIface | null;\n}\n\n// Renewal is pulled, never pushed. Per-request harnesses fetch\n// `<brokerUrl>/model` on every request. At-open harnesses (or their host)\n// POST `url` with `authorization: Bearer <token>` and a\n// `credentialRefreshRequestSchema` body before `expiresAt` and once after a\n// vendor 401; the answer is the grant's next generation (a\n// `credentialRefreshResultSchema` body with its own `refresh`), which replaces\n// this one. The broker resolves the policy again for it, so a disconnected\n// credential falls through; a revoked grant (every open revokes the previous\n// open's grants) or a closed harness session is refused (401).\nexport interface CredentialGrantRefreshIface {\n // `<brokerUrl>/refresh`.\n url: string;\n // One of this grant's own route grants (the model route's).\n token: string;\n harnessSessionId: string;\n // When `token` expires; a refresh after it is refused.\n expiresAt: string;\n}\n\nexport interface AtOpenModelCredentialIface {\n vendor: string;\n kind: InferenceCredentialKind;\n // Base URL and bearer for an OpenAI- or Anthropic-compatible endpoint (the\n // platform proxy, a corporate gateway) or the vendor itself.\n baseUrl: string | null;\n apiKey: string | null;\n // Subscription material for Final-managed harnesses only (Claude setup token,\n // Codex app-server chatgptAuthTokens); renewed through the grant's refresh route.\n subscription: { format: 'claude-setup-token' | 'chatgpt-auth-tokens'; value: string } | null;\n fingerprint: string;\n}\n\nexport const atOpenModelCredentialSchema = z.object({\n vendor: z.string(),\n kind: z.nativeEnum(InferenceCredentialKind),\n baseUrl: z.string().min(1).nullable(),\n apiKey: z.string().min(1).nullable(),\n subscription: z\n .object({\n format: z.union([z.literal('claude-setup-token'), z.literal('chatgpt-auth-tokens')]),\n value: z.string().min(1),\n })\n .nullable(),\n fingerprint: z.string(),\n}) satisfies z.ZodType<AtOpenModelCredentialIface>;\n\nexport const credentialGrantRefreshSchema = z.object({\n url: z.string().min(1),\n token: z.string().min(1),\n harnessSessionId: z.string().min(1),\n expiresAt: z.string(),\n}) satisfies z.ZodType<CredentialGrantRefreshIface>;\n\nexport const credentialGrantSchema = z.object({\n brokerUrl: z.string().min(1),\n grants: z.array(routeGrantSchema),\n atOpen: atOpenModelCredentialSchema.nullable(),\n refresh: credentialGrantRefreshSchema.nullable(),\n}) satisfies z.ZodType<CredentialGrantIface>;\n\n// An `http` MCP server entry the harness was handed in `session/new`\n// (`mcpServers`), with fresh headers. Same name and url; the harness swaps the\n// headers of the entry with that url.\nexport interface RenewedMcpServerIface {\n name: string;\n url: string;\n headers: { name: string; value: string }[];\n}\n\n// What a refresh answers: the grant's next generation, plus fresh copies of the\n// other short-lived material the harness was handed at open. Renewing the\n// `mcp` route renews the session's `http` MCP server headers; renewing\n// `sandbox` renews the bound sandbox targets' endpoint tokens.\nexport interface CredentialRefreshResultIface extends CredentialGrantIface {\n mcpServers: RenewedMcpServerIface[];\n sandboxes: Record<string, SandboxTargetEndpointIface>;\n}\n\nconst endpointTokenSchema = z.object({\n url: z.string().min(1),\n token: z.string(),\n expiresAt: z.string(),\n});\n\nexport const sandboxTargetEndpointSchema = z.object({\n target: z.string().min(1),\n bindingId: z.string().min(1),\n capabilities: z.array(z.string()),\n rpc: endpointTokenSchema.nullable(),\n mcp: endpointTokenSchema.nullable(),\n}) satisfies z.ZodType<SandboxTargetEndpointIface>;\n\nexport const renewedMcpServerSchema = z.object({\n name: z.string().min(1),\n url: z.string().min(1),\n headers: z.array(z.object({ name: z.string().min(1), value: z.string() })),\n}) satisfies z.ZodType<RenewedMcpServerIface>;\n\n// Absent renewals parse as none, so an answer without them still parses.\nexport const credentialRefreshResultSchema = credentialGrantSchema.extend({\n mcpServers: z.array(renewedMcpServerSchema).default([]),\n sandboxes: z.record(z.string(), sandboxTargetEndpointSchema).default({}),\n}) satisfies z.ZodType<CredentialRefreshResultIface, unknown>;\n\n// The refresh descriptor for a set of route grants: authenticated by the model\n// grant (else the first), due when that token expires.\nexport const grantRefreshFor = (args: {\n brokerUrl: string;\n harnessSessionId: string;\n grants: readonly RouteGrantIface[];\n}): CredentialGrantRefreshIface | null => {\n const grant =\n args.grants.find((candidate) => candidate.route === CredentialRoute.Model) ?? args.grants[0];\n if (grant == null) return null;\n return {\n url: `${args.brokerUrl.replace(/\\/+$/, '')}/refresh`,\n token: grant.token,\n harnessSessionId: args.harnessSessionId,\n expiresAt: grant.expiresAt,\n };\n};\n\nexport interface SecretReaderIface {\n get(name: string): Promise<string | null>;\n}\n\nexport interface TraceContextIface {\n traceparent: string | null;\n tracestate: string | null;\n}\n\n// A bound sandbox target as the session service hands it to a harness: a stable\n// per-binding address that starts the sandbox on the first tool call. Never a lease, a data-plane token for a live VM, or provider code.\nexport interface SandboxTargetEndpointIface {\n target: string;\n bindingId: string;\n capabilities: string[];\n rpc: { url: string; token: string; expiresAt: string } | null;\n mcp: { url: string; token: string; expiresAt: string } | null;\n}\n\nexport interface HarnessSessionContextIface {\n sessionId: string;\n organizationId: string;\n definitionId: string;\n revisionId: string;\n // Public base URL of the session service for this session (MCP over HTTP,\n // sandbox endpoints, the broker).\n sessionServiceUrl: string;\n // The region of the session service serving the session and its sandbox\n // bindings, so a harness can run near it; null when unknown.\n sessionServiceRegion?: string | null;\n}\n\n// Lifecycle signals a harness implementation may report about the runtime\n// hosting a session (invocations, metering, traces). Informational: the\n// session service records them (agent.harness_invocations, Tinybird) and never\n// depends on them for correctness.\nexport interface HarnessObserverIface {\n // The runtime accepted the invocation request (its response began).\n invocationAccepted?(event: { invocationRef: string; at: string }): void;\n invocationStarted?(event: {\n invocationRef: string;\n at: string;\n bootMs: number | null;\n // The runtime's deployed version (Workers version id, commit), for rollouts.\n versionId?: string | null;\n commitSha?: string | null;\n }): void;\n invocationKeepalive?(event: { invocationRef: string; at: string; activeWork: number }): void;\n invocationEnded?(event: {\n invocationRef: string;\n at: string;\n reason: string;\n error: string | null;\n metering: Record<string, number>;\n }): void;\n trace?(event: { name: string; at: string; fields: Record<string, JsonValue> }): void;\n}\n\nexport interface OpenHarnessSessionArgsIface {\n session: HarnessSessionContextIface;\n // The session service's id for this harness session (agent.harness_sessions);\n // implementations key their runtime state and route grants by it.\n harnessSessionId: string;\n // Hosting may authorize the child endpoint to fork this source through ACP.\n forkSource?: { ref: HarnessSessionRefIface; acpSessionId: string };\n observer?: HarnessObserverIface;\n // The binding's config, validated against configSchema, dynamic slots resolved.\n config: JsonValue;\n manifest: ResolvedAgentManifestIface;\n // Already materialized ACP MCP server entries: authored tools, connections\n // (Final's MCP server among them), sandbox MCP projections where applicable.\n mcpServers: McpServer[];\n // Declared base capabilities with the target endpoint each is bound to.\n baseTools: Partial<Record<BaseCapability, SandboxTargetEndpointIface>>;\n sandboxes: Record<string, SandboxTargetEndpointIface>;\n credentials: CredentialGrantIface;\n secrets: SecretReaderIface;\n trace: TraceContextIface;\n}\n\nexport interface ResumeHarnessSessionArgsIface extends OpenHarnessSessionArgsIface {\n ref: HarnessSessionRefIface;\n // Last log seq the session service holds from this harness session; the\n // harness replays anything newer after session/resume.\n lastSeq: number;\n}\n\n// Resolved only in memory; refs/manifests retain secret names, never TLS keys.\nexport interface HarnessClientTlsIface {\n cert: string;\n key: string;\n ca?: string;\n}\n\nexport type HarnessEndpointIface =\n | {\n ref: HarnessSessionRefIface;\n transport: AcpTransport.Ws;\n url: string;\n headers: Record<string, string>;\n resolveHeaders?: () => Promise<Record<string, string>>;\n tls?: HarnessClientTlsIface;\n }\n | {\n ref: HarnessSessionRefIface;\n transport: AcpTransport.Http;\n url: string;\n headers: Record<string, string>;\n resolveHeaders?: () => Promise<Record<string, string>>;\n tls?: HarnessClientTlsIface;\n }\n // websocket-gateway relay channel (Final-managed harnesses).\n | { ref: HarnessSessionRefIface; transport: AcpTransport.Relay; channel: string; token: string }\n // Local development, CI and conformance only.\n | {\n ref: HarnessSessionRefIface;\n transport: AcpTransport.Stdio;\n command: string;\n args: string[];\n env: Record<string, string>;\n };\n\nexport interface HarnessHealthIface {\n ok: boolean;\n detail?: string;\n checkedAt: string;\n}\n\n// The binding a description is asked for: its config (validated against the\n// configSchema of the binding-free description) and the definition's secrets.\nexport interface DescribeHarnessArgsIface {\n config: JsonValue;\n secrets: SecretReaderIface;\n}\n\nexport interface HarnessIface {\n // Without a binding: what Build renders before one exists (configSchema,\n // declared capabilities). With one: the description of that binding, which a\n // harness reaching an arbitrary agent derives from the agent itself (e.g. its\n // `initialize`). Every harness implements both; most ignore the binding.\n describe(binding?: DescribeHarnessArgsIface): Promise<HarnessDescriptionIface>;\n open(args: OpenHarnessSessionArgsIface): Promise<HarnessEndpointIface>;\n resume(args: ResumeHarnessSessionArgsIface): Promise<HarnessEndpointIface>;\n park(ref: HarnessSessionRefIface): Promise<void>;\n // Graceful by default: the program's state is durable (resumable) before it\n // stops, bounded by the implementation's timeout, then forced. `force` skips\n // the wait; the session service passes it when the program did not settle\n // ACP `session/close` within its bound.\n close(ref: HarnessSessionRefIface, opts?: CloseHarnessSessionOptsIface): Promise<void>;\n health(\n ref: HarnessSessionRefIface,\n context?: DescribeHarnessArgsIface,\n ): Promise<HarnessHealthIface>;\n}\n\nexport interface CloseHarnessSessionOptsIface {\n force?: boolean;\n // As with health, retained refs can resolve current client TLS without storing keys in the ref.\n context?: DescribeHarnessArgsIface;\n}\n\n// What an installed harness module exports: the implementation plus an\n// authoring helper that builds the manifest binding.\nexport interface HarnessModuleIface<Config> {\n ref: ProviderRef;\n harness: HarnessIface;\n binding: (config: Config) => { harness: ProviderRef; config: JsonValue };\n}\n\n// Custom harnesses in a definition's bundle. Calling the result\n// with a config yields the manifest binding; the implementation is resolved\n// from the bundle by export name.\nexport interface DefinedHarnessBindingIface {\n harness: ProviderRef;\n config: JsonValue;\n definedHarness: true;\n}\n\nexport interface DefinedHarnessIface<Config> extends HarnessIface {\n (config: Config): DefinedHarnessBindingIface;\n}\n\nexport const defineHarness = <Config extends JsonValue = JsonValue>(\n implementation: HarnessIface,\n): DefinedHarnessIface<Config> => {\n // The export name is unknown here; the compiler rewrites `bundle:<pending>`\n // to the module path that exported this harness.\n const binding = (config: Config): DefinedHarnessBindingIface => ({\n harness: bundleRef(PENDING_BUNDLE_EXPORT),\n config,\n definedHarness: true,\n });\n return Object.assign(binding, implementation);\n};\n\nexport const describeConfigSchema = (description: HarnessDescriptionIface): JsonSchema =>\n description.configSchema;\n"],
|
|
5
|
+
"mappings": "AACA,YAAY,OAAO;AACnB,SAAS,iBAAiB,wBAA8C;AACxE,SAAS,oBAAoB,+BAA+B;AAE5D,S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2BAA2B,EAAE,QAAQ,CAAC,CAAC;AACzE,CAAC;AAIM,MAAM,kBAAkB,CAAC,SAIU;AACxC,QAAM,QACJ,KAAK,OAAO,KAAK,CAAC,cAAc,UAAU,UAAU,gBAAgB,KAAK,KAAK,KAAK,OAAO,CAAC;AAC7F,MAAI,SAAS,KAAM,QAAO;AAC1B,SAAO;AAAA,IACL,KAAK,GAAG,KAAK,UAAU,QAAQ,QAAQ,EAAE,CAAC;AAAA,IAC1C,OAAO,MAAM;AAAA,IACb,kBAAkB,KAAK;AAAA,IACvB,WAAW,MAAM;AAAA,EACnB;AACF;AAwLO,MAAM,gBAAgB,CAC3B,mBACgC;AAGhC,QAAM,UAAU,CAAC,YAAgD;AAAA,IAC/D,SAAS,UAAU,qBAAqB;AAAA,IACxC;AAAA,IACA,gBAAgB;AAAA,EAClB;AACA,SAAO,OAAO,OAAO,SAAS,cAAc;AAC9C;AAEO,MAAM,uBAAuB,CAAC,gBACnC,YAAY;",
|
|
6
|
+
"names": ["AcpTransport", "McpTransportKind", "BaseToolProvision", "SandboxWire", "UserInstructionDelivery", "HarnessTrustClass", "PromptWhileRunning", "CredentialRoute", "routeGrantSchema"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export { ProcessInspectionOperation, inspectedProcessSchema, processInspectionDetailSchema, processInspectionPageSchema, processInspectionRequestSchema, processInspectionResultSchema, type InspectedProcessIface, type ProcessInspectionDetailIface, type ProcessInspectionPageIface, type ProcessInspectionRequestIface, type ProcessInspectionResultIface, } from '@finalai/agent-protocol/process-inspection';
|
|
2
|
+
export * from "./channel.mjs";
|
|
3
|
+
export * from "./credentials.mjs";
|
|
4
|
+
export * from "./dynamic.mjs";
|
|
5
|
+
export * from "./harness.mjs";
|
|
6
|
+
export * from "./json.mjs";
|
|
7
|
+
export * from "./manifest.mjs";
|
|
8
|
+
export * from "./provider-ref.mjs";
|
|
9
|
+
export * from "./sandbox/open-scope.mjs";
|
|
10
|
+
export * from "./sandbox/types.mjs";
|
|
11
|
+
export * from "./schemas.mjs";
|
|
12
|
+
export * from "./channel-context.mjs";
|
|
13
|
+
export * from "./semantic-events.mjs";
|
|
14
|
+
export * from "./sandbox/snapshots.mjs";
|
|
15
|
+
export { SandboxEditorOperation, sandboxEditorRequestSchema, sandboxEditorResultSchema, sandboxEditorSessionSchema, type SandboxEditorRequestIface, type SandboxEditorResultIface, type SandboxEditorSessionIface, } from "./sandbox/editor.mjs";
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ProcessInspectionOperation,
|
|
3
|
+
inspectedProcessSchema,
|
|
4
|
+
processInspectionDetailSchema,
|
|
5
|
+
processInspectionPageSchema,
|
|
6
|
+
processInspectionRequestSchema,
|
|
7
|
+
processInspectionResultSchema
|
|
8
|
+
} from "@finalai/agent-protocol/process-inspection";
|
|
9
|
+
export * from "./channel.mjs";
|
|
10
|
+
export * from "./credentials.mjs";
|
|
11
|
+
export * from "./dynamic.mjs";
|
|
12
|
+
export * from "./harness.mjs";
|
|
13
|
+
export * from "./json.mjs";
|
|
14
|
+
export * from "./manifest.mjs";
|
|
15
|
+
export * from "./provider-ref.mjs";
|
|
16
|
+
export * from "./sandbox/open-scope.mjs";
|
|
17
|
+
export * from "./sandbox/types.mjs";
|
|
18
|
+
export * from "./schemas.mjs";
|
|
19
|
+
export * from "./channel-context.mjs";
|
|
20
|
+
export * from "./semantic-events.mjs";
|
|
21
|
+
export * from "./sandbox/snapshots.mjs";
|
|
22
|
+
import {
|
|
23
|
+
SandboxEditorOperation,
|
|
24
|
+
sandboxEditorRequestSchema,
|
|
25
|
+
sandboxEditorResultSchema,
|
|
26
|
+
sandboxEditorSessionSchema
|
|
27
|
+
} from "./sandbox/editor.mjs";
|
|
28
|
+
export {
|
|
29
|
+
ProcessInspectionOperation,
|
|
30
|
+
SandboxEditorOperation,
|
|
31
|
+
inspectedProcessSchema,
|
|
32
|
+
processInspectionDetailSchema,
|
|
33
|
+
processInspectionPageSchema,
|
|
34
|
+
processInspectionRequestSchema,
|
|
35
|
+
processInspectionResultSchema,
|
|
36
|
+
sandboxEditorRequestSchema,
|
|
37
|
+
sandboxEditorResultSchema,
|
|
38
|
+
sandboxEditorSessionSchema
|
|
39
|
+
};
|
|
40
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../src/index.ts"],
|
|
4
|
+
"sourcesContent": ["export {\n ProcessInspectionOperation,\n inspectedProcessSchema,\n processInspectionDetailSchema,\n processInspectionPageSchema,\n processInspectionRequestSchema,\n processInspectionResultSchema,\n type InspectedProcessIface,\n type ProcessInspectionDetailIface,\n type ProcessInspectionPageIface,\n type ProcessInspectionRequestIface,\n type ProcessInspectionResultIface,\n} from '@finalai/agent-protocol/process-inspection';\nexport * from \"./channel.mjs\";\nexport * from \"./credentials.mjs\";\nexport * from \"./dynamic.mjs\";\nexport * from \"./harness.mjs\";\nexport * from \"./json.mjs\";\nexport * from \"./manifest.mjs\";\nexport * from \"./provider-ref.mjs\";\nexport * from \"./sandbox/open-scope.mjs\";\nexport * from \"./sandbox/types.mjs\";\nexport * from \"./schemas.mjs\";\n\nexport * from \"./channel-context.mjs\";\n\nexport * from \"./semantic-events.mjs\";\n\nexport * from \"./sandbox/snapshots.mjs\";\n\nexport {\n SandboxEditorOperation,\n sandboxEditorRequestSchema,\n sandboxEditorResultSchema,\n sandboxEditorSessionSchema,\n type SandboxEditorRequestIface,\n type SandboxEditorResultIface,\n type SandboxEditorSessionIface,\n} from \"./sandbox/editor.mjs\";\n"],
|
|
5
|
+
"mappings": "AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAMK;AACP,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AAEd,cAAc;AAEd,cAAc;AAEd,cAAc;AAEd;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIK;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import * as z from 'zod';
|
|
2
|
+
export type JsonPrimitive = string | number | boolean | null;
|
|
3
|
+
export type JsonValue = JsonPrimitive | JsonValue[] | {
|
|
4
|
+
[key: string]: JsonValue;
|
|
5
|
+
};
|
|
6
|
+
export type JsonObject = {
|
|
7
|
+
[key: string]: JsonValue;
|
|
8
|
+
};
|
|
9
|
+
export declare const jsonValueSchema: z.ZodType<JsonValue>;
|
|
10
|
+
export declare const jsonObjectSchema: z.ZodType<JsonObject>;
|
|
11
|
+
export type JsonSchema = JsonObject;
|
|
12
|
+
export declare const jsonSchemaSchema: z.ZodType<JsonSchema>;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import * as z from "zod";
|
|
2
|
+
const jsonValueSchema = z.lazy(
|
|
3
|
+
() => z.union([
|
|
4
|
+
z.string(),
|
|
5
|
+
z.number(),
|
|
6
|
+
z.boolean(),
|
|
7
|
+
z.null(),
|
|
8
|
+
z.array(jsonValueSchema),
|
|
9
|
+
z.record(z.string(), jsonValueSchema)
|
|
10
|
+
])
|
|
11
|
+
);
|
|
12
|
+
const jsonObjectSchema = z.record(z.string(), jsonValueSchema);
|
|
13
|
+
const jsonSchemaSchema = jsonObjectSchema;
|
|
14
|
+
export {
|
|
15
|
+
jsonObjectSchema,
|
|
16
|
+
jsonSchemaSchema,
|
|
17
|
+
jsonValueSchema
|
|
18
|
+
};
|
|
19
|
+
//# sourceMappingURL=json.mjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../src/json.ts"],
|
|
4
|
+
"sourcesContent": ["import * as z from 'zod';\n\nexport type JsonPrimitive = string | number | boolean | null;\nexport type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue };\nexport type JsonObject = { [key: string]: JsonValue };\n\nexport const jsonValueSchema: z.ZodType<JsonValue> = z.lazy(() =>\n z.union([\n z.string(),\n z.number(),\n z.boolean(),\n z.null(),\n z.array(jsonValueSchema),\n z.record(z.string(), jsonValueSchema),\n ]),\n);\n\nexport const jsonObjectSchema: z.ZodType<JsonObject> = z.record(z.string(), jsonValueSchema);\n\n// A JSON Schema document (draft 2020-12). Harness config schemas, tool input\n// schemas and channel config schemas are all JSON Schema so Build can render\n// them without running provider code.\nexport type JsonSchema = JsonObject;\nexport const jsonSchemaSchema: z.ZodType<JsonSchema> = jsonObjectSchema;\n"],
|
|
5
|
+
"mappings": "AAAA,YAAY,OAAO;AAMZ,MAAM,kBAAwC,EAAE;AAAA,EAAK,MAC1D,EAAE,MAAM;AAAA,IACN,EAAE,OAAO;AAAA,IACT,EAAE,OAAO;AAAA,IACT,EAAE,QAAQ;AAAA,IACV,EAAE,KAAK;AAAA,IACP,EAAE,MAAM,eAAe;AAAA,IACvB,EAAE,OAAO,EAAE,OAAO,GAAG,eAAe;AAAA,EACtC,CAAC;AACH;AAEO,MAAM,mBAA0C,EAAE,OAAO,EAAE,OAAO,GAAG,eAAe;AAMpF,MAAM,mBAA0C;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { ChannelRouteContextIface, WebSocketChannelRouteDefinitionIface } from "./channel.mjs";
|
|
2
|
+
import { type ChannelSocketAction } from "./channel-socket.mjs";
|
|
3
|
+
import type { JsonValue } from "./json.mjs";
|
|
4
|
+
export interface ChannelSocketConnectionIface {
|
|
5
|
+
actions: AsyncIterable<ChannelSocketAction>;
|
|
6
|
+
send(data: string | Uint8Array): void;
|
|
7
|
+
close(): void;
|
|
8
|
+
}
|
|
9
|
+
export type ChannelSocketOpenResult = {
|
|
10
|
+
ok: true;
|
|
11
|
+
protocol: string | null;
|
|
12
|
+
metadata?: JsonValue;
|
|
13
|
+
connection: ChannelSocketConnectionIface;
|
|
14
|
+
} | {
|
|
15
|
+
ok: false;
|
|
16
|
+
response: Response;
|
|
17
|
+
};
|
|
18
|
+
export declare const openChannelSocket: (args: {
|
|
19
|
+
handler: WebSocketChannelRouteDefinitionIface["handler"];
|
|
20
|
+
context: ChannelRouteContextIface;
|
|
21
|
+
signal: AbortSignal;
|
|
22
|
+
handshakeTimeoutMs?: number;
|
|
23
|
+
}) => Promise<ChannelSocketOpenResult>;
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ChannelSocketActionKind,
|
|
3
|
+
channelSocketData,
|
|
4
|
+
channelSocketMessage,
|
|
5
|
+
runChannelSocketHandler
|
|
6
|
+
} from "./channel-socket.mjs";
|
|
7
|
+
import { base64ToBytes } from "./sandbox/bytes.mjs";
|
|
8
|
+
const byteLength = (text) => new TextEncoder().encode(text).byteLength;
|
|
9
|
+
const openChannelSocket = async (args) => {
|
|
10
|
+
args.signal.throwIfAborted();
|
|
11
|
+
const closing = new AbortController();
|
|
12
|
+
const signal = AbortSignal.any([args.signal, closing.signal]);
|
|
13
|
+
let input = null;
|
|
14
|
+
let output = null;
|
|
15
|
+
const messages = new ReadableStream(
|
|
16
|
+
{
|
|
17
|
+
start: (controller) => {
|
|
18
|
+
input = controller;
|
|
19
|
+
}
|
|
20
|
+
},
|
|
21
|
+
{
|
|
22
|
+
highWaterMark: 8 * 1024 * 1024,
|
|
23
|
+
size: (data) => data instanceof Uint8Array ? data.byteLength : byteLength(data)
|
|
24
|
+
}
|
|
25
|
+
);
|
|
26
|
+
const actions = new ReadableStream(
|
|
27
|
+
{
|
|
28
|
+
start: (controller) => {
|
|
29
|
+
output = controller;
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
{ highWaterMark: 8 * 1024 * 1024, size: (action) => byteLength(JSON.stringify(action)) }
|
|
33
|
+
);
|
|
34
|
+
const close = () => {
|
|
35
|
+
if (closing.signal.aborted) return;
|
|
36
|
+
closing.abort();
|
|
37
|
+
signal.removeEventListener("abort", close);
|
|
38
|
+
try {
|
|
39
|
+
input?.close();
|
|
40
|
+
} catch {
|
|
41
|
+
}
|
|
42
|
+
try {
|
|
43
|
+
output?.close();
|
|
44
|
+
} catch {
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
signal.addEventListener("abort", close, { once: true });
|
|
48
|
+
const readMessages = async function* () {
|
|
49
|
+
const reader2 = messages.getReader();
|
|
50
|
+
const cancel = () => {
|
|
51
|
+
void reader2.cancel().catch(() => void 0);
|
|
52
|
+
};
|
|
53
|
+
signal.addEventListener("abort", cancel, { once: true });
|
|
54
|
+
if (signal.aborted) cancel();
|
|
55
|
+
try {
|
|
56
|
+
for (; ; ) {
|
|
57
|
+
const item = await reader2.read();
|
|
58
|
+
if (item.done) return;
|
|
59
|
+
yield item.value;
|
|
60
|
+
}
|
|
61
|
+
} finally {
|
|
62
|
+
signal.removeEventListener("abort", cancel);
|
|
63
|
+
reader2.releaseLock();
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
const context = {
|
|
67
|
+
request: args.context.request,
|
|
68
|
+
secrets: {
|
|
69
|
+
get: (name) => {
|
|
70
|
+
signal.throwIfAborted();
|
|
71
|
+
return args.context.secrets.get(name);
|
|
72
|
+
}
|
|
73
|
+
},
|
|
74
|
+
receive: (value) => {
|
|
75
|
+
signal.throwIfAborted();
|
|
76
|
+
return args.context.receive(value);
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
const handshake = setTimeout(close, args.handshakeTimeoutMs ?? 3e4);
|
|
80
|
+
void runChannelSocketHandler({
|
|
81
|
+
handler: args.handler,
|
|
82
|
+
context,
|
|
83
|
+
signal,
|
|
84
|
+
messages: readMessages(),
|
|
85
|
+
emit: (action) => {
|
|
86
|
+
if (signal.aborted) return;
|
|
87
|
+
output?.enqueue(action);
|
|
88
|
+
if ((output?.desiredSize ?? 0) < 0) close();
|
|
89
|
+
}
|
|
90
|
+
}).catch(close).finally(close);
|
|
91
|
+
const reader = actions.getReader();
|
|
92
|
+
const first = await reader.read();
|
|
93
|
+
clearTimeout(handshake);
|
|
94
|
+
if (first.value?.kind === ChannelSocketActionKind.Reject) {
|
|
95
|
+
close();
|
|
96
|
+
reader.releaseLock();
|
|
97
|
+
const bytes = base64ToBytes(first.value.body);
|
|
98
|
+
return {
|
|
99
|
+
ok: false,
|
|
100
|
+
response: new Response(bytes.byteLength === 0 ? null : new Uint8Array(bytes), {
|
|
101
|
+
status: first.value.status,
|
|
102
|
+
headers: first.value.headers
|
|
103
|
+
})
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
if (first.value?.kind !== ChannelSocketActionKind.Accept) {
|
|
107
|
+
close();
|
|
108
|
+
reader.releaseLock();
|
|
109
|
+
return { ok: false, response: new Response("Channel socket did not accept", { status: 504 }) };
|
|
110
|
+
}
|
|
111
|
+
const outgoing = async function* () {
|
|
112
|
+
try {
|
|
113
|
+
for (; ; ) {
|
|
114
|
+
const item = await reader.read();
|
|
115
|
+
if (item.done) return;
|
|
116
|
+
yield item.value;
|
|
117
|
+
}
|
|
118
|
+
} finally {
|
|
119
|
+
reader.releaseLock();
|
|
120
|
+
close();
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
return {
|
|
124
|
+
ok: true,
|
|
125
|
+
protocol: first.value.protocol ?? null,
|
|
126
|
+
connection: {
|
|
127
|
+
actions: outgoing(),
|
|
128
|
+
close,
|
|
129
|
+
send: (data) => {
|
|
130
|
+
signal.throwIfAborted();
|
|
131
|
+
const message = channelSocketData(channelSocketMessage(data));
|
|
132
|
+
input?.enqueue(message);
|
|
133
|
+
if ((input?.desiredSize ?? 0) < 0) close();
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
};
|
|
138
|
+
export {
|
|
139
|
+
openChannelSocket
|
|
140
|
+
};
|
|
141
|
+
//# sourceMappingURL=local-channel-socket.mjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../src/local-channel-socket.ts"],
|
|
4
|
+
"sourcesContent": ["import type { ChannelRouteContextIface, WebSocketChannelRouteDefinitionIface } from \"./channel.mjs\";\nimport {\n ChannelSocketActionKind,\n channelSocketData,\n channelSocketMessage,\n runChannelSocketHandler,\n type ChannelSocketAction,\n} from \"./channel-socket.mjs\";\nimport type { JsonValue } from \"./json.mjs\";\nimport { base64ToBytes } from \"./sandbox/bytes.mjs\";\nexport interface ChannelSocketConnectionIface {\n actions: AsyncIterable<ChannelSocketAction>;\n send(data: string | Uint8Array): void;\n close(): void;\n}\n\nexport type ChannelSocketOpenResult =\n | {\n ok: true;\n protocol: string | null;\n metadata?: JsonValue;\n connection: ChannelSocketConnectionIface;\n }\n | { ok: false; response: Response };\n\nconst byteLength = (text: string): number => new TextEncoder().encode(text).byteLength;\n\nexport const openChannelSocket = async (args: {\n handler: WebSocketChannelRouteDefinitionIface['handler'];\n context: ChannelRouteContextIface;\n signal: AbortSignal;\n handshakeTimeoutMs?: number;\n}): Promise<ChannelSocketOpenResult> => {\n args.signal.throwIfAborted();\n const closing = new AbortController();\n const signal = AbortSignal.any([args.signal, closing.signal]);\n let input: ReadableStreamDefaultController<string | Uint8Array> | null = null;\n let output: ReadableStreamDefaultController<ChannelSocketAction> | null = null;\n const messages = new ReadableStream<string | Uint8Array>(\n {\n start: (controller) => {\n input = controller;\n },\n },\n {\n highWaterMark: 8 * 1024 * 1024,\n size: (data) => (data instanceof Uint8Array ? data.byteLength : byteLength(data)),\n },\n );\n const actions = new ReadableStream<ChannelSocketAction>(\n {\n start: (controller) => {\n output = controller;\n },\n },\n { highWaterMark: 8 * 1024 * 1024, size: (action) => byteLength(JSON.stringify(action)) },\n );\n const close = (): void => {\n if (closing.signal.aborted) return;\n closing.abort();\n signal.removeEventListener('abort', close);\n try {\n input?.close();\n } catch {\n /* closed */\n }\n try {\n output?.close();\n } catch {\n /* closed */\n }\n };\n signal.addEventListener('abort', close, { once: true });\n const readMessages = async function* (): AsyncGenerator<string | Uint8Array> {\n const reader = messages.getReader();\n const cancel = () => {\n void reader.cancel().catch(() => undefined);\n };\n signal.addEventListener('abort', cancel, { once: true });\n if (signal.aborted) cancel();\n try {\n for (;;) {\n const item = await reader.read();\n if (item.done) return;\n yield item.value;\n }\n } finally {\n signal.removeEventListener('abort', cancel);\n reader.releaseLock();\n }\n };\n const context: ChannelRouteContextIface = {\n request: args.context.request,\n secrets: {\n get: (name) => {\n signal.throwIfAborted();\n return args.context.secrets.get(name);\n },\n },\n receive: (value) => {\n signal.throwIfAborted();\n return args.context.receive(value);\n },\n };\n const handshake = setTimeout(close, args.handshakeTimeoutMs ?? 30_000);\n void runChannelSocketHandler({\n handler: args.handler,\n context,\n signal,\n messages: readMessages(),\n emit: (action) => {\n if (signal.aborted) return;\n output?.enqueue(action);\n if ((output?.desiredSize ?? 0) < 0) close();\n },\n })\n .catch(close)\n .finally(close);\n const reader = actions.getReader();\n const first = await reader.read();\n clearTimeout(handshake);\n if (first.value?.kind === ChannelSocketActionKind.Reject) {\n close();\n reader.releaseLock();\n const bytes = base64ToBytes(first.value.body);\n return {\n ok: false,\n response: new Response(bytes.byteLength === 0 ? null : new Uint8Array(bytes), {\n status: first.value.status,\n headers: first.value.headers,\n }),\n };\n }\n if (first.value?.kind !== ChannelSocketActionKind.Accept) {\n close();\n reader.releaseLock();\n return { ok: false, response: new Response('Channel socket did not accept', { status: 504 }) };\n }\n const outgoing = async function* (): AsyncGenerator<ChannelSocketAction> {\n try {\n for (;;) {\n const item = await reader.read();\n if (item.done) return;\n yield item.value;\n }\n } finally {\n reader.releaseLock();\n close();\n }\n };\n return {\n ok: true,\n protocol: first.value.protocol ?? null,\n connection: {\n actions: outgoing(),\n close,\n send: (data) => {\n signal.throwIfAborted();\n const message = channelSocketData(channelSocketMessage(data));\n input?.enqueue(message);\n if ((input?.desiredSize ?? 0) < 0) close();\n },\n },\n };\n};\n"],
|
|
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