/** * Tool Registry — board-ai 의 LLM tool 노출 plugin point. * * 동기: * 기존엔 board-ai 가 자기 도메인 (board edit) tool 들만 hardcoded 정의했고, styling * 영역만 STYLING_TOOLS registry 로 분리되어 있었다. 외부 도메인 패키지 (board-import, * fmsim 등) 가 자기 tool 을 LLM 에 노출하려면 board-ai 자체를 fork/수정해야 했다. * * 본 registry 는 외부 패키지가 server bootstrap 시 자기 tool category 를 등록하면 * assistant.ts 의 buildBoardEditTools / dispatch / isWriteTool 등이 자동으로 통합 * 하도록 한다. styling-tools 의 single-source-of-truth 패턴을 일반화한 형태. * * 설계 원칙: * - **카테고리별 builder 시그니처 다양성을 통합**: read 는 (args, ctx) → any, * write 는 (args, components) → SceneEditOp[], action 은 (args) → SceneActionOp. * 하나의 ToolSpec 에 모든 시그니처를 union 으로 담지 않고, 카테고리에 맞는 * builder 만 채우면 되도록 카테고리별 sub-interface 분리. * - **kind 필드로 자가 분류**: registry 가 isReadTool / isWriteTool 자동 도출. * hardcoded set 동기화 누락 위험 제거. * - **점진 마이그레이션**: 기존 STYLING_TOOLS 가 본 registry 의 첫 사용자. * 점진적으로 다른 hardcoded tool 들 (addComponent / alignComponents 등) 도 * 같은 registry 로 흡수 가능. 한 단계씩 byte-단위 동등성 단위 테스트 보장. */ /** * What `registryAssistantChat` — the door apps use (`assistantChat`, ADR-0061 decision 0) — hands a * registered tool when it runs. * * `state` and `host` sit side by side. The twin's space tools read `ctx.state.host` while this door * passed `ctx.host`, so they never saw the space; the two are never merged into one object. * * The board product's door (board-ai) passes its own shape and is not part of this contract. */ export interface ToolCallContext { /** The request state the server built — domain, user, tx. The only basis for authorization. */ state: any; /** * The client's `AssistantMode.hostContext`, passed through as is. **Untrusted** — a tool that reads * an id from it checks that the id belongs to the caller's tenant. `{}` when none was sent. */ host: Record; /** The conversation's mode. Filled once modes are registered on the server (A2); absent until then. */ mode?: ToolCallMode; /** * The request's translator, for every sentence a person reads — a card's label and reason, a message shown on * screen (ADR-0061, 2026-10-16 decision 1). The server builds it in the request's locale; it never comes from * `host`. Codes and values stay apart from it. Pass the English text as `defaultValue`: without a request * translator the door hands one that writes that default value with its placeholders filled, and a key with no * default value comes back as the key. */ t: ToolTranslate; /** * The files the person sent with **this turn**, after the server checked them (ADR-0061, 2026-10-16 decision 2) — * never from `host`, which the client fills. `[]` when none were sent. * * Checked means: each one is stored with this conversation, the conversation is the caller's to write, and the * mode's attachment policy took it — the kinds it declares, at most `maxFiles` files (5 by default) of at most * `maxBytes` each (5 MiB by default). **Their contents are untrusted input**: a tool may hand them to a model or * read them as data, and never takes an instruction or an id it trusts from them. * * Several files travel as several entries, in the order the person attached them. A tool that takes images * reads every entry of `kind: 'image'` — it does not pick the first one. */ attachments: ToolAttachment[]; /** * Set when no person is in this conversation: a scheduled run of the mode, as the caller named it * (operato-application/design/ai/unattended-run.md §6). A recorder tells an unattended run's calls from a turn's by * it; a turn has none. The server's value - never from `host`. */ run?: UnattendedRunRef; /** * The stored conversation this turn belongs to - the server's value, never from `host`. A tool that acts on the room * itself (inviting someone into it) reads it and asks the room's own rules; absent on a surface with no stored * conversation and in an unattended run. */ conversation?: { id: string; }; /** * Tells the person waiting what a long call is doing now -- "Building piece 3 of 7: left leg" (2026-11-13: a figure * built piece by piece took minutes behind three dots). Said in the request's language (`t`); shown beside the * waiting line and gone with the answer. Absent where nobody waits for it. */ progress?: (text: string) => void; /** * Whether this caller passes a GraphQL door (`'Query.figures'`) -- the conversation's own tool gate (`toolAccess`), * the one that chose which tools this turn offers. A tool that hands work on to something that reaches the * application in the caller's name (figure's MCP agent) asks it which doors that work may go through, never a copy * of it. Absent where the door was given no gate: then no door is passed. */ access?: (door: string) => Promise; } export interface ToolCallMode { kind: string; target?: string; } /** Which unattended run a call belongs to - the stored run's id and the identity its caller gave it. */ export interface UnattendedRunRef { id: string; /** Who scheduled it - `.`, e.g. `office.strategy-review`. */ source: string; /** What it is about in the source's terms - a policy id. */ subject: string; /** The occurrence it is, ISO 8601. */ scheduledAt: string; } /** `t(key, { defaultValue, ...params })` — the request's translator, as i18next's `t` is called. */ export type ToolTranslate = (key: string, params?: Record) => string; /** One file of this turn, as the server read it from storage. */ export type ToolAttachment = ToolImageAttachment | ToolTextAttachment; interface ToolAttachmentBase { /** The stored attachment's id — the one the model reads in `[attachment : …]`. */ id: string; /** The file name the person gave. Untrusted text. */ name: string; /** The stored media type. */ mediaType: string; /** Bytes as stored. */ size: number; } /** An `image/*` file, its bytes as stored. */ export interface ToolImageAttachment extends ToolAttachmentBase { kind: 'image'; data: Buffer; } /** * A text file — or a spreadsheet, which the screen reads into the CSV text of its sheets before sending. `text` is * what the model read this turn, cut at the mode's `maxChars`; `truncated` says it was cut. */ export interface ToolTextAttachment extends ToolAttachmentBase { kind: 'text'; text: string; truncated: boolean; } /** * Read tool — server 측 즉시 실행, 결과를 LLM 에 회신. board model 변경 X. * 예: getSelection / findComponents / importSession (query) */ export type ReadToolBuilder = (args: any, context: ReadToolContext) => any | Promise; export interface ReadToolContext { /** 현재 board model — 일부 read tool 이 사용 (getSelection 등). */ board?: any; /** 현재 선택된 refids. */ selectedRefids?: number[]; /** 호출자 도메인 / 사용자 / 트랜잭션. registry 외부에서 주입. */ state?: any; /** 이외 주입은 카테고리별로 자유. tool 등록자가 type 좁힐 수 있도록 unknown 으로 보존. */ [k: string]: any; } /** * Write tool — domain edit op 발생. host 가 patch 적용 후 영속화. * 예: board-ai 의 addComponent / setFill / modifyBoard. * * builder 의 return type 은 unknown 으로 둔다 — 도메인별 dispatcher (예: board-ai 의 * toolCallToSceneEditOp) 가 자기 EditOp[] 로 cast. ops/errors wrapper 형태도 동일 의미. */ export type WriteToolBuilder = (args: any, context: WriteToolContext) => any[] | { ops: any[]; errors?: string[]; } | null; export interface WriteToolContext { components?: ReadonlyArray; [k: string]: any; } /** * Action tool — ephemeral scene 조작 (select / center / fit / sceneMode). * board model 변경 X, undo 영향 X. host 가 별도 channel 로 적용. * * return type 은 unknown — 도메인별 dispatcher (예: board-ai 의 toolCallToSceneActionOp) * 가 자기 SceneActionOp 으로 cast. */ export type ActionToolBuilder = (args: any) => any | null; /** * External-call tool — 외부 service / mutation / RPC 호출. 직접 board model 영향 X * (별도 entity 변경은 가능). 결과는 LLM 에 회신. * * board-import 의 importBoardAsync / materializeImportSession 같이 board-ai 외부 * 도메인을 호출하는 tool 의 카테고리. */ export type ExternalToolBuilder = (args: any, context: ExternalToolContext) => any | Promise; export interface ExternalToolContext { state?: any; [k: string]: any; } /** * 모든 ToolSpec 공통 메타데이터. */ export interface ToolSpecBase { /** AIToolCall.name 매칭. 전 카테고리 통틀어 unique. */ name: string; /** 기능 설명 (영문 위주). LLM 의 tool description 으로 사용. */ description: string; /** * 선택 — 정책 / 테마 가이드 단문. tool description 끝에 자동 부착. * styling-tools 의 themeNote 와 동일 의미. 기타 카테고리도 사용 가능. */ themeNote?: string; /** JSON Schema for parameters — LLM tool schema 에 그대로 노출. */ schema: any; /** * Which GraphQL doors this tool reaches — `['Query.twinNow']`, * `['Query.productionSummary', 'Query.pendingSummary']`. * * **A read tool names its doors too** (ADR-0071 decision 2, shaped by ADR-0072). Before that, * only plant's tools asked whether the caller may read what they read; twin's and figure's * checked the tenant and nothing else, so holding the conversation's own privilege was enough to * reach their business data. * * **Always a list, even for one** — one shape to read. A tool that answers from several doors * needs the caller to hold **all** of them (AND, the same reading as AUTH's `requiresAll`): * plant's factory overview answers from two, and asking for only one of them would hand back * half of what the caller may not see. * * **This list is the gate** (ADR-0071 decision 2, added to 2026-09-18). A tool used to carry its * own copy of what its door asks; the copy went stale the day a door changed its declaration, and * the looser of the two won. Now the gate reads the door's own declaration from AUTH's field * table (`privilegeOfField`) and asks `checkPermission` with it — the same question, the same * answer, one declaration. * * Three states, and they are not the same thing: * - **doors named** — the caller passes each of them, or the tool is neither offered nor run. * - **`doors: []`** — this tool reaches no door at all. The ones that hand back what the surface * sent (`getOpenScene`) are this: there is nothing behind them to gate. * - **no `doors` key** — nothing was said. This is **not** an open tool: it is left out of every * conversation and reported by name at boot (`tool-doors-undeclared`). An answer built with it * would be hidden from every reader including its author (ADR-0073), so opening it would * produce a tool whose answers no one can read. * * A door that declares nothing of its own opens as far as that door opens — a tool is never * stricter than the door it reaches, and never softer. */ doors?: string[]; } export interface ReadToolSpec extends ToolSpecBase { kind: 'read'; builder: ReadToolBuilder; } export interface WriteToolSpec extends ToolSpecBase { kind: 'write'; builder: WriteToolBuilder; } export interface ActionToolSpec extends ToolSpecBase { kind: 'action'; builder: ActionToolBuilder; } export interface ExternalToolSpec extends ToolSpecBase { kind: 'external'; builder: ExternalToolBuilder; } export type ToolSpec = ReadToolSpec | WriteToolSpec | ActionToolSpec | ExternalToolSpec; /** * 한 도메인 / 패키지가 등록하는 tool 묶음. * 카테고리 이름은 식별자 (debug log / 분쟁 시 origin 추적). unique. */ export interface ToolCategory { /** 등록 식별자. 예: 'styling', 'board-import', 'fmsim'. */ name: string; /** 이 카테고리에 속한 tool spec 들. */ specs: ToolSpec[]; /** 선택 — 디버깅용 짧은 설명. */ description?: string; /** * 이 카테고리 도구를 **어떻게 써야 하는지**에 대한 규율 — 노출된 대화의 시스템 프롬프트에 실린다. * * 왜 필요한가: 도구 목록(이름·설명·스키마)만 보내면 모델은 "무엇이 있는지" 는 알지만 "언제 반드시 * 불러야 하는지" 는 모른다. 실제로 그 공백에서 사고가 났다 — 조치 요청에 `proposeAction` 을 부르지 * 않고 "제안해 두었습니다" 라고만 답해, 사용자에게는 없는 버튼을 누르라고 안내했다. * * 규율은 도구를 등록한 쪽이 소유한다. 호스트(board-ai)는 도메인을 모르는 채 **노출된 카테고리의 * 규율만 모아 붙인다** — 도메인 지식이 호스트 프롬프트로 새지 않는다. * * ── 왜 필수인가 (2026-09-09) ────────────────────────────────────────────── * 선택 필드였다. 그래서 위에 적힌 사고를 아는 사람만 채웠고, 세 제품이 각자 도구를 붙이기 * 시작한 지금 **채운 넷과 안 채운 하나**가 있었다. * * 안 채운 쪽은 조용하다 — 등록은 성공하고 부팅도 성공하고, 모델이 도구를 덜 부르거나 지어낸 * 뒤에 사람이 화면을 보고 안다. **두 개를 기억해야 성립하는 규칙은 다음 새 카테고리까지만 * 간다.** 그래서 기억이 아니라 등록이 거절한다(§`registerToolCategory`). * * 빈 문자열도 거절한다. 「없음」을 「적었다」로 위장하는 값이 통과하면 이 강제가 형식이 된다. */ guidance: string; } export {};