@nexface/tools 0.1.20 → 0.1.21
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 +11 -2
- package/dist/react.js +77 -19
- 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/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
|
@@ -22,7 +22,15 @@ export interface AgentToolPageConfirmationConfig {
|
|
|
22
22
|
title?: string;
|
|
23
23
|
description?: string;
|
|
24
24
|
}
|
|
25
|
-
export interface UseAgentToolDefaultOptions {
|
|
25
|
+
export interface UseAgentToolDefaultOptions<TInput = unknown> {
|
|
26
|
+
confirm?: (context: {
|
|
27
|
+
input: TInput;
|
|
28
|
+
signal: AbortSignal;
|
|
29
|
+
}) => boolean | {
|
|
30
|
+
message: string;
|
|
31
|
+
} | Promise<boolean | {
|
|
32
|
+
message: string;
|
|
33
|
+
}>;
|
|
26
34
|
/**
|
|
27
35
|
* @experimental Enables human-in-the-loop Chat confirmation.
|
|
28
36
|
* @beta
|
|
@@ -34,6 +42,7 @@ export interface UseAgentToolDefaultOptions {
|
|
|
34
42
|
* @beta
|
|
35
43
|
*/
|
|
36
44
|
export interface UseAgentToolPageConfirmationOptions {
|
|
45
|
+
confirm?: never;
|
|
37
46
|
requiresConfirmation: AgentToolPageConfirmationConfig;
|
|
38
47
|
}
|
|
39
48
|
export interface AgentToolBinding<TInput = unknown, TElement extends HTMLElement = HTMLElement> {
|
|
@@ -54,7 +63,7 @@ export declare function getAgentToolBindingInternals(binding: AgentToolBinding):
|
|
|
54
63
|
* @beta
|
|
55
64
|
*/
|
|
56
65
|
export declare function useAgentTool<TInput, TResult, TElement extends HTMLElement = HTMLElement>(definition: AgentToolDefinition<TInput, TResult>, execute: AgentToolExecutor<TInput, TResult>, options: UseAgentToolPageConfirmationOptions): AgentToolBinding<TInput, TElement>;
|
|
57
|
-
export declare function useAgentTool<TInput, TResult, TElement extends HTMLElement = HTMLElement>(definition: AgentToolDefinition<TInput, TResult>, execute: AgentToolExecutor<TInput, TResult>, options?: UseAgentToolDefaultOptions): AgentToolBinding<TInput, TElement>;
|
|
66
|
+
export declare function useAgentTool<TInput, TResult, TElement extends HTMLElement = HTMLElement>(definition: AgentToolDefinition<TInput, TResult>, execute: AgentToolExecutor<TInput, TResult>, options?: UseAgentToolDefaultOptions<TInput>): AgentToolBinding<TInput, TElement>;
|
|
58
67
|
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
68
|
export declare function ToolsProvider({ children, toolRuntime, webMcp, }: {
|
|
60
69
|
children: ReactNode;
|
package/dist/react.js
CHANGED
|
@@ -61,17 +61,35 @@ function useAgentBinding(definition, execute, options) {
|
|
|
61
61
|
(confirmation.mode !== "chat" && confirmation.mode !== "page"))) {
|
|
62
62
|
throw new Error("requiresConfirmation must explicitly use chat or page mode.");
|
|
63
63
|
}
|
|
64
|
+
if (options.confirm !== undefined && typeof options.confirm !== "function") {
|
|
65
|
+
throw new TypeError("confirm must be a function.");
|
|
66
|
+
}
|
|
67
|
+
if (options.confirm && confirmation) {
|
|
68
|
+
throw new TypeError("Use confirm or requiresConfirmation, not both.");
|
|
69
|
+
}
|
|
70
|
+
const callbacksRef = useRef({ execute, confirm: options.confirm });
|
|
64
71
|
const executeRef = useRef(execute);
|
|
65
|
-
executeRef.current = execute;
|
|
66
72
|
const confirmationRef = useRef(confirmation);
|
|
67
|
-
|
|
68
|
-
|
|
73
|
+
useLayoutEffect(() => {
|
|
74
|
+
executeRef.current = execute;
|
|
75
|
+
confirmationRef.current = confirmation;
|
|
76
|
+
callbacksRef.current = { execute, confirm: options.confirm };
|
|
77
|
+
});
|
|
78
|
+
const mode = options.confirm ? "callback" : confirmation?.mode;
|
|
69
79
|
const binding = useMemo(() => createAgentToolBinding(definition.name), [runtime, definition, mode]);
|
|
70
80
|
useLayoutEffect(() => {
|
|
71
81
|
const controller = new AbortController();
|
|
72
82
|
runtime.bindTool(definition, (input, context) => executeRef.current(input, context), {
|
|
73
83
|
signal: controller.signal,
|
|
74
84
|
getConfirmation: () => confirmationRef.current,
|
|
85
|
+
...(mode === "callback"
|
|
86
|
+
? {
|
|
87
|
+
getCallbacks: () => ({
|
|
88
|
+
execute: callbacksRef.current.execute,
|
|
89
|
+
confirm: callbacksRef.current.confirm,
|
|
90
|
+
}),
|
|
91
|
+
}
|
|
92
|
+
: {}),
|
|
75
93
|
resolveTarget: (input) => getAgentToolBindingInternals(binding).resolveTarget(input),
|
|
76
94
|
});
|
|
77
95
|
return () => controller.abort();
|
|
@@ -81,21 +99,36 @@ function useAgentBinding(definition, execute, options) {
|
|
|
81
99
|
export function useAgentTool(definition, execute, options = {}) {
|
|
82
100
|
return useAgentBinding(definition, execute, options);
|
|
83
101
|
}
|
|
84
|
-
function
|
|
85
|
-
if (!
|
|
102
|
+
function getAgentNavigationHandler(handlers, key) {
|
|
103
|
+
if (!handlers || typeof handlers !== "object" || !Object.hasOwn(handlers, key)) {
|
|
86
104
|
throw new Error(`Missing navigation executor: ${key}.`);
|
|
87
105
|
}
|
|
88
|
-
const
|
|
89
|
-
if (typeof
|
|
106
|
+
const handler = handlers[key];
|
|
107
|
+
if (typeof handler === "function")
|
|
108
|
+
return { execute: handler };
|
|
109
|
+
if (!handler ||
|
|
110
|
+
typeof handler !== "object" ||
|
|
111
|
+
typeof handler.execute !== "function") {
|
|
90
112
|
throw new Error(`Missing navigation executor: ${key}.`);
|
|
91
113
|
}
|
|
92
|
-
|
|
114
|
+
const value = handler;
|
|
115
|
+
if (value.confirm !== undefined && typeof value.confirm !== "function") {
|
|
116
|
+
throw new TypeError(`Navigation confirm must be a function: ${key}.`);
|
|
117
|
+
}
|
|
118
|
+
return value;
|
|
119
|
+
}
|
|
120
|
+
function navigationExecutor(execute) {
|
|
121
|
+
return async (input, context) => {
|
|
122
|
+
await execute(input, context);
|
|
123
|
+
context.signal.throwIfAborted();
|
|
124
|
+
return { status: "navigated" };
|
|
125
|
+
};
|
|
93
126
|
}
|
|
94
127
|
export function useAgentNavigation(navigation, executors) {
|
|
95
128
|
const runtime = useInternalToolRuntime();
|
|
96
129
|
const entries = getAgentNavigationEntries(navigation);
|
|
97
130
|
for (const entry of entries) {
|
|
98
|
-
|
|
131
|
+
getAgentNavigationHandler(executors, entry.key);
|
|
99
132
|
}
|
|
100
133
|
const routeKeys = new Set(entries.map((entry) => entry.key));
|
|
101
134
|
for (const key of Object.keys(executors)) {
|
|
@@ -104,24 +137,49 @@ export function useAgentNavigation(navigation, executors) {
|
|
|
104
137
|
}
|
|
105
138
|
}
|
|
106
139
|
const executorsRef = useRef(executors);
|
|
107
|
-
executorsRef.current = executors;
|
|
108
140
|
useLayoutEffect(() => {
|
|
109
|
-
|
|
141
|
+
executorsRef.current = executors;
|
|
142
|
+
});
|
|
143
|
+
const modes = entries.map((entry) => Boolean(getAgentNavigationHandler(executors, entry.key).confirm));
|
|
144
|
+
const modeKey = modes.join(",");
|
|
145
|
+
const bindings = useMemo(() => new Map(), [runtime, navigation]);
|
|
146
|
+
useLayoutEffect(() => () => {
|
|
147
|
+
for (const binding of bindings.values())
|
|
148
|
+
binding.unregister();
|
|
149
|
+
bindings.clear();
|
|
150
|
+
}, [bindings]);
|
|
151
|
+
useLayoutEffect(() => {
|
|
110
152
|
try {
|
|
111
153
|
for (const entry of entries) {
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
154
|
+
const confirmed = Boolean(getAgentNavigationHandler(executorsRef.current, entry.key).confirm);
|
|
155
|
+
const previous = bindings.get(entry.key);
|
|
156
|
+
if (previous?.confirmed === confirmed)
|
|
157
|
+
continue;
|
|
158
|
+
// Changing one route's confirmation mode only invalidates that route.
|
|
159
|
+
previous?.unregister();
|
|
160
|
+
bindings.delete(entry.key);
|
|
161
|
+
const unregister = runtime.bindTool(entry.definition, (input, context) => navigationExecutor(getAgentNavigationHandler(executorsRef.current, entry.key).execute)(input, context), confirmed
|
|
162
|
+
? {
|
|
163
|
+
getCallbacks: () => {
|
|
164
|
+
const handler = getAgentNavigationHandler(executorsRef.current, entry.key);
|
|
165
|
+
// Pin the committed callback, not a wrapper reading a mutable ref.
|
|
166
|
+
return {
|
|
167
|
+
execute: navigationExecutor(handler.execute),
|
|
168
|
+
confirm: handler.confirm,
|
|
169
|
+
};
|
|
170
|
+
},
|
|
171
|
+
}
|
|
172
|
+
: {});
|
|
173
|
+
bindings.set(entry.key, { confirmed, unregister });
|
|
117
174
|
}
|
|
118
175
|
}
|
|
119
176
|
catch (error) {
|
|
120
|
-
|
|
177
|
+
for (const binding of bindings.values())
|
|
178
|
+
binding.unregister();
|
|
179
|
+
bindings.clear();
|
|
121
180
|
throw error;
|
|
122
181
|
}
|
|
123
|
-
|
|
124
|
-
}, [runtime, navigation]);
|
|
182
|
+
}, [runtime, navigation, bindings, modeKey]);
|
|
125
183
|
}
|
|
126
184
|
export function ToolsProvider({ children, toolRuntime, webMcp = true, }) {
|
|
127
185
|
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 InternalExecutionOptions } from "./shared/runtime-execution.js";
|
|
2
3
|
import type { PageActionFeedback } from "./browser/feedback.js";
|
|
3
4
|
import { type TaskProgress } from "./shared/runtime-controller.js";
|
|
@@ -59,6 +60,14 @@ export interface ToolRuntime {
|
|
|
59
60
|
*/
|
|
60
61
|
register<TInput, TResult>(definition: AgentToolDefinition<TInput, TResult>, options: {
|
|
61
62
|
execute: RegisteredAgentTool<TInput, TResult>["execute"];
|
|
63
|
+
confirm?: (context: {
|
|
64
|
+
input: TInput;
|
|
65
|
+
signal: AbortSignal;
|
|
66
|
+
}) => boolean | {
|
|
67
|
+
message: string;
|
|
68
|
+
} | Promise<boolean | {
|
|
69
|
+
message: string;
|
|
70
|
+
}>;
|
|
62
71
|
requiresConfirmation?: never;
|
|
63
72
|
}): () => void;
|
|
64
73
|
getTools(): readonly RuntimeAgentTool[];
|
|
@@ -72,7 +81,7 @@ export interface ToolRuntime {
|
|
|
72
81
|
* @param input - Arguments matching the tool's input schema.
|
|
73
82
|
* @param options - Optional cancellation signal and display-only progress label.
|
|
74
83
|
* @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.
|
|
84
|
+
* @remarks Joins the operation active when submitted. Rejects with OPERATION_BUSY while ending. Runs the registered confirm callback when configured.
|
|
76
85
|
*/
|
|
77
86
|
execute<TInput, TResult>(tool: RuntimeAgentTool<TInput, TResult>, input: TInput, options?: {
|
|
78
87
|
signal?: AbortSignal;
|
|
@@ -116,6 +125,7 @@ export declare class AgentContextError extends Error {
|
|
|
116
125
|
constructor(code: AgentContextErrorCode, message: string);
|
|
117
126
|
}
|
|
118
127
|
export interface InternalToolRuntime extends ToolRuntime, EventTarget {
|
|
128
|
+
usesConfirmationProtocol(tool: RuntimeAgentTool): boolean;
|
|
119
129
|
beginInternalOperation(options?: {
|
|
120
130
|
signal?: AbortSignal;
|
|
121
131
|
onCancel?: () => void;
|
|
@@ -134,6 +144,10 @@ export interface InternalToolRuntime extends ToolRuntime, EventTarget {
|
|
|
134
144
|
bindTool<TInput, TResult>(definition: AgentToolDefinition<TInput, TResult>, execute: AgentToolExecutor<TInput, TResult>, options?: {
|
|
135
145
|
signal?: AbortSignal;
|
|
136
146
|
getConfirmation?: () => AgentToolConfirmationConfig | undefined;
|
|
147
|
+
getCallbacks?: () => {
|
|
148
|
+
execute: AgentToolExecutor<any, any>;
|
|
149
|
+
confirm: ConfirmationCallback<any>;
|
|
150
|
+
};
|
|
137
151
|
resolveTarget?: (input: unknown) => HTMLElement | undefined;
|
|
138
152
|
}): () => void;
|
|
139
153
|
registerContext(input: AgentContextInput, options?: {
|
|
@@ -169,13 +183,19 @@ export declare class ToolRuntimeImplementation extends EventTarget implements To
|
|
|
169
183
|
on(eventName: "toolexecution", listener: (event: AgentToolExecutionEvent) => void): () => void;
|
|
170
184
|
register<TInput, TResult>(definition: AgentToolDefinition<TInput, TResult>, options: {
|
|
171
185
|
execute: RegisteredAgentTool<TInput, TResult>["execute"];
|
|
186
|
+
confirm?: ConfirmationCallback<TInput>;
|
|
172
187
|
requiresConfirmation?: never;
|
|
173
188
|
}): () => void;
|
|
174
189
|
bindTool<TInput, TResult>(definition: AgentToolDefinition<TInput, TResult>, execute: AgentToolExecutor<TInput, TResult>, options?: {
|
|
175
190
|
signal?: AbortSignal;
|
|
176
191
|
getConfirmation?: () => AgentToolConfirmationConfig | undefined;
|
|
192
|
+
getCallbacks?: () => {
|
|
193
|
+
execute: AgentToolExecutor<any, any>;
|
|
194
|
+
confirm: ConfirmationCallback<any>;
|
|
195
|
+
};
|
|
177
196
|
resolveTarget?: (input: unknown) => HTMLElement | undefined;
|
|
178
197
|
}): () => void;
|
|
198
|
+
usesConfirmationProtocol(tool: RuntimeAgentTool): boolean;
|
|
179
199
|
registerContext(input: AgentContextInput, options?: {
|
|
180
200
|
signal?: AbortSignal;
|
|
181
201
|
}): 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 { pageDecisionSymbol } from "./shared/runtime-execution.js";
|
|
3
4
|
import { PageCommandError } from "./browser/locator.js";
|
|
@@ -235,19 +236,38 @@ export class ToolRuntimeImplementation extends EventTarget {
|
|
|
235
236
|
catch (cause) {
|
|
236
237
|
throw new TypeError(`Tool "${definition.name}" was not registered: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
|
|
237
238
|
}
|
|
238
|
-
|
|
239
|
+
if (options.confirm !== undefined && typeof options.confirm !== "function") {
|
|
240
|
+
throw new TypeError("confirm must be a function.");
|
|
241
|
+
}
|
|
242
|
+
const confirm = options.confirm;
|
|
243
|
+
const callback = (input, { signal }) => execute(input, { signal });
|
|
244
|
+
return this.#bindTool(copied, callback, confirm
|
|
245
|
+
? {
|
|
246
|
+
getCallbacks: () => ({ execute: callback, confirm }),
|
|
247
|
+
}
|
|
248
|
+
: {});
|
|
239
249
|
}
|
|
240
250
|
bindTool(definition, execute, options = {}) {
|
|
241
251
|
assertAgentToolInputSchema(definition.inputSchema, `Tool "${definition.name}" was not registered: inputSchema`);
|
|
242
252
|
return this.#bindTool(definition, execute, options);
|
|
243
253
|
}
|
|
254
|
+
usesConfirmationProtocol(tool) {
|
|
255
|
+
const binding = this.#bindings.get(tool.definition.name);
|
|
256
|
+
return binding?.runtimeTool === tool && binding.definition !== tool.definition;
|
|
257
|
+
}
|
|
244
258
|
#bindTool(definition, execute, options = {}) {
|
|
245
259
|
if (this.#bindings.has(definition.name)) {
|
|
246
260
|
throw new AgentToolError("DUPLICATE_BINDING", `Tool "${definition.name}" already has an active binding.`);
|
|
247
261
|
}
|
|
248
262
|
const lifecycleController = new AbortController();
|
|
263
|
+
const exposedDefinition = options.getCallbacks
|
|
264
|
+
? confirmationDefinition(definition)
|
|
265
|
+
: definition;
|
|
266
|
+
const confirmationHandler = options.getCallbacks
|
|
267
|
+
? createConfirmationHandler(definition, lifecycleController.signal)
|
|
268
|
+
: undefined;
|
|
249
269
|
const runtimeTool = Object.freeze({
|
|
250
|
-
definition,
|
|
270
|
+
definition: exposedDefinition,
|
|
251
271
|
get confirmation() {
|
|
252
272
|
const confirmation = options.getConfirmation?.();
|
|
253
273
|
return confirmation === undefined ? undefined : Object.freeze({ ...confirmation });
|
|
@@ -255,10 +275,16 @@ export class ToolRuntimeImplementation extends EventTarget {
|
|
|
255
275
|
lifecycleSignal: lifecycleController.signal,
|
|
256
276
|
});
|
|
257
277
|
const binding = {
|
|
258
|
-
...(options.resolveTarget
|
|
278
|
+
...(options.resolveTarget
|
|
279
|
+
? {
|
|
280
|
+
resolveTarget: (input) => options.resolveTarget(confirmationHandler ? confirmationHandler.resolveInput(input) : input),
|
|
281
|
+
}
|
|
282
|
+
: {}),
|
|
259
283
|
definition,
|
|
260
284
|
runtimeTool,
|
|
261
|
-
execute
|
|
285
|
+
execute: confirmationHandler
|
|
286
|
+
? (input, context) => confirmationHandler.execute(input, context, options.getCallbacks())
|
|
287
|
+
: execute,
|
|
262
288
|
...(options.getConfirmation ? { getConfirmation: options.getConfirmation } : {}),
|
|
263
289
|
lifecycleController,
|
|
264
290
|
};
|
|
@@ -469,6 +495,15 @@ export class ToolRuntimeImplementation extends EventTarget {
|
|
|
469
495
|
if (binding.runtimeTool !== tool) {
|
|
470
496
|
return Promise.reject(new AgentToolError("CONTRACT_MISMATCH", `Tool "${name}" is registered with a different Runtime Tool.`));
|
|
471
497
|
}
|
|
498
|
+
// Snapshot protocol arguments before waiting in the execution queue.
|
|
499
|
+
if (binding.runtimeTool.definition !== binding.definition) {
|
|
500
|
+
try {
|
|
501
|
+
input = structuredClone(input);
|
|
502
|
+
}
|
|
503
|
+
catch {
|
|
504
|
+
return Promise.reject(new AgentToolError("INVALID_INPUT", "Tool arguments must be structured-cloneable."));
|
|
505
|
+
}
|
|
506
|
+
}
|
|
472
507
|
return this.#enqueue((operationId) => this.#executeApplication(name, input, options, binding, operationId), options.signal);
|
|
473
508
|
}
|
|
474
509
|
try {
|
|
@@ -632,7 +667,7 @@ export class ToolRuntimeImplementation extends EventTarget {
|
|
|
632
667
|
if (this.#bindings.get(name) !== binding) {
|
|
633
668
|
throw new AgentToolError("UNKNOWN_TOOL", `Tool "${name}" is no longer registered for this call.`);
|
|
634
669
|
}
|
|
635
|
-
const errors = validateAgentToolInput(binding.definition.inputSchema, input);
|
|
670
|
+
const errors = validateAgentToolInput(binding.runtimeTool.definition.inputSchema, input);
|
|
636
671
|
if (errors.length) {
|
|
637
672
|
throw new AgentToolError("INVALID_INPUT", errors.join(" "), { errors });
|
|
638
673
|
}
|
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
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 }
|