diff --git a/.changeset/eager-tools-narrow.md b/.changeset/eager-tools-narrow.md new file mode 100644 index 0000000000..fe2e8b7307 --- /dev/null +++ b/.changeset/eager-tools-narrow.md @@ -0,0 +1,5 @@ +--- +'@conciv/extension': patch +--- + +Tools declared through a shared definition object (the pattern that lets a client and a server file agree on one contract) kept their name only as a widened `string`, so they were silently absent from the typed registry client and invisible to the tool-name collision diagnostics. A `toolDefinition()` helper on the UI-free `@conciv/extension/tool` subpath gives those objects an inference site that preserves the literal name, and every shared definition across the bundled extensions now goes through it. A tool's declared `errors` are carried through to the typed client too: `isDefinedError` narrows a call-site failure to the declared code with its `data` type instead of collapsing to `never`. Only a tool that is provably server-bound carries its declared errors alone; a client-bound declaration, and a renderer-only one (which cannot know how its separately compiled runtime twin is bound), both additionally expose the transport codes the forwarding layer can raise. diff --git a/packages/extension/src/define-extension.ts b/packages/extension/src/define-extension.ts index 1da13bf494..d3f07bea04 100644 --- a/packages/extension/src/define-extension.ts +++ b/packages/extension/src/define-extension.ts @@ -1,7 +1,7 @@ import type {Component} from 'solid-js' import type {z} from 'zod' import type {ThemeTokens} from '@conciv/ui-kit-system' -import type {RegisteredTools, ToolBuilder} from './define-tool.js' +import type {RegisteredTools, ToolBinding, ToolBuilder, ToolErrors} from './define-tool.js' import type {AnyAttachmentBuilder} from './define-attachment.js' import type { ClientFactoryResult, @@ -18,7 +18,14 @@ import type { import type {PageVerbMap} from './page-verbs.js' import {useExtensionValue} from './host-context.js' -export type AnyToolBuilder = ToolBuilder, z.ZodType, unknown> +export type AnyToolBuilder = ToolBuilder< + string, + z.ZodObject, + z.ZodType, + ToolErrors, + ToolBinding | undefined, + unknown +> export type ExtensionMeta< Name extends string, diff --git a/packages/extension/src/define-tool.ts b/packages/extension/src/define-tool.ts index 9cbd5730cc..c6fd362dee 100644 --- a/packages/extension/src/define-tool.ts +++ b/packages/extension/src/define-tool.ts @@ -25,12 +25,17 @@ export function isToolError(value: unknown): value is ToolError { return value instanceof Error && 'isToolError' in value && value.isToolError === true } -export type ToolDefinition, Output extends z.ZodType> = { +export type ToolDefinition< + Name extends string, + Schema extends z.ZodObject, + Output extends z.ZodType, + Errors extends ToolErrors = Record, +> = { name: Name description: string inputSchema: Schema outputSchema?: Output - errors?: ToolErrors + errors?: Errors meta?: ToolMeta promptSnippet?: string promptGuidelines?: string[] @@ -38,25 +43,38 @@ export type ToolDefinition, + Output extends z.ZodType, + Errors extends ToolErrors = Record, +>(definition: ToolDefinition): ToolDefinition { + return definition +} + export type ToolBuilder< Name extends string = string, Schema extends z.ZodObject = z.ZodObject, Output extends z.ZodType = z.ZodType, + Errors extends ToolErrors = ToolErrors, + Binding extends ToolBinding | undefined = ToolBinding | undefined, Ctx = unknown, > = Omit & { name: Name inputSchema: Schema outputSchema?: Output - errors?: ToolErrors + errors?: Errors meta?: ToolMeta - binding?: ToolBinding + binding?: Binding __ctx?: Ctx __clientExecute?: (input: unknown) => Promise server: ( execute: (input: z.infer, ctx: HandlerCtx, request: ToolRequest) => Promise | unknown, - ) => ToolBuilder - client: (execute?: (input: z.infer) => Promise | unknown) => ToolBuilder - render: (renderer: ToolRenderer) => ToolBuilder + ) => ToolBuilder + client: ( + execute?: (input: z.infer) => Promise | unknown, + ) => ToolBuilder + render: (renderer: ToolRenderer) => ToolBuilder } type ToolNameOf = Tool extends {name: infer Name extends string} ? (string extends Name ? never : Name) : never @@ -69,9 +87,30 @@ type ToolOutputSchemaOf = Tool extends {outputSchema?: infer Schema} : z.ZodUnknown : z.ZodUnknown -export type RegisteredTool = { +type ToolErrorsOf = Tool extends {errors?: infer Errors} + ? NonNullable extends ToolErrors + ? NonNullable + : Record + : Record + +export type ProjectedToolBinding = ToolBinding | 'unknown' + +type ToolBindingOf = Tool extends {binding?: infer Binding} + ? [Extract] extends [never] + ? 'unknown' + : Extract + : 'unknown' + +export type RegisteredTool< + Schema extends z.ZodType, + Output extends z.ZodType, + Errors extends ToolErrors, + Binding extends ProjectedToolBinding, +> = { inputSchema: Schema outputSchema: Output + errors: Errors + binding: Binding } export type ToolNameProblem = {toolNameProblem: Message} @@ -127,11 +166,18 @@ type ToolTupleProblem = | ToolNamePathProblem> export type RegisteredTools = [ToolTupleProblem] extends [never] - ? {[Tool in Tools[number] as ToolNameOf]: RegisteredTool, ToolOutputSchemaOf>} + ? { + [Tool in Tools[number] as ToolNameOf]: RegisteredTool< + ToolInputSchemaOf, + ToolOutputSchemaOf, + ToolErrorsOf, + ToolBindingOf + > + } : ToolTupleProblem -type ToolState = { - binding?: ToolBinding +type ToolState = { + binding?: Binding execute?: (input: unknown, ctx?: unknown, request?: ToolRequest) => Promise serverRun?: (input: unknown, ctx?: unknown, request?: ToolRequest) => Promise clientExecute?: (input: unknown) => Promise @@ -152,10 +198,17 @@ function assertUnbound(name: string, binding: ToolBinding | undefined): void { if (binding !== undefined) throw new Error(`tool "${name}" already has a ${binding} binding`) } -function toolBuilder, Output extends z.ZodType, Ctx>( - definition: ToolDefinition, - state: ToolState, -): ToolBuilder { +function toolBuilder< + Name extends string, + Schema extends z.ZodObject, + Output extends z.ZodType, + Errors extends ToolErrors, + Binding extends ToolBinding | undefined, + Ctx, +>( + definition: ToolDefinition, + state: ToolState, +): ToolBuilder { return { name: definition.name, description: definition.description, @@ -178,7 +231,7 @@ function toolBuilder, ctx: unknown, request: ToolRequest | undefined) => execute(parsed, ctx as HandlerCtx, request as ToolRequest) - return toolBuilder(definition, { + return toolBuilder(definition, { ...state, binding: 'server', execute: async (raw, ctx, request) => invoke(definition.inputSchema.parse(raw), ctx, request), @@ -187,15 +240,17 @@ function toolBuilder(definition, clientState) - return toolBuilder(definition, { + const clientState: ToolState<'client'> = {...state, binding: 'client'} + if (execute === undefined) { + return toolBuilder(definition, clientState) + } + return toolBuilder(definition, { ...clientState, clientExecute: async (raw) => execute(definition.inputSchema.parse(raw)), }) }, render(renderer) { - return toolBuilder(definition, {...state, render: renderer}) + return toolBuilder(definition, {...state, render: renderer}) }, } } @@ -204,7 +259,10 @@ export function defineTool< const Name extends string, Schema extends z.ZodObject, Output extends z.ZodType, ->(definition: ToolDefinition): ToolBuilder { + Errors extends ToolErrors = Record, +>( + definition: ToolDefinition, +): ToolBuilder { assertToolMeta(definition.name, definition.meta) - return toolBuilder(definition, {}) + return toolBuilder(definition, {}) } diff --git a/packages/extension/src/index.ts b/packages/extension/src/index.ts index 5709897d88..cc6bf407a0 100644 --- a/packages/extension/src/index.ts +++ b/packages/extension/src/index.ts @@ -6,7 +6,7 @@ export type { ExtensionMeta, RegisterExtension, } from './define-extension.js' -export {defineTool, isToolError, toolError} from './define-tool.js' +export {defineTool, isToolError, toolDefinition, toolError} from './define-tool.js' export type { RegisteredTool, RegisteredTools, diff --git a/packages/extension/src/tool-registry.ts b/packages/extension/src/tool-registry.ts index 62783780fd..e6e9144463 100644 --- a/packages/extension/src/tool-registry.ts +++ b/packages/extension/src/tool-registry.ts @@ -1,11 +1,19 @@ import {z} from 'zod' import type {PageErrorCode} from '@conciv/protocol/page-types' import type {ExtensionRegistry} from '@conciv/protocol/config-types' -import {createRouterClient, os, type AnyRouter, type ORPCErrorConstructorMap, type Procedure} from '@orpc/server' +import { + createRouterClient, + os, + type AnyRouter, + type MergedErrorMap, + type ORPCErrorConstructorMap, + type Procedure, +} from '@orpc/server' import type {AnyToolBuilder} from './define-extension.js' import { FORBIDDEN_TOOL_SEGMENTS, isToolError, + type ProjectedToolBinding, type ToolBinding, type ToolErrors, type ToolMeta, @@ -29,11 +37,24 @@ type ToolPathHead = Path extends `${infer Head}.${string}` type ToolPathTail = Path extends `${Head}.${infer Tail}` ? Tail : never +type RegistryErrorMap = Binding extends 'server' + ? Errors + : MergedErrorMap + type ToolProcedure = Tool extends { inputSchema: infer Input extends z.ZodType outputSchema: infer Output extends z.ZodType + errors: infer Errors extends ToolErrors + binding: infer Binding extends ProjectedToolBinding } - ? Procedure, RegistryToolMeta> + ? Procedure< + RegistryCallContext, + RegistryCallContext, + Input, + Output, + RegistryErrorMap, + RegistryToolMeta + > : never type ToolRouterNode = { @@ -72,13 +93,15 @@ export type ToolRouterFor = [RegistryNameProblem] extends [n export type ExtensionToolRouter = ToolRouterFor -export const TOOL_TRANSPORT_ERRORS: ToolErrors = { +export const TOOL_TRANSPORT_ERRORS = { NO_PAGE_CLIENT: {message: 'no widget connected'}, PAGE_TIMEOUT: {message: 'the page did not reply in time'}, UNKNOWN_TOOL: {message: 'the page does not know this tool'}, INVALID_ARGS: {message: 'the page rejected the arguments'}, HANDLER_ERROR: {message: 'the page failed to run this tool'}, -} +} satisfies ToolErrors + +export type ToolTransportErrors = typeof TOOL_TRANSPORT_ERRORS const PAGE_FAILURE_TO_TRANSPORT: Record = { 'no-widget': 'NO_PAGE_CLIENT', diff --git a/packages/extension/test/extension-registry.test-d.ts b/packages/extension/test/extension-registry.test-d.ts index c55ba3b8aa..8688bdaafe 100644 --- a/packages/extension/test/extension-registry.test-d.ts +++ b/packages/extension/test/extension-registry.test-d.ts @@ -7,6 +7,7 @@ import { defineExtension, defineTool, getExtensionApi, + toolDefinition, type AnyToolBuilder, type ExtensionApi, type RegisteredTools, @@ -26,7 +27,50 @@ const doubler = defineTool({ meta: {summary: 'double the number it is given'}, }).client((input) => ({doubled: input.value * 2})) -const demo = defineExtension({name: 'demo', configSchema: cfgSchema, tools: [doubler]}).client(() => ({ +const treblerDef = toolDefinition({ + name: 'demo.trebler', + description: 'triple a number', + inputSchema: z.object({value: z.number()}), + outputSchema: z.object({tripled: z.number()}), + meta: {summary: 'triple the number it is given'}, +}) + +const trebler = defineTool(treblerDef).client((input) => ({tripled: input.value * 3})) + +const locator = defineTool({ + name: 'demo.locator', + description: 'find an element on the page', + inputSchema: z.object({target: z.string()}), + outputSchema: z.object({found: z.boolean()}), + errors: {ELEMENT_NOT_FOUND: {message: 'no element matched the target', data: z.object({target: z.string()})}}, + meta: {summary: 'find an element on the page by selector'}, +}).client(() => ({found: true})) + +const guard = defineTool({ + name: 'demo.guard', + description: 'reject a factor that is too large', + inputSchema: z.object({factor: z.number()}), + outputSchema: z.object({accepted: z.boolean()}), + errors: {FACTOR_TOO_LARGE: {message: 'the factor exceeds the allowed range'}}, + meta: {summary: 'check a factor against the allowed range'}, +}).server(() => ({accepted: true})) + +const pickerDef = toolDefinition({ + name: 'demo.picker', + description: 'let the user pick an element in the page', + inputSchema: z.object({}), + outputSchema: z.object({picked: z.string()}), + errors: {PICK_CANCELLED: {message: 'the user dismissed the picker'}}, + meta: {summary: 'let the user point at an element in the page'}, +}) + +const pickerRenderer = defineTool(pickerDef).render(() => null) + +const demo = defineExtension({ + name: 'demo', + configSchema: cfgSchema, + tools: [doubler, trebler, locator, guard, pickerRenderer], +}).client(() => ({ value: {ratio: 2}, })) @@ -68,6 +112,16 @@ const doublerTwin = defineTool({ meta: {summary: 'another tool that claims the same name'}, }).client((input) => ({twice: input.amount * 2})) +const treblerTwinDef = toolDefinition({ + name: 'demo.trebler', + description: 'triple a number, differently', + inputSchema: z.object({amount: z.number()}), + outputSchema: z.object({thrice: z.number()}), + meta: {summary: 'another shared definition claiming the same name'}, +}) + +const treblerTwin = defineTool(treblerTwinDef).client((input) => ({thrice: input.amount * 3})) + const emptySegment = defineTool({ name: 'page..fill', description: 'a name with an empty segment', @@ -112,10 +166,18 @@ type HostileRegistry = RegisterExtension declare const registry: ToolRegistry -type DoublerError = - typeof client.demo.doubler extends Client - ? Failure - : never +type FailureOf = + Procedure extends Client ? Failure : never + +type DefinedErrorOf = Extract, ORPCError> + +type DoublerError = FailureOf + +type LocatorError = FailureOf + +type GuardError = FailureOf + +type TransportErrorCode = 'NO_PAGE_CLIENT' | 'PAGE_TIMEOUT' | 'UNKNOWN_TOOL' | 'INVALID_ARGS' | 'HANDLER_ERROR' test('config key + value type are derived from the registry (z.input, defaults optional)', () => { expectTypeOf['demo']>().toMatchTypeOf< @@ -139,6 +201,18 @@ test('an extension tool is reachable on the typed client, typed by its own schem expectTypeOf(client.demo.doubler).returns.resolves.toEqualTypeOf<{doubled: number}>() }) +test('a tool declared through a shared definition reaches the client under its literal name', () => { + expectTypeOf(client.demo.trebler).parameter(0).toEqualTypeOf<{value: number}>() + expectTypeOf(client.demo.trebler).returns.resolves.toEqualTypeOf<{tripled: number}>() +}) + +test('a shared definition colliding with another tool resolves to a diagnostic', () => { + expectTypeOf>().toMatchTypeOf>() + expectTypeOf>().toMatchTypeOf< + ToolNameProblem + >() +}) + test('the tool input type is enforced at the call site', () => { // @ts-expect-error the tool's input schema requires a number expectTypeOf(client.demo.doubler).toBeCallableWith({value: 'two'}) @@ -188,20 +262,47 @@ test('a registry with no name collision stays a usable router', () => { expectTypeOf>().toBeObject() }) -test('the derived client declares no errors, so isDefinedError narrows to never on it', () => { - expectTypeOf().toEqualTypeOf() - expectTypeOf>>().toEqualTypeOf() +test('a declared tool error narrows through isDefinedError with its code and its data type', () => { + function narrow(error: LocatorError) { + if (!isDefinedError(error)) return + if (error.code !== 'ELEMENT_NOT_FOUND') return + expectTypeOf(error.data).toEqualTypeOf<{target: string}>() + } + expectTypeOf(narrow).toBeFunction() +}) + +test('a client-bound tool carries its declared error alongside the transport codes', () => { + expectTypeOf['code']>().toEqualTypeOf< + 'ELEMENT_NOT_FOUND' | TransportErrorCode + >() +}) + +test('a client-bound tool that declares nothing still carries the transport codes', () => { + expectTypeOf['code']>().toEqualTypeOf() +}) + +test('an unbound renderer declaration still reports the transport codes its runtime twin can raise', () => { + expectTypeOf['code']>().toEqualTypeOf< + 'PICK_CANCELLED' | TransportErrorCode + >() }) -test('isDefinedError narrows the derived client error to never, not just the union check', () => { - function narrow(error: DoublerError) { - if (isDefinedError(error)) { - expectTypeOf(error).toEqualTypeOf() - } +test('a server-bound tool carries its declared error and no transport code', () => { + expectTypeOf['code']>().toEqualTypeOf<'FACTOR_TOO_LARGE'>() +}) + +test('an undeclared error stays outside the defined-error union', () => { + function narrow(error: GuardError) { + if (isDefinedError(error)) return + expectTypeOf(error).toEqualTypeOf() } expectTypeOf(narrow).toBeFunction() }) +test('the declared failure union still admits a plain thrown Error', () => { + expectTypeOf().toMatchTypeOf() +}) + test('register only accepts the context its tool declared', () => { registry.register(scaler, {context: {factor: 2}}) // @ts-expect-error the tool's handler declares ctx: {factor: number} diff --git a/packages/extensions/recorder/src/tool/def.ts b/packages/extensions/recorder/src/tool/def.ts index d5920f8e01..4072afdf84 100644 --- a/packages/extensions/recorder/src/tool/def.ts +++ b/packages/extensions/recorder/src/tool/def.ts @@ -1,3 +1,4 @@ +import {toolDefinition} from '@conciv/extension/tool' import {z} from 'zod' export const StartInput = z.object({}) @@ -9,23 +10,23 @@ export const PullInput = z.object({ keyframes: z.number().int().min(0).max(8).default(3), }) -export const startToolDef = { +export const startToolDef = toolDefinition({ name: 'recording_start', description: "Start a marked recording of the user's app page. Returns a captureId. Use before performing page actions you want to review, then call recording_stop.", inputSchema: StartInput, -} +}) -export const stopToolDef = { +export const stopToolDef = toolDefinition({ name: 'recording_stop', description: 'Stop a marked recording and get back what happened: a semantic action log (clicks, inputs, navigations, errors) plus keyframe screenshots.', inputSchema: StopInput, -} +}) -export const pullToolDef = { +export const pullToolDef = toolDefinition({ name: 'recording_pull', description: 'Pull the last N seconds of the always-on page recording (flight recorder). Returns a semantic action log plus keyframe screenshots. Use when the user refers to something that just happened in their app, or after an error.', inputSchema: PullInput, -} +}) diff --git a/packages/extensions/tanstack/src/tool/def.ts b/packages/extensions/tanstack/src/tool/def.ts index 1b11a370c0..a515af813b 100644 --- a/packages/extensions/tanstack/src/tool/def.ts +++ b/packages/extensions/tanstack/src/tool/def.ts @@ -1,106 +1,107 @@ +import {toolDefinition} from '@conciv/extension/tool' import {z} from 'zod' export const RouterStateInput = z.object({}) export const RouteTreeInput = z.object({}) -export const routerStateDef = { +export const routerStateDef = toolDefinition({ name: 'tanstack_router_state', description: "Read the running app's current TanStack Router state: matched routes, params, search, loader status. Use it to see what the user is looking at before acting.", inputSchema: RouterStateInput, -} +}) -export const routeTreeDef = { +export const routeTreeDef = toolDefinition({ name: 'tanstack_route_tree', description: "Read the running app's TanStack Router route tree: the nested route definitions, their paths, kinds, and which routes declare a loader. Use it to understand the app's routing structure.", inputSchema: RouteTreeInput, -} +}) export const LoaderDataInput = z.object({routeId: z.string().optional()}) -export const loaderDataDef = { +export const loaderDataDef = toolDefinition({ name: 'tanstack_loader_data', description: 'Read the dehydrated loader data for the current (or a named) TanStack route - the server/loader-fetched data the route is rendering. Use it to see the data behind what the user sees.', inputSchema: LoaderDataInput, -} +}) export const QueryCacheInput = z.object({}) -export const queryCacheDef = { +export const queryCacheDef = toolDefinition({ name: 'tanstack_query_cache', description: "Read the running app's TanStack Query cache: each query's key, status (fresh/stale/fetching/error), observer count, and dehydrated data. Use it to see what data the app has fetched and cached.", inputSchema: QueryCacheInput, -} +}) export const NavigateInput = z.object({to: z.string(), replace: z.boolean().optional()}) -export const navigateDef = { +export const navigateDef = toolDefinition({ name: 'tanstack_navigate', description: "Navigate the running app's TanStack Router to a path. This changes what the user is currently viewing but destroys nothing - no data is deleted and you can navigate back.", inputSchema: NavigateInput, -} +}) export const RouterInvalidateInput = z.object({}) -export const routerInvalidateDef = { +export const routerInvalidateDef = toolDefinition({ name: 'tanstack_invalidate', description: 'Invalidate the TanStack Router (re-run active loaders).', inputSchema: RouterInvalidateInput, -} +}) export const BackInput = z.object({}) -export const backDef = { +export const backDef = toolDefinition({ name: 'tanstack_back', description: "Navigate the running app's TanStack Router history back one entry. Navigational.", inputSchema: BackInput, -} +}) export const QueryInvalidateInput = z.object({key: z.string()}) -export const queryInvalidateDef = { +export const queryInvalidateDef = toolDefinition({ name: 'tanstack_query_invalidate', description: 'Invalidate a specific TanStack Query by its serialized key (JSON of the queryKey). Unknown keys are a no-op.', inputSchema: QueryInvalidateInput, -} +}) export const QueryRefetchInput = z.object({key: z.string()}) -export const queryRefetchDef = { +export const queryRefetchDef = toolDefinition({ name: 'tanstack_query_refetch', description: 'Refetch a specific TanStack Query by its serialized key.', inputSchema: QueryRefetchInput, -} +}) export const BuildErrorsInput = z.object({}) -export const buildErrorsDef = { +export const buildErrorsDef = toolDefinition({ name: 'tanstack_build_errors', description: "Read recent build/transform errors from the running TanStack dev server (compile failures, bad imports). Use it when the app is broken or a change didn't take effect.", inputSchema: BuildErrorsInput, -} +}) export const RouteManifestInput = z.object({}) -export const routeManifestDef = { +export const routeManifestDef = toolDefinition({ name: 'tanstack_route_manifest', description: "Read the app's route manifest from routeTree.gen (all defined routes, paths, dynamic segments). Use it to see what routes exist, not just the matched ones.", inputSchema: RouteManifestInput, -} +}) export const ServerFnTraceInput = z.object({count: z.number().int().positive().max(100).optional()}) -export const serverFnTraceDef = { +export const serverFnTraceDef = toolDefinition({ name: 'tanstack_server_fn_trace', description: 'Read recent TanStack server-function calls: which server fn ran (file + export), duration, and status. Use it to see server-side data fetching triggered by the app.', inputSchema: ServerFnTraceInput, -} +}) diff --git a/packages/extensions/test-runner/src/tool/def.ts b/packages/extensions/test-runner/src/tool/def.ts index 3347a97d20..ae20c0b7e3 100644 --- a/packages/extensions/test-runner/src/tool/def.ts +++ b/packages/extensions/test-runner/src/tool/def.ts @@ -1,10 +1,11 @@ +import {toolDefinition} from '@conciv/extension/tool' import {z} from 'zod' export const TestInput = z.object({action: z.enum(['list', 'run', 'status']), pattern: z.string().optional()}) -export const testToolDef = { +export const testToolDef = toolDefinition({ name: 'test_runner', description: 'Drive the live test runner: list tests, run a pattern, or check status.', inputSchema: TestInput, streamTitle: 'Running tests', -} +}) diff --git a/packages/extensions/whiteboard/src/tool/anchor/def.ts b/packages/extensions/whiteboard/src/tool/anchor/def.ts index ec9902128d..d0cc74df1f 100644 --- a/packages/extensions/whiteboard/src/tool/anchor/def.ts +++ b/packages/extensions/whiteboard/src/tool/anchor/def.ts @@ -1,10 +1,11 @@ +import {toolDefinition} from '@conciv/extension/tool' import {z} from 'zod' export const AnchorResolveInput = z.object({cid: z.string()}) -export const anchorResolveDef = { +export const anchorResolveDef = toolDefinition({ name: 'anchor.resolve', description: 'Check whether a source-linked comment still points at its element (fresh/moved/drifted).', inputSchema: AnchorResolveInput, promptSnippet: 'Use anchor.resolve to see if a comment has drifted from the code it was attached to.', -} +}) diff --git a/packages/extensions/whiteboard/src/tool/canvas/def.ts b/packages/extensions/whiteboard/src/tool/canvas/def.ts index 41b66b9e56..11372656f0 100644 --- a/packages/extensions/whiteboard/src/tool/canvas/def.ts +++ b/packages/extensions/whiteboard/src/tool/canvas/def.ts @@ -1,3 +1,4 @@ +import {toolDefinition} from '@conciv/extension/tool' import {z} from 'zod' const skeleton = z @@ -32,16 +33,16 @@ export const CanvasCommitInput = z.object({}) export const CanvasDiscardInput = z.object({}) export const CanvasPreviewInput = z.object({}) -export const canvasReadDef = { +export const canvasReadDef = toolDefinition({ name: 'canvas.read', description: 'List canvas elements. scope "live" (default) reads the published canvas; scope "draft" reads the hidden work-in-progress draft.', inputSchema: CanvasReadInput, promptSnippet: 'Use canvas.read to see what is already drawn before adding more; pass scope "draft" to inspect the draft.', -} +}) -export const canvasSvgDef = { +export const canvasSvgDef = toolDefinition({ name: 'canvas.svg', description: 'Draw by writing SVG markup (paths, shapes, text, fills). Converted in the browser into editable Excalidraw elements. Drawings land in the hidden draft; commit publishes them.', @@ -49,83 +50,83 @@ export const canvasSvgDef = { streamTitle: 'Drawing on the canvas', promptSnippet: 'Use canvas.svg for anything organic or illustrated: write SVG paths with layered fills, then iterate with canvas.preview before canvas.commit.', -} +}) -export const canvasDrawDef = { +export const canvasDrawDef = toolDefinition({ name: 'canvas.draw', description: 'Add Excalidraw element skeletons (rectangle, ellipse, diamond, text, arrow, line) to the hidden draft; commit publishes them.', inputSchema: CanvasDrawInput, streamTitle: 'Drawing on the canvas', promptSnippet: 'Use canvas.draw to sketch shapes and text for the user; pass an array of element skeletons.', -} +}) -export const canvasDiagramDef = { +export const canvasDiagramDef = toolDefinition({ name: 'canvas.diagram', description: 'Render a Mermaid diagram (flowchart, sequence, class, ...) into the hidden draft; commit publishes it.', inputSchema: CanvasDiagramInput, streamTitle: 'Drawing a diagram', promptSnippet: 'Use canvas.diagram with Mermaid source to render a structured diagram on the canvas.', -} +}) -export const canvasConnectDef = { +export const canvasConnectDef = toolDefinition({ name: 'canvas.connect', description: 'Draw a binding arrow from one element to another by elementId.', inputSchema: CanvasConnectInput, promptSnippet: 'Use canvas.connect to link two existing elements with an arrow.', -} +}) -export const canvasUpdateDef = { +export const canvasUpdateDef = toolDefinition({ name: 'canvas.update', description: 'Patch fields of an existing canvas element by elementId.', inputSchema: CanvasUpdateInput, promptSnippet: 'Use canvas.update to change an element you previously drew.', -} +}) -export const canvasDeleteDef = { +export const canvasDeleteDef = toolDefinition({ name: 'canvas.delete', description: 'Remove an element from the canvas by elementId.', inputSchema: CanvasDeleteInput, approval: 'ask', promptSnippet: 'Use canvas.delete to remove an element. Destructive; the user is asked to confirm.', -} as const +}) -export const canvasClearDef = { +export const canvasClearDef = toolDefinition({ name: 'canvas.clear', description: 'Remove every element from the canvas.', inputSchema: CanvasClearInput, approval: 'ask', promptSnippet: 'Use canvas.clear to wipe the canvas. Destructive; the user is asked to confirm.', -} as const +}) -export const canvasExportDef = { +export const canvasExportDef = toolDefinition({ name: 'canvas.export', description: 'Export the canvas: json returns elements; png returns a real Excalidraw rendering (requires an open canvas tab).', inputSchema: CanvasExportInput, promptSnippet: 'Use canvas.export with format png and scope draft for a ground-truth render before canvas.commit.', -} +}) -export const canvasCommitDef = { +export const canvasCommitDef = toolDefinition({ name: 'canvas.commit', description: 'Publish the hidden draft to the shared canvas. The agent cursor performs the drawing for the user.', inputSchema: CanvasCommitInput, streamTitle: 'Publishing the drawing', promptSnippet: 'Always finish a drawing with canvas.commit; until then the user sees nothing.', -} +}) -export const canvasDiscardDef = { +export const canvasDiscardDef = toolDefinition({ name: 'canvas.discard', description: 'Throw away the hidden draft without publishing anything.', inputSchema: CanvasDiscardInput, promptSnippet: 'Use canvas.discard to abandon a draft and start over.', -} +}) -export const canvasPreviewDef = { +export const canvasPreviewDef = toolDefinition({ name: 'canvas.preview', description: 'Fast server-side PNG of the current hidden draft (approximate: plain shapes, no hand-drawn strokes). Use between refinements; canvas.export png is the ground truth.', inputSchema: CanvasPreviewInput, streamTitle: 'Checking the draft', promptSnippet: 'After drawing into the draft, call canvas.preview, critique the image, refine, repeat.', -} +}) diff --git a/packages/extensions/whiteboard/src/tool/comment/def.ts b/packages/extensions/whiteboard/src/tool/comment/def.ts index bd0d4dddf8..11e08f3188 100644 --- a/packages/extensions/whiteboard/src/tool/comment/def.ts +++ b/packages/extensions/whiteboard/src/tool/comment/def.ts @@ -1,3 +1,4 @@ +import {toolDefinition} from '@conciv/extension/tool' import {z} from 'zod' const authorKind = z.enum(['human', 'ai']) @@ -35,63 +36,63 @@ export const CommentMoveInput = z.object({ }) export const PinSetStateInput = z.object({cid: z.string(), pinState: z.enum(['locked', 'offset'])}) -export const commentCreateDef = { +export const commentCreateDef = toolDefinition({ name: 'comment.create', description: 'Pin a comment to the canvas, optionally anchored to a source element.', inputSchema: CommentCreateInput, streamTitle: 'Leaving a comment', promptSnippet: 'Use comment.create to leave a pinned note on the canvas for the user to see. x/y are scene coordinates in canvas space (use the x/y of an element from canvas.read to pin near it).', -} +}) -export const commentReplyDef = { +export const commentReplyDef = toolDefinition({ name: 'comment.reply', description: 'Add a threaded reply to an existing comment.', inputSchema: CommentReplyInput, promptSnippet: 'Use comment.reply to answer a comment; the reply joins the same thread.', -} +}) -export const commentReadDef = { +export const commentReadDef = toolDefinition({ name: 'comment.read', description: 'Read a comment and its full thread of replies.', inputSchema: CommentReadInput, promptSnippet: 'Use comment.read to see a comment and everything in its thread.', -} +}) -export const commentListDef = { +export const commentListDef = toolDefinition({ name: 'comment.list', description: 'List top-level comments, scoped to the session or all, optionally by file or status.', inputSchema: CommentListInput, promptSnippet: 'Use comment.list to find existing comments before adding more; scope "session" for the current one.', -} +}) -export const commentResolveDef = { +export const commentResolveDef = toolDefinition({ name: 'comment.resolve', description: 'Mark a comment resolved.', inputSchema: CommentResolveInput, approval: 'ask', promptSnippet: 'Use comment.resolve once a comment has been addressed.', -} as const +}) -export const commentDeleteDef = { +export const commentDeleteDef = toolDefinition({ name: 'comment.delete', description: 'Remove a comment; deleting a thread root removes the whole thread and its canvas pin.', inputSchema: CommentDeleteInput, approval: 'ask', promptSnippet: 'Use comment.delete to remove a comment the user no longer wants; deleting the first comment removes the whole thread.', -} as const +}) -export const commentMoveDef = { +export const commentMoveDef = toolDefinition({ name: 'comment.move', description: 'Move a comment pin to new canvas coordinates.', inputSchema: CommentMoveInput, promptSnippet: 'Use comment.move to reposition a comment pin on the canvas; x/y are scene coordinates.', -} +}) -export const pinSetStateDef = { +export const pinSetStateDef = toolDefinition({ name: 'pin.setState', description: 'Set a pin to locked (tracks its element) or offset (floats at a custom position).', inputSchema: PinSetStateInput, promptSnippet: 'Use pin.setState to lock a pin to its element or let it float at an offset.', -} +}) diff --git a/packages/extensions/whiteboard/src/tool/element/def.ts b/packages/extensions/whiteboard/src/tool/element/def.ts index c7e9e0fc7a..3fe798fddb 100644 --- a/packages/extensions/whiteboard/src/tool/element/def.ts +++ b/packages/extensions/whiteboard/src/tool/element/def.ts @@ -1,10 +1,11 @@ +import {toolDefinition} from '@conciv/extension/tool' import {z} from 'zod' export const ElementReferenceInput = z.object({file: z.string(), component: z.string()}) -export const elementReferenceDef = { +export const elementReferenceDef = toolDefinition({ name: 'element.reference', description: 'Locate a React component (or JSX tag) by name in a file to target it without a pick.', inputSchema: ElementReferenceInput, promptSnippet: 'Use element.reference to target a component by name (file + component) for comment.create.', -} +})