Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/eager-tools-narrow.md
Original file line number Diff line number Diff line change
@@ -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.
11 changes: 9 additions & 2 deletions packages/extension/src/define-extension.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -18,7 +18,14 @@ import type {
import type {PageVerbMap} from './page-verbs.js'
import {useExtensionValue} from './host-context.js'

export type AnyToolBuilder = ToolBuilder<string, z.ZodObject<z.ZodRawShape>, z.ZodType, unknown>
export type AnyToolBuilder = ToolBuilder<
string,
z.ZodObject<z.ZodRawShape>,
z.ZodType,
ToolErrors,
ToolBinding | undefined,
unknown
>

export type ExtensionMeta<
Name extends string,
Expand Down
102 changes: 80 additions & 22 deletions packages/extension/src/define-tool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,38 +25,56 @@ export function isToolError(value: unknown): value is ToolError {
return value instanceof Error && 'isToolError' in value && value.isToolError === true
}

export type ToolDefinition<Name extends string, Schema extends z.ZodObject<z.ZodRawShape>, Output extends z.ZodType> = {
export type ToolDefinition<
Name extends string,
Schema extends z.ZodObject<z.ZodRawShape>,
Output extends z.ZodType,
Errors extends ToolErrors = Record<never, never>,
> = {
name: Name
description: string
inputSchema: Schema
outputSchema?: Output
errors?: ToolErrors
errors?: Errors
meta?: ToolMeta
promptSnippet?: string
promptGuidelines?: string[]
streamTitle?: string
approval?: 'ask'
}

export function toolDefinition<
const Name extends string,
Schema extends z.ZodObject<z.ZodRawShape>,
Output extends z.ZodType,
Errors extends ToolErrors = Record<never, never>,
>(definition: ToolDefinition<Name, Schema, Output, Errors>): ToolDefinition<Name, Schema, Output, Errors> {
return definition
}

export type ToolBuilder<
Name extends string = string,
Schema extends z.ZodObject<z.ZodRawShape> = z.ZodObject<z.ZodRawShape>,
Output extends z.ZodType = z.ZodType,
Errors extends ToolErrors = ToolErrors,
Binding extends ToolBinding | undefined = ToolBinding | undefined,
Ctx = unknown,
> = Omit<ExtensionTool, 'name' | 'inputSchema'> & {
name: Name
inputSchema: Schema
outputSchema?: Output
errors?: ToolErrors
errors?: Errors
meta?: ToolMeta
binding?: ToolBinding
binding?: Binding
__ctx?: Ctx
__clientExecute?: (input: unknown) => Promise<unknown>
server: <HandlerCtx>(
execute: (input: z.infer<Schema>, ctx: HandlerCtx, request: ToolRequest) => Promise<unknown> | unknown,
) => ToolBuilder<Name, Schema, Output, HandlerCtx>
client: (execute?: (input: z.infer<Schema>) => Promise<unknown> | unknown) => ToolBuilder<Name, Schema, Output, Ctx>
render: (renderer: ToolRenderer) => ToolBuilder<Name, Schema, Output, Ctx>
) => ToolBuilder<Name, Schema, Output, Errors, 'server', HandlerCtx>
client: (
execute?: (input: z.infer<Schema>) => Promise<unknown> | unknown,
) => ToolBuilder<Name, Schema, Output, Errors, 'client', Ctx>
render: (renderer: ToolRenderer) => ToolBuilder<Name, Schema, Output, Errors, Binding, Ctx>
}

type ToolNameOf<Tool> = Tool extends {name: infer Name extends string} ? (string extends Name ? never : Name) : never
Expand All @@ -69,9 +87,30 @@ type ToolOutputSchemaOf<Tool> = Tool extends {outputSchema?: infer Schema}
: z.ZodUnknown
: z.ZodUnknown

export type RegisteredTool<Schema extends z.ZodType, Output extends z.ZodType> = {
type ToolErrorsOf<Tool> = Tool extends {errors?: infer Errors}
? NonNullable<Errors> extends ToolErrors
? NonNullable<Errors>
: Record<never, never>
: Record<never, never>

export type ProjectedToolBinding = ToolBinding | 'unknown'

type ToolBindingOf<Tool> = Tool extends {binding?: infer Binding}
? [Extract<Binding, ToolBinding>] extends [never]
? 'unknown'
: Extract<Binding, ToolBinding>
: '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<Message extends string> = {toolNameProblem: Message}
Expand Down Expand Up @@ -127,11 +166,18 @@ type ToolTupleProblem<Tools extends readonly unknown[]> =
| ToolNamePathProblem<ToolNamesIn<Tools>>

export type RegisteredTools<Tools extends readonly unknown[]> = [ToolTupleProblem<Tools>] extends [never]
? {[Tool in Tools[number] as ToolNameOf<Tool>]: RegisteredTool<ToolInputSchemaOf<Tool>, ToolOutputSchemaOf<Tool>>}
? {
[Tool in Tools[number] as ToolNameOf<Tool>]: RegisteredTool<
ToolInputSchemaOf<Tool>,
ToolOutputSchemaOf<Tool>,
ToolErrorsOf<Tool>,
ToolBindingOf<Tool>
>
}
: ToolTupleProblem<Tools>

type ToolState = {
binding?: ToolBinding
type ToolState<Binding extends ToolBinding | undefined> = {
binding?: Binding
execute?: (input: unknown, ctx?: unknown, request?: ToolRequest) => Promise<unknown>
serverRun?: (input: unknown, ctx?: unknown, request?: ToolRequest) => Promise<unknown>
clientExecute?: (input: unknown) => Promise<unknown>
Expand All @@ -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<Name extends string, Schema extends z.ZodObject<z.ZodRawShape>, Output extends z.ZodType, Ctx>(
definition: ToolDefinition<Name, Schema, Output>,
state: ToolState,
): ToolBuilder<Name, Schema, Output, Ctx> {
function toolBuilder<
Name extends string,
Schema extends z.ZodObject<z.ZodRawShape>,
Output extends z.ZodType,
Errors extends ToolErrors,
Binding extends ToolBinding | undefined,
Ctx,
>(
definition: ToolDefinition<Name, Schema, Output, Errors>,
state: ToolState<Binding>,
): ToolBuilder<Name, Schema, Output, Errors, Binding, Ctx> {
return {
name: definition.name,
description: definition.description,
Expand All @@ -178,7 +231,7 @@ function toolBuilder<Name extends string, Schema extends z.ZodObject<z.ZodRawSha
assertUnbound(definition.name, state.binding)
const invoke = async (parsed: z.infer<Schema>, ctx: unknown, request: ToolRequest | undefined) =>
execute(parsed, ctx as HandlerCtx, request as ToolRequest)
return toolBuilder<Name, Schema, Output, HandlerCtx>(definition, {
return toolBuilder<Name, Schema, Output, Errors, 'server', HandlerCtx>(definition, {
...state,
binding: 'server',
execute: async (raw, ctx, request) => invoke(definition.inputSchema.parse(raw), ctx, request),
Expand All @@ -187,15 +240,17 @@ function toolBuilder<Name extends string, Schema extends z.ZodObject<z.ZodRawSha
},
client(execute) {
assertUnbound(definition.name, state.binding)
const clientState: ToolState = {...state, binding: 'client'}
if (execute === undefined) return toolBuilder<Name, Schema, Output, Ctx>(definition, clientState)
return toolBuilder<Name, Schema, Output, Ctx>(definition, {
const clientState: ToolState<'client'> = {...state, binding: 'client'}
if (execute === undefined) {
return toolBuilder<Name, Schema, Output, Errors, 'client', Ctx>(definition, clientState)
}
return toolBuilder<Name, Schema, Output, Errors, 'client', Ctx>(definition, {
...clientState,
clientExecute: async (raw) => execute(definition.inputSchema.parse(raw)),
})
},
render(renderer) {
return toolBuilder<Name, Schema, Output, Ctx>(definition, {...state, render: renderer})
return toolBuilder<Name, Schema, Output, Errors, Binding, Ctx>(definition, {...state, render: renderer})
},
}
}
Expand All @@ -204,7 +259,10 @@ export function defineTool<
const Name extends string,
Schema extends z.ZodObject<z.ZodRawShape>,
Output extends z.ZodType,
>(definition: ToolDefinition<Name, Schema, Output>): ToolBuilder<Name, Schema, Output, unknown> {
Errors extends ToolErrors = Record<never, never>,
>(
definition: ToolDefinition<Name, Schema, Output, Errors>,
): ToolBuilder<Name, Schema, Output, Errors, undefined, unknown> {
assertToolMeta(definition.name, definition.meta)
return toolBuilder<Name, Schema, Output, unknown>(definition, {})
return toolBuilder<Name, Schema, Output, Errors, undefined, unknown>(definition, {})
}
2 changes: 1 addition & 1 deletion packages/extension/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
31 changes: 27 additions & 4 deletions packages/extension/src/tool-registry.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -29,11 +37,24 @@ type ToolPathHead<Path extends string> = Path extends `${infer Head}.${string}`

type ToolPathTail<Path extends string, Head extends string> = Path extends `${Head}.${infer Tail}` ? Tail : never

type RegistryErrorMap<Errors extends ToolErrors, Binding extends ProjectedToolBinding> = Binding extends 'server'
? Errors
: MergedErrorMap<Errors, ToolTransportErrors>

type ToolProcedure<Tool> = 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<RegistryCallContext, RegistryCallContext, Input, Output, Record<never, never>, RegistryToolMeta>
? Procedure<
RegistryCallContext,
RegistryCallContext,
Input,
Output,
RegistryErrorMap<Errors, Binding>,
RegistryToolMeta
>
: never

type ToolRouterNode<Tools> = {
Expand Down Expand Up @@ -72,13 +93,15 @@ export type ToolRouterFor<Registry> = [RegistryNameProblem<Registry>] extends [n

export type ExtensionToolRouter = ToolRouterFor<ExtensionRegistry>

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<PageErrorCode, string> = {
'no-widget': 'NO_PAGE_CLIENT',
Expand Down
Loading
Loading