@things-factory/ai-client-base 10.1.26 → 10.1.29
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-server/service/agentic-loop/agentic-loop.js +34 -8
- package/dist-server/service/agentic-loop/agentic-loop.js.map +1 -1
- package/dist-server/service/assistant/abort-notice.d.ts +3 -1
- package/dist-server/service/assistant/abort-notice.js +20 -6
- package/dist-server/service/assistant/abort-notice.js.map +1 -1
- package/dist-server/service/assistant/assistant-chat.d.ts +6 -0
- package/dist-server/service/assistant/assistant-chat.js +1 -1
- package/dist-server/service/assistant/assistant-chat.js.map +1 -1
- package/dist-server/service/assistant/registry-assistant.d.ts +13 -0
- package/dist-server/service/assistant/registry-assistant.js +7 -2
- package/dist-server/service/assistant/registry-assistant.js.map +1 -1
- package/dist-server/service/capability.d.ts +17 -0
- package/dist-server/service/capability.js +49 -0
- package/dist-server/service/capability.js.map +1 -0
- package/dist-server/service/index.d.ts +1 -0
- package/dist-server/service/index.js +2 -0
- package/dist-server/service/index.js.map +1 -1
- package/dist-server/service/tool-registry/registry.d.ts +8 -1
- package/dist-server/service/tool-registry/registry.js +50 -6
- package/dist-server/service/tool-registry/registry.js.map +1 -1
- package/dist-server/service/tool-registry/types.d.ts +26 -2
- package/dist-server/service/tool-registry/types.js.map +1 -1
- package/dist-server/tsconfig.tsbuildinfo +1 -1
- package/package.json +2 -2
- package/server/service/agentic-loop/agentic-loop.ts +34 -8
- package/server/service/agentic-loop/proposal-key.test.ts +83 -0
- package/server/service/assistant/abort-notice.ts +33 -11
- package/server/service/assistant/assistant-chat.test.ts +24 -2
- package/server/service/assistant/assistant-chat.ts +7 -2
- package/server/service/assistant/registry-assistant.test.ts +43 -0
- package/server/service/assistant/registry-assistant.ts +17 -2
- package/server/service/capability.test.ts +52 -0
- package/server/service/capability.ts +58 -0
- package/server/service/index.ts +2 -0
- package/server/service/tool-registry/registry.test.ts +88 -7
- package/server/service/tool-registry/registry.ts +63 -8
- package/server/service/tool-registry/types.ts +27 -2
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"capability.js","sourceRoot":"","sources":["../../server/service/capability.ts"],"names":[],"mappings":";;AAkCA,oCAcC;AAhDD;;;;;;;;;;;GAWG;AACH,6CAAyD;AAEzD,6CAA0E;AAc1E;;;;;GAKG;AACH,SAAgB,YAAY;IAC1B,MAAM,MAAM,GAAG,iBAAiB,EAAE,CAAA;IAClC,IAAI,MAAM,EAAE,CAAC;QACX,MAAM,CAAC,QAAQ,EAAE,KAAK,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;QAC5D,OAAO,EAAE,KAAK,EAAE,YAAY,EAAE,QAAQ,EAAE,QAAQ,IAAI,SAAS,EAAE,KAAK,EAAE,KAAK,IAAI,SAAS,EAAE,CAAA;IAC5F,CAAC;IAED,MAAM,GAAG,GAAG,YAAS,CAAC,GAAG,CAAC,UAAU,EAAE,IAAI,CAAiD,CAAA;IAC3F,IAAI,CAAC,GAAG;QAAE,OAAO,EAAE,KAAK,EAAE,gBAAgB,EAAE,MAAM,EAAE,WAAW,EAAE,CAAA;IACjE,IAAI,CAAC,GAAG,CAAC,QAAQ;QAAE,OAAO,EAAE,KAAK,EAAE,gBAAgB,EAAE,MAAM,EAAE,aAAa,EAAE,CAAA;IAC5E,IAAI,CAAC,IAAA,oCAAuB,GAAE,CAAC,QAAQ,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC;QACtD,OAAO,EAAE,KAAK,EAAE,gBAAgB,EAAE,QAAQ,EAAE,GAAG,CAAC,QAAQ,EAAE,MAAM,EAAE,kBAAkB,EAAE,CAAA;IACxF,CAAC;IACD,OAAO,EAAE,KAAK,EAAE,gBAAgB,EAAE,QAAQ,EAAE,GAAG,CAAC,QAAQ,EAAE,KAAK,EAAE,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,YAAY,EAAE,CAAA;AACpG,CAAC;AAED,SAAS,iBAAiB;IACxB,IAAI,CAAC;QACH,OAAO,IAAA,+BAAkB,GAAE,CAAA;IAC7B,CAAC;IAAC,MAAM,CAAC;QACP,6FAA6F;QAC7F,OAAO,SAAS,CAAA;IAClB,CAAC;AACH,CAAC","sourcesContent":["/**\n * Is there an AI on this deployment, and what is missing — asked before anything is tried.\n *\n * The twin had a button that asked the assistant, and whether to show it was decided by whether a\n * now-dead mutation had failed once. When the dock moved to the neutral door nothing called that\n * mutation any more, so the answer was \"configured\" forever: the button appeared on deployments\n * with no provider at all and failed when pressed (standard A7-a).\n *\n * A capability is read, not discovered by failing (ADR-0042 decision ②). It lives here because the\n * provider configuration does, and the answer has three states — the third is the one a screen\n * must not fold away: **not asked yet** is not \"configured\".\n */\nimport { config as envConfig } from '@things-factory/env'\n\nimport { getDefaultAIClient, listRegisteredProviders } from './factory.js'\n\nexport type AiCapabilityState = 'configured' | 'not-configured'\n\nexport interface AiCapability {\n state: AiCapabilityState\n /** Which provider answers, when one does — for the person reading a boot log, not for a screen. */\n provider?: string\n /** The default model this deployment would use. */\n model?: string\n /** Why it is not configured, as a code: no-config · no-provider · unknown-provider · no-adapter. */\n reason?: string\n}\n\n/**\n * What this server can do, as of now.\n *\n * Creating the client is what proves a provider adapter is loaded and the configuration parses, so\n * this asks for it. It never throws: a deployment with no AI is a normal deployment.\n */\nexport function aiCapability(): AiCapability {\n const client = safeDefaultClient()\n if (client) {\n const [provider, model] = String(client.id ?? '').split(':')\n return { state: 'configured', provider: provider || undefined, model: model || undefined }\n }\n\n const cfg = envConfig.get('aiClient', null) as { provider?: string; model?: string } | null\n if (!cfg) return { state: 'not-configured', reason: 'no-config' }\n if (!cfg.provider) return { state: 'not-configured', reason: 'no-provider' }\n if (!listRegisteredProviders().includes(cfg.provider)) {\n return { state: 'not-configured', provider: cfg.provider, reason: 'unknown-provider' }\n }\n return { state: 'not-configured', provider: cfg.provider, model: cfg.model, reason: 'no-adapter' }\n}\n\nfunction safeDefaultClient() {\n try {\n return getDefaultAIClient()\n } catch {\n /* A broken configuration is \"not configured\", and it is the reason below that says which. */\n return undefined\n }\n}\n"]}
|
|
@@ -9,5 +9,7 @@ tslib_1.__exportStar(require("./tool-registry/index.js"), exports);
|
|
|
9
9
|
tslib_1.__exportStar(require("./agentic-loop/index.js"), exports);
|
|
10
10
|
tslib_1.__exportStar(require("./assistant/index.js"), exports);
|
|
11
11
|
tslib_1.__exportStar(require("./analysis-contract.js"), exports);
|
|
12
|
+
/* 「이 배포에 AI 가 있나」 — 시도해서 알아내지 않고 먼저 읽는다(표준 A7-a). */
|
|
13
|
+
tslib_1.__exportStar(require("./capability.js"), exports);
|
|
12
14
|
tslib_1.__exportStar(require("./testing/tool-call-context.js"), exports);
|
|
13
15
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../server/service/index.ts"],"names":[],"mappings":";;;AAAA,qDAA0B;AAC1B,uDAA4B;AAC5B,+DAAoC;AACpC,2DAAgC;AAChC,mEAAwC;AACxC,kEAAuC;AACvC,+DAAoC;AACpC,iEAAsC;AACtC,yEAA8C","sourcesContent":["export * from './types.js'\nexport * from './factory.js'\nexport * from './providers/index.js'\nexport * from './utils/index.js'\nexport * from './tool-registry/index.js'\nexport * from './agentic-loop/index.js'\nexport * from './assistant/index.js'\nexport * from './analysis-contract.js'\nexport * from './testing/tool-call-context.js'\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../server/service/index.ts"],"names":[],"mappings":";;;AAAA,qDAA0B;AAC1B,uDAA4B;AAC5B,+DAAoC;AACpC,2DAAgC;AAChC,mEAAwC;AACxC,kEAAuC;AACvC,+DAAoC;AACpC,iEAAsC;AACtC,qDAAqD;AACrD,0DAA+B;AAC/B,yEAA8C","sourcesContent":["export * from './types.js'\nexport * from './factory.js'\nexport * from './providers/index.js'\nexport * from './utils/index.js'\nexport * from './tool-registry/index.js'\nexport * from './agentic-loop/index.js'\nexport * from './assistant/index.js'\nexport * from './analysis-contract.js'\n/* 「이 배포에 AI 가 있나」 — 시도해서 알아내지 않고 먼저 읽는다(표준 A7-a). */\nexport * from './capability.js'\nexport * from './testing/tool-call-context.js'\n"]}
|
|
@@ -28,11 +28,18 @@
|
|
|
28
28
|
import type { ToolCategory, ToolSpec } from './types';
|
|
29
29
|
/** A registration that was accepted but is not yet what the contract requires. Code + params, not prose. */
|
|
30
30
|
export interface ToolRegistryWarning {
|
|
31
|
-
|
|
31
|
+
/**
|
|
32
|
+
* `tool-privilege-undeclared` — nothing said which door this tool reaches.
|
|
33
|
+
* `tool-door-has-no-privilege` — the door was named and it declares no privilege of its own yet
|
|
34
|
+
* (twin's queries, waiting on AUTH stage two). The tool cannot be stricter than its door, so
|
|
35
|
+
* this is a different fact from saying nothing, and the report keeps the two apart.
|
|
36
|
+
*/
|
|
37
|
+
code: 'tool-privilege-undeclared' | 'tool-door-has-no-privilege' | 'tool-doors-undeclared';
|
|
32
38
|
params: {
|
|
33
39
|
category: string;
|
|
34
40
|
tool: string;
|
|
35
41
|
kind: ToolSpec['kind'];
|
|
42
|
+
doors?: string[];
|
|
36
43
|
};
|
|
37
44
|
/** For a person reading it; the code and params are what callers act on. */
|
|
38
45
|
message: string;
|
|
@@ -59,19 +59,63 @@ function registerToolCategory(category) {
|
|
|
59
59
|
* is empty across the apps, this becomes a refusal.
|
|
60
60
|
*/
|
|
61
61
|
warnings.splice(0, warnings.length, ...warnings.filter(w => w.params.category !== category.name));
|
|
62
|
+
/*
|
|
63
|
+
* ── 문을 안 적은 도구는 그 답을 **아무도 못 읽게 만든다** ─────────────────
|
|
64
|
+
*
|
|
65
|
+
* ADR-0073 뒤로 어시스턴트의 답 행에는 그 답을 만든 도구들이 지난 문이 적힌다. 선언이 없는 도구는
|
|
66
|
+
* `unresolved:<도구>` 로 적히고 그 이름은 아무도 못 지난다 — **답을 쓴 본인도** 새로 고치면
|
|
67
|
+
* 「이 답을 볼 권한이 없습니다」를 본다. 2026-09-18 트윈 모델러에서 그렇게 나왔다.
|
|
68
|
+
*
|
|
69
|
+
* 이 검사를 권한 검사와 따로 도는 이유가 그것이다. 아래 고리는 `privilege` 가 있으면 건너뛰는데,
|
|
70
|
+
* 문을 안 적은 해는 권한을 적었는지와 상관이 없다. 트윈의 저작 도구 넷이 정확히 그 자리였다 —
|
|
71
|
+
* 권한은 있고 문은 없어서 부팅이 아무 말도 안 했다.
|
|
72
|
+
*/
|
|
73
|
+
for (const spec of category.specs) {
|
|
74
|
+
if (Array.isArray(spec.doors))
|
|
75
|
+
continue;
|
|
76
|
+
warnings.push({
|
|
77
|
+
code: 'tool-doors-undeclared',
|
|
78
|
+
params: { category: category.name, tool: spec.name, kind: spec.kind },
|
|
79
|
+
message: `tool '${spec.name}' in category '${category.name}' declares no doors, so answers built with it ` +
|
|
80
|
+
'are hidden from every reader including their author — declare `doors`, or `doors: []` when it reaches none'
|
|
81
|
+
});
|
|
82
|
+
}
|
|
62
83
|
for (const spec of category.specs) {
|
|
63
|
-
|
|
84
|
+
const declared = Boolean(spec.privilege?.category && spec.privilege?.privilege);
|
|
85
|
+
if (declared)
|
|
86
|
+
continue;
|
|
87
|
+
/*
|
|
88
|
+
* An empty list says this tool reaches no door — the ones that hand back what the surface sent
|
|
89
|
+
* are that. Nothing to gate, nothing to report.
|
|
90
|
+
*/
|
|
91
|
+
if (Array.isArray(spec.doors) && spec.doors.length === 0)
|
|
92
|
+
continue;
|
|
93
|
+
if (spec.doors?.length) {
|
|
94
|
+
/*
|
|
95
|
+
* The door is named and carries no privilege yet. The tool cannot be stricter than the door
|
|
96
|
+
* it reaches, so this is not an omission by whoever wrote the tool — it is the door's turn
|
|
97
|
+
* (ADR-0071 decision 2). Reported under its own code so the two are not read as one list.
|
|
98
|
+
*/
|
|
64
99
|
warnings.push({
|
|
65
|
-
code: 'tool-privilege
|
|
66
|
-
params: { category: category.name, tool: spec.name, kind: spec.kind },
|
|
67
|
-
message: `tool '${spec.name}'
|
|
68
|
-
'
|
|
100
|
+
code: 'tool-door-has-no-privilege',
|
|
101
|
+
params: { category: category.name, tool: spec.name, kind: spec.kind, doors: spec.doors },
|
|
102
|
+
message: `tool '${spec.name}' reaches ${spec.doors.join(' + ')} and declares no privilege of its own — ` +
|
|
103
|
+
'whether those doors require anything is asked at boot, against the schema, not copied here ' +
|
|
104
|
+
'(ADR-0072 decision 5)'
|
|
69
105
|
});
|
|
106
|
+
continue;
|
|
70
107
|
}
|
|
108
|
+
warnings.push({
|
|
109
|
+
code: 'tool-privilege-undeclared',
|
|
110
|
+
params: { category: category.name, tool: spec.name, kind: spec.kind },
|
|
111
|
+
message: `tool '${spec.name}' in category '${category.name}' declares no privilege of its own — ` +
|
|
112
|
+
'a tool that changes something says who may run it. What the doors it reaches require is a ' +
|
|
113
|
+
"separate question, answered at boot against the schema (`tool-door-not-in-schema`)."
|
|
114
|
+
});
|
|
71
115
|
}
|
|
72
116
|
if (categories.has(category.name)) {
|
|
73
117
|
console.warn(`[board-ai/tool-registry] category '${category.name}' already registered — overwriting. ` +
|
|
74
|
-
|
|
118
|
+
'(normal on a dev hot reload; in production it means the same category is registered twice)');
|
|
75
119
|
}
|
|
76
120
|
// tool name 충돌 검사 — 다른 카테고리에 같은 name 있으면 거부
|
|
77
121
|
const newNames = new Set(category.specs.map(s => s.name));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registry.js","sourceRoot":"","sources":["../../../server/service/tool-registry/registry.ts"],"names":[],"mappings":";;AA6CA,0DAEC;AAKD,oDAyEC;AAmBD,8CAEC;AAMD,0CAEC;AAMD,0CAOC;AAQD,kDAQC;AAKD,oCAOC;AAMD,kCAEC;AAKD,0BAEC;AAKD,4CAEC;AASD,8CAGC;AAxMD,MAAM,UAAU,GAA8B,IAAI,GAAG,EAAE,CAAA;AAUvD,MAAM,QAAQ,GAA0B,EAAE,CAAA;AAE1C;;;GAGG;AACH,SAAgB,uBAAuB;IAC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AAED;;GAEG;AACH,SAAgB,OAAO,CAAC,IAAY,EAAE,MAA2B;IAC/D,OAAO,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,KAAK,SAAS,CAAA;AACjD,CAAC;AAED;;GAEG;AACH,SAAgB,gBAAgB,CAAC,YAAoB;IACnD,OAAO,UAAU,CAAC,GAAG,CAAC,YAAY,CAAC,EAAE,KAAK,IAAI,EAAE,CAAA;AAClD,CAAC;AAED;;;;;;GAMG;AACH,SAAgB,iBAAiB;IAC/B,UAAU,CAAC,KAAK,EAAE,CAAA;IAClB,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAA;AACrB,CAAC","sourcesContent":["/**\n * ToolCategoryRegistry — 외부 도메인 패키지가 LLM tool category 를 동적 등록하는 점.\n *\n * 사용 패턴 (외부 패키지의 server bootstrap):\n * ```ts\n * import { registerToolCategory } from '@things-factory/board-ai'\n *\n * registerToolCategory({\n * name: 'board-import',\n * specs: [\n * { kind: 'external', name: 'importBoardAsync', schema: {...}, builder: ... },\n * { kind: 'read', name: 'getImportSession', schema: {...}, builder: ... },\n * ...\n * ]\n * })\n * ```\n *\n * board-ai assistant.ts 의 buildBoardEditTools / dispatch / isWriteTool 등이\n * 본 registry 에서 자동 도출.\n *\n * 정책:\n * - 카테고리 이름은 unique. 같은 이름으로 재등록하면 덮어쓰기 (외부 패키지의\n * hot-reload / dev 환경 대응). console.warn 으로 알림.\n * - tool name 은 카테고리 간 통틀어 unique. 충돌 시 등록 거부 + 명확한 에러\n * (LLM dispatch 가 모호해지지 않도록).\n * - clear() 는 테스트 전용. 운영 환경에서 호출 금지.\n */\nimport type { ToolCategory, ToolSpec } from './types'\n\nconst categories: Map<string, ToolCategory> = new Map()\n\n/** A registration that was accepted but is not yet what the contract requires. Code + params, not prose. */\nexport interface ToolRegistryWarning {\n code: 'tool-privilege-undeclared'\n params: { category: string; tool: string; kind: ToolSpec['kind'] }\n /** For a person reading it; the code and params are what callers act on. */\n message: string\n}\n\nconst warnings: ToolRegistryWarning[] = []\n\n/**\n * What registration accepted but the contract does not yet allow. Stage one of A1 records these\n * instead of refusing; a host shows them at boot, and when the list is empty the rule becomes a refusal.\n */\nexport function getToolRegistryWarnings(): ReadonlyArray<ToolRegistryWarning> {\n return warnings.slice()\n}\n\n/**\n * 카테고리 등록. tool name 충돌 시 throw, 이름 중복 등록 시 덮어쓰기 + warn.\n */\nexport function registerToolCategory(category: ToolCategory): void {\n /*\n * 지침 없는 카테고리는 **등록하지 않는다.**\n *\n * 도구 목록만 보낸 모델이 「불러야 할 때 부른다」를 맞히지 못한 사고가 있었다 — 조치 요청에\n * `proposeAction` 을 부르지 않고 「제안해 두었습니다」라고 답해, 사용자에게 없는 버튼을 누르라고\n * 안내했다. 화면에는 아무 일도 없었고 오류도 나지 않았다(§`ToolCategory.guidance`).\n *\n * 그 뒤로 규율을 적는 자리를 만들었지만 **선택이었다.** 선택인 규율은 그 사고를 아는 사람만\n * 채운다. 여기서 거절하는 이유가 그것이다 — 빠진 것을 부팅에서 만든 사람이 보고, 모델이 헛말을\n * 한 뒤에 사용자가 보지 않는다.\n *\n * 빈 문자열·공백도 거절한다. 통과시키면 이 검사가 형식이 되고, 형식이 된 검사는 없는 것과 같다.\n */\n if (!String(category.guidance ?? '').trim()) {\n throw new Error(\n `[ai-client-base/tool-registry] category '${category.name}' has no guidance. ` +\n 'Tool descriptions say what a tool does; guidance says when the model must call one. ' +\n 'Without it a model answers as though it called a tool it did not, and nothing errors. ' +\n 'Write the rules for these tools in `guidance` — the side that registers them owns them.'\n )\n }\n\n /*\n * A tool that changes something must say which privilege it goes through (A1, 2026-09-17).\n *\n * The conversation door checks one privilege — may this person talk to the assistant. Without a\n * privilege on the tool, that single check opened every tool behind it: a user holding only\n * `ai-assistant:mutation` could reach board-import's `materializeImportSession` and create a\n * Board.\n *\n * **This is stage one of two: surface, then refuse** (ADR-0037, \"먼저 드러내고, 목록이 비면 막는다\").\n * Refusing now would stop every app whose tools predate the `privilege` field from booting, and\n * those apps compile against an installed copy that does not have the field yet. So an undeclared\n * tool still registers, and the omission is recorded as a code (`getToolRegistryWarnings`), not\n * a log line — a warning only a log carries is not distinguishable from no warning. When the list\n * is empty across the apps, this becomes a refusal.\n */\n warnings.splice(0, warnings.length, ...warnings.filter(w => w.params.category !== category.name))\n for (const spec of category.specs) {\n if (spec.kind !== 'read' && !(spec.privilege?.category && spec.privilege?.privilege)) {\n warnings.push({\n code: 'tool-privilege-undeclared',\n params: { category: category.name, tool: spec.name, kind: spec.kind },\n message:\n `tool '${spec.name}' in category '${category.name}' is '${spec.kind}' but declares no privilege — ` +\n 'declare the same { category, privilege } its GraphQL door uses'\n })\n }\n }\n\n if (categories.has(category.name)) {\n console.warn(\n `[board-ai/tool-registry] category '${category.name}' already registered — overwriting. ` +\n `(dev hot-reload 시 정상이지만 운영 환경에서 발생하면 buildup bug)`\n )\n }\n\n // tool name 충돌 검사 — 다른 카테고리에 같은 name 있으면 거부\n const newNames = new Set(category.specs.map(s => s.name))\n for (const [otherName, other] of categories) {\n if (otherName === category.name) continue // 같은 카테고리 재등록은 덮어쓰기 OK\n for (const spec of other.specs) {\n if (newNames.has(spec.name)) {\n throw new Error(\n `[board-ai/tool-registry] tool name '${spec.name}' already registered in category ` +\n `'${otherName}', cannot register in '${category.name}'. tool names must be globally unique.`\n )\n }\n }\n }\n\n categories.set(category.name, category)\n}\n\n/**\n * 대화별 도구 노출 제한 — 허용 카테고리 목록.\n *\n * `undefined` 는 **제한 없음**(등록된 전부). 호스트가 목록을 주면 그 카테고리에 속한 spec 만\n * 정의·실행 대상이 된다. 정의를 숨기는 것만으로는 부족하다 — 모델이 이름을 추측하거나 옛 대화가\n * 재생되면 숨긴 도구도 호출되므로 **dispatch 조회(findToolSpec)에도 같은 목록을 넘겨야** 한다.\n */\nexport type ToolCategoryFilter = ReadonlyArray<string> | undefined\n\n/** 허용 목록에 든 카테고리인가. 목록 없음 = 전부 허용. */\nfunction allowed(name: string, filter: ToolCategoryFilter): boolean {\n return !filter || filter.includes(name)\n}\n\n/**\n * 등록된 모든 카테고리 (등록 순서 보존). 외부에서 불변 read-only 로 사용.\n */\nexport function getToolCategories(): ReadonlyArray<ToolCategory> {\n return Array.from(categories.values())\n}\n\n/**\n * 등록된 모든 tool spec 의 평면 view. assistant.ts 의 buildBoardEditTools 가\n * LLM tool 정의 합집합으로 사용.\n */\nexport function getAllToolSpecs(): ReadonlyArray<ToolSpec> {\n return getToolSpecsFor(undefined)\n}\n\n/**\n * 허용 카테고리의 spec 평면 view. `undefined` = 전부(= getAllToolSpecs 와 동일).\n * LLM 도구 정의를 만들 때 이 함수를 쓰면 대화별 노출 제한이 그대로 반영된다.\n */\nexport function getToolSpecsFor(filter: ToolCategoryFilter): ReadonlyArray<ToolSpec> {\n const out: ToolSpec[] = []\n for (const [catName, cat] of categories) {\n if (!allowed(catName, filter)) continue\n for (const spec of cat.specs) out.push(spec)\n }\n return out\n}\n\n/**\n * 노출된 카테고리들의 **사용 규율** 모음(등록 순서). 시스템 프롬프트에 붙이는 용도.\n *\n * 도구 목록만 보내면 모델은 \"무엇이 있는지\" 는 알지만 \"언제 반드시 불러야 하는지\" 는 모른다.\n * 규율은 도구를 등록한 쪽이 소유하고, 호스트는 노출된 것만 모아 붙인다(도메인 지식이 새지 않는다).\n */\nexport function getCategoryGuidance(filter: ToolCategoryFilter): string[] {\n const out: string[] = []\n for (const [catName, cat] of categories) {\n if (!allowed(catName, filter)) continue\n const guidance = (cat.guidance ?? '').trim()\n if (guidance) out.push(guidance)\n }\n return out\n}\n\n/**\n * tool name 으로 spec 검색. 없으면 undefined.\n */\nexport function findToolSpec(name: string, filter?: ToolCategoryFilter): ToolSpec | undefined {\n for (const [catName, cat] of categories) {\n if (!allowed(catName, filter)) continue\n const spec = cat.specs.find(s => s.name === name)\n if (spec) return spec\n }\n return undefined\n}\n\n/**\n * tool name 의 카테고리 (read/write/action/external). 미등록 tool 은 undefined.\n * assistant.ts 의 isReadTool / isWriteTool / isActionTool 이 이 함수에 위임할 수 있다.\n */\nexport function getToolKind(name: string, filter?: ToolCategoryFilter): ToolSpec['kind'] | undefined {\n return findToolSpec(name, filter)?.kind\n}\n\n/**\n * 등록된 tool 인지. dispatch path 가 hardcoded set 와 registry 양쪽 fallback 시 사용.\n */\nexport function hasTool(name: string, filter?: ToolCategoryFilter): boolean {\n return findToolSpec(name, filter) !== undefined\n}\n\n/**\n * 카테고리 이름으로 spec 만 추출.\n */\nexport function getCategorySpecs(categoryName: string): ReadonlyArray<ToolSpec> {\n return categories.get(categoryName)?.specs ?? []\n}\n\n/**\n * 테스트 전용 — 모든 등록 해제. 운영 환경에서 호출 금지.\n *\n * jest 의 setupFilesAfterEach 또는 명시적 afterEach 에서 호출해 테스트 간 격리.\n * 실제로 STYLING_TOOLS 는 board-ai 자체 부트스트랩에서 다시 등록되므로 clear 후\n * 명시 register 가 필요한 것은 동적 카테고리 (board-import 등) 뿐.\n */\nexport function clearToolRegistry(): void {\n categories.clear()\n warnings.length = 0\n}\n"]}
|
|
1
|
+
{"version":3,"file":"registry.js","sourceRoot":"","sources":["../../../server/service/tool-registry/registry.ts"],"names":[],"mappings":";;AAmDA,0DAEC;AAKD,oDA0HC;AAmBD,8CAEC;AAMD,0CAEC;AAMD,0CAOC;AAQD,kDAQC;AAKD,oCAOC;AAMD,kCAEC;AAKD,0BAEC;AAKD,4CAEC;AASD,8CAGC;AA/PD,MAAM,UAAU,GAA8B,IAAI,GAAG,EAAE,CAAA;AAgBvD,MAAM,QAAQ,GAA0B,EAAE,CAAA;AAE1C;;;GAGG;AACH,SAAgB,uBAAuB;IACrC,OAAO,QAAQ,CAAC,KAAK,EAAE,CAAA;AACzB,CAAC;AAED;;GAEG;AACH,SAAgB,oBAAoB,CAAC,QAAsB;IACzD;;;;;;;;;;;;OAYG;IACH,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,QAAQ,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC;QAC5C,MAAM,IAAI,KAAK,CACb,4CA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\n * ToolCategoryRegistry — 외부 도메인 패키지가 LLM tool category 를 동적 등록하는 점.\n *\n * 사용 패턴 (외부 패키지의 server bootstrap):\n * ```ts\n * import { registerToolCategory } from '@things-factory/board-ai'\n *\n * registerToolCategory({\n * name: 'board-import',\n * specs: [\n * { kind: 'external', name: 'importBoardAsync', schema: {...}, builder: ... },\n * { kind: 'read', name: 'getImportSession', schema: {...}, builder: ... },\n * ...\n * ]\n * })\n * ```\n *\n * board-ai assistant.ts 의 buildBoardEditTools / dispatch / isWriteTool 등이\n * 본 registry 에서 자동 도출.\n *\n * 정책:\n * - 카테고리 이름은 unique. 같은 이름으로 재등록하면 덮어쓰기 (외부 패키지의\n * hot-reload / dev 환경 대응). console.warn 으로 알림.\n * - tool name 은 카테고리 간 통틀어 unique. 충돌 시 등록 거부 + 명확한 에러\n * (LLM dispatch 가 모호해지지 않도록).\n * - clear() 는 테스트 전용. 운영 환경에서 호출 금지.\n */\nimport type { ToolCategory, ToolSpec } from './types'\n\nconst categories: Map<string, ToolCategory> = new Map()\n\n/** A registration that was accepted but is not yet what the contract requires. Code + params, not prose. */\nexport interface ToolRegistryWarning {\n /**\n * `tool-privilege-undeclared` — nothing said which door this tool reaches.\n * `tool-door-has-no-privilege` — the door was named and it declares no privilege of its own yet\n * (twin's queries, waiting on AUTH stage two). The tool cannot be stricter than its door, so\n * this is a different fact from saying nothing, and the report keeps the two apart.\n */\n code: 'tool-privilege-undeclared' | 'tool-door-has-no-privilege' | 'tool-doors-undeclared'\n params: { category: string; tool: string; kind: ToolSpec['kind']; doors?: string[] }\n /** For a person reading it; the code and params are what callers act on. */\n message: string\n}\n\nconst warnings: ToolRegistryWarning[] = []\n\n/**\n * What registration accepted but the contract does not yet allow. Stage one of A1 records these\n * instead of refusing; a host shows them at boot, and when the list is empty the rule becomes a refusal.\n */\nexport function getToolRegistryWarnings(): ReadonlyArray<ToolRegistryWarning> {\n return warnings.slice()\n}\n\n/**\n * 카테고리 등록. tool name 충돌 시 throw, 이름 중복 등록 시 덮어쓰기 + warn.\n */\nexport function registerToolCategory(category: ToolCategory): void {\n /*\n * 지침 없는 카테고리는 **등록하지 않는다.**\n *\n * 도구 목록만 보낸 모델이 「불러야 할 때 부른다」를 맞히지 못한 사고가 있었다 — 조치 요청에\n * `proposeAction` 을 부르지 않고 「제안해 두었습니다」라고 답해, 사용자에게 없는 버튼을 누르라고\n * 안내했다. 화면에는 아무 일도 없었고 오류도 나지 않았다(§`ToolCategory.guidance`).\n *\n * 그 뒤로 규율을 적는 자리를 만들었지만 **선택이었다.** 선택인 규율은 그 사고를 아는 사람만\n * 채운다. 여기서 거절하는 이유가 그것이다 — 빠진 것을 부팅에서 만든 사람이 보고, 모델이 헛말을\n * 한 뒤에 사용자가 보지 않는다.\n *\n * 빈 문자열·공백도 거절한다. 통과시키면 이 검사가 형식이 되고, 형식이 된 검사는 없는 것과 같다.\n */\n if (!String(category.guidance ?? '').trim()) {\n throw new Error(\n `[ai-client-base/tool-registry] category '${category.name}' has no guidance. ` +\n 'Tool descriptions say what a tool does; guidance says when the model must call one. ' +\n 'Without it a model answers as though it called a tool it did not, and nothing errors. ' +\n 'Write the rules for these tools in `guidance` — the side that registers them owns them.'\n )\n }\n\n /*\n * A tool that changes something must say which privilege it goes through (A1, 2026-09-17).\n *\n * The conversation door checks one privilege — may this person talk to the assistant. Without a\n * privilege on the tool, that single check opened every tool behind it: a user holding only\n * `ai-assistant:mutation` could reach board-import's `materializeImportSession` and create a\n * Board.\n *\n * **This is stage one of two: surface, then refuse** (ADR-0037, \"먼저 드러내고, 목록이 비면 막는다\").\n * Refusing now would stop every app whose tools predate the `privilege` field from booting, and\n * those apps compile against an installed copy that does not have the field yet. So an undeclared\n * tool still registers, and the omission is recorded as a code (`getToolRegistryWarnings`), not\n * a log line — a warning only a log carries is not distinguishable from no warning. When the list\n * is empty across the apps, this becomes a refusal.\n */\n warnings.splice(0, warnings.length, ...warnings.filter(w => w.params.category !== category.name))\n\n /*\n * ── 문을 안 적은 도구는 그 답을 **아무도 못 읽게 만든다** ─────────────────\n *\n * ADR-0073 뒤로 어시스턴트의 답 행에는 그 답을 만든 도구들이 지난 문이 적힌다. 선언이 없는 도구는\n * `unresolved:<도구>` 로 적히고 그 이름은 아무도 못 지난다 — **답을 쓴 본인도** 새로 고치면\n * 「이 답을 볼 권한이 없습니다」를 본다. 2026-09-18 트윈 모델러에서 그렇게 나왔다.\n *\n * 이 검사를 권한 검사와 따로 도는 이유가 그것이다. 아래 고리는 `privilege` 가 있으면 건너뛰는데,\n * 문을 안 적은 해는 권한을 적었는지와 상관이 없다. 트윈의 저작 도구 넷이 정확히 그 자리였다 —\n * 권한은 있고 문은 없어서 부팅이 아무 말도 안 했다.\n */\n for (const spec of category.specs) {\n if (Array.isArray(spec.doors)) continue\n\n warnings.push({\n code: 'tool-doors-undeclared',\n params: { category: category.name, tool: spec.name, kind: spec.kind },\n message:\n `tool '${spec.name}' in category '${category.name}' declares no doors, so answers built with it ` +\n 'are hidden from every reader including their author — declare `doors`, or `doors: []` when it reaches none'\n })\n }\n\n for (const spec of category.specs) {\n const declared = Boolean(spec.privilege?.category && spec.privilege?.privilege)\n if (declared) continue\n\n /*\n * An empty list says this tool reaches no door — the ones that hand back what the surface sent\n * are that. Nothing to gate, nothing to report.\n */\n if (Array.isArray(spec.doors) && spec.doors.length === 0) continue\n\n if (spec.doors?.length) {\n /*\n * The door is named and carries no privilege yet. The tool cannot be stricter than the door\n * it reaches, so this is not an omission by whoever wrote the tool — it is the door's turn\n * (ADR-0071 decision 2). Reported under its own code so the two are not read as one list.\n */\n warnings.push({\n code: 'tool-door-has-no-privilege',\n params: { category: category.name, tool: spec.name, kind: spec.kind, doors: spec.doors },\n message:\n `tool '${spec.name}' reaches ${spec.doors.join(' + ')} and declares no privilege of its own — ` +\n 'whether those doors require anything is asked at boot, against the schema, not copied here ' +\n '(ADR-0072 decision 5)'\n })\n continue\n }\n\n warnings.push({\n code: 'tool-privilege-undeclared',\n params: { category: category.name, tool: spec.name, kind: spec.kind },\n message:\n `tool '${spec.name}' in category '${category.name}' declares no privilege of its own — ` +\n 'a tool that changes something says who may run it. What the doors it reaches require is a ' +\n \"separate question, answered at boot against the schema (`tool-door-not-in-schema`).\"\n })\n }\n\n if (categories.has(category.name)) {\n console.warn(\n `[board-ai/tool-registry] category '${category.name}' already registered — overwriting. ` +\n '(normal on a dev hot reload; in production it means the same category is registered twice)'\n )\n }\n\n // tool name 충돌 검사 — 다른 카테고리에 같은 name 있으면 거부\n const newNames = new Set(category.specs.map(s => s.name))\n for (const [otherName, other] of categories) {\n if (otherName === category.name) continue // 같은 카테고리 재등록은 덮어쓰기 OK\n for (const spec of other.specs) {\n if (newNames.has(spec.name)) {\n throw new Error(\n `[board-ai/tool-registry] tool name '${spec.name}' already registered in category ` +\n `'${otherName}', cannot register in '${category.name}'. tool names must be globally unique.`\n )\n }\n }\n }\n\n categories.set(category.name, category)\n}\n\n/**\n * 대화별 도구 노출 제한 — 허용 카테고리 목록.\n *\n * `undefined` 는 **제한 없음**(등록된 전부). 호스트가 목록을 주면 그 카테고리에 속한 spec 만\n * 정의·실행 대상이 된다. 정의를 숨기는 것만으로는 부족하다 — 모델이 이름을 추측하거나 옛 대화가\n * 재생되면 숨긴 도구도 호출되므로 **dispatch 조회(findToolSpec)에도 같은 목록을 넘겨야** 한다.\n */\nexport type ToolCategoryFilter = ReadonlyArray<string> | undefined\n\n/** 허용 목록에 든 카테고리인가. 목록 없음 = 전부 허용. */\nfunction allowed(name: string, filter: ToolCategoryFilter): boolean {\n return !filter || filter.includes(name)\n}\n\n/**\n * 등록된 모든 카테고리 (등록 순서 보존). 외부에서 불변 read-only 로 사용.\n */\nexport function getToolCategories(): ReadonlyArray<ToolCategory> {\n return Array.from(categories.values())\n}\n\n/**\n * 등록된 모든 tool spec 의 평면 view. assistant.ts 의 buildBoardEditTools 가\n * LLM tool 정의 합집합으로 사용.\n */\nexport function getAllToolSpecs(): ReadonlyArray<ToolSpec> {\n return getToolSpecsFor(undefined)\n}\n\n/**\n * 허용 카테고리의 spec 평면 view. `undefined` = 전부(= getAllToolSpecs 와 동일).\n * LLM 도구 정의를 만들 때 이 함수를 쓰면 대화별 노출 제한이 그대로 반영된다.\n */\nexport function getToolSpecsFor(filter: ToolCategoryFilter): ReadonlyArray<ToolSpec> {\n const out: ToolSpec[] = []\n for (const [catName, cat] of categories) {\n if (!allowed(catName, filter)) continue\n for (const spec of cat.specs) out.push(spec)\n }\n return out\n}\n\n/**\n * 노출된 카테고리들의 **사용 규율** 모음(등록 순서). 시스템 프롬프트에 붙이는 용도.\n *\n * 도구 목록만 보내면 모델은 \"무엇이 있는지\" 는 알지만 \"언제 반드시 불러야 하는지\" 는 모른다.\n * 규율은 도구를 등록한 쪽이 소유하고, 호스트는 노출된 것만 모아 붙인다(도메인 지식이 새지 않는다).\n */\nexport function getCategoryGuidance(filter: ToolCategoryFilter): string[] {\n const out: string[] = []\n for (const [catName, cat] of categories) {\n if (!allowed(catName, filter)) continue\n const guidance = (cat.guidance ?? '').trim()\n if (guidance) out.push(guidance)\n }\n return out\n}\n\n/**\n * tool name 으로 spec 검색. 없으면 undefined.\n */\nexport function findToolSpec(name: string, filter?: ToolCategoryFilter): ToolSpec | undefined {\n for (const [catName, cat] of categories) {\n if (!allowed(catName, filter)) continue\n const spec = cat.specs.find(s => s.name === name)\n if (spec) return spec\n }\n return undefined\n}\n\n/**\n * tool name 의 카테고리 (read/write/action/external). 미등록 tool 은 undefined.\n * assistant.ts 의 isReadTool / isWriteTool / isActionTool 이 이 함수에 위임할 수 있다.\n */\nexport function getToolKind(name: string, filter?: ToolCategoryFilter): ToolSpec['kind'] | undefined {\n return findToolSpec(name, filter)?.kind\n}\n\n/**\n * 등록된 tool 인지. dispatch path 가 hardcoded set 와 registry 양쪽 fallback 시 사용.\n */\nexport function hasTool(name: string, filter?: ToolCategoryFilter): boolean {\n return findToolSpec(name, filter) !== undefined\n}\n\n/**\n * 카테고리 이름으로 spec 만 추출.\n */\nexport function getCategorySpecs(categoryName: string): ReadonlyArray<ToolSpec> {\n return categories.get(categoryName)?.specs ?? []\n}\n\n/**\n * 테스트 전용 — 모든 등록 해제. 운영 환경에서 호출 금지.\n *\n * jest 의 setupFilesAfterEach 또는 명시적 afterEach 에서 호출해 테스트 간 격리.\n * 실제로 STYLING_TOOLS 는 board-ai 자체 부트스트랩에서 다시 등록되므로 clear 후\n * 명시 register 가 필요한 것은 동적 카테고리 (board-import 등) 뿐.\n */\nexport function clearToolRegistry(): void {\n categories.clear()\n warnings.length = 0\n}\n"]}
|
|
@@ -130,10 +130,34 @@ export interface ToolSpecBase {
|
|
|
130
130
|
* The privilege a caller needs before this tool is offered or run. See `ToolPrivilege`.
|
|
131
131
|
*
|
|
132
132
|
* Expected for `write`, `action` and `external` — registration records a
|
|
133
|
-
* `tool-privilege-undeclared` warning for one without it (A1 stage one).
|
|
134
|
-
* offered on domain membership alone, and its builder must check what it reads.
|
|
133
|
+
* `tool-privilege-undeclared` warning for one without it (A1 stage one).
|
|
135
134
|
*/
|
|
136
135
|
privilege?: ToolPrivilege;
|
|
136
|
+
/**
|
|
137
|
+
* Which GraphQL doors this tool reaches — `['Query.twinNow']`,
|
|
138
|
+
* `['Query.productionSummary', 'Query.pendingSummary']`.
|
|
139
|
+
*
|
|
140
|
+
* **A read tool names its doors too** (ADR-0071 decision 2, shaped by ADR-0072). Before that,
|
|
141
|
+
* only plant's tools asked whether the caller may read what they read; twin's and figure's
|
|
142
|
+
* checked the tenant and nothing else, so holding the conversation's own privilege was enough to
|
|
143
|
+
* reach their business data.
|
|
144
|
+
*
|
|
145
|
+
* **Always a list, even for one** — one shape to read. A tool that answers from several doors
|
|
146
|
+
* needs the caller to hold **all** of them (AND, the same reading as AUTH's `requiresAll`):
|
|
147
|
+
* plant's factory overview answers from two, and asking for only one of them would hand back
|
|
148
|
+
* half of what the caller may not see.
|
|
149
|
+
*
|
|
150
|
+
* Three states, and the boot report keeps them apart:
|
|
151
|
+
* - doors and a privilege — the gate checks it
|
|
152
|
+
* - `doors: []` — this tool reaches no door at all. The ones that hand back what the surface
|
|
153
|
+
* sent (`getOpenScene`, `getStationScreen`) are this: there is nothing behind them to gate.
|
|
154
|
+
* - doors with no privilege — the doors themselves declare none yet (twin's queries, waiting
|
|
155
|
+
* on AUTH stage two). A tool cannot be stricter than the door it reaches.
|
|
156
|
+
*
|
|
157
|
+
* The privilege is **the door's**, copied, and a test in each app compares the copy with the
|
|
158
|
+
* directive on that field. When the schema can be read at boot, the copy goes away.
|
|
159
|
+
*/
|
|
160
|
+
doors?: string[];
|
|
137
161
|
}
|
|
138
162
|
export interface ReadToolSpec extends ToolSpecBase {
|
|
139
163
|
kind: 'read';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../server/service/tool-registry/types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,uEAAuE;AACvE,kEAAkE;AAClE,iFAAiF;AACjF,mEAAmE;AACnE,wDAAwD","sourcesContent":["/**\n * Tool Registry — board-ai 의 LLM tool 노출 plugin point.\n *\n * 동기:\n * 기존엔 board-ai 가 자기 도메인 (board edit) tool 들만 hardcoded 정의했고, styling\n * 영역만 STYLING_TOOLS registry 로 분리되어 있었다. 외부 도메인 패키지 (board-import,\n * fmsim 등) 가 자기 tool 을 LLM 에 노출하려면 board-ai 자체를 fork/수정해야 했다.\n *\n * 본 registry 는 외부 패키지가 server bootstrap 시 자기 tool category 를 등록하면\n * assistant.ts 의 buildBoardEditTools / dispatch / isWriteTool 등이 자동으로 통합\n * 하도록 한다. styling-tools 의 single-source-of-truth 패턴을 일반화한 형태.\n *\n * 설계 원칙:\n * - **카테고리별 builder 시그니처 다양성을 통합**: read 는 (args, ctx) → any,\n * write 는 (args, components) → SceneEditOp[], action 은 (args) → SceneActionOp.\n * 하나의 ToolSpec 에 모든 시그니처를 union 으로 담지 않고, 카테고리에 맞는\n * builder 만 채우면 되도록 카테고리별 sub-interface 분리.\n * - **kind 필드로 자가 분류**: registry 가 isReadTool / isWriteTool 자동 도출.\n * hardcoded set 동기화 누락 위험 제거.\n * - **점진 마이그레이션**: 기존 STYLING_TOOLS 가 본 registry 의 첫 사용자.\n * 점진적으로 다른 hardcoded tool 들 (addComponent / alignComponents 등) 도\n * 같은 registry 로 흡수 가능. 한 단계씩 byte-단위 동등성 단위 테스트 보장.\n */\n// 본 registry 는 LLM tool 노출 plugin point 에 한정되므로 도메인 type (SceneEditOp,\n// SceneActionOp 등) 은 알지 않는다. builder return 은 unknown 으로 두고, 카테고리\n// dispatcher (board-ai 의 toolCallToSceneEditOp / toolCallToSceneActionOp 등) 가 자기\n// 도메인 type 으로 좁힌다. 사용자가 ToolSpec<TWrite, TAction> generic 까지 정밀화하면\n// 좋겠지만, 11~50 개 spec 마다 type 인자 전파가 부담이라 unknown 으로 합의.\n\n// ── ToolCallContext — what the neutral conversation door hands a registered tool (A3) ──\n\n/**\n * What `registryAssistantChat` — the door apps use (`assistantChat`, ADR-0061 decision 0) — hands a\n * registered tool when it runs.\n *\n * `state` and `host` sit side by side. The twin's space tools read `ctx.state.host` while this door\n * passed `ctx.host`, so they never saw the space; the two are never merged into one object.\n *\n * The board product's door (board-ai) passes its own shape and is not part of this contract.\n */\nexport interface ToolCallContext {\n /** The request state the server built — domain, user, tx. The only basis for authorization. */\n state: any\n /**\n * The client's `AssistantMode.hostContext`, passed through as is. **Untrusted** — a tool that reads\n * an id from it checks that the id belongs to the caller's tenant. `{}` when none was sent.\n */\n host: Record<string, any>\n /** The conversation's mode. Filled once modes are registered on the server (A2); absent until then. */\n mode?: ToolCallMode\n}\n\nexport interface ToolCallMode {\n kind: string\n target?: string\n}\n\n// ── 카테고리별 builder 시그니처 ──────────────────────────────────────\n\n/**\n * Read tool — server 측 즉시 실행, 결과를 LLM 에 회신. board model 변경 X.\n * 예: getSelection / findComponents / importSession (query)\n */\nexport type ReadToolBuilder = (\n args: any,\n context: ReadToolContext\n) => any | Promise<any>\n\nexport interface ReadToolContext {\n /** 현재 board model — 일부 read tool 이 사용 (getSelection 등). */\n board?: any\n /** 현재 선택된 refids. */\n selectedRefids?: number[]\n /** 호출자 도메인 / 사용자 / 트랜잭션. registry 외부에서 주입. */\n state?: any\n /** 이외 주입은 카테고리별로 자유. tool 등록자가 type 좁힐 수 있도록 unknown 으로 보존. */\n [k: string]: any\n}\n/**\n * Write tool — domain edit op 발생. host 가 patch 적용 후 영속화.\n * 예: board-ai 의 addComponent / setFill / modifyBoard.\n *\n * builder 의 return type 은 unknown 으로 둔다 — 도메인별 dispatcher (예: board-ai 의\n * toolCallToSceneEditOp) 가 자기 EditOp[] 로 cast. ops/errors wrapper 형태도 동일 의미.\n */\nexport type WriteToolBuilder = (\n args: any,\n context: WriteToolContext\n) => any[] | { ops: any[]; errors?: string[] } | null\n\nexport interface WriteToolContext {\n components?: ReadonlyArray<any>\n [k: string]: any\n}\n/**\n * Action tool — ephemeral scene 조작 (select / center / fit / sceneMode).\n * board model 변경 X, undo 영향 X. host 가 별도 channel 로 적용.\n *\n * return type 은 unknown — 도메인별 dispatcher (예: board-ai 의 toolCallToSceneActionOp)\n * 가 자기 SceneActionOp 으로 cast.\n */\nexport type ActionToolBuilder = (args: any) => any | null\n\n/**\n * External-call tool — 외부 service / mutation / RPC 호출. 직접 board model 영향 X\n * (별도 entity 변경은 가능). 결과는 LLM 에 회신.\n *\n * board-import 의 importBoardAsync / materializeImportSession 같이 board-ai 외부\n * 도메인을 호출하는 tool 의 카테고리.\n */\nexport type ExternalToolBuilder = (\n args: any,\n context: ExternalToolContext\n) => any | Promise<any>\n\nexport interface ExternalToolContext {\n state?: any\n [k: string]: any\n}\n// ── ToolSpec — 카테고리별 변형 ──────────────────────────────────────\n\n/**\n * The privilege a tool requires — the same `category`/`privilege` the tool's GraphQL door declares\n * (`@privilege(category, privilege, owner?, super?)`), so the fields mirror `PrivilegeObject`.\n *\n * A tool is not a new door; it is another way into a door that already exists. A tool that creates\n * a Board goes through the privilege that creating a Board already needs. Minting an AI-only\n * privilege name would put two doors on one effect, and one of them would end up looser.\n */\nexport interface ToolPrivilege {\n category: string\n privilege: string\n /** Domain owners pass without the privilege — mirror the door's `domainOwnerGranted`. */\n owner?: boolean\n /** Super users pass without the privilege — mirror the door's `superUserGranted`. */\n super?: boolean\n}\n\n/**\n * 모든 ToolSpec 공통 메타데이터.\n */\nexport interface ToolSpecBase {\n /** AIToolCall.name 매칭. 전 카테고리 통틀어 unique. */\n name: string\n /** 기능 설명 (영문 위주). LLM 의 tool description 으로 사용. */\n description: string\n /**\n * 선택 — 정책 / 테마 가이드 단문. tool description 끝에 자동 부착.\n * styling-tools 의 themeNote 와 동일 의미. 기타 카테고리도 사용 가능.\n */\n themeNote?: string\n /** JSON Schema for parameters — LLM tool schema 에 그대로 노출. */\n schema: any\n /**\n * The privilege a caller needs before this tool is offered or run. See `ToolPrivilege`.\n *\n * Expected for `write`, `action` and `external` — registration records a\n * `tool-privilege-undeclared` warning for one without it (A1 stage one). A
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../server/service/tool-registry/types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,uEAAuE;AACvE,kEAAkE;AAClE,iFAAiF;AACjF,mEAAmE;AACnE,wDAAwD","sourcesContent":["/**\n * Tool Registry — board-ai 의 LLM tool 노출 plugin point.\n *\n * 동기:\n * 기존엔 board-ai 가 자기 도메인 (board edit) tool 들만 hardcoded 정의했고, styling\n * 영역만 STYLING_TOOLS registry 로 분리되어 있었다. 외부 도메인 패키지 (board-import,\n * fmsim 등) 가 자기 tool 을 LLM 에 노출하려면 board-ai 자체를 fork/수정해야 했다.\n *\n * 본 registry 는 외부 패키지가 server bootstrap 시 자기 tool category 를 등록하면\n * assistant.ts 의 buildBoardEditTools / dispatch / isWriteTool 등이 자동으로 통합\n * 하도록 한다. styling-tools 의 single-source-of-truth 패턴을 일반화한 형태.\n *\n * 설계 원칙:\n * - **카테고리별 builder 시그니처 다양성을 통합**: read 는 (args, ctx) → any,\n * write 는 (args, components) → SceneEditOp[], action 은 (args) → SceneActionOp.\n * 하나의 ToolSpec 에 모든 시그니처를 union 으로 담지 않고, 카테고리에 맞는\n * builder 만 채우면 되도록 카테고리별 sub-interface 분리.\n * - **kind 필드로 자가 분류**: registry 가 isReadTool / isWriteTool 자동 도출.\n * hardcoded set 동기화 누락 위험 제거.\n * - **점진 마이그레이션**: 기존 STYLING_TOOLS 가 본 registry 의 첫 사용자.\n * 점진적으로 다른 hardcoded tool 들 (addComponent / alignComponents 등) 도\n * 같은 registry 로 흡수 가능. 한 단계씩 byte-단위 동등성 단위 테스트 보장.\n */\n// 본 registry 는 LLM tool 노출 plugin point 에 한정되므로 도메인 type (SceneEditOp,\n// SceneActionOp 등) 은 알지 않는다. builder return 은 unknown 으로 두고, 카테고리\n// dispatcher (board-ai 의 toolCallToSceneEditOp / toolCallToSceneActionOp 등) 가 자기\n// 도메인 type 으로 좁힌다. 사용자가 ToolSpec<TWrite, TAction> generic 까지 정밀화하면\n// 좋겠지만, 11~50 개 spec 마다 type 인자 전파가 부담이라 unknown 으로 합의.\n\n// ── ToolCallContext — what the neutral conversation door hands a registered tool (A3) ──\n\n/**\n * What `registryAssistantChat` — the door apps use (`assistantChat`, ADR-0061 decision 0) — hands a\n * registered tool when it runs.\n *\n * `state` and `host` sit side by side. The twin's space tools read `ctx.state.host` while this door\n * passed `ctx.host`, so they never saw the space; the two are never merged into one object.\n *\n * The board product's door (board-ai) passes its own shape and is not part of this contract.\n */\nexport interface ToolCallContext {\n /** The request state the server built — domain, user, tx. The only basis for authorization. */\n state: any\n /**\n * The client's `AssistantMode.hostContext`, passed through as is. **Untrusted** — a tool that reads\n * an id from it checks that the id belongs to the caller's tenant. `{}` when none was sent.\n */\n host: Record<string, any>\n /** The conversation's mode. Filled once modes are registered on the server (A2); absent until then. */\n mode?: ToolCallMode\n}\n\nexport interface ToolCallMode {\n kind: string\n target?: string\n}\n\n// ── 카테고리별 builder 시그니처 ──────────────────────────────────────\n\n/**\n * Read tool — server 측 즉시 실행, 결과를 LLM 에 회신. board model 변경 X.\n * 예: getSelection / findComponents / importSession (query)\n */\nexport type ReadToolBuilder = (\n args: any,\n context: ReadToolContext\n) => any | Promise<any>\n\nexport interface ReadToolContext {\n /** 현재 board model — 일부 read tool 이 사용 (getSelection 등). */\n board?: any\n /** 현재 선택된 refids. */\n selectedRefids?: number[]\n /** 호출자 도메인 / 사용자 / 트랜잭션. registry 외부에서 주입. */\n state?: any\n /** 이외 주입은 카테고리별로 자유. tool 등록자가 type 좁힐 수 있도록 unknown 으로 보존. */\n [k: string]: any\n}\n/**\n * Write tool — domain edit op 발생. host 가 patch 적용 후 영속화.\n * 예: board-ai 의 addComponent / setFill / modifyBoard.\n *\n * builder 의 return type 은 unknown 으로 둔다 — 도메인별 dispatcher (예: board-ai 의\n * toolCallToSceneEditOp) 가 자기 EditOp[] 로 cast. ops/errors wrapper 형태도 동일 의미.\n */\nexport type WriteToolBuilder = (\n args: any,\n context: WriteToolContext\n) => any[] | { ops: any[]; errors?: string[] } | null\n\nexport interface WriteToolContext {\n components?: ReadonlyArray<any>\n [k: string]: any\n}\n/**\n * Action tool — ephemeral scene 조작 (select / center / fit / sceneMode).\n * board model 변경 X, undo 영향 X. host 가 별도 channel 로 적용.\n *\n * return type 은 unknown — 도메인별 dispatcher (예: board-ai 의 toolCallToSceneActionOp)\n * 가 자기 SceneActionOp 으로 cast.\n */\nexport type ActionToolBuilder = (args: any) => any | null\n\n/**\n * External-call tool — 외부 service / mutation / RPC 호출. 직접 board model 영향 X\n * (별도 entity 변경은 가능). 결과는 LLM 에 회신.\n *\n * board-import 의 importBoardAsync / materializeImportSession 같이 board-ai 외부\n * 도메인을 호출하는 tool 의 카테고리.\n */\nexport type ExternalToolBuilder = (\n args: any,\n context: ExternalToolContext\n) => any | Promise<any>\n\nexport interface ExternalToolContext {\n state?: any\n [k: string]: any\n}\n// ── ToolSpec — 카테고리별 변형 ──────────────────────────────────────\n\n/**\n * The privilege a tool requires — the same `category`/`privilege` the tool's GraphQL door declares\n * (`@privilege(category, privilege, owner?, super?)`), so the fields mirror `PrivilegeObject`.\n *\n * A tool is not a new door; it is another way into a door that already exists. A tool that creates\n * a Board goes through the privilege that creating a Board already needs. Minting an AI-only\n * privilege name would put two doors on one effect, and one of them would end up looser.\n */\nexport interface ToolPrivilege {\n category: string\n privilege: string\n /** Domain owners pass without the privilege — mirror the door's `domainOwnerGranted`. */\n owner?: boolean\n /** Super users pass without the privilege — mirror the door's `superUserGranted`. */\n super?: boolean\n}\n\n/**\n * 모든 ToolSpec 공통 메타데이터.\n */\nexport interface ToolSpecBase {\n /** AIToolCall.name 매칭. 전 카테고리 통틀어 unique. */\n name: string\n /** 기능 설명 (영문 위주). LLM 의 tool description 으로 사용. */\n description: string\n /**\n * 선택 — 정책 / 테마 가이드 단문. tool description 끝에 자동 부착.\n * styling-tools 의 themeNote 와 동일 의미. 기타 카테고리도 사용 가능.\n */\n themeNote?: string\n /** JSON Schema for parameters — LLM tool schema 에 그대로 노출. */\n schema: any\n /**\n * The privilege a caller needs before this tool is offered or run. See `ToolPrivilege`.\n *\n * Expected for `write`, `action` and `external` — registration records a\n * `tool-privilege-undeclared` warning for one without it (A1 stage one).\n */\n privilege?: ToolPrivilege\n\n /**\n * Which GraphQL doors this tool reaches — `['Query.twinNow']`,\n * `['Query.productionSummary', 'Query.pendingSummary']`.\n *\n * **A read tool names its doors too** (ADR-0071 decision 2, shaped by ADR-0072). Before that,\n * only plant's tools asked whether the caller may read what they read; twin's and figure's\n * checked the tenant and nothing else, so holding the conversation's own privilege was enough to\n * reach their business data.\n *\n * **Always a list, even for one** — one shape to read. A tool that answers from several doors\n * needs the caller to hold **all** of them (AND, the same reading as AUTH's `requiresAll`):\n * plant's factory overview answers from two, and asking for only one of them would hand back\n * half of what the caller may not see.\n *\n * Three states, and the boot report keeps them apart:\n * - doors and a privilege — the gate checks it\n * - `doors: []` — this tool reaches no door at all. The ones that hand back what the surface\n * sent (`getOpenScene`, `getStationScreen`) are this: there is nothing behind them to gate.\n * - doors with no privilege — the doors themselves declare none yet (twin's queries, waiting\n * on AUTH stage two). A tool cannot be stricter than the door it reaches.\n *\n * The privilege is **the door's**, copied, and a test in each app compares the copy with the\n * directive on that field. When the schema can be read at boot, the copy goes away.\n */\n doors?: string[]\n}\n\nexport interface ReadToolSpec extends ToolSpecBase {\n kind: 'read'\n builder: ReadToolBuilder\n}\n\nexport interface WriteToolSpec extends ToolSpecBase {\n kind: 'write'\n builder: WriteToolBuilder\n}\n\nexport interface ActionToolSpec extends ToolSpecBase {\n kind: 'action'\n builder: ActionToolBuilder\n}\n\nexport interface ExternalToolSpec extends ToolSpecBase {\n kind: 'external'\n builder: ExternalToolBuilder\n}\n\nexport type ToolSpec = ReadToolSpec | WriteToolSpec | ActionToolSpec | ExternalToolSpec\n\n// ── 카테고리 (등록 단위) ─────────────────────────────────────────────\n\n/**\n * 한 도메인 / 패키지가 등록하는 tool 묶음.\n * 카테고리 이름은 식별자 (debug log / 분쟁 시 origin 추적). unique.\n */\nexport interface ToolCategory {\n /** 등록 식별자. 예: 'styling', 'board-import', 'fmsim'. */\n name: string\n /** 이 카테고리에 속한 tool spec 들. */\n specs: ToolSpec[]\n /** 선택 — 디버깅용 짧은 설명. */\n description?: string\n /**\n * 이 카테고리 도구를 **어떻게 써야 하는지**에 대한 규율 — 노출된 대화의 시스템 프롬프트에 실린다.\n *\n * 왜 필요한가: 도구 목록(이름·설명·스키마)만 보내면 모델은 \"무엇이 있는지\" 는 알지만 \"언제 반드시\n * 불러야 하는지\" 는 모른다. 실제로 그 공백에서 사고가 났다 — 조치 요청에 `proposeAction` 을 부르지\n * 않고 \"제안해 두었습니다\" 라고만 답해, 사용자에게는 없는 버튼을 누르라고 안내했다.\n *\n * 규율은 도구를 등록한 쪽이 소유한다. 호스트(board-ai)는 도메인을 모르는 채 **노출된 카테고리의\n * 규율만 모아 붙인다** — 도메인 지식이 호스트 프롬프트로 새지 않는다.\n *\n * ── 왜 필수인가 (2026-09-09) ──────────────────────────────────────────────\n * 선택 필드였다. 그래서 위에 적힌 사고를 아는 사람만 채웠고, 세 제품이 각자 도구를 붙이기\n * 시작한 지금 **채운 넷과 안 채운 하나**가 있었다.\n *\n * 안 채운 쪽은 조용하다 — 등록은 성공하고 부팅도 성공하고, 모델이 도구를 덜 부르거나 지어낸\n * 뒤에 사람이 화면을 보고 안다. **두 개를 기억해야 성립하는 규칙은 다음 새 카테고리까지만\n * 간다.** 그래서 기억이 아니라 등록이 거절한다(§`registerToolCategory`).\n *\n * 빈 문자열도 거절한다. 「없음」을 「적었다」로 위장하는 값이 통과하면 이 강제가 형식이 된다.\n */\n guidance: string\n}\n"]}
|