@nexface/tools 0.1.21-alpha.4 → 0.1.21-alpha.6

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.
@@ -1,4 +1,6 @@
1
1
  import type { AgentToolDefinition } from "./types.js";
2
+ export declare function isConfirmationRequest(value: unknown): value is object;
3
+ export declare function confirmationInstructions(field: "confirmation" | "nxf_confirmation"): string;
2
4
  export declare function confirmationDefinition(definition: AgentToolDefinition<any, any>): AgentToolDefinition<{
3
5
  input?: Record<string, unknown>;
4
6
  confirmation?: {
@@ -2,7 +2,13 @@ import { defineAgentTool } from "./definition.js";
2
2
  import { AgentToolError } from "./shared/errors.js";
3
3
  import { validateAgentToolInput } from "./shared/schema.js";
4
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.";
5
+ const confirmationRequests = new WeakSet();
6
+ export function isConfirmationRequest(value) {
7
+ return typeof value === "object" && value !== null && confirmationRequests.has(value);
8
+ }
9
+ export function confirmationInstructions(field) {
10
+ return `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 { ${field}: { requestId, approved } }: true to approve, false to reject. Stop after rejection. If execution has an unknown outcome, verify its status before retrying.`;
11
+ }
6
12
  export function confirmationDefinition(definition) {
7
13
  const exposed = defineAgentTool({
8
14
  ...definition,
@@ -56,12 +62,14 @@ export function createConfirmationHandler(definition, lifecycle) {
56
62
  const outcome = await requests.start(wire.input, context, callbacks);
57
63
  if (outcome.kind === "completed")
58
64
  return outcome.result;
59
- return {
65
+ const request = {
60
66
  status: "confirmation_required",
61
67
  requestId: outcome.requestId,
62
68
  message: outcome.message,
63
- nextAction: instructions,
69
+ nextAction: confirmationInstructions("confirmation"),
64
70
  };
71
+ confirmationRequests.add(request);
72
+ return request;
65
73
  },
66
74
  resolveInput(wire) {
67
75
  if (!wire || typeof wire !== "object")
@@ -15,7 +15,6 @@ const reservedContextNames = new Set([
15
15
  ]);
16
16
  const reservedToolNames = new Set([
17
17
  ...reservedContextNames,
18
- "nxf_showToolResults",
19
18
  "nxf_loadSkill",
20
19
  "nxf_beginOperation",
21
20
  "nxf_endOperation",
package/dist/react.d.ts CHANGED
@@ -22,13 +22,7 @@ export interface AgentToolPageConfirmationConfig {
22
22
  title?: string;
23
23
  description?: string;
24
24
  }
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> {
25
+ export interface UseAgentToolDefaultOptions<TInput = unknown> {
32
26
  confirm?: (context: {
33
27
  input: TInput;
34
28
  signal: AbortSignal;
@@ -37,17 +31,6 @@ export interface UseAgentToolDefaultOptions<TInput = unknown, TResult = unknown>
37
31
  } | Promise<boolean | {
38
32
  message: string;
39
33
  }>;
40
- /**
41
- * @experimental
42
- * @warning Experimental API. Its signature and behavior may change.
43
- * @remarks Renders a successful result when referenced in the final chat reply. JSON-compatible results retain their types; void becomes null and other results are unknown.
44
- * @beta
45
- */
46
- _render?: (context: {
47
- input: TInput;
48
- status: "running" | "success" | "error" | "cancelled";
49
- result?: ToolRenderResult<TResult>;
50
- }) => ReactNode;
51
34
  /**
52
35
  * @experimental Enables human-in-the-loop Chat confirmation.
53
36
  * @beta
@@ -58,7 +41,7 @@ export interface UseAgentToolDefaultOptions<TInput = unknown, TResult = unknown>
58
41
  * @experimental Enables human-in-the-loop Page confirmation.
59
42
  * @beta
60
43
  */
61
- export interface UseAgentToolPageConfirmationOptions<TInput = unknown, TResult = unknown> extends Omit<UseAgentToolDefaultOptions<TInput, TResult>, "requiresConfirmation"> {
44
+ export interface UseAgentToolPageConfirmationOptions {
62
45
  confirm?: never;
63
46
  requiresConfirmation: AgentToolPageConfirmationConfig;
64
47
  }
@@ -79,8 +62,8 @@ export declare function getAgentToolBindingInternals(binding: AgentToolBinding):
79
62
  * @experimental The Page confirmation overload is experimental.
80
63
  * @beta
81
64
  */
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>;
65
+ export declare function useAgentTool<TInput, TResult, TElement extends HTMLElement = HTMLElement>(definition: AgentToolDefinition<TInput, TResult>, execute: AgentToolExecutor<TInput, TResult>, options: UseAgentToolPageConfirmationOptions): 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>;
84
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;
85
68
  export declare function ToolsProvider({ children, toolRuntime, webMcp, }: {
86
69
  children: ReactNode;
package/dist/react.js CHANGED
@@ -55,21 +55,6 @@ 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(() => {
60
- if (!options._render)
61
- return undefined;
62
- return {
63
- definition,
64
- ...(confirmationProtocol ? { confirmationProtocol: true } : {}),
65
- render: options._render,
66
- };
67
- }, [definition, options._render, confirmationProtocol]);
68
- const presentationRef = useRef(presentation);
69
- useLayoutEffect(() => {
70
- presentationRef.current = presentation;
71
- runtime.notifyToolPresentationChange();
72
- }, [runtime, presentation]);
73
58
  if (confirmation !== undefined &&
74
59
  (!confirmation ||
75
60
  typeof confirmation !== "object" ||
@@ -97,7 +82,6 @@ function useAgentBinding(definition, execute, options) {
97
82
  runtime.bindTool(definition, (input, context) => executeRef.current(input, context), {
98
83
  signal: controller.signal,
99
84
  getConfirmation: () => confirmationRef.current,
100
- getPresentation: () => presentationRef.current,
101
85
  ...(mode === "callback"
102
86
  ? {
103
87
  getCallbacks: () => ({
package/dist/runtime.d.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  import type { ConfirmationCallback } from "./confirmation.js";
2
- import { type ToolPresentation } from "./shared/tool-presentation.js";
3
2
  import { type InternalExecutionOptions } from "./shared/runtime-execution.js";
4
3
  import type { PageActionFeedback } from "./browser/feedback.js";
5
4
  import { type TaskProgress } from "./shared/runtime-controller.js";
@@ -126,7 +125,6 @@ export declare class AgentContextError extends Error {
126
125
  constructor(code: AgentContextErrorCode, message: string);
127
126
  }
128
127
  export interface InternalToolRuntime extends ToolRuntime, EventTarget {
129
- notifyToolPresentationChange(): void;
130
128
  usesConfirmationProtocol(tool: RuntimeAgentTool): boolean;
131
129
  beginInternalOperation(options?: {
132
130
  signal?: AbortSignal;
@@ -146,7 +144,6 @@ export interface InternalToolRuntime extends ToolRuntime, EventTarget {
146
144
  bindTool<TInput, TResult>(definition: AgentToolDefinition<TInput, TResult>, execute: AgentToolExecutor<TInput, TResult>, options?: {
147
145
  signal?: AbortSignal;
148
146
  getConfirmation?: () => AgentToolConfirmationConfig | undefined;
149
- getPresentation?: () => ToolPresentation | undefined;
150
147
  getCallbacks?: () => {
151
148
  execute: AgentToolExecutor<any, any>;
152
149
  confirm: ConfirmationCallback<any>;
@@ -182,7 +179,6 @@ export declare class ToolRuntimeImplementation extends EventTarget implements To
182
179
  requestOperationCancel(id: string): void;
183
180
  setPageActionFeedback(listener: (event: AgentToolExecutionEvent, feedback: PageActionFeedback, signal?: AbortSignal) => void | Promise<void>): () => void;
184
181
  constructor(options?: ToolRuntimeOptions);
185
- notifyToolPresentationChange(): void;
186
182
  on(eventName: "toolchange", listener: (event: ToolRuntimeToolChangeEvent) => void): () => void;
187
183
  on(eventName: "toolexecution", listener: (event: AgentToolExecutionEvent) => void): () => void;
188
184
  register<TInput, TResult>(definition: AgentToolDefinition<TInput, TResult>, options: {
@@ -193,7 +189,6 @@ export declare class ToolRuntimeImplementation extends EventTarget implements To
193
189
  bindTool<TInput, TResult>(definition: AgentToolDefinition<TInput, TResult>, execute: AgentToolExecutor<TInput, TResult>, options?: {
194
190
  signal?: AbortSignal;
195
191
  getConfirmation?: () => AgentToolConfirmationConfig | undefined;
196
- getPresentation?: () => ToolPresentation | undefined;
197
192
  getCallbacks?: () => {
198
193
  execute: AgentToolExecutor<any, any>;
199
194
  confirm: ConfirmationCallback<any>;
package/dist/runtime.js CHANGED
@@ -1,6 +1,5 @@
1
1
  import { confirmationDefinition, createConfirmationHandler } from "./confirmation-protocol.js";
2
2
  import { searchNavigationTools, searchToolDefinition } from "./tool-search.js";
3
- import { toolPresentationSymbol, } from "./shared/tool-presentation.js";
4
3
  import { pageDecisionSymbol } from "./shared/runtime-execution.js";
5
4
  import { PageCommandError } from "./browser/locator.js";
6
5
  import { measurePagePhase } from "./browser/diagnostics.js";
@@ -205,21 +204,6 @@ export class ToolRuntimeImplementation extends EventTarget {
205
204
  getRegisteredTools: () => this.getRegisteredTools(),
206
205
  });
207
206
  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"));
223
207
  }
224
208
  on(eventName, listener) {
225
209
  const handleEvent = (event) => {
@@ -291,7 +275,6 @@ export class ToolRuntimeImplementation extends EventTarget {
291
275
  lifecycleSignal: lifecycleController.signal,
292
276
  });
293
277
  const binding = {
294
- ...(options.getPresentation ? { getPresentation: options.getPresentation } : {}),
295
278
  ...(options.resolveTarget
296
279
  ? {
297
280
  resolveTarget: (input) => options.resolveTarget(confirmationHandler ? confirmationHandler.resolveInput(input) : input),
package/dist/webmcp.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { confirmationInstructions, isConfirmationRequest } from "./confirmation-protocol.js";
2
+ import { AgentToolError } from "./shared/errors.js";
1
3
  function getWebMcpModelContext() {
2
4
  if (typeof document === "undefined")
3
5
  return undefined;
@@ -78,6 +80,13 @@ export function connectToolRuntimeToWebMcp(runtime) {
78
80
  queueMicrotask(() => disposeUnusedConnection(runtime, current));
79
81
  };
80
82
  }
83
+ function evaluationConfirmationRequired() {
84
+ return {
85
+ isError: true,
86
+ _meta: { "x-nexface-eval": "host-confirmation-required" },
87
+ content: [{ type: "text", text: "Nexface evaluation requires user confirmation." }],
88
+ };
89
+ }
81
90
  function createConnection(runtime, modelContext) {
82
91
  const registrations = new Map();
83
92
  let disposed = false;
@@ -86,7 +95,12 @@ function createConnection(runtime, modelContext) {
86
95
  const begin = {
87
96
  name: "nxf_beginOperation",
88
97
  description: "Begin a continuous page operation before using page tools. Call nxf_endOperation with the returned operationId when all page work is done, before your final response. Repeated begin returns the same active operation. Omitting begin shows feedback only while each tool executes.",
89
- inputSchema: { type: "object", properties: {}, additionalProperties: false },
98
+ inputSchema: {
99
+ "x-nexface": { version: 2, control: true },
100
+ type: "object",
101
+ properties: {},
102
+ additionalProperties: false,
103
+ },
90
104
  execute: async (input, options = {}) => {
91
105
  options.signal?.throwIfAborted();
92
106
  controls.signal.throwIfAborted();
@@ -116,6 +130,7 @@ function createConnection(runtime, modelContext) {
116
130
  description: "End the page operation identified by operationId after all page work. Waits for its admitted tools to settle. Does not stop an external agent or undo changes.",
117
131
  inputSchema: {
118
132
  type: "object",
133
+ "x-nexface": { version: 2, control: true },
119
134
  properties: { operationId: { type: "string" } },
120
135
  required: ["operationId"],
121
136
  additionalProperties: false,
@@ -163,47 +178,100 @@ function createConnection(runtime, modelContext) {
163
178
  registrations.set(definition.name, registration);
164
179
  let result;
165
180
  try {
181
+ const business = confirmed
182
+ ? definition.inputSchema.properties.input
183
+ : definition.inputSchema;
184
+ for (const key of ["nxf_progressLabel", "nxf_confirmation"]) {
185
+ if (Object.hasOwn(business.properties ?? {}, key))
186
+ throw new TypeError(`WebMCP reserves the top-level property "${key}".`);
187
+ }
188
+ const { enum: allowedInputs, ...businessSchema } = business;
189
+ const businessValues = allowedInputs?.filter((value) => !!value && typeof value === "object" && !Array.isArray(value));
190
+ const enumConstraint = businessValues
191
+ ? {
192
+ anyOf: businessValues.length
193
+ ? businessValues.map((value) => ({
194
+ properties: {
195
+ ...Object.fromEntries(Object.entries(value).map(([key, item]) => [key, { const: item }])),
196
+ nxf_progressLabel: { type: "string" },
197
+ },
198
+ required: Object.keys(value),
199
+ additionalProperties: false,
200
+ }))
201
+ : [false],
202
+ }
203
+ : {};
204
+ const properties = {
205
+ ...business.properties,
206
+ nxf_progressLabel: {
207
+ type: "string",
208
+ description: "Briefly describe the action in the user's language.",
209
+ },
210
+ };
211
+ const metadata = { version: 2, effect: definition.effect ?? "action" };
166
212
  result = modelContext.registerTool({
213
+ annotations: { readOnlyHint: definition.effect === "read" },
167
214
  name: definition.name,
168
215
  description: definition.description,
169
216
  inputSchema: {
170
- type: "object",
171
- properties: {
172
- ...(confirmed
173
- ? definition.inputSchema.properties
174
- : {
175
- input: definition.inputSchema,
176
- }),
177
- progressLabel: {
178
- type: "string",
179
- description: "Briefly describe this tool action in the user’s language. Do not expose internal identifiers or claim success before completion.",
180
- },
181
- },
182
- ...(confirmed ? {} : { required: ["input"] }),
183
- additionalProperties: false,
217
+ ...businessSchema,
218
+ "x-nexface": metadata,
219
+ properties: confirmed
220
+ ? {
221
+ ...properties,
222
+ nxf_confirmation: {
223
+ ...definition.inputSchema.properties.confirmation,
224
+ description: "After the user answers, send only this field.",
225
+ },
226
+ }
227
+ : properties,
228
+ ...(confirmed
229
+ ? {
230
+ required: [],
231
+ oneOf: [
232
+ {
233
+ ...enumConstraint,
234
+ required: business.required ?? [],
235
+ not: { required: ["nxf_confirmation"] },
236
+ },
237
+ { required: ["nxf_confirmation"], maxProperties: 1 },
238
+ ],
239
+ }
240
+ : { ...enumConstraint, not: { required: ["nxf_confirmation"] } }),
184
241
  },
185
242
  execute: async (parameters, options = {}) => {
243
+ // Native WebMCP invokes the current registration, which can change after discovery.
244
+ const evaluation = globalThis[Symbol.for("@nexface/evals/phase")];
245
+ if (evaluation === "forbidden")
246
+ throw new Error("Unexpected tool origin.");
247
+ if (evaluation === "navigate" && definition.effect !== "navigate")
248
+ throw new Error("Expected a navigation tool.");
249
+ if (evaluation &&
250
+ (tool.confirmation ||
251
+ (confirmed && Object.hasOwn(parameters ?? {}, "nxf_confirmation"))))
252
+ return evaluationConfirmationRequired();
253
+ if (evaluation === "read" && definition.effect !== "read")
254
+ throw new Error("Nexface evaluation requires a read-only tool.");
255
+ if (!parameters || typeof parameters !== "object" || Array.isArray(parameters))
256
+ throw new TypeError("WebMCP arguments must be an object.");
186
257
  const args = parameters;
187
- if (!args ||
188
- typeof args !== "object" ||
189
- Array.isArray(args) ||
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")) ||
195
- (args.progressLabel !== undefined && typeof args.progressLabel !== "string")) {
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 }.");
199
- }
200
- const { progressLabel, ...payload } = args;
201
- return runtime.execute(tool, confirmed ? payload : args.input, {
258
+ const { nxf_progressLabel: label, nxf_confirmation: answer, ...input } = args;
259
+ const hasAnswer = Object.hasOwn(args, "nxf_confirmation");
260
+ if (hasAnswer && (!confirmed || Object.keys(args).length !== 1))
261
+ throw new AgentToolError("INVALID_INPUT", "Send nxf_confirmation alone to a confirmation tool.");
262
+ if (label !== undefined && typeof label !== "string")
263
+ throw new TypeError("nxf_progressLabel must be a string.");
264
+ const payload = hasAnswer ? { confirmation: answer } : confirmed ? { input } : input;
265
+ const result = await runtime.execute(tool, payload, {
202
266
  ...(options.signal ? { signal: options.signal } : {}),
203
- ...(typeof args.progressLabel === "string"
204
- ? { progressLabel: args.progressLabel }
205
- : {}),
267
+ ...(typeof label === "string" ? { progressLabel: label } : {}),
206
268
  });
269
+ if (confirmed && isConfirmationRequest(result)) {
270
+ if (evaluation)
271
+ return evaluationConfirmationRequired();
272
+ return { ...result, nextAction: confirmationInstructions("nxf_confirmation") };
273
+ }
274
+ return result;
207
275
  },
208
276
  }, { signal: controller.signal });
209
277
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nexface/tools",
3
- "version": "0.1.21-alpha.4",
3
+ "version": "0.1.21-alpha.6",
4
4
  "type": "module",
5
5
  "types": "./dist/index.d.ts",
6
6
  "exports": {
@@ -1,17 +0,0 @@
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;
@@ -1,5 +0,0 @@
1
- // Generated from shared/tool-presentation.ts. Do not edit manually.
2
- export const toolPresentationSymbol = Symbol.for("@nexface/tools/tool-presentation");
3
- export function getToolPresentationController(runtime) {
4
- return runtime[toolPresentationSymbol];
5
- }