scoped-execution-protocol 0.0.0-stage → 2.0.0-rc.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.
@@ -0,0 +1,360 @@
1
+ import { ElicitationNeeded } from "../apps.js";
2
+ import { contentHash } from "../canonical.js";
3
+ import { attenuateCapability } from "../kernel.js";
4
+ import { canAccessPolicy, DEFAULT_CLEARANCE, intersectClearance } from "../privacy.js";
5
+ import { EFFECT_RANK, SXPError, SXP_VERSION } from "../types.js";
6
+ const PUBLIC_CLEARANCE = { ...DEFAULT_CLEARANCE, max_classification: "public" };
7
+ function isObject(value) {
8
+ return value !== null && typeof value === "object" && !Array.isArray(value);
9
+ }
10
+ export function generateA2AAgentCard(kernel, baseUrl = "https://agent.local", clearance = PUBLIC_CLEARANCE, protocolVersion = "1.0") {
11
+ const url = baseUrl.replace(/\/$/, "");
12
+ const card = {
13
+ name: kernel.agentId, description: `Run registered tools on ${kernel.agentId}.`, version: SXP_VERSION,
14
+ capabilities: { streaming: false, pushNotifications: false },
15
+ defaultInputModes: ["text/plain", "application/json"], defaultOutputModes: ["application/json"],
16
+ skills: kernel.listPublicTools(clearance).map((t) => ({
17
+ id: t.name, name: t.name, description: t.description || `Execute ${t.name}`, tags: [t.effect],
18
+ })),
19
+ };
20
+ if (protocolVersion !== "1.0")
21
+ return { ...card, url, protocolVersion: "0.3.0", preferredTransport: "JSONRPC" };
22
+ return {
23
+ ...card,
24
+ supportedInterfaces: ["1.0", "0.3"].map((version) => ({ url, protocolBinding: "JSONRPC", protocolVersion: version })),
25
+ };
26
+ }
27
+ export function wrapA2APeer(agentName, sendTaskFn, opts) {
28
+ return {
29
+ name: agentName,
30
+ effect: opts.mutating ? "unverified_write" : "read",
31
+ untrusted: true,
32
+ externalEgress: true,
33
+ description: opts.description ?? `Wrapped A2A peer '${agentName}' at ${opts.peerOrigin}`,
34
+ sinkClearance: opts.sinkClearance ?? { max_classification: "public", allowed_residencies: ["*"], allowed_purposes: ["*"] },
35
+ fn: async (args) => {
36
+ const raw = await sendTaskFn(args);
37
+ if (isObject(raw)) {
38
+ const task = isObject(raw.task) ? raw.task : raw;
39
+ const status = isObject(task.status) ? task.status : undefined;
40
+ if (status?.state === "input-required" || status?.state === "TASK_STATE_INPUT_REQUIRED") {
41
+ const message = isObject(status.message) ? status.message : {};
42
+ const parts = Array.isArray(message.parts) ? message.parts : [];
43
+ const text = parts.filter(isObject).map((part) => part.text).filter((part) => typeof part === "string").join("\n");
44
+ const msg = text || (typeof message.text === "string" ? message.text : "Remote A2A agent requires input.");
45
+ throw new ElicitationNeeded(msg, {
46
+ kind: "input",
47
+ inputSchema: status.inputSchema ?? { type: "object" },
48
+ });
49
+ }
50
+ }
51
+ return raw;
52
+ },
53
+ };
54
+ }
55
+ function taskToDict(rec, kernel, clearance, v1 = false) {
56
+ const message = {
57
+ messageId: `${rec.taskId}-${rec.updatedAtMs}`, contextId: rec.contextId, taskId: rec.taskId,
58
+ role: v1 ? "ROLE_AGENT" : "agent",
59
+ parts: [v1 ? { text: rec.message } : { kind: "text", text: rec.message }],
60
+ ...(v1 ? {} : { kind: "message" }),
61
+ };
62
+ const artifacts = rec.artifacts.flatMap((item) => {
63
+ const metadata = item.metadata;
64
+ const handle = kernel.store.getHandle(metadata.sxp_ref_id);
65
+ if (!handle || (handle.expires_at_ms != null && Date.now() > handle.expires_at_ms) || !canAccessPolicy(clearance, handle.policy))
66
+ return [];
67
+ if (rec.state === "completed")
68
+ message.parts[0].text = handle.l0_summary;
69
+ const data = kernel.store.inspect(handle.ref_id, "fields", { clearance }).data;
70
+ return [{ ...structuredClone(item), parts: [v1 ? { data } : { kind: "data", data }] }];
71
+ });
72
+ return {
73
+ id: rec.taskId, contextId: rec.contextId,
74
+ status: {
75
+ state: v1 ? `TASK_STATE_${rec.state.toUpperCase().replaceAll("-", "_")}` : rec.state,
76
+ timestamp: new Date(rec.updatedAtMs).toISOString(), message,
77
+ },
78
+ artifacts,
79
+ ...(v1 ? {} : { kind: "task" }),
80
+ };
81
+ }
82
+ function rpcError(id, code, message) {
83
+ return { jsonrpc: "2.0", id, error: { code, message } };
84
+ }
85
+ export class A2ABridge {
86
+ kernel;
87
+ baseUrl;
88
+ callerClearance;
89
+ tasks = new Map();
90
+ trustedInput;
91
+ maxTasks;
92
+ retentionMs;
93
+ messages = new Map();
94
+ namespace = crypto.randomUUID();
95
+ constructor(kernel, opts) {
96
+ this.maxTasks = opts?.maxTasks ?? 4096;
97
+ this.retentionMs = opts?.retentionMs ?? 3_600_000;
98
+ if (![this.maxTasks, this.retentionMs].every((v) => Number.isSafeInteger(v) && v > 0))
99
+ throw new RangeError("Invalid A2A task limits.");
100
+ this.kernel = kernel;
101
+ this.baseUrl = opts?.baseUrl ?? "https://agent.local";
102
+ this.callerClearance = opts?.callerClearance ?? PUBLIC_CLEARANCE;
103
+ this.trustedInput = opts?.trustedInput ?? false;
104
+ }
105
+ pruneTasks() {
106
+ const cutoff = Date.now() - this.retentionMs;
107
+ const expired = new Set();
108
+ for (const [id, task] of this.tasks) {
109
+ if (task.state !== "working" && task.updatedAtMs <= cutoff) {
110
+ this.tasks.delete(id);
111
+ expired.add(id);
112
+ }
113
+ }
114
+ if (expired.size) {
115
+ for (const [id, entry] of this.messages) {
116
+ if (entry.taskId && expired.has(entry.taskId))
117
+ this.messages.delete(id);
118
+ }
119
+ }
120
+ }
121
+ generateAgentCard(protocolVersion = "1.0") {
122
+ return generateA2AAgentCard(this.kernel, this.baseUrl, this.callerClearance, protocolVersion);
123
+ }
124
+ messageParams(params, v1) {
125
+ const message = params.message;
126
+ if (!isObject(message) || message.role !== (v1 ? "ROLE_USER" : "user"))
127
+ throw new Error("A user message is required.");
128
+ const { messageId, parts, contextId, taskId } = message;
129
+ if (typeof messageId !== "string" || !messageId || !Array.isArray(parts) || parts.length === 0) {
130
+ throw new Error("A messageId and at least one part are required.");
131
+ }
132
+ let args = {};
133
+ const texts = [];
134
+ const metadata = message.metadata ?? {};
135
+ if (!isObject(metadata))
136
+ throw new Error("Message metadata must be an object.");
137
+ let target = metadata["sxp.skill"];
138
+ for (const part of parts) {
139
+ if (!isObject(part))
140
+ throw new Error("Invalid message part.");
141
+ if (typeof part.text === "string" && !Object.hasOwn(part, "data"))
142
+ texts.push(part.text);
143
+ else if (isObject(part.data) && !Object.hasOwn(part, "text")) {
144
+ const data = part.data;
145
+ if (typeof data.skill === "string" && isObject(data.args)) {
146
+ if (target != null && target !== data.skill)
147
+ throw new Error("Message contains conflicting skill IDs.");
148
+ target = data.skill;
149
+ args = { ...args, ...data.args };
150
+ }
151
+ else
152
+ args = { ...args, ...data };
153
+ }
154
+ else
155
+ throw new Error("SXP accepts text parts and object-valued data parts.");
156
+ }
157
+ if (texts.length && !Object.hasOwn(args, "text"))
158
+ args.text = texts.join("\n");
159
+ if ([taskId, contextId, target].some((id) => id != null && (typeof id !== "string" || !id))) {
160
+ throw new Error("Task, context and skill IDs must be nonempty strings.");
161
+ }
162
+ return { id: taskId, context: contextId, skill: target, args, input: args, preview: metadata["sxp.preview"] === true, messageId };
163
+ }
164
+ async handleJsonRpc(request) {
165
+ this.pruneTasks();
166
+ const { id, method } = request;
167
+ const params = request.params ?? {};
168
+ if (!isObject(params))
169
+ return rpcError(id, -32602, "Parameters must be an object.");
170
+ if (method === "SendMessage" || method === "message/send" || method === "tasks/send") {
171
+ const v1 = method === "SendMessage";
172
+ return v1 || Object.hasOwn(params, "message") ? this.sendMessage(id, params, v1) : this.handleSend(id, params);
173
+ }
174
+ if (["GetTask", "tasks/get", "CancelTask", "tasks/cancel"].includes(method)) {
175
+ if (typeof params.id !== "string")
176
+ return rpcError(id, -32602, "Task ID must be a string.");
177
+ const rec = this.tasks.get(params.id);
178
+ if (!rec)
179
+ return rpcError(id, -32001, "Task not found");
180
+ if (method === "CancelTask" || method === "tasks/cancel") {
181
+ if (rec.state === "working" || (method === "CancelTask" && rec.state !== "input-required")) {
182
+ return rpcError(id, -32002, "Task cannot be canceled");
183
+ }
184
+ const rolled = [...rec.compensateHandles].reverse().filter((handle) => this.kernel.rollbackHandle(handle));
185
+ rec.args = {};
186
+ rec.state = "canceled";
187
+ rec.message = `Task canceled; rolled back ${rolled.length} handle(s).`;
188
+ rec.updatedAtMs = Date.now();
189
+ }
190
+ return { jsonrpc: "2.0", id, result: taskToDict(rec, this.kernel, this.callerClearance, method === "GetTask" || method === "CancelTask") };
191
+ }
192
+ return rpcError(id, -32601, `Unsupported A2A method: ${method}`);
193
+ }
194
+ async sendMessage(id, params, v1) {
195
+ let parsed, fingerprint;
196
+ try {
197
+ const snapshot = structuredClone(params);
198
+ parsed = this.messageParams(snapshot, v1);
199
+ fingerprint = await contentHash([v1, snapshot]);
200
+ }
201
+ catch (err) {
202
+ return rpcError(id, -32602, err instanceof Error ? err.message : "Invalid message.");
203
+ }
204
+ const messageId = String(parsed.messageId);
205
+ let entry = this.messages.get(messageId);
206
+ if (entry && entry.fingerprint !== fingerprint)
207
+ return rpcError(id, -32602, "Message ID was reused with different content.");
208
+ if (!entry) {
209
+ if (this.messages.size >= 4 * this.maxTasks)
210
+ return rpcError(id, -32000, "Message retention capacity reached.");
211
+ const result = Promise.resolve().then(async () => {
212
+ const response = await this.handleSend(id, parsed);
213
+ if (!isObject(response.result)) {
214
+ this.messages.delete(messageId);
215
+ return { error: response.error };
216
+ }
217
+ const taskId = String(response.result.id);
218
+ this.messages.get(messageId).taskId = taskId;
219
+ return { taskId };
220
+ }).catch((error) => {
221
+ this.messages.delete(messageId);
222
+ throw error;
223
+ });
224
+ entry = { fingerprint, result };
225
+ this.messages.set(messageId, entry);
226
+ }
227
+ const outcome = await entry.result;
228
+ if ("error" in outcome)
229
+ return { jsonrpc: "2.0", id, error: outcome.error };
230
+ const record = this.tasks.get(outcome.taskId);
231
+ if (!record)
232
+ return rpcError(id, -32001, "Task not found");
233
+ const task = taskToDict(record, this.kernel, this.callerClearance, v1);
234
+ return { jsonrpc: "2.0", id, result: v1 ? { task } : task };
235
+ }
236
+ approveTask(taskId) {
237
+ this.pruneTasks();
238
+ const task = this.tasks.get(taskId);
239
+ const token = task?.state === "input-required" && task.pendingConfirmToken;
240
+ if (!token)
241
+ throw new Error("Task is not awaiting approval.");
242
+ this.kernel.approvePreview(token);
243
+ }
244
+ async streamSse(params) {
245
+ this.pruneTasks();
246
+ const resp = await this.handleSend("sse", params);
247
+ if (resp.error)
248
+ return [`event: error\ndata: ${JSON.stringify(resp.error)}\n\n`];
249
+ const task = resp.result;
250
+ const chunks = [`event: task.status\ndata: ${JSON.stringify({ id: task.id, status: task.status })}\n\n`];
251
+ for (const art of task.artifacts ?? []) {
252
+ chunks.push(`event: task.artifact\ndata: ${JSON.stringify({ id: task.id, artifact: art })}\n\n`);
253
+ }
254
+ return chunks;
255
+ }
256
+ async handleSend(id, params) {
257
+ const tid = params.id ?? `task_${crypto.randomUUID()}`;
258
+ if (typeof tid !== "string")
259
+ return rpcError(id, -32602, "Task ID must be a string.");
260
+ const existing = this.tasks.get(tid);
261
+ if (existing) {
262
+ if (params.context != null && params.context !== existing.contextId)
263
+ return rpcError(id, -32001, "Task not found in this context");
264
+ if (existing.state !== "input-required")
265
+ return rpcError(id, -32002, "Task is not awaiting input.");
266
+ const reply = params.input ?? {};
267
+ if (!isObject(reply))
268
+ return rpcError(id, -32602, "Task input must be an object.");
269
+ if (existing.pendingConfirmToken)
270
+ return this.executeTask(id, existing, false, existing.pendingConfirmToken);
271
+ if (existing.pendingElicitId) {
272
+ try {
273
+ this.kernel.resolveElicitationResponse(existing.pendingElicitId, reply);
274
+ }
275
+ catch {
276
+ return rpcError(id, -32602, "Invalid elicitation response.");
277
+ }
278
+ existing.args = { ...existing.args, ...reply };
279
+ existing.pendingElicitId = undefined;
280
+ }
281
+ return this.executeTask(id, existing);
282
+ }
283
+ if (params.messageId !== undefined && params.id != null)
284
+ return rpcError(id, -32001, "Task not found");
285
+ let target = params.skill ?? params.target;
286
+ if (target == null && params.messageId !== undefined) {
287
+ const skills = this.kernel.listPublicTools(this.callerClearance);
288
+ if (skills.length !== 1)
289
+ return rpcError(id, -32602, "Select a skill using message.metadata['sxp.skill'].");
290
+ target = skills[0].name;
291
+ }
292
+ const args = params.args ?? {};
293
+ if (typeof target !== "string" || !isObject(args))
294
+ return rpcError(id, -32602, "A skill and object-valued arguments are required.");
295
+ const spec = this.kernel.targets.get(target);
296
+ if (!spec || !canAccessPolicy(this.callerClearance, spec.outputPolicy ?? { classification: "internal" })) {
297
+ return rpcError(id, -32003, "Skill is unavailable at this clearance.");
298
+ }
299
+ if (this.tasks.size >= this.maxTasks)
300
+ return rpcError(id, -32000, "Task retention capacity reached.");
301
+ const rec = {
302
+ taskId: tid, contextId: typeof params.context === "string" ? params.context : `ctx_${crypto.randomUUID()}`,
303
+ target, previewWrites: params.messageId !== undefined, args: structuredClone(args), state: "working", message: "", artifacts: [], compensateHandles: [], updatedAtMs: Date.now(),
304
+ };
305
+ this.tasks.set(tid, rec);
306
+ return this.executeTask(id, rec, params.preview === true);
307
+ }
308
+ async executeTask(id, rec, preview = false, confirmToken) {
309
+ rec.state = "working";
310
+ try {
311
+ const parent = this.kernel.capability;
312
+ const clearance = intersectClearance(parent.clearance ?? DEFAULT_CLEARANCE, this.callerClearance);
313
+ const capability = attenuateCapability(parent, {
314
+ subject: parent.subject, clearance, ...(this.trustedInput ? {} : { taint: "untrusted_data", max_effect: "read" }),
315
+ });
316
+ const effect = this.kernel.targets.get(rec.target)?.effect ?? "read";
317
+ if (rec.previewWrites && effect !== "read" && !confirmToken) {
318
+ if (EFFECT_RANK[effect] > EFFECT_RANK[capability.max_effect] || this.kernel.dag.branchTaint.get(this.kernel.activeBranch)) {
319
+ throw new SXPError("CAPABILITY_ESCALATION", "The bridge lacks authority to commit this action.");
320
+ }
321
+ preview = true;
322
+ }
323
+ const res = await this.kernel.callInbound("a2a", `${this.namespace}_${rec.taskId}`, rec.target, rec.args, {
324
+ preview, confirmToken, capability,
325
+ });
326
+ if (res.pausedForElicitation && res.elicitation) {
327
+ rec.pendingConfirmToken = undefined;
328
+ rec.state = "input-required";
329
+ rec.pendingElicitId = res.elicitation.elicit_id;
330
+ rec.message = res.elicitation.prompt;
331
+ }
332
+ else if (res.preview && res.confirmToken) {
333
+ rec.state = "input-required";
334
+ rec.pendingConfirmToken = res.confirmToken;
335
+ rec.message = res.pausedForHuman ? "Awaiting human approval." : "Awaiting commit.";
336
+ }
337
+ else if (res.handle) {
338
+ const handle = res.handle;
339
+ if (res.compensateHandle)
340
+ rec.compensateHandles.push(res.compensateHandle);
341
+ rec.state = "completed";
342
+ rec.message = "Completed.";
343
+ rec.pendingConfirmToken = undefined;
344
+ rec.artifacts = [{
345
+ artifactId: `${rec.taskId}-result`, name: handle.label, parts: [],
346
+ metadata: { sxp_ref: handle.short_id, sxp_ref_id: handle.ref_id, provenance: handle.provenance },
347
+ }];
348
+ }
349
+ }
350
+ catch (err) {
351
+ const waiting = err instanceof SXPError && err.code === "HUMAN_APPROVAL_REQUIRED";
352
+ rec.state = waiting ? "input-required" : "failed";
353
+ rec.message = waiting ? "Awaiting human approval." : "Skill execution failed.";
354
+ }
355
+ if (rec.state === "completed" || rec.state === "failed")
356
+ rec.args = {};
357
+ rec.updatedAtMs = Date.now();
358
+ return { jsonrpc: "2.0", id, result: taskToDict(rec, this.kernel, this.callerClearance) };
359
+ }
360
+ }
@@ -0,0 +1,25 @@
1
+ import type { AgentKernel } from "../kernel.js";
2
+ import { type Clearance, type DataPolicy } from "../types.js";
3
+ export declare function buildAgUiEvent(type: string, runId: string, extra?: Record<string, unknown>): Record<string, unknown>;
4
+ export declare class AGUIBridge {
5
+ readonly kernel: AgentKernel;
6
+ readonly uiClearance: Clearance;
7
+ constructor(kernel: AgentKernel, opts?: {
8
+ uiClearance?: Clearance;
9
+ });
10
+ static buildConfirmCard(action: string, confirmToken: string, impactSummary?: string): Record<string, unknown>;
11
+ static buildElicitForm(req: {
12
+ elicit_id: string;
13
+ source_id: string;
14
+ kind: string;
15
+ prompt: string;
16
+ input_schema: Record<string, unknown>;
17
+ }): Record<string, unknown>;
18
+ runCallStream(runId: string, target: string, args: Record<string, unknown>, opts?: {
19
+ threadId?: string;
20
+ preview?: boolean;
21
+ confirmToken?: string;
22
+ argumentPolicy?: DataPolicy;
23
+ }): Promise<Array<Record<string, unknown>>>;
24
+ static toSse(events: Array<Record<string, unknown>>): string;
25
+ }
@@ -0,0 +1,82 @@
1
+ import { canonicalJson } from "../canonical.js";
2
+ import { canAccessPolicy, maskPii } from "../privacy.js";
3
+ import { SXPError } from "../types.js";
4
+ export function buildAgUiEvent(type, runId, extra = {}) {
5
+ return { type, runId, timestamp: Date.now(), ...extra };
6
+ }
7
+ export class AGUIBridge {
8
+ kernel;
9
+ uiClearance;
10
+ constructor(kernel, opts) {
11
+ this.kernel = kernel;
12
+ this.uiClearance = opts?.uiClearance ?? kernel.substrateClearance;
13
+ }
14
+ static buildConfirmCard(action, confirmToken, impactSummary = "") {
15
+ return {
16
+ a2ui_version: "0.1",
17
+ component: "ConfirmCard",
18
+ props: { action, confirmToken, impactSummary },
19
+ };
20
+ }
21
+ static buildElicitForm(req) {
22
+ return {
23
+ a2ui_version: "0.1",
24
+ component: "ElicitForm",
25
+ props: { elicitId: req.elicit_id, sourceId: req.source_id, kind: req.kind, prompt: req.prompt, schema: req.input_schema },
26
+ };
27
+ }
28
+ async runCallStream(runId, target, args, opts) {
29
+ const run = { threadId: opts?.threadId ?? runId, runId };
30
+ const toolCallId = `call_${crypto.randomUUID()}`;
31
+ const events = [
32
+ buildAgUiEvent("RUN_STARTED", runId, run),
33
+ { type: "TOOL_CALL_START", toolCallId, toolCallName: target },
34
+ ];
35
+ const finished = buildAgUiEvent("RUN_FINISHED", runId, run);
36
+ try {
37
+ const policy = opts?.argumentPolicy;
38
+ const projectedArgs = policy && canAccessPolicy(this.uiClearance, policy) ? maskPii(args, new Set(policy.pii_fields)) : {};
39
+ events.push({ type: "TOOL_CALL_ARGS", toolCallId, delta: canonicalJson(projectedArgs) }, { type: "TOOL_CALL_END", toolCallId });
40
+ const res = await this.kernel.call(target, args, { preview: opts?.preview, confirmToken: opts?.confirmToken });
41
+ let interrupt;
42
+ if (res.pausedForElicitation && res.elicitation) {
43
+ const req = res.elicitation;
44
+ interrupt = {
45
+ id: req.elicit_id, reason: "elicitation_required", toolCallId,
46
+ responseSchema: req.input_schema, metadata: { a2ui: AGUIBridge.buildElicitForm(req) },
47
+ };
48
+ }
49
+ else if (res.preview && res.confirmToken && res.handle) {
50
+ if (!canAccessPolicy(this.uiClearance, res.handle.policy) || (policy && !canAccessPolicy(this.uiClearance, policy))) {
51
+ throw new SXPError("PRIVACY_VIOLATION", "UI clearance does not allow this preview.");
52
+ }
53
+ interrupt = {
54
+ id: res.confirmToken, reason: res.pausedForHuman ? "human_approval_required" : "confirmation_required", toolCallId,
55
+ metadata: { a2ui: AGUIBridge.buildConfirmCard(target, res.confirmToken, `Confirm ${target}`) },
56
+ };
57
+ }
58
+ if (interrupt) {
59
+ finished.outcome = { type: "interrupt", interrupts: [interrupt] };
60
+ }
61
+ else if (res.handle) {
62
+ const handle = res.handle;
63
+ const visible = canAccessPolicy(this.uiClearance, handle.policy);
64
+ const summary = visible ? handle.l0_summary : "[REDACTED]";
65
+ events.push({ type: "TOOL_CALL_RESULT", messageId: `msg_${crypto.randomUUID()}`, toolCallId, content: summary, role: "tool" });
66
+ if (visible)
67
+ events.push({
68
+ type: "STATE_DELTA",
69
+ delta: [{ op: "add", path: `/refs/${handle.short_id}`, value: { label: handle.label, summary } }],
70
+ });
71
+ }
72
+ events.push(finished);
73
+ }
74
+ catch (err) {
75
+ events.push(buildAgUiEvent("RUN_ERROR", runId, { ...run, message: "Tool execution failed.", code: err instanceof SXPError ? err.code : "TOOL_EXECUTION_ERROR" }));
76
+ }
77
+ return events;
78
+ }
79
+ static toSse(events) {
80
+ return events.map((ev) => `event: ${String(ev.type)}\ndata: ${JSON.stringify(ev)}\n\n`).join("");
81
+ }
82
+ }
@@ -0,0 +1,36 @@
1
+ /** Route a host's registered tool calls through the existing SXP kernel. */
2
+ import type { AppConnector } from "../apps.js";
3
+ import type { AgentKernel, CallResult } from "../kernel.js";
4
+ import { ResultProjection } from "../policy.js";
5
+ import { type DataPolicy, type ElicitationRequest, type RefHandle } from "../types.js";
6
+ export type ToolHostOutcome = {
7
+ kind: "result";
8
+ data: unknown;
9
+ refId: string;
10
+ } | {
11
+ kind: "approval_required";
12
+ preview: CallResult;
13
+ } | {
14
+ kind: "input_required";
15
+ elicitation: ElicitationRequest;
16
+ };
17
+ export declare class ToolHostAdapter {
18
+ readonly kernel: AgentKernel;
19
+ private readonly registered;
20
+ constructor(kernel: AgentKernel);
21
+ /** Set result and approval policies on the supplied connectors, then register them. */
22
+ attach(apps: readonly AppConnector[], opts?: {
23
+ resultProjections?: Record<string, ResultProjection>;
24
+ }): Promise<void>;
25
+ private tool;
26
+ /** Report targets currently registered through this adapter. */
27
+ coverage(targets: readonly string[]): Record<string, boolean>;
28
+ /** Read a tool result or ask the host to present a write for approval. */
29
+ invoke(target: string, args: Record<string, unknown>, opts?: {
30
+ scope?: string;
31
+ }): Promise<ToolHostOutcome>;
32
+ /** Store a result returned by a provider as untrusted data for host inspection. */
33
+ ingestResult(data: unknown, opts?: {
34
+ policy?: DataPolicy;
35
+ }): Promise<RefHandle>;
36
+ }
@@ -0,0 +1,93 @@
1
+ import { ResultProjection } from "../policy.js";
2
+ import { SXPError } from "../types.js";
3
+ export class ToolHostAdapter {
4
+ kernel;
5
+ registered = new Map();
6
+ constructor(kernel) {
7
+ this.kernel = kernel;
8
+ }
9
+ /** Set result and approval policies on the supplied connectors, then register them. */
10
+ async attach(apps, opts) {
11
+ const projections = new Map(Object.entries(opts?.resultProjections ?? {}));
12
+ const appIds = new Set();
13
+ const tools = new Map();
14
+ for (const app of apps) {
15
+ if (appIds.has(app.appId) || this.kernel.apps.has(app.appId)) {
16
+ throw new TypeError(`App '${app.appId}' is already registered.`);
17
+ }
18
+ appIds.add(app.appId);
19
+ for (const action of app.actions.values()) {
20
+ const target = `${app.appId}.${action.name}`;
21
+ if (tools.has(target) || this.kernel.targets.has(target)) {
22
+ throw new TypeError(`Tool '${target}' is already registered.`);
23
+ }
24
+ tools.set(target, action);
25
+ }
26
+ }
27
+ for (const [target, projection] of projections) {
28
+ const action = tools.get(target);
29
+ if (!action)
30
+ throw new TypeError("Result projections must name tools being attached.");
31
+ if (!(projection instanceof ResultProjection))
32
+ throw new TypeError("Expected a compiled ResultProjection.");
33
+ if (action.resultProjection && action.resultProjection !== projection) {
34
+ throw new TypeError("This tool already has a result projection.");
35
+ }
36
+ }
37
+ for (const [name, action] of tools) {
38
+ if ((action.effect ?? "read") !== "read" && (projections.has(name) || action.resultProjection)) {
39
+ throw new TypeError("Result projections require a read tool.");
40
+ }
41
+ }
42
+ for (const app of apps) {
43
+ for (const action of app.actions.values()) {
44
+ const target = `${app.appId}.${action.name}`;
45
+ action.resultProjection = projections.get(target) ?? action.resultProjection;
46
+ if ((action.effect ?? "read") !== "read") {
47
+ action.previewRequiresEffect = true;
48
+ action.requiresHumanApproval = true;
49
+ }
50
+ }
51
+ await this.kernel.connectApp(app);
52
+ for (const action of app.actions.values()) {
53
+ const target = `${app.appId}.${action.name}`;
54
+ this.registered.set(target, this.kernel.targets.get(target));
55
+ }
56
+ }
57
+ }
58
+ tool(target) {
59
+ const spec = this.registered.get(target);
60
+ return this.kernel.targets.get(target) === spec ? spec : undefined;
61
+ }
62
+ /** Report targets currently registered through this adapter. */
63
+ coverage(targets) {
64
+ return Object.fromEntries(targets.map((target) => [target, this.tool(target) !== undefined]));
65
+ }
66
+ /** Read a tool result or ask the host to present a write for approval. */
67
+ async invoke(target, args, opts) {
68
+ const spec = this.tool(target);
69
+ if (!spec)
70
+ throw new SXPError("UNKNOWN_TOOL", "Tool is outside this host adapter.");
71
+ const branch = this.kernel.activeBranch;
72
+ const result = await this.kernel.call(target, args, { scope: opts?.scope, preview: (spec.effect ?? "read") !== "read" });
73
+ if (this.kernel.activeBranch !== branch) {
74
+ throw new SXPError("STATE_DRIFT", "Active branch changed during the host tool call.");
75
+ }
76
+ if (result.preview)
77
+ return { kind: "approval_required", preview: result };
78
+ if (result.elicitation)
79
+ return { kind: "input_required", elicitation: result.elicitation };
80
+ const inspected = await this.kernel.inspect(result.handle.ref_id, "raw");
81
+ if (this.kernel.activeBranch !== branch) {
82
+ throw new SXPError("STATE_DRIFT", "Active branch changed during the host tool call.");
83
+ }
84
+ return { kind: "result", data: inspected.data, refId: result.handle.ref_id };
85
+ }
86
+ /** Store a result returned by a provider as untrusted data for host inspection. */
87
+ ingestResult(data, opts) {
88
+ return this.kernel.store.put(data, {
89
+ label: "provider_result", taint: "untrusted_data",
90
+ policy: opts?.policy ?? { classification: "internal", ephemeral: true },
91
+ });
92
+ }
93
+ }
@@ -0,0 +1,12 @@
1
+ import { AppConnector } from "../apps.js";
2
+ import type { TargetConfig } from "../kernel.js";
3
+ import type { Clearance } from "../types.js";
4
+ export declare function wrapHttpEndpoint(name: string, httpCallFn: (args: Record<string, unknown>) => unknown | Promise<unknown>, opts: {
5
+ originUrl: string;
6
+ method?: string;
7
+ description?: string;
8
+ sinkClearance?: Clearance;
9
+ }): TargetConfig;
10
+ export declare function wrapOpenApiSpec(appId: string, spec: Record<string, unknown>, callFn: (method: string, path: string, args: Record<string, unknown>) => unknown | Promise<unknown>, opts?: {
11
+ summary?: string;
12
+ }): AppConnector;
@@ -0,0 +1,55 @@
1
+ import { AppConnector } from "../apps.js";
2
+ /** Safe verbs read, PUT is retry-safe, DELETE cannot be taken back, anything else is an unverified write. */
3
+ function effectForMethod(method) {
4
+ if (method === "GET" || method === "HEAD" || method === "OPTIONS")
5
+ return "read";
6
+ if (method === "PUT")
7
+ return "idempotent";
8
+ if (method === "DELETE")
9
+ return "irreversible";
10
+ return "unverified_write";
11
+ }
12
+ export function wrapHttpEndpoint(name, httpCallFn, opts) {
13
+ const m = (opts.method ?? "GET").toUpperCase();
14
+ const effect = effectForMethod(m);
15
+ return {
16
+ name,
17
+ effect,
18
+ untrusted: true,
19
+ externalEgress: true,
20
+ description: opts.description ?? `HTTP ${m} ${opts.originUrl}`,
21
+ sinkClearance: opts.sinkClearance ?? { max_classification: "public", allowed_residencies: ["*"], allowed_purposes: ["*"] },
22
+ fn: (args) => httpCallFn(args),
23
+ };
24
+ }
25
+ export function wrapOpenApiSpec(appId, spec, callFn, opts) {
26
+ const info = spec.info ?? {};
27
+ const connector = new AppConnector(appId, {
28
+ summary: opts?.summary ?? String(info.title ?? `OpenAPI app '${appId}'`),
29
+ version: String(info.version ?? "0.1.0"),
30
+ untrusted: true,
31
+ });
32
+ const paths = spec.paths ?? {};
33
+ for (const [pathStr, methods] of Object.entries(paths)) {
34
+ if (!methods || typeof methods !== "object")
35
+ continue;
36
+ for (const [httpMethod, opRaw] of Object.entries(methods)) {
37
+ const m = httpMethod.toUpperCase();
38
+ if (!["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD"].includes(m))
39
+ continue;
40
+ if (!opRaw || typeof opRaw !== "object")
41
+ continue;
42
+ const op = opRaw;
43
+ const opId = String(op.operationId ?? `${m.toLowerCase()}_${pathStr.replace(/[^a-zA-Z0-9]+/g, "_").replace(/^_+|_+$/g, "")}`);
44
+ const eff = effectForMethod(m);
45
+ connector.action({
46
+ name: opId,
47
+ effect: eff,
48
+ untrusted: true,
49
+ description: String(op.summary ?? op.description ?? `${m} ${pathStr}`),
50
+ fn: (args) => callFn(m, pathStr, args),
51
+ });
52
+ }
53
+ }
54
+ return connector;
55
+ }