@things-factory/ai-client-base 10.1.3 → 10.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist-server/service/assistant/abort-notice.d.ts +7 -0
- package/dist-server/service/assistant/abort-notice.js +29 -0
- package/dist-server/service/assistant/abort-notice.js.map +1 -0
- package/dist-server/service/assistant/assistant-chat.d.ts +41 -0
- package/dist-server/service/assistant/assistant-chat.js +63 -0
- package/dist-server/service/assistant/assistant-chat.js.map +1 -0
- package/dist-server/service/assistant/index.d.ts +4 -0
- package/dist-server/service/assistant/index.js +13 -0
- package/dist-server/service/assistant/index.js.map +1 -0
- package/dist-server/service/assistant/registry-gate.d.ts +31 -0
- package/dist-server/service/assistant/registry-gate.js +61 -0
- package/dist-server/service/assistant/registry-gate.js.map +1 -0
- package/dist-server/service/assistant/summarize.d.ts +7 -0
- package/dist-server/service/assistant/summarize.js +67 -0
- package/dist-server/service/assistant/summarize.js.map +1 -0
- package/dist-server/service/index.d.ts +1 -0
- package/dist-server/service/index.js +1 -0
- package/dist-server/service/index.js.map +1 -1
- package/dist-server/service/tool-registry/registry.js +19 -0
- package/dist-server/service/tool-registry/registry.js.map +1 -1
- package/dist-server/service/tool-registry/types.d.ts +11 -1
- package/dist-server/service/tool-registry/types.js.map +1 -1
- package/dist-server/service/utils/grounding.d.ts +25 -2
- package/dist-server/service/utils/grounding.js +44 -8
- package/dist-server/service/utils/grounding.js.map +1 -1
- package/dist-server/tsconfig.tsbuildinfo +1 -1
- package/package.json +2 -2
- package/server/service/assistant/abort-notice.ts +44 -0
- package/server/service/assistant/assistant-chat.test.ts +218 -0
- package/server/service/assistant/assistant-chat.ts +99 -0
- package/server/service/assistant/index.ts +9 -0
- package/server/service/assistant/registry-gate.ts +76 -0
- package/server/service/assistant/summarize.ts +61 -0
- package/server/service/index.ts +1 -0
- package/server/service/tool-registry/registry.test.ts +59 -4
- package/server/service/tool-registry/registry.ts +22 -0
- package/server/service/tool-registry/types.ts +11 -1
- package/server/service/utils/grounding.test.ts +49 -0
- package/server/service/utils/grounding.ts +74 -8
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { AgenticLoopResult } from '../agentic-loop/index.js';
|
|
2
|
+
/**
|
|
3
|
+
* 중단 이유 → 답에 덧붙일 한 줄. 정상 종료면 빈 문자열이다.
|
|
4
|
+
*
|
|
5
|
+
* 답을 고치지 않고 **뒤에 붙인다** — 모델이 한 말을 우리가 다시 쓰지 않는다.
|
|
6
|
+
*/
|
|
7
|
+
export declare function formatAbortNotice(abortReason: AgenticLoopResult<any>['abortReason']): string;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.formatAbortNotice = formatAbortNotice;
|
|
4
|
+
const index_js_1 = require("../utils/index.js");
|
|
5
|
+
/**
|
|
6
|
+
* 중단 이유 → 답에 덧붙일 한 줄. 정상 종료면 빈 문자열이다.
|
|
7
|
+
*
|
|
8
|
+
* 답을 고치지 않고 **뒤에 붙인다** — 모델이 한 말을 우리가 다시 쓰지 않는다.
|
|
9
|
+
*/
|
|
10
|
+
function formatAbortNotice(abortReason) {
|
|
11
|
+
if (!abortReason)
|
|
12
|
+
return '';
|
|
13
|
+
switch (abortReason.type) {
|
|
14
|
+
case 'aborted':
|
|
15
|
+
return '\n\n_(요청이 중단되어 일부만 처리됐어요.)_';
|
|
16
|
+
case 'provider_error':
|
|
17
|
+
/* 남의 말(SDK 원문)을 사용자에게 보여주지 않는다 — "Error fetching from undefined: [503 …]" 은
|
|
18
|
+
* 사용자가 할 수 있는 일을 알려주지 않는다. 일시 장애는 이미 몇 번 다시 시도한 뒤이므로,
|
|
19
|
+
* 지금 필요한 안내는 "잠시 후 다시" 하나다. 원문은 서버 로그에 남는다. */
|
|
20
|
+
return (0, index_js_1.isTransientAIError)({ message: abortReason.message })
|
|
21
|
+
? '\n\n_(AI 서비스가 일시적으로 응답하지 않았어요. 잠시 후 다시 시도해 주세요.)_'
|
|
22
|
+
: '\n\n_(처리 중 오류가 발생했어요. 같은 요청이 계속 실패하면 관리자에게 알려 주세요.)_';
|
|
23
|
+
case 'max_iterations':
|
|
24
|
+
return `\n\n_(작업이 너무 길어 ${abortReason.iter}회에서 중단했어요. 더 작게 나눠 요청해보세요.)_`;
|
|
25
|
+
case 'repeated_validation_failure':
|
|
26
|
+
return `\n\n_(\`${abortReason.toolName}\` 호출이 ${abortReason.consecutive}회 연속 실패해 중단했어요. 요청을 다시 표현해보세요.)_`;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
//# sourceMappingURL=abort-notice.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"abort-notice.js","sourceRoot":"","sources":["../../../server/service/assistant/abort-notice.ts"],"names":[],"mappings":";;AA0BA,8CAiBC;AAxBD,gDAAsD;AAEtD;;;;GAIG;AACH,SAAgB,iBAAiB,CAAC,WAAkD;IAClF,IAAI,CAAC,WAAW;QAAE,OAAO,EAAE,CAAA;IAC3B,QAAQ,WAAW,CAAC,IAAI,EAAE,CAAC;QACzB,KAAK,SAAS;YACZ,OAAO,6BAA6B,CAAA;QACtC,KAAK,gBAAgB;YACnB;;2DAE+C;YAC/C,OAAO,IAAA,6BAAkB,EAAC,EAAE,OAAO,EAAE,WAAW,CAAC,OAAO,EAAE,CAAC;gBACzD,CAAC,CAAC,mDAAmD;gBACrD,CAAC,CAAC,sDAAsD,CAAA;QAC5D,KAAK,gBAAgB;YACnB,OAAO,mBAAmB,WAAW,CAAC,IAAI,8BAA8B,CAAA;QAC1E,KAAK,6BAA6B;YAChC,OAAO,WAAW,WAAW,CAAC,QAAQ,UAAU,WAAW,CAAC,WAAW,kCAAkC,CAAA;IAC7G,CAAC;AACH,CAAC","sourcesContent":["/*\n * Why the loop stopped, said to the person who asked.\n *\n * ── Why this is here and not in a product (2026-09-10) ───────────────────────────\n * This came out of `board-ai`. It is not board's: every product that runs the agentic loop can\n * have it stop early, and a reply that was cut off looks exactly like a reply that finished.\n *\n * The loop already reports why it stopped — `AgenticLoopResult.abortReason`. Nothing forces the\n * caller to say so. A product that forgets prints a truncated answer as though it were complete,\n * and the person acts on half of it. That failure is silent by construction, which is why the\n * notice belongs beside the loop rather than beside each product's prose.\n *\n * ── Known debt: the strings are Korean ─────────────────────────────────────────\n * They were Korean in board-ai and they still are. Moving them does not make that worse, but a\n * framework package is the wrong home for untranslated user-facing text. When this needs a second\n * locale, the shape is a caller-supplied translator, not a table in here — the notice is one line\n * appended to a reply the product already owns.\n */\nimport type { AgenticLoopResult } from '../agentic-loop/index.js'\nimport { isTransientAIError } from '../utils/index.js'\n\n/**\n * 중단 이유 → 답에 덧붙일 한 줄. 정상 종료면 빈 문자열이다.\n *\n * 답을 고치지 않고 **뒤에 붙인다** — 모델이 한 말을 우리가 다시 쓰지 않는다.\n */\nexport function formatAbortNotice(abortReason: AgenticLoopResult<any>['abortReason']): string {\n if (!abortReason) return ''\n switch (abortReason.type) {\n case 'aborted':\n return '\\n\\n_(요청이 중단되어 일부만 처리됐어요.)_'\n case 'provider_error':\n /* 남의 말(SDK 원문)을 사용자에게 보여주지 않는다 — \"Error fetching from undefined: [503 …]\" 은\n * 사용자가 할 수 있는 일을 알려주지 않는다. 일시 장애는 이미 몇 번 다시 시도한 뒤이므로,\n * 지금 필요한 안내는 \"잠시 후 다시\" 하나다. 원문은 서버 로그에 남는다. */\n return isTransientAIError({ message: abortReason.message })\n ? '\\n\\n_(AI 서비스가 일시적으로 응답하지 않았어요. 잠시 후 다시 시도해 주세요.)_'\n : '\\n\\n_(처리 중 오류가 발생했어요. 같은 요청이 계속 실패하면 관리자에게 알려 주세요.)_'\n case 'max_iterations':\n return `\\n\\n_(작업이 너무 길어 ${abortReason.iter}회에서 중단했어요. 더 작게 나눠 요청해보세요.)_`\n case 'repeated_validation_failure':\n return `\\n\\n_(\\`${abortReason.toolName}\\` 호출이 ${abortReason.consecutive}회 연속 실패해 중단했어요. 요청을 다시 표현해보세요.)_`\n }\n}\n"]}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { type AgenticLoopInput, type AgenticLoopResult } from '../agentic-loop/index.js';
|
|
2
|
+
import { type GroundingSources } from '../utils/index.js';
|
|
3
|
+
export interface AssistantChatInput<TCtx = unknown, TOp = unknown> extends AgenticLoopInput<TCtx, TOp> {
|
|
4
|
+
/**
|
|
5
|
+
* 이 턴에 모델이 본 것 — **도구 결과 말고** 전부. 도구 결과는 이 함수가 루프에서 받아 더한다.
|
|
6
|
+
*
|
|
7
|
+
* 빠뜨리면 정상 답이 경고를 받는다(오탐). 시스템 프롬프트에 적어 보낸 타입 이름을 모델이 말하는
|
|
8
|
+
* 것은 근거 있는 발언이다.
|
|
9
|
+
*/
|
|
10
|
+
groundingSources?: Omit<GroundingSources, 'toolResults'>;
|
|
11
|
+
/**
|
|
12
|
+
* 접지 검사를 끈다 — **기본은 켜짐.**
|
|
13
|
+
*
|
|
14
|
+
* 끄는 것이 맞는 자리가 있다: 식별자를 다루지 않는 대화(문서 상담·개념 질문)는 근거집합에 식별자가
|
|
15
|
+
* 없어 모든 고유명사가 경고로 나온다. 그때는 끄는 것이 정직하고, **켠 채로 경고를 버리는 것**이
|
|
16
|
+
* 정직하지 않다.
|
|
17
|
+
*/
|
|
18
|
+
skipGrounding?: boolean;
|
|
19
|
+
}
|
|
20
|
+
export interface AssistantChatResult<TOp = unknown> {
|
|
21
|
+
/**
|
|
22
|
+
* 사용자에게 보일 답 — 모델의 마지막 말 + 중단 통지.
|
|
23
|
+
*
|
|
24
|
+
* 모델의 말을 고치지 않는다. 통지는 **뒤에 붙는다.**
|
|
25
|
+
*/
|
|
26
|
+
reply: string;
|
|
27
|
+
/** 통지가 붙기 전의 답. 접지 검사가 본 것이고, 호스트가 다시 판정할 때 쓴다. */
|
|
28
|
+
baseText: string;
|
|
29
|
+
/** 근거 밖의 식별자를 지목한 자리들. 없으면 undefined — 빈 배열을 주지 않는다. */
|
|
30
|
+
groundingWarnings?: string[];
|
|
31
|
+
/** 루프 결과 원본 — 쓰기 호출·조치·제안·도구 흔적. 호스트가 자기 뜻으로 해석한다. */
|
|
32
|
+
loop: AgenticLoopResult<TOp>;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* 한 턴을 돌린다.
|
|
36
|
+
*
|
|
37
|
+
* `lastText` 가 없을 수 있다(도구만 부르고 말을 안 한 턴). 그 경우 `baseText` 는 빈 문자열이고,
|
|
38
|
+
* 무엇을 대신 말할지는 호스트가 정한다 — 여기서 「변경했습니다」 같은 말을 지어내지 않는다.
|
|
39
|
+
* 도메인을 모르는 자리에서 결과를 서술하면 그것이 곧 지어낸 원인이 된다.
|
|
40
|
+
*/
|
|
41
|
+
export declare function assistantChat<TCtx = unknown, TOp = unknown>(input: AssistantChatInput<TCtx, TOp>): Promise<AssistantChatResult<TOp>>;
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.assistantChat = assistantChat;
|
|
4
|
+
/*
|
|
5
|
+
* One turn of an assistant — the loop **with the guards that must not be optional.**
|
|
6
|
+
*
|
|
7
|
+
* ── Why this exists (2026-09-10) ────────────────────────────────────────────────
|
|
8
|
+
* `runAgenticLoop` is neutral and has been since 2026-09-05, when the same loop running in two
|
|
9
|
+
* places was consolidated. The note on that change is the reason this file exists: it was "not a
|
|
10
|
+
* duplication, a defect" — the two copies had **their safety measures set opposite ways**.
|
|
11
|
+
*
|
|
12
|
+
* The loop came out. The guards around it did not. They stayed in `board-ai`, wrapped around
|
|
13
|
+
* `DefaultBoardAIAssistant.chat`, which meant a product with no board of its own could only get
|
|
14
|
+
* them by going through the board editor. The plant lane read that correctly — it uses none of
|
|
15
|
+
* board's session machinery — and asked whether it could call `runAgenticLoop` directly instead.
|
|
16
|
+
*
|
|
17
|
+
* The answer was no, and the reason is written in `board-ai`'s own grounding file: the twin's
|
|
18
|
+
* header route had a grounding guard and its dock route did not, so **the same question was
|
|
19
|
+
* verified on one side and not the other.** A per-product door makes that three ways. This file is
|
|
20
|
+
* the door instead.
|
|
21
|
+
*
|
|
22
|
+
* ── What is guaranteed here, and what the host still owns ───────────────────────
|
|
23
|
+
* Guaranteed, because a caller cannot skip it:
|
|
24
|
+
* · the loop stops for a reason and the reason reaches the reply (`formatAbortNotice`)
|
|
25
|
+
* · the reply is checked against what the model was actually given (`groundingWarnings`)
|
|
26
|
+
*
|
|
27
|
+
* Still the host's, because only the host knows the domain:
|
|
28
|
+
* · which tools exist and what a write call means → `gate`, `dispatch`
|
|
29
|
+
* · what counts as evidence beyond the tool results → `groundingSources`
|
|
30
|
+
*
|
|
31
|
+
* ── Grounding sources: leaving one out produces false warnings ──────────────────
|
|
32
|
+
* The corpus is everything the model saw this turn. The tool results are added here, from
|
|
33
|
+
* `groundedTexts` — the raw strings sent back as `tool_result`, never `toolUsages[].result`, which
|
|
34
|
+
* is depth-limited for display. A check reading the display copy can pass while the model was
|
|
35
|
+
* handed `{}`; an un-awaited async builder did exactly that.
|
|
36
|
+
*
|
|
37
|
+
* Anything else the host put in front of the model — a system prompt, a state summary, the user's
|
|
38
|
+
* own words — has to be declared, or a correct answer quoting it gets warned about.
|
|
39
|
+
*/
|
|
40
|
+
const index_js_1 = require("../agentic-loop/index.js");
|
|
41
|
+
const index_js_2 = require("../utils/index.js");
|
|
42
|
+
const abort_notice_js_1 = require("./abort-notice.js");
|
|
43
|
+
/**
|
|
44
|
+
* 한 턴을 돌린다.
|
|
45
|
+
*
|
|
46
|
+
* `lastText` 가 없을 수 있다(도구만 부르고 말을 안 한 턴). 그 경우 `baseText` 는 빈 문자열이고,
|
|
47
|
+
* 무엇을 대신 말할지는 호스트가 정한다 — 여기서 「변경했습니다」 같은 말을 지어내지 않는다.
|
|
48
|
+
* 도메인을 모르는 자리에서 결과를 서술하면 그것이 곧 지어낸 원인이 된다.
|
|
49
|
+
*/
|
|
50
|
+
async function assistantChat(input) {
|
|
51
|
+
const { groundingSources, skipGrounding, ...loopInput } = input;
|
|
52
|
+
const loop = await (0, index_js_1.runAgenticLoop)(loopInput);
|
|
53
|
+
const baseText = loop.lastText ?? '';
|
|
54
|
+
const reply = baseText + (0, abort_notice_js_1.formatAbortNotice)(loop.abortReason);
|
|
55
|
+
let warnings;
|
|
56
|
+
if (!skipGrounding && baseText) {
|
|
57
|
+
const corpus = (0, index_js_2.buildGroundedCorpus)({ ...(groundingSources ?? {}), toolResults: loop.groundedTexts });
|
|
58
|
+
const found = (0, index_js_2.groundingWarnings)(baseText, corpus);
|
|
59
|
+
warnings = found.length > 0 ? found : undefined;
|
|
60
|
+
}
|
|
61
|
+
return { reply, baseText, groundingWarnings: warnings, loop };
|
|
62
|
+
}
|
|
63
|
+
//# sourceMappingURL=assistant-chat.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"assistant-chat.js","sourceRoot":"","sources":["../../../server/service/assistant/assistant-chat.ts"],"names":[],"mappings":";;AAgFA,sCAkBC;AAlGD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,uDAAwG;AACxG,gDAAiG;AACjG,uDAAqD;AAmCrD;;;;;;GAMG;AACI,KAAK,UAAU,aAAa,CACjC,KAAoC;IAEpC,MAAM,EAAE,gBAAgB,EAAE,aAAa,EAAE,GAAG,SAAS,EAAE,GAAG,KAAK,CAAA;IAE/D,MAAM,IAAI,GAAG,MAAM,IAAA,yBAAc,EAAY,SAAS,CAAC,CAAA;IAEvD,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,IAAI,EAAE,CAAA;IACpC,MAAM,KAAK,GAAG,QAAQ,GAAG,IAAA,mCAAiB,EAAC,IAAI,CAAC,WAAW,CAAC,CAAA;IAE5D,IAAI,QAA8B,CAAA;IAClC,IAAI,CAAC,aAAa,IAAI,QAAQ,EAAE,CAAC;QAC/B,MAAM,MAAM,GAAG,IAAA,8BAAmB,EAAC,EAAE,GAAG,CAAC,gBAAgB,IAAI,EAAE,CAAC,EAAE,WAAW,EAAE,IAAI,CAAC,aAAa,EAAE,CAAC,CAAA;QACpG,MAAM,KAAK,GAAG,IAAA,4BAAiB,EAAC,QAAQ,EAAE,MAAM,CAAC,CAAA;QACjD,QAAQ,GAAG,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAA;IACjD,CAAC;IAED,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,iBAAiB,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAA;AAC/D,CAAC","sourcesContent":["/*\n * One turn of an assistant — the loop **with the guards that must not be optional.**\n *\n * ── Why this exists (2026-09-10) ────────────────────────────────────────────────\n * `runAgenticLoop` is neutral and has been since 2026-09-05, when the same loop running in two\n * places was consolidated. The note on that change is the reason this file exists: it was \"not a\n * duplication, a defect\" — the two copies had **their safety measures set opposite ways**.\n *\n * The loop came out. The guards around it did not. They stayed in `board-ai`, wrapped around\n * `DefaultBoardAIAssistant.chat`, which meant a product with no board of its own could only get\n * them by going through the board editor. The plant lane read that correctly — it uses none of\n * board's session machinery — and asked whether it could call `runAgenticLoop` directly instead.\n *\n * The answer was no, and the reason is written in `board-ai`'s own grounding file: the twin's\n * header route had a grounding guard and its dock route did not, so **the same question was\n * verified on one side and not the other.** A per-product door makes that three ways. This file is\n * the door instead.\n *\n * ── What is guaranteed here, and what the host still owns ───────────────────────\n * Guaranteed, because a caller cannot skip it:\n * · the loop stops for a reason and the reason reaches the reply (`formatAbortNotice`)\n * · the reply is checked against what the model was actually given (`groundingWarnings`)\n *\n * Still the host's, because only the host knows the domain:\n * · which tools exist and what a write call means → `gate`, `dispatch`\n * · what counts as evidence beyond the tool results → `groundingSources`\n *\n * ── Grounding sources: leaving one out produces false warnings ──────────────────\n * The corpus is everything the model saw this turn. The tool results are added here, from\n * `groundedTexts` — the raw strings sent back as `tool_result`, never `toolUsages[].result`, which\n * is depth-limited for display. A check reading the display copy can pass while the model was\n * handed `{}`; an un-awaited async builder did exactly that.\n *\n * Anything else the host put in front of the model — a system prompt, a state summary, the user's\n * own words — has to be declared, or a correct answer quoting it gets warned about.\n */\nimport { runAgenticLoop, type AgenticLoopInput, type AgenticLoopResult } from '../agentic-loop/index.js'\nimport { buildGroundedCorpus, groundingWarnings, type GroundingSources } from '../utils/index.js'\nimport { formatAbortNotice } from './abort-notice.js'\n\nexport interface AssistantChatInput<TCtx = unknown, TOp = unknown> extends AgenticLoopInput<TCtx, TOp> {\n /**\n * 이 턴에 모델이 본 것 — **도구 결과 말고** 전부. 도구 결과는 이 함수가 루프에서 받아 더한다.\n *\n * 빠뜨리면 정상 답이 경고를 받는다(오탐). 시스템 프롬프트에 적어 보낸 타입 이름을 모델이 말하는\n * 것은 근거 있는 발언이다.\n */\n groundingSources?: Omit<GroundingSources, 'toolResults'>\n /**\n * 접지 검사를 끈다 — **기본은 켜짐.**\n *\n * 끄는 것이 맞는 자리가 있다: 식별자를 다루지 않는 대화(문서 상담·개념 질문)는 근거집합에 식별자가\n * 없어 모든 고유명사가 경고로 나온다. 그때는 끄는 것이 정직하고, **켠 채로 경고를 버리는 것**이\n * 정직하지 않다.\n */\n skipGrounding?: boolean\n}\n\nexport interface AssistantChatResult<TOp = unknown> {\n /**\n * 사용자에게 보일 답 — 모델의 마지막 말 + 중단 통지.\n *\n * 모델의 말을 고치지 않는다. 통지는 **뒤에 붙는다.**\n */\n reply: string\n /** 통지가 붙기 전의 답. 접지 검사가 본 것이고, 호스트가 다시 판정할 때 쓴다. */\n baseText: string\n /** 근거 밖의 식별자를 지목한 자리들. 없으면 undefined — 빈 배열을 주지 않는다. */\n groundingWarnings?: string[]\n /** 루프 결과 원본 — 쓰기 호출·조치·제안·도구 흔적. 호스트가 자기 뜻으로 해석한다. */\n loop: AgenticLoopResult<TOp>\n}\n\n/**\n * 한 턴을 돌린다.\n *\n * `lastText` 가 없을 수 있다(도구만 부르고 말을 안 한 턴). 그 경우 `baseText` 는 빈 문자열이고,\n * 무엇을 대신 말할지는 호스트가 정한다 — 여기서 「변경했습니다」 같은 말을 지어내지 않는다.\n * 도메인을 모르는 자리에서 결과를 서술하면 그것이 곧 지어낸 원인이 된다.\n */\nexport async function assistantChat<TCtx = unknown, TOp = unknown>(\n input: AssistantChatInput<TCtx, TOp>\n): Promise<AssistantChatResult<TOp>> {\n const { groundingSources, skipGrounding, ...loopInput } = input\n\n const loop = await runAgenticLoop<TCtx, TOp>(loopInput)\n\n const baseText = loop.lastText ?? ''\n const reply = baseText + formatAbortNotice(loop.abortReason)\n\n let warnings: string[] | undefined\n if (!skipGrounding && baseText) {\n const corpus = buildGroundedCorpus({ ...(groundingSources ?? {}), toolResults: loop.groundedTexts })\n const found = groundingWarnings(baseText, corpus)\n warnings = found.length > 0 ? found : undefined\n }\n\n return { reply, baseText, groundingWarnings: warnings, loop }\n}\n"]}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const tslib_1 = require("tslib");
|
|
4
|
+
/*
|
|
5
|
+
* The neutral assistant layer — the agentic loop plus the guards that must not be optional.
|
|
6
|
+
*
|
|
7
|
+
* See `assistant-chat.ts` for why this is not in a product package.
|
|
8
|
+
*/
|
|
9
|
+
tslib_1.__exportStar(require("./abort-notice.js"), exports);
|
|
10
|
+
tslib_1.__exportStar(require("./summarize.js"), exports);
|
|
11
|
+
tslib_1.__exportStar(require("./registry-gate.js"), exports);
|
|
12
|
+
tslib_1.__exportStar(require("./assistant-chat.js"), exports);
|
|
13
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../server/service/assistant/index.ts"],"names":[],"mappings":";;;AAAA;;;;GAIG;AACH,4DAAiC;AACjC,yDAA8B;AAC9B,6DAAkC;AAClC,8DAAmC","sourcesContent":["/*\n * The neutral assistant layer — the agentic loop plus the guards that must not be optional.\n *\n * See `assistant-chat.ts` for why this is not in a product package.\n */\nexport * from './abort-notice.js'\nexport * from './summarize.js'\nexport * from './registry-gate.js'\nexport * from './assistant-chat.js'\n"]}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { type ToolCategoryFilter, type ToolSpec } from '../tool-registry/index.js';
|
|
2
|
+
/** 이름 하나에 대한 판정. 정의 조립과 dispatch 가 **같은 것**을 쓴다. */
|
|
3
|
+
export interface ToolGate {
|
|
4
|
+
/** 이 대화에 허용된 카테고리 목록. 없음 = 전부. */
|
|
5
|
+
filter: ToolCategoryFilter;
|
|
6
|
+
isRead(name: string): boolean;
|
|
7
|
+
isWrite(name: string): boolean;
|
|
8
|
+
isAction(name: string): boolean;
|
|
9
|
+
spec(name: string): ToolSpec | undefined;
|
|
10
|
+
}
|
|
11
|
+
/** 호스트가 자기 도구를 더할 때 주는 것. 준 것만 더해지고, 안 준 축은 레지스트리 판정 그대로다. */
|
|
12
|
+
export interface ToolGateExtension {
|
|
13
|
+
isRead?(name: string): boolean;
|
|
14
|
+
isWrite?(name: string): boolean;
|
|
15
|
+
isAction?(name: string): boolean;
|
|
16
|
+
spec?(name: string): ToolSpec | undefined;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* 레지스트리만 보고 답하는 게이트.
|
|
20
|
+
*
|
|
21
|
+
* `external` 은 읽기로 본다 — 등록한 쪽이 「밖에서 값을 가져온다」고 말한 것이고, 그것은 쓰지 않는다.
|
|
22
|
+
*/
|
|
23
|
+
export declare function registryToolGate(filter?: ToolCategoryFilter): ToolGate;
|
|
24
|
+
/**
|
|
25
|
+
* 호스트의 판정을 **더한다.** 겹치면 어느 쪽이든 참이면 참이다 — 게이트는 「이 이름을 다룰 수 있나」를
|
|
26
|
+
* 묻고, 두 출처 중 하나가 안다고 하면 다룰 수 있다.
|
|
27
|
+
*
|
|
28
|
+
* 한쪽으로 덮지 않는 이유: 덮으면 호스트가 자기 이름집합에 없는 등록 도구를 **조용히 잠근다.** 그러면
|
|
29
|
+
* 대화면이 카테고리를 허용했는데 호출이 미등록으로 회신되고, 원인이 두 자리에 나뉘어 있어 못 찾는다.
|
|
30
|
+
*/
|
|
31
|
+
export declare function extendToolGate(base: ToolGate, extension: ToolGateExtension): ToolGate;
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.registryToolGate = registryToolGate;
|
|
4
|
+
exports.extendToolGate = extendToolGate;
|
|
5
|
+
/*
|
|
6
|
+
* Which tools this conversation may call — the registry half.
|
|
7
|
+
*
|
|
8
|
+
* ── Why a gate at all ───────────────────────────────────────────────────────────
|
|
9
|
+
* One product grows several conversation surfaces (a board authoring dock, an operations dock, a
|
|
10
|
+
* header assistant). Board edits can be reverted; an operations command reaches a real factory.
|
|
11
|
+
* If both sets hang in one conversation, the boundary is a label on the screen.
|
|
12
|
+
*
|
|
13
|
+
* **Hiding the definitions is not enough.** A model can guess a name, and an older conversation
|
|
14
|
+
* can be replayed with tool calls still in it. So the same gate has to decide *both* what is
|
|
15
|
+
* offered and what may be dispatched. A name that fails the gate is reported back to the model as
|
|
16
|
+
* unregistered — never a silent no-op, which the model would read as success.
|
|
17
|
+
*
|
|
18
|
+
* ── Why the registry half is here and the rest is not (2026-09-10) ──────────────
|
|
19
|
+
* This came out of `board-ai`, where the gate answered from two sources at once: the tool registry
|
|
20
|
+
* *and* board's own core tool-name sets. The first is neutral — any host asking "what kind of tool
|
|
21
|
+
* is this name, and may this conversation see it" wants the same answer. The second is board's.
|
|
22
|
+
*
|
|
23
|
+
* So the registry half lives here and a host **extends** it with whatever it owns
|
|
24
|
+
* (`extendToolGate`). Splitting it this way is what lets a product with no board of its own get
|
|
25
|
+
* the same dispatch discipline, instead of each product writing its own gate and diverging — which
|
|
26
|
+
* is what happened with the grounding guard: the twin's header route had it and the dock route did
|
|
27
|
+
* not, so the same question was verified on one side and not the other.
|
|
28
|
+
*/
|
|
29
|
+
const index_js_1 = require("../tool-registry/index.js");
|
|
30
|
+
/**
|
|
31
|
+
* 레지스트리만 보고 답하는 게이트.
|
|
32
|
+
*
|
|
33
|
+
* `external` 은 읽기로 본다 — 등록한 쪽이 「밖에서 값을 가져온다」고 말한 것이고, 그것은 쓰지 않는다.
|
|
34
|
+
*/
|
|
35
|
+
function registryToolGate(filter) {
|
|
36
|
+
const kind = (name) => (0, index_js_1.getToolKind)(name, filter);
|
|
37
|
+
return {
|
|
38
|
+
filter,
|
|
39
|
+
isRead: name => kind(name) === 'read' || kind(name) === 'external',
|
|
40
|
+
isWrite: name => kind(name) === 'write',
|
|
41
|
+
isAction: name => kind(name) === 'action',
|
|
42
|
+
spec: name => (0, index_js_1.findToolSpec)(name, filter)
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* 호스트의 판정을 **더한다.** 겹치면 어느 쪽이든 참이면 참이다 — 게이트는 「이 이름을 다룰 수 있나」를
|
|
47
|
+
* 묻고, 두 출처 중 하나가 안다고 하면 다룰 수 있다.
|
|
48
|
+
*
|
|
49
|
+
* 한쪽으로 덮지 않는 이유: 덮으면 호스트가 자기 이름집합에 없는 등록 도구를 **조용히 잠근다.** 그러면
|
|
50
|
+
* 대화면이 카테고리를 허용했는데 호출이 미등록으로 회신되고, 원인이 두 자리에 나뉘어 있어 못 찾는다.
|
|
51
|
+
*/
|
|
52
|
+
function extendToolGate(base, extension) {
|
|
53
|
+
return {
|
|
54
|
+
filter: base.filter,
|
|
55
|
+
isRead: name => base.isRead(name) || !!extension.isRead?.(name),
|
|
56
|
+
isWrite: name => base.isWrite(name) || !!extension.isWrite?.(name),
|
|
57
|
+
isAction: name => base.isAction(name) || !!extension.isAction?.(name),
|
|
58
|
+
spec: name => base.spec(name) ?? extension.spec?.(name)
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
//# sourceMappingURL=registry-gate.js.map
|
|
@@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C,SAAS,CAAC,QAAQ,EAAE,CAAC,IAAI,CAAC;QACrE,IAAI,EAAE,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,SAAS,CAAC,IAAI,EAAE,CAAC,IAAI,CAAC;KACxD,CAAA;AACH,CAAC","sourcesContent":["/*\n * Which tools this conversation may call — the registry half.\n *\n * ── Why a gate at all ───────────────────────────────────────────────────────────\n * One product grows several conversation surfaces (a board authoring dock, an operations dock, a\n * header assistant). Board edits can be reverted; an operations command reaches a real factory.\n * If both sets hang in one conversation, the boundary is a label on the screen.\n *\n * **Hiding the definitions is not enough.** A model can guess a name, and an older conversation\n * can be replayed with tool calls still in it. So the same gate has to decide *both* what is\n * offered and what may be dispatched. A name that fails the gate is reported back to the model as\n * unregistered — never a silent no-op, which the model would read as success.\n *\n * ── Why the registry half is here and the rest is not (2026-09-10) ──────────────\n * This came out of `board-ai`, where the gate answered from two sources at once: the tool registry\n * *and* board's own core tool-name sets. The first is neutral — any host asking \"what kind of tool\n * is this name, and may this conversation see it\" wants the same answer. The second is board's.\n *\n * So the registry half lives here and a host **extends** it with whatever it owns\n * (`extendToolGate`). Splitting it this way is what lets a product with no board of its own get\n * the same dispatch discipline, instead of each product writing its own gate and diverging — which\n * is what happened with the grounding guard: the twin's header route had it and the dock route did\n * not, so the same question was verified on one side and not the other.\n */\nimport { findToolSpec, getToolKind, type ToolCategoryFilter, type ToolSpec } from '../tool-registry/index.js'\n\n/** 이름 하나에 대한 판정. 정의 조립과 dispatch 가 **같은 것**을 쓴다. */\nexport interface ToolGate {\n /** 이 대화에 허용된 카테고리 목록. 없음 = 전부. */\n filter: ToolCategoryFilter\n isRead(name: string): boolean\n isWrite(name: string): boolean\n isAction(name: string): boolean\n spec(name: string): ToolSpec | undefined\n}\n\n/** 호스트가 자기 도구를 더할 때 주는 것. 준 것만 더해지고, 안 준 축은 레지스트리 판정 그대로다. */\nexport interface ToolGateExtension {\n isRead?(name: string): boolean\n isWrite?(name: string): boolean\n isAction?(name: string): boolean\n spec?(name: string): ToolSpec | undefined\n}\n\n/**\n * 레지스트리만 보고 답하는 게이트.\n *\n * `external` 은 읽기로 본다 — 등록한 쪽이 「밖에서 값을 가져온다」고 말한 것이고, 그것은 쓰지 않는다.\n */\nexport function registryToolGate(filter?: ToolCategoryFilter): ToolGate {\n const kind = (name: string) => getToolKind(name, filter)\n return {\n filter,\n isRead: name => kind(name) === 'read' || kind(name) === 'external',\n isWrite: name => kind(name) === 'write',\n isAction: name => kind(name) === 'action',\n spec: name => findToolSpec(name, filter)\n }\n}\n\n/**\n * 호스트의 판정을 **더한다.** 겹치면 어느 쪽이든 참이면 참이다 — 게이트는 「이 이름을 다룰 수 있나」를\n * 묻고, 두 출처 중 하나가 안다고 하면 다룰 수 있다.\n *\n * 한쪽으로 덮지 않는 이유: 덮으면 호스트가 자기 이름집합에 없는 등록 도구를 **조용히 잠근다.** 그러면\n * 대화면이 카테고리를 허용했는데 호출이 미등록으로 회신되고, 원인이 두 자리에 나뉘어 있어 못 찾는다.\n */\nexport function extendToolGate(base: ToolGate, extension: ToolGateExtension): ToolGate {\n return {\n filter: base.filter,\n isRead: name => base.isRead(name) || !!extension.isRead?.(name),\n isWrite: name => base.isWrite(name) || !!extension.isWrite?.(name),\n isAction: name => base.isAction(name) || !!extension.isAction?.(name),\n spec: name => base.spec(name) ?? extension.spec?.(name)\n }\n}\n"]}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/*
|
|
3
|
+
* Tool results, cut down to what a screen can hold.
|
|
4
|
+
*
|
|
5
|
+
* ── Why this is here and not in a product (2026-09-10) ───────────────────────────
|
|
6
|
+
* This came out of `board-ai`, and measuring the other consumer is what settled it: `twin-ai`
|
|
7
|
+
* passes `summarizeToolResult: v => v` — the identity function. So one product compressed its
|
|
8
|
+
* tool results before persisting them and the other did not, for no stated reason. That is the
|
|
9
|
+
* shape of a layer living in the wrong package: the second product does not decide differently,
|
|
10
|
+
* it just never gets the decision.
|
|
11
|
+
*
|
|
12
|
+
* ── ⚠ This is for the screen, never for a judgement ─────────────────────────────
|
|
13
|
+
* The output is depth- and length-limited, so it is **not evidence of what the model received**.
|
|
14
|
+
* A check that reads these summaries can pass while the model was handed `{}` — an un-awaited
|
|
15
|
+
* async builder did exactly that, and the screen still showed a successful call.
|
|
16
|
+
*
|
|
17
|
+
* What the model actually received is `AgenticLoopResult.groundedTexts`. Grounding already uses
|
|
18
|
+
* it, and anything that judges correctness must use it too.
|
|
19
|
+
*/
|
|
20
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
21
|
+
exports.summarizeToolResult = summarizeToolResult;
|
|
22
|
+
/** 문자열은 이 길이에서 자른다. 자른 사실과 잘린 양을 남긴다 — 조용히 짧아지지 않는다. */
|
|
23
|
+
const MAX_STRING = 200;
|
|
24
|
+
/** 배열은 이 개수까지 보이고 나머지는 수로 말한다. */
|
|
25
|
+
const MAX_ITEMS = 5;
|
|
26
|
+
/** 배열 안의 배열은 이 깊이에서 모양만 남긴다. */
|
|
27
|
+
const MAX_ARRAY_DEPTH = 2;
|
|
28
|
+
/** 객체는 이 깊이에서 키 이름만 남긴다. */
|
|
29
|
+
const MAX_OBJECT_DEPTH = 3;
|
|
30
|
+
/** 깊이 한계에서 남길 키 개수. */
|
|
31
|
+
const MAX_KEYS = 6;
|
|
32
|
+
/**
|
|
33
|
+
* 도구 결과를 화면·영속에 쓸 크기로 줄인다.
|
|
34
|
+
*
|
|
35
|
+
* 줄인 자리마다 **줄였다는 표시**를 남긴다(`…[+N chars]` · `…[+N items]` · `[Array(N)]`).
|
|
36
|
+
* 표시가 없으면 읽는 사람이 그것을 원본으로 믿는다.
|
|
37
|
+
*/
|
|
38
|
+
function summarizeToolResult(value, depth = 0) {
|
|
39
|
+
if (value === null || value === undefined)
|
|
40
|
+
return value;
|
|
41
|
+
if (typeof value === 'string') {
|
|
42
|
+
return value.length > MAX_STRING ? `${value.slice(0, MAX_STRING)}…[+${value.length - MAX_STRING} chars]` : value;
|
|
43
|
+
}
|
|
44
|
+
if (typeof value === 'number' || typeof value === 'boolean')
|
|
45
|
+
return value;
|
|
46
|
+
if (Array.isArray(value)) {
|
|
47
|
+
if (depth >= MAX_ARRAY_DEPTH)
|
|
48
|
+
return `[Array(${value.length})]`;
|
|
49
|
+
const out = value.slice(0, MAX_ITEMS).map(v => summarizeToolResult(v, depth + 1));
|
|
50
|
+
if (value.length > MAX_ITEMS)
|
|
51
|
+
out.push(`…[+${value.length - MAX_ITEMS} items]`);
|
|
52
|
+
return out;
|
|
53
|
+
}
|
|
54
|
+
if (typeof value === 'object') {
|
|
55
|
+
if (depth >= MAX_OBJECT_DEPTH) {
|
|
56
|
+
const keys = Object.keys(value).slice(0, MAX_KEYS).join(',');
|
|
57
|
+
return `{${keys}${Object.keys(value).length > MAX_KEYS ? ',…' : ''}}`;
|
|
58
|
+
}
|
|
59
|
+
const out = {};
|
|
60
|
+
for (const key of Object.keys(value)) {
|
|
61
|
+
out[key] = summarizeToolResult(value[key], depth + 1);
|
|
62
|
+
}
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
return undefined;
|
|
66
|
+
}
|
|
67
|
+
//# sourceMappingURL=summarize.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"summarize.js","sourceRoot":"","sources":["../../../server/service/assistant/summarize.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;GAiBG;;AAmBH,kDAwBC;AAzCD,wDAAwD;AACxD,MAAM,UAAU,GAAG,GAAG,CAAA;AACtB,kCAAkC;AAClC,MAAM,SAAS,GAAG,CAAC,CAAA;AACnB,gCAAgC;AAChC,MAAM,eAAe,GAAG,CAAC,CAAA;AACzB,4BAA4B;AAC5B,MAAM,gBAAgB,GAAG,CAAC,CAAA;AAC1B,uBAAuB;AACvB,MAAM,QAAQ,GAAG,CAAC,CAAA;AAElB;;;;;GAKG;AACH,SAAgB,mBAAmB,CAAC,K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C,MAAM,GAAG,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,GAAG,CAAA;QACvE,CAAC;QACD,MAAM,GAAG,GAAQ,EAAE,CAAA;QACnB,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;YACrC,GAAG,CAAC,GAAG,CAAC,GAAG,mBAAmB,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC,CAAA;QACvD,CAAC;QACD,OAAO,GAAG,CAAA;IACZ,CAAC;IACD,OAAO,SAAS,CAAA;AAClB,CAAC","sourcesContent":["/*\n * Tool results, cut down to what a screen can hold.\n *\n * ── Why this is here and not in a product (2026-09-10) ───────────────────────────\n * This came out of `board-ai`, and measuring the other consumer is what settled it: `twin-ai`\n * passes `summarizeToolResult: v => v` — the identity function. So one product compressed its\n * tool results before persisting them and the other did not, for no stated reason. That is the\n * shape of a layer living in the wrong package: the second product does not decide differently,\n * it just never gets the decision.\n *\n * ── ⚠ This is for the screen, never for a judgement ─────────────────────────────\n * The output is depth- and length-limited, so it is **not evidence of what the model received**.\n * A check that reads these summaries can pass while the model was handed `{}` — an un-awaited\n * async builder did exactly that, and the screen still showed a successful call.\n *\n * What the model actually received is `AgenticLoopResult.groundedTexts`. Grounding already uses\n * it, and anything that judges correctness must use it too.\n */\n\n/** 문자열은 이 길이에서 자른다. 자른 사실과 잘린 양을 남긴다 — 조용히 짧아지지 않는다. */\nconst MAX_STRING = 200\n/** 배열은 이 개수까지 보이고 나머지는 수로 말한다. */\nconst MAX_ITEMS = 5\n/** 배열 안의 배열은 이 깊이에서 모양만 남긴다. */\nconst MAX_ARRAY_DEPTH = 2\n/** 객체는 이 깊이에서 키 이름만 남긴다. */\nconst MAX_OBJECT_DEPTH = 3\n/** 깊이 한계에서 남길 키 개수. */\nconst MAX_KEYS = 6\n\n/**\n * 도구 결과를 화면·영속에 쓸 크기로 줄인다.\n *\n * 줄인 자리마다 **줄였다는 표시**를 남긴다(`…[+N chars]` · `…[+N items]` · `[Array(N)]`).\n * 표시가 없으면 읽는 사람이 그것을 원본으로 믿는다.\n */\nexport function summarizeToolResult(value: any, depth = 0): any {\n if (value === null || value === undefined) return value\n if (typeof value === 'string') {\n return value.length > MAX_STRING ? `${value.slice(0, MAX_STRING)}…[+${value.length - MAX_STRING} chars]` : value\n }\n if (typeof value === 'number' || typeof value === 'boolean') return value\n if (Array.isArray(value)) {\n if (depth >= MAX_ARRAY_DEPTH) return `[Array(${value.length})]`\n const out = value.slice(0, MAX_ITEMS).map(v => summarizeToolResult(v, depth + 1))\n if (value.length > MAX_ITEMS) out.push(`…[+${value.length - MAX_ITEMS} items]`)\n return out\n }\n if (typeof value === 'object') {\n if (depth >= MAX_OBJECT_DEPTH) {\n const keys = Object.keys(value).slice(0, MAX_KEYS).join(',')\n return `{${keys}${Object.keys(value).length > MAX_KEYS ? ',…' : ''}}`\n }\n const out: any = {}\n for (const key of Object.keys(value)) {\n out[key] = summarizeToolResult(value[key], depth + 1)\n }\n return out\n }\n return undefined\n}\n"]}
|
|
@@ -7,4 +7,5 @@ tslib_1.__exportStar(require("./providers/index.js"), exports);
|
|
|
7
7
|
tslib_1.__exportStar(require("./utils/index.js"), exports);
|
|
8
8
|
tslib_1.__exportStar(require("./tool-registry/index.js"), exports);
|
|
9
9
|
tslib_1.__exportStar(require("./agentic-loop/index.js"), exports);
|
|
10
|
+
tslib_1.__exportStar(require("./assistant/index.js"), exports);
|
|
10
11
|
//# 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","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'\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","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'\n"]}
|
|
@@ -15,6 +15,25 @@ const categories = new Map();
|
|
|
15
15
|
* 카테고리 등록. tool name 충돌 시 throw, 이름 중복 등록 시 덮어쓰기 + warn.
|
|
16
16
|
*/
|
|
17
17
|
function registerToolCategory(category) {
|
|
18
|
+
/*
|
|
19
|
+
* 지침 없는 카테고리는 **등록하지 않는다.**
|
|
20
|
+
*
|
|
21
|
+
* 도구 목록만 보낸 모델이 「불러야 할 때 부른다」를 맞히지 못한 사고가 있었다 — 조치 요청에
|
|
22
|
+
* `proposeAction` 을 부르지 않고 「제안해 두었습니다」라고 답해, 사용자에게 없는 버튼을 누르라고
|
|
23
|
+
* 안내했다. 화면에는 아무 일도 없었고 오류도 나지 않았다(§`ToolCategory.guidance`).
|
|
24
|
+
*
|
|
25
|
+
* 그 뒤로 규율을 적는 자리를 만들었지만 **선택이었다.** 선택인 규율은 그 사고를 아는 사람만
|
|
26
|
+
* 채운다. 여기서 거절하는 이유가 그것이다 — 빠진 것을 부팅에서 만든 사람이 보고, 모델이 헛말을
|
|
27
|
+
* 한 뒤에 사용자가 보지 않는다.
|
|
28
|
+
*
|
|
29
|
+
* 빈 문자열·공백도 거절한다. 통과시키면 이 검사가 형식이 되고, 형식이 된 검사는 없는 것과 같다.
|
|
30
|
+
*/
|
|
31
|
+
if (!String(category.guidance ?? '').trim()) {
|
|
32
|
+
throw new Error(`[ai-client-base/tool-registry] category '${category.name}' has no guidance. ` +
|
|
33
|
+
'Tool descriptions say what a tool does; guidance says when the model must call one. ' +
|
|
34
|
+
'Without it a model answers as though it called a tool it did not, and nothing errors. ' +
|
|
35
|
+
'Write the rules for these tools in `guidance` — the side that registers them owns them.');
|
|
36
|
+
}
|
|
18
37
|
if (categories.has(category.name)) {
|
|
19
38
|
console.warn(`[board-ai/tool-registry] category '${category.name}' already registered — overwriting. ` +
|
|
20
39
|
`(dev hot-reload 시 정상이지만 운영 환경에서 발생하면 buildup bug)`);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registry.js","sourceRoot":"","sources":["../../../server/service/tool-registry/registry.ts"],"names":[],"mappings":";;AAkCA,
|
|
1
|
+
{"version":3,"file":"registry.js","sourceRoot":"","sources":["../../../server/service/tool-registry/registry.ts"],"names":[],"mappings":";;AAkCA,oDA6CC;AAmBD,8CAEC;AAMD,0CAEC;AAMD,0CAOC;AAQD,kDAQC;AAKD,oCAOC;AAMD,kCAEC;AAKD,0BAEC;AAKD,4CAEC;AASD,8CAEC;AAzJD,MAAM,UAAU,GAA8B,IAAI,GAAG,EAAE,CAAA;AAEvD;;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,4CAA4C,QAAQ,CAAC,IAAI,qBAAqB;YAC5E,sFAAsF;YACtF,wFAAwF;YACxF,yFAAyF,CAC5F,CAAA;IACH,CAAC;IAED,IAAI,UAAU,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;QAClC,OAAO,CAAC,IAAI,CACV,sCAAsC,QAAQ,CAAC,IAAI,sCAAsC;YACvF,mDAAmD,CACtD,CAAA;IACH,CAAC;IAED,4CAA4C;IAC5C,MAAM,QAAQ,GAAG,IAAI,GAAG,CAAC,QAAQ,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ACH,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;AACpB,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/**\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 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}\n"]}
|
|
@@ -124,6 +124,16 @@ export interface ToolCategory {
|
|
|
124
124
|
*
|
|
125
125
|
* 규율은 도구를 등록한 쪽이 소유한다. 호스트(board-ai)는 도메인을 모르는 채 **노출된 카테고리의
|
|
126
126
|
* 규율만 모아 붙인다** — 도메인 지식이 호스트 프롬프트로 새지 않는다.
|
|
127
|
+
*
|
|
128
|
+
* ── 왜 필수인가 (2026-09-09) ──────────────────────────────────────────────
|
|
129
|
+
* 선택 필드였다. 그래서 위에 적힌 사고를 아는 사람만 채웠고, 세 제품이 각자 도구를 붙이기
|
|
130
|
+
* 시작한 지금 **채운 넷과 안 채운 하나**가 있었다.
|
|
131
|
+
*
|
|
132
|
+
* 안 채운 쪽은 조용하다 — 등록은 성공하고 부팅도 성공하고, 모델이 도구를 덜 부르거나 지어낸
|
|
133
|
+
* 뒤에 사람이 화면을 보고 안다. **두 개를 기억해야 성립하는 규칙은 다음 새 카테고리까지만
|
|
134
|
+
* 간다.** 그래서 기억이 아니라 등록이 거절한다(§`registerToolCategory`).
|
|
135
|
+
*
|
|
136
|
+
* 빈 문자열도 거절한다. 「없음」을 「적었다」로 위장하는 값이 통과하면 이 강제가 형식이 된다.
|
|
127
137
|
*/
|
|
128
|
-
guidance
|
|
138
|
+
guidance: string;
|
|
129
139
|
}
|
|
@@ -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) → BoardEditOp[], action 은 (args) → BoardActionOp.\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 (BoardEditOp,\n// BoardActionOp 등) 은 알지 않는다. builder return 은 unknown 으로 두고, 카테고리\n// dispatcher (board-ai 의 toolCallToBoardEditOp / toolCallToBoardActionOp 등) 가 자기\n// 도메인 type 으로 좁힌다. 사용자가 ToolSpec<TWrite, TAction> generic 까지 정밀화하면\n// 좋겠지만, 11~50 개 spec 마다 type 인자 전파가 부담이라 unknown 으로 합의.\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/**\n * Write tool — domain edit op 발생. host 가 patch 적용 후 영속화.\n * 예: board-ai 의 addComponent / setFill / modifyBoard.\n *\n * builder 의 return type 은 unknown 으로 둔다 — 도메인별 dispatcher (예: board-ai 의\n * toolCallToBoardEditOp) 가 자기 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/**\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 의 toolCallToBoardActionOp)\n * 가 자기 BoardActionOp 으로 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\n// ── ToolSpec — 카테고리별 변형 ──────────────────────────────────────\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\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 guidance
|
|
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) → BoardEditOp[], action 은 (args) → BoardActionOp.\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 (BoardEditOp,\n// BoardActionOp 등) 은 알지 않는다. builder return 은 unknown 으로 두고, 카테고리\n// dispatcher (board-ai 의 toolCallToBoardEditOp / toolCallToBoardActionOp 등) 가 자기\n// 도메인 type 으로 좁힌다. 사용자가 ToolSpec<TWrite, TAction> generic 까지 정밀화하면\n// 좋겠지만, 11~50 개 spec 마다 type 인자 전파가 부담이라 unknown 으로 합의.\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/**\n * Write tool — domain edit op 발생. host 가 patch 적용 후 영속화.\n * 예: board-ai 의 addComponent / setFill / modifyBoard.\n *\n * builder 의 return type 은 unknown 으로 둔다 — 도메인별 dispatcher (예: board-ai 의\n * toolCallToBoardEditOp) 가 자기 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/**\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 의 toolCallToBoardActionOp)\n * 가 자기 BoardActionOp 으로 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\n// ── ToolSpec — 카테고리별 변형 ──────────────────────────────────────\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\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"]}
|
|
@@ -17,9 +17,15 @@
|
|
|
17
17
|
* 기준이 없다. 그래서 보수적으로 id 관례(하이픈 포함 소문자-영숫자)만 추출한다 —
|
|
18
18
|
* 한국어·하이픈 없는 일반어는 애초에 매칭하지 않는다.
|
|
19
19
|
*/
|
|
20
|
-
/** 문자열에서 id 후보 토큰을 뽑는다(중복 제거). */
|
|
20
|
+
/** 문자열에서 id 후보 토큰을 뽑는다(중복 제거). **쓰인 그대로** 담는다 — 사람에게 보일 값이다. */
|
|
21
21
|
export declare function extractIdTokens(s: string): Set<string>;
|
|
22
|
-
/**
|
|
22
|
+
/**
|
|
23
|
+
* 답이 언급한 id − 근거 코퍼스의 id = 미확인(환각 후보). 순서는 답에 나온 순서.
|
|
24
|
+
*
|
|
25
|
+
* **대조는 대소문자를 무시한다.** 모델이 `WO-2609B` 를 `wo-2609b` 로 적는 것은 표기이지 다른
|
|
26
|
+
* 대상이 아니다. 엄격히 보면 그 한 글자 차이로 정상 답이 경고를 받고, 그런 경고가 몇 번 나오면
|
|
27
|
+
* 사람이 경고 자체를 안 본다. 대소문자만 다른 두 식별자를 쓰는 체계라면 그것이 먼저 고칠 문제다.
|
|
28
|
+
*/
|
|
23
29
|
export declare function checkGrounding(reply: string, groundedCorpus: string): string[];
|
|
24
30
|
/**
|
|
25
31
|
* 소음 제거 — 미확인 토큰 중 **엔티티 참조로 보이는 것만** 남긴다.
|
|
@@ -42,3 +48,20 @@ export declare function filterEntityLike(tokens: string[], groundedCorpus: strin
|
|
|
42
48
|
* 반환이 비면 접지 정상(경고 없음).
|
|
43
49
|
*/
|
|
44
50
|
export declare function groundingWarnings(reply: string, groundedCorpus: string): string[];
|
|
51
|
+
export interface GroundingSources {
|
|
52
|
+
/** 시스템 프롬프트 — 생성 가능한 타입 목록·규칙 등. 여기 있는 이름을 말하는 것은 정상이다. */
|
|
53
|
+
systemPrompt?: string;
|
|
54
|
+
/** 호스트가 대화 앞에 붙인 문맥 — 보드 요약·현장 상태·저작 중인 자산. */
|
|
55
|
+
hostContext?: string;
|
|
56
|
+
/** 사용자·어시스턴트 이력 텍스트. 사용자가 말한 식별자를 되받는 것은 정상이다. */
|
|
57
|
+
messages?: string[];
|
|
58
|
+
/**
|
|
59
|
+
* `tool_result` 로 회신된 **원문**(시간순).
|
|
60
|
+
*
|
|
61
|
+
* ⚠ `toolUsages[].result` 를 넣지 말 것 — 그것은 화면 표시용으로 깊이·길이가 잘린 값이다. 잘려
|
|
62
|
+
* 나간 식별자를 「근거 없음」으로 오판한다. 넣을 값은 `AgenticLoopResult.groundedTexts` 다.
|
|
63
|
+
*/
|
|
64
|
+
toolResults?: string[];
|
|
65
|
+
}
|
|
66
|
+
/** 근거집합을 한 덩어리로. 식별자 토큰만 대조하므로 구분자는 개행으로 충분하다. */
|
|
67
|
+
export declare function buildGroundedCorpus(sources: GroundingSources): string;
|