@nexface/tools 0.1.20-alpha.0 → 0.1.20-alpha.2
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/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 +9 -0
- package/dist/react.js +80 -20
- package/dist/registration.js +3 -0
- package/dist/runtime.d.ts +21 -1
- package/dist/runtime.js +40 -5
- package/dist/shared/errors.d.ts +1 -1
- package/dist/shared/errors.js +2 -0
- package/dist/shared/tool-presentation.d.ts +1 -0
- package/dist/webmcp.js +17 -12
- package/package.json +1 -1
|
@@ -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
|
@@ -29,6 +29,14 @@ type ToolResultData<T> = unknown extends T ? T : T extends string | number | boo
|
|
|
29
29
|
} : never;
|
|
30
30
|
type ToolRenderResult<T> = unknown extends T ? unknown : [T] extends [void] ? null : [T] extends [ToolResultData<T>] ? T : unknown;
|
|
31
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
|
+
}>;
|
|
32
40
|
/**
|
|
33
41
|
* @experimental
|
|
34
42
|
* @warning Experimental API. Its signature and behavior may change.
|
|
@@ -51,6 +59,7 @@ export interface UseAgentToolDefaultOptions<TInput = unknown, TResult = unknown>
|
|
|
51
59
|
* @beta
|
|
52
60
|
*/
|
|
53
61
|
export interface UseAgentToolPageConfirmationOptions<TInput = unknown, TResult = unknown> extends Omit<UseAgentToolDefaultOptions<TInput, TResult>, "requiresConfirmation"> {
|
|
62
|
+
confirm?: never;
|
|
54
63
|
requiresConfirmation: AgentToolPageConfirmationConfig;
|
|
55
64
|
}
|
|
56
65
|
export interface AgentToolBinding<TInput = unknown, TElement extends HTMLElement = HTMLElement> {
|
package/dist/react.js
CHANGED
|
@@ -55,12 +55,14 @@ 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);
|
|
58
59
|
const presentation = useMemo(() => options._render
|
|
59
60
|
? {
|
|
60
61
|
definition,
|
|
62
|
+
...(confirmationProtocol ? { confirmationProtocol: true } : {}),
|
|
61
63
|
render: options._render,
|
|
62
64
|
}
|
|
63
|
-
: undefined, [definition, options._render]);
|
|
65
|
+
: undefined, [definition, options._render, confirmationProtocol]);
|
|
64
66
|
const presentationRef = useRef(presentation);
|
|
65
67
|
useLayoutEffect(() => {
|
|
66
68
|
presentationRef.current = presentation;
|
|
@@ -72,11 +74,21 @@ function useAgentBinding(definition, execute, options) {
|
|
|
72
74
|
(confirmation.mode !== "chat" && confirmation.mode !== "page"))) {
|
|
73
75
|
throw new Error("requiresConfirmation must explicitly use chat or page mode.");
|
|
74
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 });
|
|
75
84
|
const executeRef = useRef(execute);
|
|
76
|
-
executeRef.current = execute;
|
|
77
85
|
const confirmationRef = useRef(confirmation);
|
|
78
|
-
|
|
79
|
-
|
|
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;
|
|
80
92
|
const binding = useMemo(() => createAgentToolBinding(definition.name), [runtime, definition, mode]);
|
|
81
93
|
useLayoutEffect(() => {
|
|
82
94
|
const controller = new AbortController();
|
|
@@ -84,6 +96,14 @@ function useAgentBinding(definition, execute, options) {
|
|
|
84
96
|
signal: controller.signal,
|
|
85
97
|
getConfirmation: () => confirmationRef.current,
|
|
86
98
|
getPresentation: () => presentationRef.current,
|
|
99
|
+
...(mode === "callback"
|
|
100
|
+
? {
|
|
101
|
+
getCallbacks: () => ({
|
|
102
|
+
execute: callbacksRef.current.execute,
|
|
103
|
+
confirm: callbacksRef.current.confirm,
|
|
104
|
+
}),
|
|
105
|
+
}
|
|
106
|
+
: {}),
|
|
87
107
|
resolveTarget: (input) => getAgentToolBindingInternals(binding).resolveTarget(input),
|
|
88
108
|
});
|
|
89
109
|
return () => controller.abort();
|
|
@@ -93,21 +113,36 @@ function useAgentBinding(definition, execute, options) {
|
|
|
93
113
|
export function useAgentTool(definition, execute, options = {}) {
|
|
94
114
|
return useAgentBinding(definition, execute, options);
|
|
95
115
|
}
|
|
96
|
-
function
|
|
97
|
-
if (!
|
|
116
|
+
function getAgentNavigationHandler(handlers, key) {
|
|
117
|
+
if (!handlers || typeof handlers !== "object" || !Object.hasOwn(handlers, key)) {
|
|
98
118
|
throw new Error(`Missing navigation executor: ${key}.`);
|
|
99
119
|
}
|
|
100
|
-
const
|
|
101
|
-
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") {
|
|
102
126
|
throw new Error(`Missing navigation executor: ${key}.`);
|
|
103
127
|
}
|
|
104
|
-
|
|
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
|
+
};
|
|
105
140
|
}
|
|
106
141
|
export function useAgentNavigation(navigation, executors) {
|
|
107
142
|
const runtime = useInternalToolRuntime();
|
|
108
143
|
const entries = getAgentNavigationEntries(navigation);
|
|
109
144
|
for (const entry of entries) {
|
|
110
|
-
|
|
145
|
+
getAgentNavigationHandler(executors, entry.key);
|
|
111
146
|
}
|
|
112
147
|
const routeKeys = new Set(entries.map((entry) => entry.key));
|
|
113
148
|
for (const key of Object.keys(executors)) {
|
|
@@ -116,24 +151,49 @@ export function useAgentNavigation(navigation, executors) {
|
|
|
116
151
|
}
|
|
117
152
|
}
|
|
118
153
|
const executorsRef = useRef(executors);
|
|
119
|
-
executorsRef.current = executors;
|
|
120
154
|
useLayoutEffect(() => {
|
|
121
|
-
|
|
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(() => {
|
|
122
166
|
try {
|
|
123
167
|
for (const entry of entries) {
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
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 });
|
|
129
188
|
}
|
|
130
189
|
}
|
|
131
190
|
catch (error) {
|
|
132
|
-
|
|
191
|
+
for (const binding of bindings.values())
|
|
192
|
+
binding.unregister();
|
|
193
|
+
bindings.clear();
|
|
133
194
|
throw error;
|
|
134
195
|
}
|
|
135
|
-
|
|
136
|
-
}, [runtime, navigation]);
|
|
196
|
+
}, [runtime, navigation, bindings, modeKey]);
|
|
137
197
|
}
|
|
138
198
|
export function ToolsProvider({ children, toolRuntime, webMcp = true, }) {
|
|
139
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,4 @@
|
|
|
1
|
+
import type { ConfirmationCallback } from "./confirmation.js";
|
|
1
2
|
import { type ToolPresentation } from "./shared/tool-presentation.js";
|
|
2
3
|
import { type InternalExecutionOptions } from "./shared/runtime-execution.js";
|
|
3
4
|
import type { PageActionFeedback } from "./browser/feedback.js";
|
|
@@ -60,6 +61,14 @@ export interface ToolRuntime {
|
|
|
60
61
|
*/
|
|
61
62
|
register<TInput, TResult>(definition: AgentToolDefinition<TInput, TResult>, options: {
|
|
62
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
|
+
}>;
|
|
63
72
|
requiresConfirmation?: never;
|
|
64
73
|
}): () => void;
|
|
65
74
|
getTools(): readonly RuntimeAgentTool[];
|
|
@@ -73,7 +82,7 @@ export interface ToolRuntime {
|
|
|
73
82
|
* @param input - Arguments matching the tool's input schema.
|
|
74
83
|
* @param options - Optional cancellation signal and display-only progress label.
|
|
75
84
|
* @returns The tool result, or a rejected promise when execution fails.
|
|
76
|
-
* @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.
|
|
77
86
|
*/
|
|
78
87
|
execute<TInput, TResult>(tool: RuntimeAgentTool<TInput, TResult>, input: TInput, options?: {
|
|
79
88
|
signal?: AbortSignal;
|
|
@@ -118,6 +127,7 @@ export declare class AgentContextError extends Error {
|
|
|
118
127
|
}
|
|
119
128
|
export interface InternalToolRuntime extends ToolRuntime, EventTarget {
|
|
120
129
|
notifyToolPresentationChange(): void;
|
|
130
|
+
usesConfirmationProtocol(tool: RuntimeAgentTool): boolean;
|
|
121
131
|
beginInternalOperation(options?: {
|
|
122
132
|
signal?: AbortSignal;
|
|
123
133
|
onCancel?: () => void;
|
|
@@ -137,6 +147,10 @@ export interface InternalToolRuntime extends ToolRuntime, EventTarget {
|
|
|
137
147
|
signal?: AbortSignal;
|
|
138
148
|
getConfirmation?: () => AgentToolConfirmationConfig | undefined;
|
|
139
149
|
getPresentation?: () => ToolPresentation | undefined;
|
|
150
|
+
getCallbacks?: () => {
|
|
151
|
+
execute: AgentToolExecutor<any, any>;
|
|
152
|
+
confirm: ConfirmationCallback<any>;
|
|
153
|
+
};
|
|
140
154
|
resolveTarget?: (input: unknown) => HTMLElement | undefined;
|
|
141
155
|
}): () => void;
|
|
142
156
|
registerContext(input: AgentContextInput, options?: {
|
|
@@ -173,14 +187,20 @@ export declare class ToolRuntimeImplementation extends EventTarget implements To
|
|
|
173
187
|
on(eventName: "toolexecution", listener: (event: AgentToolExecutionEvent) => void): () => void;
|
|
174
188
|
register<TInput, TResult>(definition: AgentToolDefinition<TInput, TResult>, options: {
|
|
175
189
|
execute: RegisteredAgentTool<TInput, TResult>["execute"];
|
|
190
|
+
confirm?: ConfirmationCallback<TInput>;
|
|
176
191
|
requiresConfirmation?: never;
|
|
177
192
|
}): () => void;
|
|
178
193
|
bindTool<TInput, TResult>(definition: AgentToolDefinition<TInput, TResult>, execute: AgentToolExecutor<TInput, TResult>, options?: {
|
|
179
194
|
signal?: AbortSignal;
|
|
180
195
|
getConfirmation?: () => AgentToolConfirmationConfig | undefined;
|
|
181
196
|
getPresentation?: () => ToolPresentation | undefined;
|
|
197
|
+
getCallbacks?: () => {
|
|
198
|
+
execute: AgentToolExecutor<any, any>;
|
|
199
|
+
confirm: ConfirmationCallback<any>;
|
|
200
|
+
};
|
|
182
201
|
resolveTarget?: (input: unknown) => HTMLElement | undefined;
|
|
183
202
|
}): () => void;
|
|
203
|
+
usesConfirmationProtocol(tool: RuntimeAgentTool): boolean;
|
|
184
204
|
registerContext(input: AgentContextInput, options?: {
|
|
185
205
|
signal?: AbortSignal;
|
|
186
206
|
}): AgentContextRegistration;
|
package/dist/runtime.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { confirmationDefinition, createConfirmationHandler } from "./confirmation-protocol.js";
|
|
1
2
|
import { searchNavigationTools, searchToolDefinition } from "./tool-search.js";
|
|
2
3
|
import { toolPresentationSymbol, } from "./shared/tool-presentation.js";
|
|
3
4
|
import { pageDecisionSymbol } from "./shared/runtime-execution.js";
|
|
@@ -251,19 +252,38 @@ export class ToolRuntimeImplementation extends EventTarget {
|
|
|
251
252
|
catch (cause) {
|
|
252
253
|
throw new TypeError(`Tool "${definition.name}" was not registered: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
|
|
253
254
|
}
|
|
254
|
-
|
|
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
|
+
: {});
|
|
255
265
|
}
|
|
256
266
|
bindTool(definition, execute, options = {}) {
|
|
257
267
|
assertAgentToolInputSchema(definition.inputSchema, `Tool "${definition.name}" was not registered: inputSchema`);
|
|
258
268
|
return this.#bindTool(definition, execute, options);
|
|
259
269
|
}
|
|
270
|
+
usesConfirmationProtocol(tool) {
|
|
271
|
+
const binding = this.#bindings.get(tool.definition.name);
|
|
272
|
+
return binding?.runtimeTool === tool && binding.definition !== tool.definition;
|
|
273
|
+
}
|
|
260
274
|
#bindTool(definition, execute, options = {}) {
|
|
261
275
|
if (this.#bindings.has(definition.name)) {
|
|
262
276
|
throw new AgentToolError("DUPLICATE_BINDING", `Tool "${definition.name}" already has an active binding.`);
|
|
263
277
|
}
|
|
264
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;
|
|
265
285
|
const runtimeTool = Object.freeze({
|
|
266
|
-
definition,
|
|
286
|
+
definition: exposedDefinition,
|
|
267
287
|
get confirmation() {
|
|
268
288
|
const confirmation = options.getConfirmation?.();
|
|
269
289
|
return confirmation === undefined ? undefined : Object.freeze({ ...confirmation });
|
|
@@ -272,10 +292,16 @@ export class ToolRuntimeImplementation extends EventTarget {
|
|
|
272
292
|
});
|
|
273
293
|
const binding = {
|
|
274
294
|
...(options.getPresentation ? { getPresentation: options.getPresentation } : {}),
|
|
275
|
-
...(options.resolveTarget
|
|
295
|
+
...(options.resolveTarget
|
|
296
|
+
? {
|
|
297
|
+
resolveTarget: (input) => options.resolveTarget(confirmationHandler ? confirmationHandler.resolveInput(input) : input),
|
|
298
|
+
}
|
|
299
|
+
: {}),
|
|
276
300
|
definition,
|
|
277
301
|
runtimeTool,
|
|
278
|
-
execute
|
|
302
|
+
execute: confirmationHandler
|
|
303
|
+
? (input, context) => confirmationHandler.execute(input, context, options.getCallbacks())
|
|
304
|
+
: execute,
|
|
279
305
|
...(options.getConfirmation ? { getConfirmation: options.getConfirmation } : {}),
|
|
280
306
|
lifecycleController,
|
|
281
307
|
};
|
|
@@ -486,6 +512,15 @@ export class ToolRuntimeImplementation extends EventTarget {
|
|
|
486
512
|
if (binding.runtimeTool !== tool) {
|
|
487
513
|
return Promise.reject(new AgentToolError("CONTRACT_MISMATCH", `Tool "${name}" is registered with a different Runtime Tool.`));
|
|
488
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
|
+
}
|
|
489
524
|
return this.#enqueue((operationId) => this.#executeApplication(name, input, options, binding, operationId), options.signal);
|
|
490
525
|
}
|
|
491
526
|
try {
|
|
@@ -649,7 +684,7 @@ export class ToolRuntimeImplementation extends EventTarget {
|
|
|
649
684
|
if (this.#bindings.get(name) !== binding) {
|
|
650
685
|
throw new AgentToolError("UNKNOWN_TOOL", `Tool "${name}" is no longer registered for this call.`);
|
|
651
686
|
}
|
|
652
|
-
const errors = validateAgentToolInput(binding.definition.inputSchema, input);
|
|
687
|
+
const errors = validateAgentToolInput(binding.runtimeTool.definition.inputSchema, input);
|
|
653
688
|
if (errors.length) {
|
|
654
689
|
throw new AgentToolError("INVALID_INPUT", errors.join(" "), { errors });
|
|
655
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
|
@@ -6,6 +6,7 @@ export interface ToolRenderContext<TInput = unknown, TResult = unknown> {
|
|
|
6
6
|
}
|
|
7
7
|
export interface ToolPresentation {
|
|
8
8
|
definition: ReturnType<ToolRuntime["getTools"]>[number]["definition"];
|
|
9
|
+
confirmationProtocol?: true;
|
|
9
10
|
render(context: ToolRenderContext): unknown;
|
|
10
11
|
}
|
|
11
12
|
export interface ToolPresentationController {
|
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 }
|