@nexface/tools 0.1.19 → 0.1.20-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/controller.d.ts +1 -0
- package/dist/browser/controller.js +3 -0
- package/dist/browser/input-observation.d.ts +11 -0
- package/dist/browser/input-observation.js +65 -0
- package/dist/browser/snapshot.js +1 -1
- package/dist/browser/toolset.js +18 -4
- package/dist/browser/types.d.ts +8 -0
- package/dist/confirmation-protocol.d.ts +38 -0
- package/dist/confirmation-protocol.js +75 -0
- package/dist/confirmation.d.ts +29 -0
- package/dist/confirmation.js +78 -0
- package/dist/navigation.d.ts +16 -2
- package/dist/react.d.ts +30 -4
- package/dist/react.js +91 -19
- package/dist/registration.js +3 -0
- package/dist/runtime.d.ts +26 -1
- package/dist/runtime.js +57 -5
- package/dist/shared/errors.d.ts +1 -1
- package/dist/shared/errors.js +2 -0
- package/dist/shared/tool-presentation.d.ts +17 -0
- package/dist/shared/tool-presentation.js +5 -0
- package/dist/webmcp.js +17 -12
- package/package.json +1 -1
|
@@ -13,6 +13,7 @@ export declare class PageController {
|
|
|
13
13
|
private readonly limits;
|
|
14
14
|
private readonly animator;
|
|
15
15
|
private readonly executions;
|
|
16
|
+
inputObserver: ((element: Element, command: PageCommand) => void) | undefined;
|
|
16
17
|
constructor(limits: ExecutionLimits, animator: ActionFeedback);
|
|
17
18
|
beginExecution(executionId: string, registry: SnapshotRegistry): void;
|
|
18
19
|
cancelExecution(executionId: string): void;
|
|
@@ -291,6 +291,7 @@ export class PageController {
|
|
|
291
291
|
limits;
|
|
292
292
|
animator;
|
|
293
293
|
executions = new Map();
|
|
294
|
+
inputObserver;
|
|
294
295
|
constructor(limits, animator) {
|
|
295
296
|
this.limits = limits;
|
|
296
297
|
this.animator = animator;
|
|
@@ -678,6 +679,8 @@ export class PageController {
|
|
|
678
679
|
}
|
|
679
680
|
ensureActionable(element);
|
|
680
681
|
this.requireStillActive(record);
|
|
682
|
+
if (command.method === "fill")
|
|
683
|
+
this.inputObserver?.(element, command);
|
|
681
684
|
const result = this.performAction(element, command);
|
|
682
685
|
this.recordCompletedAction(record, command);
|
|
683
686
|
return result;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { ExecutionResult, PageCommand } from "./types.js";
|
|
2
|
+
type Feedback = NonNullable<ExecutionResult["inputFeedback"]>;
|
|
3
|
+
export declare class InputObservation {
|
|
4
|
+
private readonly maxResultChars;
|
|
5
|
+
private readonly edits;
|
|
6
|
+
constructor(maxResultChars: number);
|
|
7
|
+
record(element: Element, command: PageCommand): void;
|
|
8
|
+
read(): Feedback;
|
|
9
|
+
clear(): void;
|
|
10
|
+
}
|
|
11
|
+
export {};
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { isAgentIgnored } from "./dom.js";
|
|
2
|
+
const sensitive = (element) => isAgentIgnored(element) ||
|
|
3
|
+
(element instanceof HTMLInputElement && ["password", "file", "hidden"].includes(element.type));
|
|
4
|
+
// Scoped to one execution; no DOM references are included in the receipt.
|
|
5
|
+
export class InputObservation {
|
|
6
|
+
maxResultChars;
|
|
7
|
+
edits = new Map();
|
|
8
|
+
constructor(maxResultChars) {
|
|
9
|
+
this.maxResultChars = maxResultChars;
|
|
10
|
+
}
|
|
11
|
+
record(element, command) {
|
|
12
|
+
if (command.method !== "fill")
|
|
13
|
+
return;
|
|
14
|
+
this.edits.delete(element);
|
|
15
|
+
this.edits.set(element, {
|
|
16
|
+
callIndex: command.commandSeq,
|
|
17
|
+
value: sensitive(element) ? "" : String(command.args[0] ?? ""),
|
|
18
|
+
redacted: sensitive(element),
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
read() {
|
|
22
|
+
const feedback = [];
|
|
23
|
+
let budget = Math.floor(this.maxResultChars / 4);
|
|
24
|
+
for (const [element, edit] of this.edits) {
|
|
25
|
+
const entry = { callIndex: edit.callIndex };
|
|
26
|
+
try {
|
|
27
|
+
if (edit.redacted || sensitive(element))
|
|
28
|
+
entry.unavailable = "redacted";
|
|
29
|
+
else if (!element.isConnected)
|
|
30
|
+
entry.unavailable = "detached";
|
|
31
|
+
else {
|
|
32
|
+
const observed = element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement
|
|
33
|
+
? element.value
|
|
34
|
+
: element instanceof HTMLElement && element.isContentEditable
|
|
35
|
+
? (element.textContent ?? "")
|
|
36
|
+
: undefined;
|
|
37
|
+
if (observed === undefined)
|
|
38
|
+
entry.unavailable = "not-readable";
|
|
39
|
+
else {
|
|
40
|
+
entry.requestedValue = edit.value.slice(0, 256);
|
|
41
|
+
entry.observedValue = observed.slice(0, 256);
|
|
42
|
+
entry.valueMatches = observed === edit.value;
|
|
43
|
+
if (observed.length > 256 || edit.value.length > 256)
|
|
44
|
+
entry.truncated = true;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
delete entry.requestedValue;
|
|
50
|
+
delete entry.observedValue;
|
|
51
|
+
delete entry.valueMatches;
|
|
52
|
+
entry.unavailable = "not-readable";
|
|
53
|
+
}
|
|
54
|
+
const size = JSON.stringify(entry).length + 1;
|
|
55
|
+
if (size > budget)
|
|
56
|
+
break;
|
|
57
|
+
budget -= size;
|
|
58
|
+
feedback.push(entry);
|
|
59
|
+
}
|
|
60
|
+
return feedback;
|
|
61
|
+
}
|
|
62
|
+
clear() {
|
|
63
|
+
this.edits.clear();
|
|
64
|
+
}
|
|
65
|
+
}
|
package/dist/browser/snapshot.js
CHANGED
|
@@ -415,7 +415,7 @@ function renderTree(nodes, context) {
|
|
|
415
415
|
const name = node.name ? ` ${JSON.stringify(normalizeText(node.name))}` : "";
|
|
416
416
|
const state = serializeState(node.state);
|
|
417
417
|
const scrollability = serializeScrollability(node.scrollable);
|
|
418
|
-
const nextRef = (node.actionable || node.scrollable) && (!node.genericAction || context.genericRefs <
|
|
418
|
+
const nextRef = (node.actionable || node.scrollable) && (!node.genericAction || context.genericRefs < 150)
|
|
419
419
|
? `@${context.refs.size + 1}`
|
|
420
420
|
: undefined;
|
|
421
421
|
const refText = nextRef ? ` [ref=${nextRef}]` : "";
|
package/dist/browser/toolset.js
CHANGED
|
@@ -3,6 +3,7 @@ import { AgentToolError } from "../runtime.js";
|
|
|
3
3
|
import { validateAgentToolInput } from "../shared/schema.js";
|
|
4
4
|
import { getSnapshotTool, executeActionTool, applyActionTool } from "../shared/page-tools.js";
|
|
5
5
|
export { getSnapshotTool, executeActionTool, applyActionTool } from "../shared/page-tools.js";
|
|
6
|
+
import { InputObservation } from "./input-observation.js";
|
|
6
7
|
import { PageController } from "./controller.js";
|
|
7
8
|
import { ActionFeedback } from "./feedback.js";
|
|
8
9
|
import { createSnapshot } from "./snapshot.js";
|
|
@@ -288,6 +289,8 @@ export function createBrowserToolset(options = {}) {
|
|
|
288
289
|
const onAbort = () => cancel();
|
|
289
290
|
signal.addEventListener("abort", onAbort, { once: true });
|
|
290
291
|
const tracker = startPageTransitionTracker(mode);
|
|
292
|
+
const inputs = new InputObservation(limits.maxResultChars);
|
|
293
|
+
controller.inputObserver = (element, command) => inputs.record(element, command);
|
|
291
294
|
feedback.listener = onFeedback;
|
|
292
295
|
feedback.assertActive = assertActive;
|
|
293
296
|
let result;
|
|
@@ -353,10 +356,21 @@ export function createBrowserToolset(options = {}) {
|
|
|
353
356
|
throw new AgentToolError("EXECUTION_OUTCOME_UNKNOWN", error instanceof Error ? error.message : "Browser execution failed.", { refsExpired: true });
|
|
354
357
|
}
|
|
355
358
|
finally {
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
359
|
+
try {
|
|
360
|
+
if (result) {
|
|
361
|
+
const inputFeedback = inputs.read();
|
|
362
|
+
if (inputFeedback.length)
|
|
363
|
+
result.inputFeedback = inputFeedback;
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
finally {
|
|
367
|
+
controller.inputObserver = undefined;
|
|
368
|
+
inputs.clear();
|
|
369
|
+
feedback.listener = undefined;
|
|
370
|
+
feedback.assertActive = undefined;
|
|
371
|
+
tracker.dispose();
|
|
372
|
+
signal.removeEventListener("abort", onAbort);
|
|
373
|
+
}
|
|
360
374
|
}
|
|
361
375
|
};
|
|
362
376
|
const executeCode = {
|
package/dist/browser/types.d.ts
CHANGED
|
@@ -94,6 +94,14 @@ export interface ExecutionResult {
|
|
|
94
94
|
statement?: string;
|
|
95
95
|
};
|
|
96
96
|
snapshot?: PageSnapshot;
|
|
97
|
+
inputFeedback?: {
|
|
98
|
+
callIndex: number;
|
|
99
|
+
requestedValue?: string;
|
|
100
|
+
observedValue?: string;
|
|
101
|
+
valueMatches?: boolean;
|
|
102
|
+
unavailable?: "detached" | "redacted" | "not-readable";
|
|
103
|
+
truncated?: boolean;
|
|
104
|
+
}[];
|
|
97
105
|
snapshotUnavailable?: boolean;
|
|
98
106
|
postSnapshotTimedOut?: boolean;
|
|
99
107
|
refsExpired?: boolean;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { AgentToolDefinition } from "./types.js";
|
|
2
|
+
export declare function confirmationDefinition(definition: AgentToolDefinition<any, any>): AgentToolDefinition<{
|
|
3
|
+
input?: Record<string, unknown>;
|
|
4
|
+
confirmation?: {
|
|
5
|
+
requestId: string;
|
|
6
|
+
approved: boolean;
|
|
7
|
+
};
|
|
8
|
+
}, unknown>;
|
|
9
|
+
export declare function createConfirmationHandler(definition: AgentToolDefinition<any, any>, lifecycle: AbortSignal): {
|
|
10
|
+
execute(wire: Record<string, unknown>, context: Parameters<(input: unknown, context: Parameters<import("./types.js").AgentToolExecutor<any, any>>[1], callbacks: {
|
|
11
|
+
execute: import("./types.js").AgentToolExecutor<any, any>;
|
|
12
|
+
confirm?: import("./confirmation.js").ConfirmationCallback<any>;
|
|
13
|
+
}) => Promise<{
|
|
14
|
+
kind: "completed";
|
|
15
|
+
result: any;
|
|
16
|
+
requestId?: never;
|
|
17
|
+
message?: never;
|
|
18
|
+
} | {
|
|
19
|
+
kind: "pending";
|
|
20
|
+
requestId: `${string}-${string}-${string}-${string}-${string}`;
|
|
21
|
+
message: string;
|
|
22
|
+
result?: never;
|
|
23
|
+
}>>[1], callbacks: Parameters<(input: unknown, context: Parameters<import("./types.js").AgentToolExecutor<any, any>>[1], callbacks: {
|
|
24
|
+
execute: import("./types.js").AgentToolExecutor<any, any>;
|
|
25
|
+
confirm?: import("./confirmation.js").ConfirmationCallback<any>;
|
|
26
|
+
}) => Promise<{
|
|
27
|
+
kind: "completed";
|
|
28
|
+
result: any;
|
|
29
|
+
requestId?: never;
|
|
30
|
+
message?: never;
|
|
31
|
+
} | {
|
|
32
|
+
kind: "pending";
|
|
33
|
+
requestId: `${string}-${string}-${string}-${string}-${string}`;
|
|
34
|
+
message: string;
|
|
35
|
+
result?: never;
|
|
36
|
+
}>>[2]): Promise<any>;
|
|
37
|
+
resolveInput(wire: unknown): unknown;
|
|
38
|
+
};
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { defineAgentTool } from "./definition.js";
|
|
2
|
+
import { AgentToolError } from "./shared/errors.js";
|
|
3
|
+
import { validateAgentToolInput } from "./shared/schema.js";
|
|
4
|
+
import { createConfirmationRequests } from "./confirmation.js";
|
|
5
|
+
const instructions = "Ask this message using the host's permitted user-input tool with Confirm/Reject choices, or chat if unavailable. Wait for an explicit answer to this question, then call the same tool with only { confirmation: { requestId, approved } }: true to approve, false to reject. Stop after rejection. If execution has an unknown outcome, verify its status before retrying.";
|
|
6
|
+
export function confirmationDefinition(definition) {
|
|
7
|
+
const exposed = defineAgentTool({
|
|
8
|
+
...definition,
|
|
9
|
+
inputSchema: {
|
|
10
|
+
type: "object",
|
|
11
|
+
properties: {
|
|
12
|
+
input: {
|
|
13
|
+
...definition.inputSchema,
|
|
14
|
+
description: [
|
|
15
|
+
"Business arguments for the initial call. Omit confirmation.",
|
|
16
|
+
definition.inputSchema.description,
|
|
17
|
+
]
|
|
18
|
+
.filter(Boolean)
|
|
19
|
+
.join(" "),
|
|
20
|
+
},
|
|
21
|
+
confirmation: {
|
|
22
|
+
type: "object",
|
|
23
|
+
description: "Use after a confirmation request and the user's explicit answer. Omit input.",
|
|
24
|
+
properties: {
|
|
25
|
+
requestId: { type: "string", minLength: 1 },
|
|
26
|
+
approved: { type: "boolean" },
|
|
27
|
+
},
|
|
28
|
+
required: ["requestId", "approved"],
|
|
29
|
+
additionalProperties: false,
|
|
30
|
+
},
|
|
31
|
+
},
|
|
32
|
+
additionalProperties: false,
|
|
33
|
+
},
|
|
34
|
+
});
|
|
35
|
+
return exposed;
|
|
36
|
+
}
|
|
37
|
+
// The chat protocol owns wire arguments, schema and model-facing instructions.
|
|
38
|
+
export function createConfirmationHandler(definition, lifecycle) {
|
|
39
|
+
const requests = createConfirmationRequests(lifecycle);
|
|
40
|
+
const resolvedInputs = new WeakMap();
|
|
41
|
+
return {
|
|
42
|
+
async execute(wire, context, callbacks) {
|
|
43
|
+
const hasInput = Object.hasOwn(wire, "input");
|
|
44
|
+
const hasAnswer = Object.hasOwn(wire, "confirmation");
|
|
45
|
+
if (hasInput === hasAnswer) {
|
|
46
|
+
throw new AgentToolError("INVALID_INPUT", "Provide exactly one of input or confirmation.");
|
|
47
|
+
}
|
|
48
|
+
if (hasAnswer) {
|
|
49
|
+
const { requestId, approved } = wire.confirmation;
|
|
50
|
+
resolvedInputs.set(wire, requests.resolveInput(requestId));
|
|
51
|
+
return requests.decide(requestId, approved, context);
|
|
52
|
+
}
|
|
53
|
+
const errors = validateAgentToolInput(definition.inputSchema, wire.input);
|
|
54
|
+
if (errors.length)
|
|
55
|
+
throw new AgentToolError("INVALID_INPUT", errors.join(" "), { errors });
|
|
56
|
+
const outcome = await requests.start(wire.input, context, callbacks);
|
|
57
|
+
if (outcome.kind === "completed")
|
|
58
|
+
return outcome.result;
|
|
59
|
+
return {
|
|
60
|
+
status: "confirmation_required",
|
|
61
|
+
requestId: outcome.requestId,
|
|
62
|
+
message: outcome.message,
|
|
63
|
+
nextAction: instructions,
|
|
64
|
+
};
|
|
65
|
+
},
|
|
66
|
+
resolveInput(wire) {
|
|
67
|
+
if (!wire || typeof wire !== "object")
|
|
68
|
+
return undefined;
|
|
69
|
+
const args = wire;
|
|
70
|
+
return args.confirmation?.requestId
|
|
71
|
+
? (resolvedInputs.get(wire) ?? requests.resolveInput(args.confirmation.requestId))
|
|
72
|
+
: args.input;
|
|
73
|
+
},
|
|
74
|
+
};
|
|
75
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { AgentToolExecutor } from "./types.js";
|
|
2
|
+
export type ConfirmationCallback<TInput> = (context: {
|
|
3
|
+
input: TInput;
|
|
4
|
+
signal: AbortSignal;
|
|
5
|
+
}) => boolean | {
|
|
6
|
+
message: string;
|
|
7
|
+
} | Promise<boolean | {
|
|
8
|
+
message: string;
|
|
9
|
+
}>;
|
|
10
|
+
type Callbacks = {
|
|
11
|
+
execute: AgentToolExecutor<any, any>;
|
|
12
|
+
confirm?: ConfirmationCallback<any>;
|
|
13
|
+
};
|
|
14
|
+
export declare function createConfirmationRequests(lifecycle: AbortSignal): {
|
|
15
|
+
resolveInput(requestId: string): unknown;
|
|
16
|
+
decide(requestId: string, approved: boolean, context: Parameters<AgentToolExecutor<any, any>>[1]): Promise<any>;
|
|
17
|
+
start(input: unknown, context: Parameters<AgentToolExecutor<any, any>>[1], callbacks: Callbacks): Promise<{
|
|
18
|
+
kind: "completed";
|
|
19
|
+
result: any;
|
|
20
|
+
requestId?: never;
|
|
21
|
+
message?: never;
|
|
22
|
+
} | {
|
|
23
|
+
kind: "pending";
|
|
24
|
+
requestId: `${string}-${string}-${string}-${string}-${string}`;
|
|
25
|
+
message: string;
|
|
26
|
+
result?: never;
|
|
27
|
+
}>;
|
|
28
|
+
};
|
|
29
|
+
export {};
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { AgentToolError } from "./shared/errors.js";
|
|
2
|
+
// Each binding owns its requests, independently of any host transport.
|
|
3
|
+
export function createConfirmationRequests(lifecycle) {
|
|
4
|
+
const pending = new Map();
|
|
5
|
+
lifecycle.addEventListener("abort", () => pending.clear(), { once: true });
|
|
6
|
+
return {
|
|
7
|
+
resolveInput(requestId) {
|
|
8
|
+
return pending.get(requestId)?.input;
|
|
9
|
+
},
|
|
10
|
+
async decide(requestId, approved, context) {
|
|
11
|
+
context.signal.throwIfAborted();
|
|
12
|
+
lifecycle.throwIfAborted();
|
|
13
|
+
const request = pending.get(requestId);
|
|
14
|
+
if (!request) {
|
|
15
|
+
throw new AgentToolError("TOOL_CONFIRMATION_INVALIDATED", "The confirmation request is unknown, invalidated, or already settled.", { toolExecuted: false });
|
|
16
|
+
}
|
|
17
|
+
// Consume before executing, including when the executor subsequently fails.
|
|
18
|
+
pending.delete(requestId);
|
|
19
|
+
if (!approved)
|
|
20
|
+
return { status: "rejected", requestId, toolExecuted: false };
|
|
21
|
+
return request.execute(request.input, context);
|
|
22
|
+
},
|
|
23
|
+
async start(input, context, callbacks) {
|
|
24
|
+
const signal = AbortSignal.any([context.signal, lifecycle]);
|
|
25
|
+
signal.throwIfAborted();
|
|
26
|
+
const snapshot = structuredClone(input);
|
|
27
|
+
const decision = callbacks.confirm
|
|
28
|
+
? await waitForDecision(() => callbacks.confirm({ input: structuredClone(snapshot), signal }), signal)
|
|
29
|
+
: true;
|
|
30
|
+
signal.throwIfAborted();
|
|
31
|
+
if (decision === false) {
|
|
32
|
+
return { kind: "completed", result: { status: "rejected", toolExecuted: false } };
|
|
33
|
+
}
|
|
34
|
+
if (decision === true) {
|
|
35
|
+
return { kind: "completed", result: await callbacks.execute(snapshot, context) };
|
|
36
|
+
}
|
|
37
|
+
if (!decision ||
|
|
38
|
+
typeof decision !== "object" ||
|
|
39
|
+
typeof decision.message !== "string" ||
|
|
40
|
+
!decision.message.trim() ||
|
|
41
|
+
Object.keys(decision).some((key) => key !== "message")) {
|
|
42
|
+
throw new AgentToolError("INVALID_CONFIRMATION_RESULT", "confirm must return a boolean or { message: non-empty string }.", { toolExecuted: false });
|
|
43
|
+
}
|
|
44
|
+
if (pending.size >= 128) {
|
|
45
|
+
throw new AgentToolError("TOOL_CONFIRMATION_LIMIT", "Too many pending confirmations for this tool. Resolve or reject existing requests first.", { toolExecuted: false });
|
|
46
|
+
}
|
|
47
|
+
const requestId = crypto.randomUUID();
|
|
48
|
+
pending.set(requestId, { input: snapshot, execute: callbacks.execute });
|
|
49
|
+
return { kind: "pending", requestId, message: decision.message };
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
function waitForDecision(run, signal) {
|
|
54
|
+
return new Promise((resolve, reject) => {
|
|
55
|
+
const abort = () => {
|
|
56
|
+
cleanup();
|
|
57
|
+
reject(signal.reason);
|
|
58
|
+
};
|
|
59
|
+
const cleanup = () => signal.removeEventListener("abort", abort);
|
|
60
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
61
|
+
if (signal.aborted) {
|
|
62
|
+
abort();
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
Promise.resolve()
|
|
66
|
+
.then(() => {
|
|
67
|
+
signal.throwIfAborted();
|
|
68
|
+
return run();
|
|
69
|
+
})
|
|
70
|
+
.then((value) => {
|
|
71
|
+
cleanup();
|
|
72
|
+
resolve(value);
|
|
73
|
+
}, (error) => {
|
|
74
|
+
cleanup();
|
|
75
|
+
reject(error);
|
|
76
|
+
});
|
|
77
|
+
});
|
|
78
|
+
}
|
package/dist/navigation.d.ts
CHANGED
|
@@ -15,9 +15,23 @@ export interface AgentNavigationConfig<TRoutes extends Record<string, AgentNavig
|
|
|
15
15
|
routes: TRoutes;
|
|
16
16
|
}
|
|
17
17
|
export type AgentNavigationExecutors<TNavigation extends AgentNavigation> = TNavigation extends AgentNavigation<infer TRoutes> ? {
|
|
18
|
-
[TKey in keyof TRoutes]: (input: TRoutes[TKey] extends {
|
|
18
|
+
[TKey in keyof TRoutes]: ((input: TRoutes[TKey] extends {
|
|
19
19
|
readonly inputSchema: infer TSchema extends AgentToolInputSchema;
|
|
20
|
-
} ? InferJsonSchema<TSchema> : Record<string, never>, context: AgentToolExecutionContext) => void | Promise<void
|
|
20
|
+
} ? InferJsonSchema<TSchema> : Record<string, never>, context: AgentToolExecutionContext) => void | Promise<void>) | {
|
|
21
|
+
execute: (input: TRoutes[TKey] extends {
|
|
22
|
+
readonly inputSchema: infer TSchema extends AgentToolInputSchema;
|
|
23
|
+
} ? InferJsonSchema<TSchema> : Record<string, never>, context: AgentToolExecutionContext) => void | Promise<void>;
|
|
24
|
+
confirm?: (context: {
|
|
25
|
+
input: TRoutes[TKey] extends {
|
|
26
|
+
readonly inputSchema: infer TSchema extends AgentToolInputSchema;
|
|
27
|
+
} ? InferJsonSchema<TSchema> : Record<string, never>;
|
|
28
|
+
signal: AbortSignal;
|
|
29
|
+
}) => boolean | {
|
|
30
|
+
message: string;
|
|
31
|
+
} | Promise<boolean | {
|
|
32
|
+
message: string;
|
|
33
|
+
}>;
|
|
34
|
+
};
|
|
21
35
|
} : never;
|
|
22
36
|
interface InternalAgentNavigationRoute {
|
|
23
37
|
key: string;
|
package/dist/react.d.ts
CHANGED
|
@@ -22,7 +22,32 @@ export interface AgentToolPageConfirmationConfig {
|
|
|
22
22
|
title?: string;
|
|
23
23
|
description?: string;
|
|
24
24
|
}
|
|
25
|
-
|
|
25
|
+
type ToolResultData<T> = unknown extends T ? T : T extends string | number | boolean | null ? T : T extends readonly unknown[] ? {
|
|
26
|
+
[K in keyof T]: ToolResultData<T[K]>;
|
|
27
|
+
} : T extends (...args: never[]) => unknown ? never : T extends object ? {
|
|
28
|
+
[K in keyof T]: ToolResultData<T[K]>;
|
|
29
|
+
} : never;
|
|
30
|
+
type ToolRenderResult<T> = unknown extends T ? unknown : [T] extends [void] ? null : [T] extends [ToolResultData<T>] ? T : unknown;
|
|
31
|
+
export interface UseAgentToolDefaultOptions<TInput = unknown, TResult = unknown> {
|
|
32
|
+
confirm?: (context: {
|
|
33
|
+
input: TInput;
|
|
34
|
+
signal: AbortSignal;
|
|
35
|
+
}) => boolean | {
|
|
36
|
+
message: string;
|
|
37
|
+
} | Promise<boolean | {
|
|
38
|
+
message: string;
|
|
39
|
+
}>;
|
|
40
|
+
/**
|
|
41
|
+
* @experimental
|
|
42
|
+
* @warning Experimental API. Its signature and behavior may change.
|
|
43
|
+
* @remarks JSON-compatible results retain their types. Other results are unknown after serialization; void results are null.
|
|
44
|
+
* @beta
|
|
45
|
+
*/
|
|
46
|
+
_render?: (context: {
|
|
47
|
+
input: TInput;
|
|
48
|
+
status: "running" | "success" | "error" | "cancelled";
|
|
49
|
+
result?: ToolRenderResult<TResult>;
|
|
50
|
+
}) => ReactNode;
|
|
26
51
|
/**
|
|
27
52
|
* @experimental Enables human-in-the-loop Chat confirmation.
|
|
28
53
|
* @beta
|
|
@@ -33,7 +58,8 @@ export interface UseAgentToolDefaultOptions {
|
|
|
33
58
|
* @experimental Enables human-in-the-loop Page confirmation.
|
|
34
59
|
* @beta
|
|
35
60
|
*/
|
|
36
|
-
export interface UseAgentToolPageConfirmationOptions {
|
|
61
|
+
export interface UseAgentToolPageConfirmationOptions<TInput = unknown, TResult = unknown> extends Omit<UseAgentToolDefaultOptions<TInput, TResult>, "requiresConfirmation"> {
|
|
62
|
+
confirm?: never;
|
|
37
63
|
requiresConfirmation: AgentToolPageConfirmationConfig;
|
|
38
64
|
}
|
|
39
65
|
export interface AgentToolBinding<TInput = unknown, TElement extends HTMLElement = HTMLElement> {
|
|
@@ -53,8 +79,8 @@ export declare function getAgentToolBindingInternals(binding: AgentToolBinding):
|
|
|
53
79
|
* @experimental The Page confirmation overload is experimental.
|
|
54
80
|
* @beta
|
|
55
81
|
*/
|
|
56
|
-
export declare function useAgentTool<TInput, TResult, TElement extends HTMLElement = HTMLElement>(definition: AgentToolDefinition<TInput, TResult>, execute: AgentToolExecutor<TInput,
|
|
57
|
-
export declare function useAgentTool<TInput, TResult, TElement extends HTMLElement = HTMLElement>(definition: AgentToolDefinition<TInput, TResult>, execute: AgentToolExecutor<TInput,
|
|
82
|
+
export declare function useAgentTool<TInput, TResult, TElement extends HTMLElement = HTMLElement, TOutput extends TResult = TResult>(definition: AgentToolDefinition<TInput, TResult>, execute: AgentToolExecutor<TInput, TOutput>, options: UseAgentToolPageConfirmationOptions<NoInfer<TInput>, NoInfer<TOutput>>): AgentToolBinding<TInput, TElement>;
|
|
83
|
+
export declare function useAgentTool<TInput, TResult, TElement extends HTMLElement = HTMLElement, TOutput extends TResult = TResult>(definition: AgentToolDefinition<TInput, TResult>, execute: AgentToolExecutor<TInput, TOutput>, options?: UseAgentToolDefaultOptions<NoInfer<TInput>, NoInfer<TOutput>>): AgentToolBinding<TInput, TElement>;
|
|
58
84
|
export declare function useAgentNavigation<TNavigation extends AgentNavigation, const TExecutors extends AgentNavigationExecutors<TNavigation>>(navigation: TNavigation, executors: TExecutors & Record<Exclude<keyof TExecutors, keyof AgentNavigationExecutors<TNavigation>>, never>): void;
|
|
59
85
|
export declare function ToolsProvider({ children, toolRuntime, webMcp, }: {
|
|
60
86
|
children: ReactNode;
|
package/dist/react.js
CHANGED
|
@@ -55,23 +55,55 @@ function createAgentToolBinding(toolName) {
|
|
|
55
55
|
function useAgentBinding(definition, execute, options) {
|
|
56
56
|
const runtime = useInternalToolRuntime();
|
|
57
57
|
const confirmation = options.requiresConfirmation;
|
|
58
|
+
const confirmationProtocol = Boolean(options.confirm);
|
|
59
|
+
const presentation = useMemo(() => options._render
|
|
60
|
+
? {
|
|
61
|
+
definition,
|
|
62
|
+
...(confirmationProtocol ? { confirmationProtocol: true } : {}),
|
|
63
|
+
render: options._render,
|
|
64
|
+
}
|
|
65
|
+
: undefined, [definition, options._render, confirmationProtocol]);
|
|
66
|
+
const presentationRef = useRef(presentation);
|
|
67
|
+
useLayoutEffect(() => {
|
|
68
|
+
presentationRef.current = presentation;
|
|
69
|
+
runtime.notifyToolPresentationChange();
|
|
70
|
+
}, [runtime, presentation]);
|
|
58
71
|
if (confirmation !== undefined &&
|
|
59
72
|
(!confirmation ||
|
|
60
73
|
typeof confirmation !== "object" ||
|
|
61
74
|
(confirmation.mode !== "chat" && confirmation.mode !== "page"))) {
|
|
62
75
|
throw new Error("requiresConfirmation must explicitly use chat or page mode.");
|
|
63
76
|
}
|
|
77
|
+
if (options.confirm !== undefined && typeof options.confirm !== "function") {
|
|
78
|
+
throw new TypeError("confirm must be a function.");
|
|
79
|
+
}
|
|
80
|
+
if (options.confirm && confirmation) {
|
|
81
|
+
throw new TypeError("Use confirm or requiresConfirmation, not both.");
|
|
82
|
+
}
|
|
83
|
+
const callbacksRef = useRef({ execute, confirm: options.confirm });
|
|
64
84
|
const executeRef = useRef(execute);
|
|
65
|
-
executeRef.current = execute;
|
|
66
85
|
const confirmationRef = useRef(confirmation);
|
|
67
|
-
|
|
68
|
-
|
|
86
|
+
useLayoutEffect(() => {
|
|
87
|
+
executeRef.current = execute;
|
|
88
|
+
confirmationRef.current = confirmation;
|
|
89
|
+
callbacksRef.current = { execute, confirm: options.confirm };
|
|
90
|
+
});
|
|
91
|
+
const mode = options.confirm ? "callback" : confirmation?.mode;
|
|
69
92
|
const binding = useMemo(() => createAgentToolBinding(definition.name), [runtime, definition, mode]);
|
|
70
93
|
useLayoutEffect(() => {
|
|
71
94
|
const controller = new AbortController();
|
|
72
95
|
runtime.bindTool(definition, (input, context) => executeRef.current(input, context), {
|
|
73
96
|
signal: controller.signal,
|
|
74
97
|
getConfirmation: () => confirmationRef.current,
|
|
98
|
+
getPresentation: () => presentationRef.current,
|
|
99
|
+
...(mode === "callback"
|
|
100
|
+
? {
|
|
101
|
+
getCallbacks: () => ({
|
|
102
|
+
execute: callbacksRef.current.execute,
|
|
103
|
+
confirm: callbacksRef.current.confirm,
|
|
104
|
+
}),
|
|
105
|
+
}
|
|
106
|
+
: {}),
|
|
75
107
|
resolveTarget: (input) => getAgentToolBindingInternals(binding).resolveTarget(input),
|
|
76
108
|
});
|
|
77
109
|
return () => controller.abort();
|
|
@@ -81,21 +113,36 @@ function useAgentBinding(definition, execute, options) {
|
|
|
81
113
|
export function useAgentTool(definition, execute, options = {}) {
|
|
82
114
|
return useAgentBinding(definition, execute, options);
|
|
83
115
|
}
|
|
84
|
-
function
|
|
85
|
-
if (!
|
|
116
|
+
function getAgentNavigationHandler(handlers, key) {
|
|
117
|
+
if (!handlers || typeof handlers !== "object" || !Object.hasOwn(handlers, key)) {
|
|
86
118
|
throw new Error(`Missing navigation executor: ${key}.`);
|
|
87
119
|
}
|
|
88
|
-
const
|
|
89
|
-
if (typeof
|
|
120
|
+
const handler = handlers[key];
|
|
121
|
+
if (typeof handler === "function")
|
|
122
|
+
return { execute: handler };
|
|
123
|
+
if (!handler ||
|
|
124
|
+
typeof handler !== "object" ||
|
|
125
|
+
typeof handler.execute !== "function") {
|
|
90
126
|
throw new Error(`Missing navigation executor: ${key}.`);
|
|
91
127
|
}
|
|
92
|
-
|
|
128
|
+
const value = handler;
|
|
129
|
+
if (value.confirm !== undefined && typeof value.confirm !== "function") {
|
|
130
|
+
throw new TypeError(`Navigation confirm must be a function: ${key}.`);
|
|
131
|
+
}
|
|
132
|
+
return value;
|
|
133
|
+
}
|
|
134
|
+
function navigationExecutor(execute) {
|
|
135
|
+
return async (input, context) => {
|
|
136
|
+
await execute(input, context);
|
|
137
|
+
context.signal.throwIfAborted();
|
|
138
|
+
return { status: "navigated" };
|
|
139
|
+
};
|
|
93
140
|
}
|
|
94
141
|
export function useAgentNavigation(navigation, executors) {
|
|
95
142
|
const runtime = useInternalToolRuntime();
|
|
96
143
|
const entries = getAgentNavigationEntries(navigation);
|
|
97
144
|
for (const entry of entries) {
|
|
98
|
-
|
|
145
|
+
getAgentNavigationHandler(executors, entry.key);
|
|
99
146
|
}
|
|
100
147
|
const routeKeys = new Set(entries.map((entry) => entry.key));
|
|
101
148
|
for (const key of Object.keys(executors)) {
|
|
@@ -104,24 +151,49 @@ export function useAgentNavigation(navigation, executors) {
|
|
|
104
151
|
}
|
|
105
152
|
}
|
|
106
153
|
const executorsRef = useRef(executors);
|
|
107
|
-
executorsRef.current = executors;
|
|
108
154
|
useLayoutEffect(() => {
|
|
109
|
-
|
|
155
|
+
executorsRef.current = executors;
|
|
156
|
+
});
|
|
157
|
+
const modes = entries.map((entry) => Boolean(getAgentNavigationHandler(executors, entry.key).confirm));
|
|
158
|
+
const modeKey = modes.join(",");
|
|
159
|
+
const bindings = useMemo(() => new Map(), [runtime, navigation]);
|
|
160
|
+
useLayoutEffect(() => () => {
|
|
161
|
+
for (const binding of bindings.values())
|
|
162
|
+
binding.unregister();
|
|
163
|
+
bindings.clear();
|
|
164
|
+
}, [bindings]);
|
|
165
|
+
useLayoutEffect(() => {
|
|
110
166
|
try {
|
|
111
167
|
for (const entry of entries) {
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
168
|
+
const confirmed = Boolean(getAgentNavigationHandler(executorsRef.current, entry.key).confirm);
|
|
169
|
+
const previous = bindings.get(entry.key);
|
|
170
|
+
if (previous?.confirmed === confirmed)
|
|
171
|
+
continue;
|
|
172
|
+
// Changing one route's confirmation mode only invalidates that route.
|
|
173
|
+
previous?.unregister();
|
|
174
|
+
bindings.delete(entry.key);
|
|
175
|
+
const unregister = runtime.bindTool(entry.definition, (input, context) => navigationExecutor(getAgentNavigationHandler(executorsRef.current, entry.key).execute)(input, context), confirmed
|
|
176
|
+
? {
|
|
177
|
+
getCallbacks: () => {
|
|
178
|
+
const handler = getAgentNavigationHandler(executorsRef.current, entry.key);
|
|
179
|
+
// Pin the committed callback, not a wrapper reading a mutable ref.
|
|
180
|
+
return {
|
|
181
|
+
execute: navigationExecutor(handler.execute),
|
|
182
|
+
confirm: handler.confirm,
|
|
183
|
+
};
|
|
184
|
+
},
|
|
185
|
+
}
|
|
186
|
+
: {});
|
|
187
|
+
bindings.set(entry.key, { confirmed, unregister });
|
|
117
188
|
}
|
|
118
189
|
}
|
|
119
190
|
catch (error) {
|
|
120
|
-
|
|
191
|
+
for (const binding of bindings.values())
|
|
192
|
+
binding.unregister();
|
|
193
|
+
bindings.clear();
|
|
121
194
|
throw error;
|
|
122
195
|
}
|
|
123
|
-
|
|
124
|
-
}, [runtime, navigation]);
|
|
196
|
+
}, [runtime, navigation, bindings, modeKey]);
|
|
125
197
|
}
|
|
126
198
|
export function ToolsProvider({ children, toolRuntime, webMcp = true, }) {
|
|
127
199
|
const runtime = getInternalToolRuntime(toolRuntime);
|
package/dist/registration.js
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import { assertAgentToolInputSchema } from "./shared/schema.js";
|
|
2
2
|
export function registerAgentTool(definition, options) {
|
|
3
3
|
assertAgentToolRegistration(definition, options);
|
|
4
|
+
if ("confirm" in options) {
|
|
5
|
+
throw new TypeError("Use toolRuntime.register for tools with confirm.");
|
|
6
|
+
}
|
|
4
7
|
assertAgentToolInputSchema(definition.inputSchema, `Tool "${definition.name}" was not registered: inputSchema`);
|
|
5
8
|
return Object.freeze({ definition, execute: options.execute });
|
|
6
9
|
}
|
package/dist/runtime.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import type { ConfirmationCallback } from "./confirmation.js";
|
|
2
|
+
import { type ToolPresentation } from "./shared/tool-presentation.js";
|
|
1
3
|
import { type InternalExecutionOptions } from "./shared/runtime-execution.js";
|
|
2
4
|
import type { PageActionFeedback } from "./browser/feedback.js";
|
|
3
5
|
import { type TaskProgress } from "./shared/runtime-controller.js";
|
|
@@ -59,6 +61,14 @@ export interface ToolRuntime {
|
|
|
59
61
|
*/
|
|
60
62
|
register<TInput, TResult>(definition: AgentToolDefinition<TInput, TResult>, options: {
|
|
61
63
|
execute: RegisteredAgentTool<TInput, TResult>["execute"];
|
|
64
|
+
confirm?: (context: {
|
|
65
|
+
input: TInput;
|
|
66
|
+
signal: AbortSignal;
|
|
67
|
+
}) => boolean | {
|
|
68
|
+
message: string;
|
|
69
|
+
} | Promise<boolean | {
|
|
70
|
+
message: string;
|
|
71
|
+
}>;
|
|
62
72
|
requiresConfirmation?: never;
|
|
63
73
|
}): () => void;
|
|
64
74
|
getTools(): readonly RuntimeAgentTool[];
|
|
@@ -72,7 +82,7 @@ export interface ToolRuntime {
|
|
|
72
82
|
* @param input - Arguments matching the tool's input schema.
|
|
73
83
|
* @param options - Optional cancellation signal and display-only progress label.
|
|
74
84
|
* @returns The tool result, or a rejected promise when execution fails.
|
|
75
|
-
* @remarks Joins the operation active when submitted. Rejects with OPERATION_BUSY while ending.
|
|
85
|
+
* @remarks Joins the operation active when submitted. Rejects with OPERATION_BUSY while ending. Runs the registered confirm callback when configured.
|
|
76
86
|
*/
|
|
77
87
|
execute<TInput, TResult>(tool: RuntimeAgentTool<TInput, TResult>, input: TInput, options?: {
|
|
78
88
|
signal?: AbortSignal;
|
|
@@ -116,6 +126,8 @@ export declare class AgentContextError extends Error {
|
|
|
116
126
|
constructor(code: AgentContextErrorCode, message: string);
|
|
117
127
|
}
|
|
118
128
|
export interface InternalToolRuntime extends ToolRuntime, EventTarget {
|
|
129
|
+
notifyToolPresentationChange(): void;
|
|
130
|
+
usesConfirmationProtocol(tool: RuntimeAgentTool): boolean;
|
|
119
131
|
beginInternalOperation(options?: {
|
|
120
132
|
signal?: AbortSignal;
|
|
121
133
|
onCancel?: () => void;
|
|
@@ -134,6 +146,11 @@ export interface InternalToolRuntime extends ToolRuntime, EventTarget {
|
|
|
134
146
|
bindTool<TInput, TResult>(definition: AgentToolDefinition<TInput, TResult>, execute: AgentToolExecutor<TInput, TResult>, options?: {
|
|
135
147
|
signal?: AbortSignal;
|
|
136
148
|
getConfirmation?: () => AgentToolConfirmationConfig | undefined;
|
|
149
|
+
getPresentation?: () => ToolPresentation | undefined;
|
|
150
|
+
getCallbacks?: () => {
|
|
151
|
+
execute: AgentToolExecutor<any, any>;
|
|
152
|
+
confirm: ConfirmationCallback<any>;
|
|
153
|
+
};
|
|
137
154
|
resolveTarget?: (input: unknown) => HTMLElement | undefined;
|
|
138
155
|
}): () => void;
|
|
139
156
|
registerContext(input: AgentContextInput, options?: {
|
|
@@ -165,17 +182,25 @@ export declare class ToolRuntimeImplementation extends EventTarget implements To
|
|
|
165
182
|
requestOperationCancel(id: string): void;
|
|
166
183
|
setPageActionFeedback(listener: (event: AgentToolExecutionEvent, feedback: PageActionFeedback, signal?: AbortSignal) => void | Promise<void>): () => void;
|
|
167
184
|
constructor(options?: ToolRuntimeOptions);
|
|
185
|
+
notifyToolPresentationChange(): void;
|
|
168
186
|
on(eventName: "toolchange", listener: (event: ToolRuntimeToolChangeEvent) => void): () => void;
|
|
169
187
|
on(eventName: "toolexecution", listener: (event: AgentToolExecutionEvent) => void): () => void;
|
|
170
188
|
register<TInput, TResult>(definition: AgentToolDefinition<TInput, TResult>, options: {
|
|
171
189
|
execute: RegisteredAgentTool<TInput, TResult>["execute"];
|
|
190
|
+
confirm?: ConfirmationCallback<TInput>;
|
|
172
191
|
requiresConfirmation?: never;
|
|
173
192
|
}): () => void;
|
|
174
193
|
bindTool<TInput, TResult>(definition: AgentToolDefinition<TInput, TResult>, execute: AgentToolExecutor<TInput, TResult>, options?: {
|
|
175
194
|
signal?: AbortSignal;
|
|
176
195
|
getConfirmation?: () => AgentToolConfirmationConfig | undefined;
|
|
196
|
+
getPresentation?: () => ToolPresentation | undefined;
|
|
197
|
+
getCallbacks?: () => {
|
|
198
|
+
execute: AgentToolExecutor<any, any>;
|
|
199
|
+
confirm: ConfirmationCallback<any>;
|
|
200
|
+
};
|
|
177
201
|
resolveTarget?: (input: unknown) => HTMLElement | undefined;
|
|
178
202
|
}): () => void;
|
|
203
|
+
usesConfirmationProtocol(tool: RuntimeAgentTool): boolean;
|
|
179
204
|
registerContext(input: AgentContextInput, options?: {
|
|
180
205
|
signal?: AbortSignal;
|
|
181
206
|
}): AgentContextRegistration;
|
package/dist/runtime.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
+
import { confirmationDefinition, createConfirmationHandler } from "./confirmation-protocol.js";
|
|
1
2
|
import { searchNavigationTools, searchToolDefinition } from "./tool-search.js";
|
|
3
|
+
import { toolPresentationSymbol, } from "./shared/tool-presentation.js";
|
|
2
4
|
import { pageDecisionSymbol } from "./shared/runtime-execution.js";
|
|
3
5
|
import { PageCommandError } from "./browser/locator.js";
|
|
4
6
|
import { measurePagePhase } from "./browser/diagnostics.js";
|
|
@@ -203,6 +205,21 @@ export class ToolRuntimeImplementation extends EventTarget {
|
|
|
203
205
|
getRegisteredTools: () => this.getRegisteredTools(),
|
|
204
206
|
});
|
|
205
207
|
Object.defineProperty(this, runtimeControllerSymbol, { value: controller });
|
|
208
|
+
const presentations = {
|
|
209
|
+
get: (name) => this.#bindings.get(name)?.getPresentation?.(),
|
|
210
|
+
subscribe: (listener) => {
|
|
211
|
+
this.addEventListener("toolchange", listener);
|
|
212
|
+
this.addEventListener("toolpresentationchange", listener);
|
|
213
|
+
return () => {
|
|
214
|
+
this.removeEventListener("toolchange", listener);
|
|
215
|
+
this.removeEventListener("toolpresentationchange", listener);
|
|
216
|
+
};
|
|
217
|
+
},
|
|
218
|
+
};
|
|
219
|
+
Object.defineProperty(this, toolPresentationSymbol, { value: Object.freeze(presentations) });
|
|
220
|
+
}
|
|
221
|
+
notifyToolPresentationChange() {
|
|
222
|
+
this.dispatchEvent(new Event("toolpresentationchange"));
|
|
206
223
|
}
|
|
207
224
|
on(eventName, listener) {
|
|
208
225
|
const handleEvent = (event) => {
|
|
@@ -235,19 +252,38 @@ export class ToolRuntimeImplementation extends EventTarget {
|
|
|
235
252
|
catch (cause) {
|
|
236
253
|
throw new TypeError(`Tool "${definition.name}" was not registered: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
|
|
237
254
|
}
|
|
238
|
-
|
|
255
|
+
if (options.confirm !== undefined && typeof options.confirm !== "function") {
|
|
256
|
+
throw new TypeError("confirm must be a function.");
|
|
257
|
+
}
|
|
258
|
+
const confirm = options.confirm;
|
|
259
|
+
const callback = (input, { signal }) => execute(input, { signal });
|
|
260
|
+
return this.#bindTool(copied, callback, confirm
|
|
261
|
+
? {
|
|
262
|
+
getCallbacks: () => ({ execute: callback, confirm }),
|
|
263
|
+
}
|
|
264
|
+
: {});
|
|
239
265
|
}
|
|
240
266
|
bindTool(definition, execute, options = {}) {
|
|
241
267
|
assertAgentToolInputSchema(definition.inputSchema, `Tool "${definition.name}" was not registered: inputSchema`);
|
|
242
268
|
return this.#bindTool(definition, execute, options);
|
|
243
269
|
}
|
|
270
|
+
usesConfirmationProtocol(tool) {
|
|
271
|
+
const binding = this.#bindings.get(tool.definition.name);
|
|
272
|
+
return binding?.runtimeTool === tool && binding.definition !== tool.definition;
|
|
273
|
+
}
|
|
244
274
|
#bindTool(definition, execute, options = {}) {
|
|
245
275
|
if (this.#bindings.has(definition.name)) {
|
|
246
276
|
throw new AgentToolError("DUPLICATE_BINDING", `Tool "${definition.name}" already has an active binding.`);
|
|
247
277
|
}
|
|
248
278
|
const lifecycleController = new AbortController();
|
|
279
|
+
const exposedDefinition = options.getCallbacks
|
|
280
|
+
? confirmationDefinition(definition)
|
|
281
|
+
: definition;
|
|
282
|
+
const confirmationHandler = options.getCallbacks
|
|
283
|
+
? createConfirmationHandler(definition, lifecycleController.signal)
|
|
284
|
+
: undefined;
|
|
249
285
|
const runtimeTool = Object.freeze({
|
|
250
|
-
definition,
|
|
286
|
+
definition: exposedDefinition,
|
|
251
287
|
get confirmation() {
|
|
252
288
|
const confirmation = options.getConfirmation?.();
|
|
253
289
|
return confirmation === undefined ? undefined : Object.freeze({ ...confirmation });
|
|
@@ -255,10 +291,17 @@ export class ToolRuntimeImplementation extends EventTarget {
|
|
|
255
291
|
lifecycleSignal: lifecycleController.signal,
|
|
256
292
|
});
|
|
257
293
|
const binding = {
|
|
258
|
-
...(options.
|
|
294
|
+
...(options.getPresentation ? { getPresentation: options.getPresentation } : {}),
|
|
295
|
+
...(options.resolveTarget
|
|
296
|
+
? {
|
|
297
|
+
resolveTarget: (input) => options.resolveTarget(confirmationHandler ? confirmationHandler.resolveInput(input) : input),
|
|
298
|
+
}
|
|
299
|
+
: {}),
|
|
259
300
|
definition,
|
|
260
301
|
runtimeTool,
|
|
261
|
-
execute
|
|
302
|
+
execute: confirmationHandler
|
|
303
|
+
? (input, context) => confirmationHandler.execute(input, context, options.getCallbacks())
|
|
304
|
+
: execute,
|
|
262
305
|
...(options.getConfirmation ? { getConfirmation: options.getConfirmation } : {}),
|
|
263
306
|
lifecycleController,
|
|
264
307
|
};
|
|
@@ -469,6 +512,15 @@ export class ToolRuntimeImplementation extends EventTarget {
|
|
|
469
512
|
if (binding.runtimeTool !== tool) {
|
|
470
513
|
return Promise.reject(new AgentToolError("CONTRACT_MISMATCH", `Tool "${name}" is registered with a different Runtime Tool.`));
|
|
471
514
|
}
|
|
515
|
+
// Snapshot protocol arguments before waiting in the execution queue.
|
|
516
|
+
if (binding.runtimeTool.definition !== binding.definition) {
|
|
517
|
+
try {
|
|
518
|
+
input = structuredClone(input);
|
|
519
|
+
}
|
|
520
|
+
catch {
|
|
521
|
+
return Promise.reject(new AgentToolError("INVALID_INPUT", "Tool arguments must be structured-cloneable."));
|
|
522
|
+
}
|
|
523
|
+
}
|
|
472
524
|
return this.#enqueue((operationId) => this.#executeApplication(name, input, options, binding, operationId), options.signal);
|
|
473
525
|
}
|
|
474
526
|
try {
|
|
@@ -632,7 +684,7 @@ export class ToolRuntimeImplementation extends EventTarget {
|
|
|
632
684
|
if (this.#bindings.get(name) !== binding) {
|
|
633
685
|
throw new AgentToolError("UNKNOWN_TOOL", `Tool "${name}" is no longer registered for this call.`);
|
|
634
686
|
}
|
|
635
|
-
const errors = validateAgentToolInput(binding.definition.inputSchema, input);
|
|
687
|
+
const errors = validateAgentToolInput(binding.runtimeTool.definition.inputSchema, input);
|
|
636
688
|
if (errors.length) {
|
|
637
689
|
throw new AgentToolError("INVALID_INPUT", errors.join(" "), { errors });
|
|
638
690
|
}
|
package/dist/shared/errors.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export declare const TOOL_ERROR_CODES: readonly ["EXECUTION_OUTCOME_UNKNOWN", "ACTION_IN_FLIGHT", "ACTION_NOT_HANDLED", "ACTION_TARGET_UNAVAILABLE", "BROWSER_EXECUTION_FAILED", "BROWSER_SNAPSHOT_REQUIRED", "BROWSER_TOOLS_UNAVAILABLE", "CONTRACT_MISMATCH", "DUPLICATE_BINDING", "INVALID_INPUT", "INVALID_TOOL_RUNTIME", "OPERATION_BUSY", "TOOL_CANCELLED", "TOOL_CONFIRMATION_INVALIDATED", "TOOL_CONFIRMATION_REJECTED", "TOOL_ERROR", "TOOL_REGISTRATION_TIMEOUT", "TOOL_SKIPPED", "TOOL_UNAVAILABLE", "UNKNOWN_TOOL"];
|
|
1
|
+
export declare const TOOL_ERROR_CODES: readonly ["EXECUTION_OUTCOME_UNKNOWN", "ACTION_IN_FLIGHT", "ACTION_NOT_HANDLED", "ACTION_TARGET_UNAVAILABLE", "BROWSER_EXECUTION_FAILED", "BROWSER_SNAPSHOT_REQUIRED", "BROWSER_TOOLS_UNAVAILABLE", "CONTRACT_MISMATCH", "DUPLICATE_BINDING", "INVALID_INPUT", "INVALID_CONFIRMATION_RESULT", "TOOL_CONFIRMATION_LIMIT", "INVALID_TOOL_RUNTIME", "OPERATION_BUSY", "TOOL_CANCELLED", "TOOL_CONFIRMATION_INVALIDATED", "TOOL_CONFIRMATION_REJECTED", "TOOL_ERROR", "TOOL_REGISTRATION_TIMEOUT", "TOOL_SKIPPED", "TOOL_UNAVAILABLE", "UNKNOWN_TOOL"];
|
|
2
2
|
type AgentToolErrorCode = (typeof TOOL_ERROR_CODES)[number];
|
|
3
3
|
export declare class AgentToolError extends Error {
|
|
4
4
|
readonly code: AgentToolErrorCode;
|
package/dist/shared/errors.js
CHANGED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { ToolRuntime } from "../runtime.js";
|
|
2
|
+
export interface ToolRenderContext<TInput = unknown, TResult = unknown> {
|
|
3
|
+
input: TInput;
|
|
4
|
+
status: "running" | "success" | "error" | "cancelled";
|
|
5
|
+
result?: TResult;
|
|
6
|
+
}
|
|
7
|
+
export interface ToolPresentation {
|
|
8
|
+
definition: ReturnType<ToolRuntime["getTools"]>[number]["definition"];
|
|
9
|
+
confirmationProtocol?: true;
|
|
10
|
+
render(context: ToolRenderContext): unknown;
|
|
11
|
+
}
|
|
12
|
+
export interface ToolPresentationController {
|
|
13
|
+
get(name: string): ToolPresentation | undefined;
|
|
14
|
+
subscribe(listener: () => void): () => void;
|
|
15
|
+
}
|
|
16
|
+
export declare const toolPresentationSymbol: unique symbol;
|
|
17
|
+
export declare function getToolPresentationController(runtime: ToolRuntime): ToolPresentationController | undefined;
|
package/dist/webmcp.js
CHANGED
|
@@ -157,6 +157,7 @@ function createConnection(runtime, modelContext) {
|
|
|
157
157
|
};
|
|
158
158
|
const register = (tool) => {
|
|
159
159
|
const { definition } = tool;
|
|
160
|
+
const confirmed = runtime.usesConfirmationProtocol(tool);
|
|
160
161
|
const controller = new AbortController();
|
|
161
162
|
const registration = { controller, tool };
|
|
162
163
|
registrations.set(definition.name, registration);
|
|
@@ -168,17 +169,17 @@ function createConnection(runtime, modelContext) {
|
|
|
168
169
|
inputSchema: {
|
|
169
170
|
type: "object",
|
|
170
171
|
properties: {
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
172
|
+
...(confirmed
|
|
173
|
+
? definition.inputSchema.properties
|
|
174
|
+
: {
|
|
175
|
+
input: definition.inputSchema,
|
|
176
|
+
}),
|
|
176
177
|
progressLabel: {
|
|
177
178
|
type: "string",
|
|
178
179
|
description: "Briefly describe this tool action in the user’s language. Do not expose internal identifiers or claim success before completion.",
|
|
179
180
|
},
|
|
180
181
|
},
|
|
181
|
-
required: ["input"],
|
|
182
|
+
...(confirmed ? {} : { required: ["input"] }),
|
|
182
183
|
additionalProperties: false,
|
|
183
184
|
},
|
|
184
185
|
execute: async (parameters, options = {}) => {
|
|
@@ -186,14 +187,18 @@ function createConnection(runtime, modelContext) {
|
|
|
186
187
|
if (!args ||
|
|
187
188
|
typeof args !== "object" ||
|
|
188
189
|
Array.isArray(args) ||
|
|
189
|
-
!
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
190
|
+
(!confirmed &&
|
|
191
|
+
(!args.input || typeof args.input !== "object" || Array.isArray(args.input))) ||
|
|
192
|
+
Object.keys(args).some((key) => key !== "input" &&
|
|
193
|
+
key !== "progressLabel" &&
|
|
194
|
+
!(confirmed && key === "confirmation")) ||
|
|
193
195
|
(args.progressLabel !== undefined && typeof args.progressLabel !== "string")) {
|
|
194
|
-
throw new TypeError(
|
|
196
|
+
throw new TypeError(confirmed
|
|
197
|
+
? "WebMCP confirmation tools require input or confirmation, with an optional string progressLabel."
|
|
198
|
+
: "WebMCP tools require { input: object, progressLabel?: string }.");
|
|
195
199
|
}
|
|
196
|
-
|
|
200
|
+
const { progressLabel, ...payload } = args;
|
|
201
|
+
return runtime.execute(tool, confirmed ? payload : args.input, {
|
|
197
202
|
...(options.signal ? { signal: options.signal } : {}),
|
|
198
203
|
...(typeof args.progressLabel === "string"
|
|
199
204
|
? { progressLabel: args.progressLabel }
|