@things-factory/board-import 10.0.0-beta.71 → 10.0.0-beta.73

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.
Files changed (83) hide show
  1. package/dist-server/index.d.ts +1 -1
  2. package/dist-server/index.js +1 -1
  3. package/dist-server/index.js.map +1 -1
  4. package/dist-server/service/adapters/dxf-adapter.d.ts +1 -1
  5. package/dist-server/service/adapters/dxf-adapter.js +18 -4
  6. package/dist-server/service/adapters/dxf-adapter.js.map +1 -1
  7. package/dist-server/service/adapters/image-adapter.d.ts +32 -0
  8. package/dist-server/service/adapters/image-adapter.js +420 -0
  9. package/dist-server/service/adapters/image-adapter.js.map +1 -0
  10. package/dist-server/service/ai/types.d.ts +96 -4
  11. package/dist-server/service/ai/types.js +221 -12
  12. package/dist-server/service/ai/types.js.map +1 -1
  13. package/dist-server/service/converters/generic-to.d.ts +17 -8
  14. package/dist-server/service/converters/generic-to.js +44 -44
  15. package/dist-server/service/converters/generic-to.js.map +1 -1
  16. package/dist-server/service/import-session/import-actions.d.ts +79 -0
  17. package/dist-server/service/import-session/import-actions.js +98 -0
  18. package/dist-server/service/import-session/import-actions.js.map +1 -0
  19. package/dist-server/service/import-session/import-session-resolver.d.ts +22 -1
  20. package/dist-server/service/import-session/import-session-resolver.js +166 -38
  21. package/dist-server/service/import-session/import-session-resolver.js.map +1 -1
  22. package/dist-server/service/import-session/import-worker.js +55 -13
  23. package/dist-server/service/import-session/import-worker.js.map +1 -1
  24. package/dist-server/service/import-session/index.d.ts +5 -3
  25. package/dist-server/service/import-session/index.js +16 -9
  26. package/dist-server/service/import-session/index.js.map +1 -1
  27. package/dist-server/service/import-session/materialize-from-session.d.ts +66 -0
  28. package/dist-server/service/import-session/materialize-from-session.js +104 -0
  29. package/dist-server/service/import-session/materialize-from-session.js.map +1 -0
  30. package/dist-server/service/import-session/suggest-board-name.d.ts +80 -0
  31. package/dist-server/service/import-session/suggest-board-name.js +195 -0
  32. package/dist-server/service/import-session/suggest-board-name.js.map +1 -0
  33. package/dist-server/service/import-tools.d.ts +10 -0
  34. package/dist-server/service/import-tools.js +227 -0
  35. package/dist-server/service/import-tools.js.map +1 -0
  36. package/dist-server/service/index.d.ts +22 -19
  37. package/dist-server/service/index.js +46 -36
  38. package/dist-server/service/index.js.map +1 -1
  39. package/dist-server/service/pipeline/index.d.ts +42 -9
  40. package/dist-server/service/pipeline/index.js +92 -23
  41. package/dist-server/service/pipeline/index.js.map +1 -1
  42. package/dist-server/service/pipeline/stage2-mapping.d.ts +20 -5
  43. package/dist-server/service/pipeline/stage2-mapping.js +84 -26
  44. package/dist-server/service/pipeline/stage2-mapping.js.map +1 -1
  45. package/dist-server/service/pipeline/stage3-board.d.ts +2 -2
  46. package/dist-server/service/pipeline/stage3-board.js +65 -10
  47. package/dist-server/service/pipeline/stage3-board.js.map +1 -1
  48. package/dist-server/service/pipeline/stage4-binding.d.ts +1 -1
  49. package/dist-server/service/pipeline/stage4-binding.js +2 -2
  50. package/dist-server/service/pipeline/stage4-binding.js.map +1 -1
  51. package/dist-server/service/registry/index.d.ts +1 -1
  52. package/dist-server/service/registry/index.js.map +1 -1
  53. package/dist-server/service/types/index.d.ts +35 -0
  54. package/dist-server/service/types/index.js.map +1 -1
  55. package/dist-server/tsconfig.tsbuildinfo +1 -1
  56. package/package.json +7 -6
  57. package/server/index.ts +1 -1
  58. package/server/service/adapters/dxf-adapter.ts +17 -4
  59. package/server/service/adapters/image-adapter.test.ts +545 -0
  60. package/server/service/adapters/image-adapter.ts +464 -0
  61. package/server/service/ai/types.ts +354 -19
  62. package/server/service/converters/generic-to.test.ts +91 -0
  63. package/server/service/converters/generic-to.ts +66 -49
  64. package/server/service/import-session/import-actions.test.ts +185 -0
  65. package/server/service/import-session/import-actions.ts +164 -0
  66. package/server/service/import-session/import-session-resolver.ts +171 -39
  67. package/server/service/import-session/import-worker.ts +56 -12
  68. package/server/service/import-session/index.ts +19 -3
  69. package/server/service/import-session/materialize-from-session.test.ts +274 -0
  70. package/server/service/import-session/materialize-from-session.ts +158 -0
  71. package/server/service/import-session/suggest-board-name.test.ts +271 -0
  72. package/server/service/import-session/suggest-board-name.ts +279 -0
  73. package/server/service/import-tools.test.ts +137 -0
  74. package/server/service/import-tools.ts +255 -0
  75. package/server/service/index.ts +35 -18
  76. package/server/service/pipeline/index.ts +118 -23
  77. package/server/service/pipeline/stage2-mapping.test.ts +204 -0
  78. package/server/service/pipeline/stage2-mapping.ts +102 -27
  79. package/server/service/pipeline/stage3-board.test.ts +133 -0
  80. package/server/service/pipeline/stage3-board.ts +76 -11
  81. package/server/service/pipeline/stage4-binding.ts +2 -2
  82. package/server/service/registry/index.ts +1 -1
  83. package/server/service/types/index.ts +36 -0
@@ -0,0 +1,279 @@
1
+ /**
2
+ * suggestBoardName — ImportSession 으로부터 새 Board 의 후보 이름을 추천한다.
3
+ *
4
+ * 정책:
5
+ * 1) base 후보 우선순위: input.hint → session.options.userPrompt → session.result.metadata.viewTypeReasoning
6
+ * → attachment.name stem → 'Imported board'
7
+ * 2) base 정규화: 확장자 제거, _-. → 공백, 다중 공백 단일화, 50자 절단, trim
8
+ * 3) 도메인 격리 + 단일 LIKE query: `WHERE domain_id = ? AND (name = base OR name LIKE 'base (%)')`
9
+ * 한 번에 충돌 후보 다 가져오고 메모리에서 사용 가능한 가장 작은 (n) 결정
10
+ * 4) 결과: base 가 충돌 없으면 base, 있으면 'base (2)' / 'base (3)' / ...
11
+ *
12
+ * materializeFromSession 과 동일한 *RepoLike 패턴 — typeorm 의존성 주입으로 단위테스트 가능.
13
+ */
14
+
15
+ const FALLBACK = 'Imported board'
16
+
17
+ export interface SuggestBoardNameInput {
18
+ /** ImportSession id — 옵션. 있으면 거기서 hint / attachment 정보 추출. */
19
+ sessionId?: string
20
+ /**
21
+ * 명시 hint. session 정보보다 우선. 사용자가 wizard 에서 직접 메모를 쳐서 그것 기반 추천을
22
+ * 받고 싶을 때 사용.
23
+ */
24
+ hint?: string
25
+ }
26
+
27
+ export interface SessionForSuggest {
28
+ id: string
29
+ attachmentId?: string
30
+ optionsJson?: string | null
31
+ resultJson?: string | null
32
+ }
33
+
34
+ export interface AttachmentForSuggest {
35
+ id: string
36
+ name?: string
37
+ }
38
+
39
+ export interface SuggestSessionRepoLike {
40
+ findOneBy(criteria: any): Promise<SessionForSuggest | null>
41
+ }
42
+
43
+ export interface SuggestAttachmentRepoLike {
44
+ findOneBy(criteria: any): Promise<AttachmentForSuggest | null>
45
+ }
46
+
47
+ export interface SuggestBoardRepoLike {
48
+ /**
49
+ * 도메인 격리된 LIKE 쿼리. find({ where: { name: Like('base%'), domain: { id } } }) 형태로
50
+ * 호출자가 wiring. typeorm Like operator 노출을 피하기 위해 단순 string 으로 받음.
51
+ */
52
+ findExistingNames(opts: { domainId: string; basePrefix: string }): Promise<string[]>
53
+ }
54
+
55
+ export interface SuggestContext {
56
+ domain: { id: string; [k: string]: any }
57
+ }
58
+
59
+ export interface SuggestDeps {
60
+ sessionRepo: SuggestSessionRepoLike
61
+ attachmentRepo: SuggestAttachmentRepoLike
62
+ boardRepo: SuggestBoardRepoLike
63
+ }
64
+
65
+ export async function suggestBoardName(
66
+ input: SuggestBoardNameInput,
67
+ context: SuggestContext,
68
+ deps: SuggestDeps
69
+ ): Promise<string> {
70
+ const base = await resolveBaseName(input, context, deps)
71
+ const cleaned = sanitize(base) || FALLBACK
72
+
73
+ const existingNames = await deps.boardRepo.findExistingNames({
74
+ domainId: context.domain.id,
75
+ basePrefix: cleaned
76
+ })
77
+ return pickAvailableSuffix(cleaned, existingNames)
78
+ }
79
+
80
+ /**
81
+ * Board 이름 + 설명을 함께 추천. 이름은 짧고 심플 (운영 카드/리스트 표시용),
82
+ * 설명은 자세히 (사용자 hint + AI importStrategy + 통계 요약).
83
+ *
84
+ * 정책:
85
+ * - **name**: hint / userPrompt / VLM reasoning / attachment stem 에서 짧은 base 추출 후
86
+ * 30자 이내로 자르고, 충돌 검사 + (n) suffix
87
+ * - **description**: userPrompt + AI importStrategy + (있으면) reasoning + 카테고리 분포
88
+ * 를 자연어 단락으로 합성. 없으면 빈 문자열
89
+ */
90
+ export interface SuggestBoardMetaResult {
91
+ name: string
92
+ description: string
93
+ }
94
+
95
+ export async function suggestBoardMeta(
96
+ input: SuggestBoardNameInput,
97
+ context: SuggestContext,
98
+ deps: SuggestDeps
99
+ ): Promise<SuggestBoardMetaResult> {
100
+ // 보드 정체성 = AI 가 도면을 보고 식별한 subject. import 처리 메타 (importStrategy /
101
+ // categoryDist / userPrompt — AI 에게 한 지시) 와는 별 차원이라 영속 데이터에 섞지 않는다.
102
+ const { subjectName, subjectDescription } = await resolveSubject(input, context, deps)
103
+
104
+ // name: subjectName > input.hint > attachment.name stem > FALLBACK
105
+ // 사용자가 명시 hint 를 줬으면 그것이 우선 (직접 의도). VLM subjectName 은 그 다음.
106
+ const baseName =
107
+ (input.hint && input.hint.trim() && firstSentence(input.hint)) ||
108
+ subjectName ||
109
+ (await resolveAttachmentStem(input, context, deps)) ||
110
+ FALLBACK
111
+ const cleanedName = shortenName(sanitize(baseName) || FALLBACK)
112
+
113
+ const existingNames = await deps.boardRepo.findExistingNames({
114
+ domainId: context.domain.id,
115
+ basePrefix: cleanedName
116
+ })
117
+ const name = pickAvailableSuffix(cleanedName, existingNames)
118
+
119
+ // description: subjectDescription > input.hint (full) > 빈 문자열
120
+ // AI 가 도면을 본 자세한 묘사가 있으면 그것이 가장 가치 있음.
121
+ const description =
122
+ subjectDescription || (input.hint && input.hint.trim()) || ''
123
+
124
+ return { name, description }
125
+ }
126
+
127
+ /** AI 가 도면을 보고 식별한 subject (보드 정체성) — VLM 응답의 subjectName / subjectDescription. */
128
+ async function resolveSubject(
129
+ input: SuggestBoardNameInput,
130
+ context: SuggestContext,
131
+ deps: SuggestDeps
132
+ ): Promise<{ subjectName?: string; subjectDescription?: string }> {
133
+ if (!input.sessionId) return {}
134
+ const session = await deps.sessionRepo.findOneBy({
135
+ id: input.sessionId,
136
+ domain: { id: context.domain.id }
137
+ })
138
+ if (!session) return {}
139
+ const result = parseJsonSafe(session.resultJson)
140
+ const subjectName = typeof result?.metadata?.subjectName === 'string'
141
+ ? result.metadata.subjectName.trim()
142
+ : undefined
143
+ const subjectDescription = typeof result?.metadata?.subjectDescription === 'string'
144
+ ? result.metadata.subjectDescription.trim()
145
+ : undefined
146
+ return { subjectName, subjectDescription }
147
+ }
148
+
149
+ /** subject 미산출 시 fallback — attachment.name stem 만. */
150
+ async function resolveAttachmentStem(
151
+ input: SuggestBoardNameInput,
152
+ context: SuggestContext,
153
+ deps: SuggestDeps
154
+ ): Promise<string | undefined> {
155
+ if (!input.sessionId) return undefined
156
+ const session = await deps.sessionRepo.findOneBy({
157
+ id: input.sessionId,
158
+ domain: { id: context.domain.id }
159
+ })
160
+ if (!session?.attachmentId) return undefined
161
+ const att = await deps.attachmentRepo.findOneBy({
162
+ id: session.attachmentId,
163
+ domain: { id: context.domain.id }
164
+ })
165
+ return stemOf(att?.name) || undefined
166
+ }
167
+
168
+ /**
169
+ * 짧은 이름 — 단순 30자 단위로 단어 경계에서 자르기. 너무 길면 그대로 자르되 단어 보존.
170
+ */
171
+ function shortenName(s: string): string {
172
+ if (s.length <= 30) return s
173
+ // 30자 이내 마지막 공백에서 자르기
174
+ const truncated = s.slice(0, 30)
175
+ const lastSpace = truncated.lastIndexOf(' ')
176
+ if (lastSpace > 10) return truncated.slice(0, lastSpace).trim()
177
+ return truncated.trim()
178
+ }
179
+
180
+
181
+ // ── helpers ──────────────────────────────────────────────────────────
182
+
183
+ async function resolveBaseName(
184
+ input: SuggestBoardNameInput,
185
+ context: SuggestContext,
186
+ deps: SuggestDeps
187
+ ): Promise<string> {
188
+ // 1) 명시 hint
189
+ if (input.hint && input.hint.trim()) return firstSentence(input.hint)
190
+
191
+ // 2) session 정보
192
+ if (input.sessionId) {
193
+ const session = await deps.sessionRepo.findOneBy({
194
+ id: input.sessionId,
195
+ domain: { id: context.domain.id }
196
+ })
197
+ if (session) {
198
+ // 2a) userPrompt 우선
199
+ const opts = parseJsonSafe(session.optionsJson)
200
+ const userPrompt = typeof opts?.userPrompt === 'string' ? opts.userPrompt.trim() : ''
201
+ if (userPrompt) return firstSentence(userPrompt)
202
+
203
+ // 2b) VLM reasoning
204
+ const result = parseJsonSafe(session.resultJson)
205
+ const reasoning =
206
+ typeof result?.boardModel?.importMeta?.viewTypeReasoning === 'string'
207
+ ? result.boardModel.importMeta.viewTypeReasoning.trim()
208
+ : typeof result?.metadata?.viewTypeReasoning === 'string'
209
+ ? result.metadata.viewTypeReasoning.trim()
210
+ : ''
211
+ if (reasoning) return firstSentence(reasoning)
212
+
213
+ // 2c) attachment name stem
214
+ if (session.attachmentId) {
215
+ const att = await deps.attachmentRepo.findOneBy({
216
+ id: session.attachmentId,
217
+ domain: { id: context.domain.id }
218
+ })
219
+ const stem = stemOf(att?.name)
220
+ if (stem) return stem
221
+ }
222
+ }
223
+ }
224
+
225
+ return FALLBACK
226
+ }
227
+
228
+ function parseJsonSafe(s: string | null | undefined): any {
229
+ if (!s) return undefined
230
+ try {
231
+ return JSON.parse(s)
232
+ } catch {
233
+ return undefined
234
+ }
235
+ }
236
+
237
+ function firstSentence(text: string): string {
238
+ // 첫 문장 종결 부호 또는 줄바꿈까지. 미발견 시 전체.
239
+ const m = text.match(/^([^.\n!?]{1,120})[.\n!?]?/)
240
+ return (m?.[1] ?? text).trim()
241
+ }
242
+
243
+ function stemOf(name: string | undefined | null): string {
244
+ if (!name) return ''
245
+ // 마지막 . 이후 (확장자) 제거. 점이 여러 번이면 가장 마지막만.
246
+ const lastDot = name.lastIndexOf('.')
247
+ if (lastDot > 0) return name.slice(0, lastDot)
248
+ return name
249
+ }
250
+
251
+ /**
252
+ * 정규화: _-. → 공백, 다중 공백 단일화, trim, 50자 절단.
253
+ * 결과가 빈 문자열이면 '' 반환 (호출자가 fallback).
254
+ */
255
+ function sanitize(s: string): string {
256
+ if (!s) return ''
257
+ let cleaned = s.replace(/[_\-.]+/g, ' ').replace(/\s+/g, ' ').trim()
258
+ if (cleaned.length > 50) cleaned = cleaned.slice(0, 50).trim()
259
+ return cleaned
260
+ }
261
+
262
+ /**
263
+ * existingNames 안에서 base 가 그대로 비어있으면 base 반환, 아니면 'base (2)', '(3)', ...
264
+ * case-insensitive 비교 (postgres ilike 호환).
265
+ */
266
+ export function pickAvailableSuffix(base: string, existingNames: string[]): string {
267
+ const lower = base.toLowerCase()
268
+ const taken = new Set<string>()
269
+ for (const name of existingNames) {
270
+ if (typeof name === 'string') taken.add(name.toLowerCase())
271
+ }
272
+ if (!taken.has(lower)) return base
273
+ for (let n = 2; n < 10000; n++) {
274
+ const candidate = `${base} (${n})`
275
+ if (!taken.has(candidate.toLowerCase())) return candidate
276
+ }
277
+ // 9999개 충돌 이라는 비현실 시나리오 — 마지막 fallback
278
+ return `${base} (${Date.now()})`
279
+ }
@@ -0,0 +1,137 @@
1
+ /**
2
+ * board-import 의 LLM tool 등록 + builder wiring — 단위 테스트.
3
+ *
4
+ * registry 통합 (등록 / kind 분류 / schema 노출) 외에 builder 가 service 함수와 정확히
5
+ * 결합되었는지 검증. service 함수 본체는 별도 파일 (import-actions.test, materialize-from-
6
+ * session.test) 에서 검증되어 있으므로 본 파일은 wiring 만 — ctx 누락 / placeholder 미사용
7
+ * 회귀 방지.
8
+ */
9
+ import {
10
+ clearToolRegistry,
11
+ findToolSpec,
12
+ getToolKind,
13
+ getCategorySpecs
14
+ } from '@things-factory/ai-client-base'
15
+ import { registerBoardImportTools } from './import-tools'
16
+
17
+ beforeEach(() => {
18
+ clearToolRegistry()
19
+ registerBoardImportTools()
20
+ })
21
+
22
+ afterEach(() => {
23
+ clearToolRegistry()
24
+ })
25
+
26
+ // ── 카테고리 등록 검증 ─────────────────────────────────────────────
27
+
28
+ describe('import-tools — 카테고리 등록', () => {
29
+ test("'board-import' 카테고리 등록", () => {
30
+ expect(getCategorySpecs('board-import').length).toBeGreaterThan(0)
31
+ })
32
+
33
+ test('listImportAdapters / importBoardAsync / getImportSession / materializeImportSession 모두 등록', () => {
34
+ expect(findToolSpec('listImportAdapters')).toBeDefined()
35
+ expect(findToolSpec('importBoardAsync')).toBeDefined()
36
+ expect(findToolSpec('getImportSession')).toBeDefined()
37
+ expect(findToolSpec('materializeImportSession')).toBeDefined()
38
+ })
39
+ })
40
+
41
+ // ── kind 분류 ────────────────────────────────────────────────────
42
+
43
+ describe('import-tools — kind 분류', () => {
44
+ test('listImportAdapters / getImportSession 은 read', () => {
45
+ expect(getToolKind('listImportAdapters')).toBe('read')
46
+ expect(getToolKind('getImportSession')).toBe('read')
47
+ })
48
+
49
+ test('importBoardAsync / materializeImportSession 은 external', () => {
50
+ expect(getToolKind('importBoardAsync')).toBe('external')
51
+ expect(getToolKind('materializeImportSession')).toBe('external')
52
+ })
53
+ })
54
+
55
+ // ── schema 노출 ──────────────────────────────────────────────────
56
+
57
+ describe('import-tools — schema 노출', () => {
58
+ test('importBoardAsync schema 가 attachmentId required', () => {
59
+ const spec = findToolSpec('importBoardAsync')
60
+ expect(spec?.schema?.required).toContain('attachmentId')
61
+ })
62
+
63
+ test('materializeImportSession schema 가 sessionId / name required + type enum', () => {
64
+ const spec = findToolSpec('materializeImportSession')
65
+ expect(spec?.schema?.required).toEqual(expect.arrayContaining(['sessionId', 'name']))
66
+ expect(spec?.schema?.properties?.type?.enum).toEqual(['main', 'sub', 'popup'])
67
+ })
68
+
69
+ test('materializeImportSession 은 사용자 confirm 강조 themeNote 보유', () => {
70
+ const spec = findToolSpec('materializeImportSession')
71
+ expect(spec?.themeNote).toContain('confirm')
72
+ })
73
+ })
74
+
75
+ // ── builder wiring — ctx 누락 시 명확 에러 ───────────────────────────
76
+
77
+ describe('import-tools — builder ctx 누락', () => {
78
+ test('importBoardAsync 가 ctx.state 없으면 의미있는 에러', async () => {
79
+ const spec = findToolSpec('importBoardAsync')
80
+ if (spec?.kind !== 'external') throw new Error('expected external')
81
+ await expect(spec.builder({ attachmentId: 'a1' }, {})).rejects.toThrow(/ctx\.state\.domain/)
82
+ })
83
+
84
+ test('getImportSession 가 ctx.state 없으면 의미있는 에러', async () => {
85
+ const spec = findToolSpec('getImportSession')
86
+ if (spec?.kind !== 'read') throw new Error('expected read')
87
+ await expect(spec.builder({ sessionId: 's1' }, {})).rejects.toThrow(/ctx\.state\.domain/)
88
+ })
89
+
90
+ test('materializeImportSession 가 ctx.state 없으면 의미있는 에러', async () => {
91
+ const spec = findToolSpec('materializeImportSession')
92
+ if (spec?.kind !== 'external') throw new Error('expected external')
93
+ await expect(
94
+ spec.builder({ sessionId: 's1', name: 'New' }, {})
95
+ ).rejects.toThrow(/ctx\.state\.domain/)
96
+ })
97
+ })
98
+
99
+ // ── builder wiring — listImportAdapters (ctx 무관) ───────────────────
100
+ //
101
+ // listImportAdapters builder 는 require('./pipeline/index') 로 DEFAULT_ADAPTERS 를
102
+ // inspect 한다. pipeline 모듈 load chain (DxfAdapter / ImageAdapter / ai-client-base /
103
+ // 외부 라이브러리) 의 typeorm-bound 또는 type-graphql Field reflection 평가가 단위 test
104
+ // 환경에서 fail 하므로 본 단위 테스트에서는 격리 어렵다 — 통합 test (실 server bootstrap
105
+ // 환경) 또는 e2e 에서 검증해야 한다. 핵심 wiring (kind / schema / ctx 누락 에러) 은
106
+ // 위 describe 블록들이 충분히 보호.
107
+ //
108
+ // 향후 jest setup 에서 type-graphql / typeorm DataSource init 을 mock 해 격리 가능하면
109
+ // describe.skip → describe 로 복원.
110
+ describe.skip('import-tools — listImportAdapters (통합 test 영역)', () => {
111
+ test('AdapterInfo 배열 반환 — DXF 와 image 적어도 노출', async () => {
112
+ const spec = findToolSpec('listImportAdapters')
113
+ if (spec?.kind !== 'read') throw new Error('expected read')
114
+ const r = await spec.builder({}, {})
115
+ expect(Array.isArray(r)).toBe(true)
116
+ const formats = (r as any[]).map(a => a.format)
117
+ expect(formats).toContain('dxf')
118
+ expect(formats).toContain('image')
119
+ })
120
+
121
+ test('AdapterInfo 의 capabilities 가 모든 boolean 5 필드 보유', async () => {
122
+ const spec = findToolSpec('listImportAdapters')
123
+ if (spec?.kind !== 'read') throw new Error('expected read')
124
+ const r = await spec.builder({}, {})
125
+ for (const info of r as any[]) {
126
+ expect(info.capabilities).toEqual(
127
+ expect.objectContaining({
128
+ has2D: expect.any(Boolean),
129
+ has3D: expect.any(Boolean),
130
+ hasSemanticLabels: expect.any(Boolean),
131
+ hasTextLabels: expect.any(Boolean),
132
+ hasAttributes: expect.any(Boolean)
133
+ })
134
+ )
135
+ }
136
+ })
137
+ })
@@ -0,0 +1,255 @@
1
+ /**
2
+ * board-import 의 LLM tool 카테고리 등록.
3
+ *
4
+ * board-ai 의 chat 흐름 안에서 사용자가 "이 도면을 보드로 만들어줘" / "import 결과 검수
5
+ * 후 이 이름으로 저장" 같은 자연어를 발화하면 LLM 이 본 카테고리의 tool 들을 호출한다.
6
+ *
7
+ * 노출되는 tool:
8
+ * - listImportAdapters (read) : 등록된 FormatAdapter 능력 조회
9
+ * - importBoardAsync (external) : Attachment → ImportSession 비동기 시작
10
+ * - getImportSession (read) : ImportSession 진행/결과 조회
11
+ * - materializeImportSession (external) : ImportSession.result → 새 Board entity
12
+ *
13
+ * dispatch wiring:
14
+ * board-ai 의 chat 메서드가 ToolCallContext (resolver state — domain/user/tx) 를 closure 로
15
+ * 주입한다. builder 는 ctx.state 에서 typeorm getRepository / domain / user 를 추출해
16
+ * service-level 함수 (import-actions, materialize-from-session) 를 호출한다.
17
+ *
18
+ * 이 layer 가 없으면 builder 가 typeorm 에 직접 의존해야 했고, board-ai 가 typeorm 까지
19
+ * 알게 되는 leakage 가 생겼을 것 — 의도적으로 builder 가 ctx.state.typeorm 같은 식으로
20
+ * 접근하지 않고 things-factory 표준 getRepository 를 호출.
21
+ */
22
+ import { getRepository } from '@things-factory/shell'
23
+ import {
24
+ registerToolCategory,
25
+ type ToolCategory,
26
+ type ToolSpec
27
+ } from '@things-factory/ai-client-base'
28
+
29
+ // 모든 server-side 의존성 (entity / service 함수 / 외부 패키지) 은 module-level import
30
+ // 없이 lazy require — module load 만으로 typeorm decorator / 외부 controllers chain
31
+ // (예: board-service 의 puppeteer pool) 이 평가되어 jest 환경에서 깨지는 것을 회피.
32
+ // 운영에서는 builder 첫 호출 시 cache 채워져 이후 호출은 직접 dispatch.
33
+ //
34
+ // 이 패턴은 LLM tool layer 의 일반 정책으로 가져갈 수 있다 — registerToolCategory 가
35
+ // 평가되는 시점은 server bootstrap 의 매우 이른 단계라, 그때 typeorm DataSource init 이
36
+ // 아직 끝나지 않았을 가능성이 있다.
37
+ let _depsCache: any | undefined
38
+ function getDeps(): any {
39
+ if (!_depsCache) {
40
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
41
+ const isMod = require('./import-session/import-session')
42
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
43
+ const bsMod = require('@things-factory/board-service')
44
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
45
+ const actionsMod = require('./import-session/import-actions')
46
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
47
+ const materializeMod = require('./import-session/materialize-from-session')
48
+ _depsCache = {
49
+ ImportSession: isMod.ImportSession,
50
+ Board: bsMod.Board,
51
+ Group: bsMod.Group,
52
+ startImportJobAsync: actionsMod.startImportJobAsync,
53
+ fetchImportSession: actionsMod.fetchImportSession,
54
+ describeAdapter: actionsMod.describeAdapter,
55
+ materializeFromSession: materializeMod.materializeFromSession
56
+ }
57
+ }
58
+ return _depsCache
59
+ }
60
+
61
+ /**
62
+ * tool builder 의 ctx.state 가 도메인 식별을 갖는지 검증. 미설정이면 명확한 에러로 실패 —
63
+ * board-ai 의 toolCallContext wiring 누락 / 비인증 호출 등을 빠르게 찾기 위해.
64
+ */
65
+ function requireDomainContext(state: any): { domain: any; user: any } {
66
+ if (!state || !state.domain) {
67
+ throw new Error(
68
+ '[board-import] tool builder 의 ctx.state.domain 미설정. ' +
69
+ 'board-ai 의 ChatOptions.toolCallContext 에 ResolverContext.state 가 전달됐는지 확인.'
70
+ )
71
+ }
72
+ return { domain: state.domain, user: state.user }
73
+ }
74
+
75
+ const importToolsCategory: ToolCategory = {
76
+ name: 'board-import',
77
+ description: 'Drawing/CAD/IFC/image → Board 변환 파이프라인 (zero-to-twin).',
78
+ specs: [
79
+ {
80
+ kind: 'read',
81
+ name: 'listImportAdapters',
82
+ description:
83
+ '등록된 도면 import 어댑터 (DXF / Image / 향후 IFC, glTF 등) 의 능력 조회. ' +
84
+ '사용자가 어떤 형식 import 가 가능한지 묻거나, LLM 이 적절한 어댑터 선택을 inspect 할 때 사용.',
85
+ schema: { type: 'object', properties: {} },
86
+ builder: async () => {
87
+ // 동적 import — pipeline 모듈의 DEFAULT_ADAPTERS 를 inspect.
88
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
89
+ const pipelineModule = require('./pipeline/index')
90
+ const adapters: any[] = pipelineModule.DEFAULT_ADAPTERS ?? []
91
+ return adapters.map(getDeps().describeAdapter)
92
+ }
93
+ },
94
+ {
95
+ kind: 'external',
96
+ name: 'importBoardAsync',
97
+ description:
98
+ 'Attachment(도면/조감도/사진) 을 비동기로 보드 모델로 변환 시작. 즉시 ImportSession 을 ' +
99
+ '반환하고 백그라운드에서 진행. status 가 completed 가 될 때까지 getImportSession 으로 ' +
100
+ 'polling 해서 결과를 확인. 형식은 자동 감지 — DXF / GLTF / image 등.',
101
+ schema: {
102
+ type: 'object',
103
+ properties: {
104
+ attachmentId: {
105
+ type: 'string',
106
+ description: 'Attachment id (attachment-base 에 미리 업로드된 도면 파일).'
107
+ },
108
+ chatSessionId: {
109
+ type: 'string',
110
+ description: 'board-ai chat session id (선택). 진행 메시지가 chat 흐름에 합류.'
111
+ },
112
+ scopes: {
113
+ type: 'array',
114
+ items: { type: 'string' },
115
+ description: 'ImportRule 의 scope (예: ["fmsim"]). 도메인별 매핑 규칙 활성화.'
116
+ },
117
+ parseOptions: {
118
+ type: 'object',
119
+ description: 'Adapter 파싱 옵션 (excludeLayers / maxEntities / context 등).',
120
+ additionalProperties: true
121
+ }
122
+ },
123
+ required: ['attachmentId']
124
+ },
125
+ builder: async (args, ctx) => {
126
+ const { domain, user } = requireDomainContext(ctx?.state)
127
+ const session = await getDeps().startImportJobAsync(
128
+ {
129
+ attachmentId: args.attachmentId,
130
+ chatSessionId: args.chatSessionId,
131
+ scopes: args.scopes,
132
+ parseOptions: args.parseOptions
133
+ },
134
+ { domain, user },
135
+ getRepository(getDeps().ImportSession) as any
136
+ )
137
+ return {
138
+ sessionId: session.id,
139
+ status: session.status,
140
+ progress: session.progress,
141
+ message: session.message
142
+ }
143
+ }
144
+ },
145
+ {
146
+ kind: 'read',
147
+ name: 'getImportSession',
148
+ description:
149
+ 'ImportSession 의 진행/결과 조회. status 가 queued/parsing/mapping/assembling/binding 인 ' +
150
+ '동안은 progress 와 message 를 반환, completed 면 result.boardModel 까지 포함. failed 면 ' +
151
+ 'message 에 에러 사유.',
152
+ schema: {
153
+ type: 'object',
154
+ properties: {
155
+ sessionId: { type: 'string', description: 'ImportSession id (importBoardAsync 가 반환).' }
156
+ },
157
+ required: ['sessionId']
158
+ },
159
+ builder: async (args, ctx) => {
160
+ const { domain, user } = requireDomainContext(ctx?.state)
161
+ const session = await getDeps().fetchImportSession(
162
+ args.sessionId,
163
+ { domain, user },
164
+ getRepository(getDeps().ImportSession) as any
165
+ )
166
+ if (!session) return { found: false }
167
+ return {
168
+ found: true,
169
+ sessionId: session.id,
170
+ status: session.status,
171
+ progress: session.progress,
172
+ message: session.message,
173
+ // result 는 큰 boardModel 을 포함할 수 있어 status 가 completed 일 때만.
174
+ result: session.status === 'completed' ? session.result : undefined,
175
+ totalEntities: session.totalEntities,
176
+ completedAt: session.completedAt
177
+ }
178
+ }
179
+ },
180
+ {
181
+ kind: 'external',
182
+ name: 'materializeImportSession',
183
+ description:
184
+ '완료된 ImportSession 의 결과 boardModel 을 새 Board entity 로 영속화. status 가 ' +
185
+ 'completed 인 세션만 처리. 결과 Board 는 state="draft" 로 생성되므로 사용자가 검수 후 ' +
186
+ '발행해야 한다.',
187
+ themeNote:
188
+ '⚠ 사용자의 명시적 confirm 후에만 호출. import 결과 미리보기를 보여주고 "이 이름으로 ' +
189
+ '저장하시겠어요?" 같은 확인 받은 다음 발동.',
190
+ schema: {
191
+ type: 'object',
192
+ properties: {
193
+ sessionId: { type: 'string' },
194
+ name: { type: 'string', description: '새 Board 이름 — 같은 도메인 내 unique.' },
195
+ description: { type: 'string' },
196
+ groupId: { type: 'string' },
197
+ type: { type: 'string', enum: ['main', 'sub', 'popup'] },
198
+ thumbnail: {
199
+ type: 'string',
200
+ description: 'Base64 thumbnail. 미지정 시 빈 placeholder 사용 (별도 thumbnail 생성 호출).'
201
+ }
202
+ },
203
+ required: ['sessionId', 'name']
204
+ },
205
+ builder: async (args, ctx) => {
206
+ const { domain, user } = requireDomainContext(ctx?.state)
207
+ const session = await getDeps().fetchImportSession(
208
+ args.sessionId,
209
+ { domain, user },
210
+ getRepository(getDeps().ImportSession) as any
211
+ )
212
+ const { Board, Group, materializeFromSession } = getDeps()
213
+ const board = await materializeFromSession(
214
+ session as any,
215
+ {
216
+ sessionId: args.sessionId,
217
+ name: args.name,
218
+ description: args.description,
219
+ groupId: args.groupId,
220
+ type: args.type,
221
+ thumbnail: args.thumbnail
222
+ },
223
+ { domain, user },
224
+ {
225
+ boardRepo: getRepository(Board) as any,
226
+ groupRepo: getRepository(Group) as any
227
+ }
228
+ )
229
+ // 큰 model 본문은 LLM 회신에서 제외 — id 와 메타만.
230
+ return {
231
+ boardId: (board as any).id,
232
+ name: (board as any).name,
233
+ state: (board as any).state,
234
+ sourceImportSessionId: (board as any).sourceImportSessionId
235
+ }
236
+ }
237
+ }
238
+ ] as ToolSpec[]
239
+ }
240
+
241
+ // 등록 — module 로드 시 side-effect.
242
+ registerToolCategory(importToolsCategory)
243
+
244
+ /**
245
+ * 명시적 register 함수 — 테스트나 lazy bootstrap 에서 import 만으로 발동되는 side-effect 가
246
+ * 부담스러울 때 import 후 명시 호출 가능.
247
+ */
248
+ export function registerBoardImportTools(): void {
249
+ registerToolCategory(importToolsCategory)
250
+ }
251
+
252
+ /**
253
+ * 테스트용 — registerToolCategory 의 입력으로 사용된 카테고리 객체. 외부에서 inspect 가능.
254
+ */
255
+ export const BOARD_IMPORT_TOOL_CATEGORY = importToolsCategory