@things-factory/ai-client-base 10.1.277 → 10.1.279

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 (155) hide show
  1. package/dist-server/service/agent/ai-client-for.js +2 -0
  2. package/dist-server/service/agent/ai-model-price.d.ts +22 -0
  3. package/dist-server/service/agent/ai-model-price.js +81 -0
  4. package/dist-server/service/agent/ai-usage-summary.d.ts +8 -1
  5. package/dist-server/service/agent/ai-usage-summary.js +17 -4
  6. package/dist-server/service/agent/ai-usage.d.ts +2 -0
  7. package/dist-server/service/agent/ai-usage.js +12 -2
  8. package/dist-server/service/agent/index.d.ts +2 -0
  9. package/dist-server/service/agent/index.js +4 -1
  10. package/dist-server/service/agent/model-price-boot.d.ts +1 -0
  11. package/dist-server/service/agent/model-price-boot.js +14 -0
  12. package/dist-server/service/agent/model-price.d.ts +77 -0
  13. package/dist-server/service/agent/model-price.js +214 -0
  14. package/dist-server/service/index.d.ts +3 -1
  15. package/dist-server/service/index.js +3 -1
  16. package/dist-server/service/providers/anthropic.js +2 -5
  17. package/dist-server/service/providers/gemini.js +2 -6
  18. package/dist-server/service/providers/openai.js +2 -5
  19. package/dist-server/service/providers/usage.d.ts +18 -0
  20. package/dist-server/service/providers/usage.js +50 -0
  21. package/dist-server/service/types.d.ts +6 -0
  22. package/package.json +20 -6
  23. package/translations/en.json +5 -1
  24. package/translations/es.json +5 -1
  25. package/translations/ja.json +5 -1
  26. package/translations/ko.json +5 -1
  27. package/translations/ms.json +5 -1
  28. package/translations/zh.json +5 -1
  29. package/dist-server/index.js.map +0 -1
  30. package/dist-server/service/agent/agent-directory.js.map +0 -1
  31. package/dist-server/service/agent/agent-settings-save.js.map +0 -1
  32. package/dist-server/service/agent/agent-spec.js.map +0 -1
  33. package/dist-server/service/agent/ai-client-for.js.map +0 -1
  34. package/dist-server/service/agent/ai-usage-summary.js.map +0 -1
  35. package/dist-server/service/agent/ai-usage.js.map +0 -1
  36. package/dist-server/service/agent/index.js.map +0 -1
  37. package/dist-server/service/agent/provider-models.js.map +0 -1
  38. package/dist-server/service/agentic-loop/agentic-loop.js.map +0 -1
  39. package/dist-server/service/agentic-loop/index.js.map +0 -1
  40. package/dist-server/service/analysis-contract.js.map +0 -1
  41. package/dist-server/service/assistant/abort-notice.js.map +0 -1
  42. package/dist-server/service/assistant/assistant-chat.js.map +0 -1
  43. package/dist-server/service/assistant/index.js.map +0 -1
  44. package/dist-server/service/assistant/open-subject.js.map +0 -1
  45. package/dist-server/service/assistant/registry-assistant.js.map +0 -1
  46. package/dist-server/service/assistant/registry-gate.js.map +0 -1
  47. package/dist-server/service/assistant/summarize.js.map +0 -1
  48. package/dist-server/service/assistant/tool-budget.js.map +0 -1
  49. package/dist-server/service/assistant/tool-scope.js.map +0 -1
  50. package/dist-server/service/capability.js.map +0 -1
  51. package/dist-server/service/decision/config.js.map +0 -1
  52. package/dist-server/service/decision/decision.js.map +0 -1
  53. package/dist-server/service/decision/index.js.map +0 -1
  54. package/dist-server/service/decision/jev.js.map +0 -1
  55. package/dist-server/service/factory.js.map +0 -1
  56. package/dist-server/service/index.js.map +0 -1
  57. package/dist-server/service/providers/anthropic.js.map +0 -1
  58. package/dist-server/service/providers/gemini.js.map +0 -1
  59. package/dist-server/service/providers/index.js.map +0 -1
  60. package/dist-server/service/providers/openai.js.map +0 -1
  61. package/dist-server/service/providers/request-options.js.map +0 -1
  62. package/dist-server/service/testing/tool-call-context.js.map +0 -1
  63. package/dist-server/service/tool-registry/call-recorder.js.map +0 -1
  64. package/dist-server/service/tool-registry/index.js.map +0 -1
  65. package/dist-server/service/tool-registry/registry.js.map +0 -1
  66. package/dist-server/service/tool-registry/translate.js.map +0 -1
  67. package/dist-server/service/tool-registry/types.js.map +0 -1
  68. package/dist-server/service/types.js.map +0 -1
  69. package/dist-server/service/utils/grounding.js.map +0 -1
  70. package/dist-server/service/utils/index.js.map +0 -1
  71. package/dist-server/service/utils/parse-json.js.map +0 -1
  72. package/dist-server/service/utils/transient.js.map +0 -1
  73. package/dist-server/tsconfig.tsbuildinfo +0 -1
  74. package/docs/grounded-analysis-contract.md +0 -54
  75. package/experiments/entity360/README.md +0 -224
  76. package/experiments/entity360/apps.cjs +0 -103
  77. package/experiments/entity360/apps.test.cjs +0 -24
  78. package/experiments/entity360/baseline-apps-results.json +0 -3357
  79. package/experiments/entity360/baseline-expanded-results.json +0 -5952
  80. package/experiments/entity360/baseline-results.json +0 -1507
  81. package/experiments/entity360/expanded.cjs +0 -65
  82. package/experiments/entity360/fixtures.json +0 -100
  83. package/experiments/entity360/index.html +0 -44
  84. package/experiments/entity360/jev-apps-results.json +0 -3440
  85. package/experiments/entity360/jev-expanded-results.json +0 -6095
  86. package/experiments/entity360/jev-results.json +0 -1542
  87. package/experiments/entity360/run.cjs +0 -100
  88. package/server/index.ts +0 -19
  89. package/server/service/agent/agent-directory.test.ts +0 -206
  90. package/server/service/agent/agent-directory.ts +0 -198
  91. package/server/service/agent/agent-settings-save.test.ts +0 -151
  92. package/server/service/agent/agent-settings-save.ts +0 -205
  93. package/server/service/agent/agent-spec.ts +0 -103
  94. package/server/service/agent/ai-client-for.test.ts +0 -170
  95. package/server/service/agent/ai-client-for.ts +0 -215
  96. package/server/service/agent/ai-usage-summary.test.ts +0 -65
  97. package/server/service/agent/ai-usage-summary.ts +0 -146
  98. package/server/service/agent/ai-usage.ts +0 -97
  99. package/server/service/agent/index.ts +0 -7
  100. package/server/service/agent/one-door.test.ts +0 -57
  101. package/server/service/agent/provider-models.ts +0 -43
  102. package/server/service/agentic-loop/agentic-loop.test.ts +0 -1118
  103. package/server/service/agentic-loop/agentic-loop.ts +0 -745
  104. package/server/service/agentic-loop/index.ts +0 -1
  105. package/server/service/agentic-loop/proposal-key.test.ts +0 -83
  106. package/server/service/analysis-contract.test.ts +0 -20
  107. package/server/service/analysis-contract.ts +0 -77
  108. package/server/service/assistant/abort-notice.ts +0 -67
  109. package/server/service/assistant/assistant-chat.test.ts +0 -240
  110. package/server/service/assistant/assistant-chat.ts +0 -104
  111. package/server/service/assistant/index.ts +0 -13
  112. package/server/service/assistant/open-subject.test.ts +0 -91
  113. package/server/service/assistant/open-subject.ts +0 -140
  114. package/server/service/assistant/registry-assistant.test.ts +0 -627
  115. package/server/service/assistant/registry-assistant.ts +0 -240
  116. package/server/service/assistant/registry-gate.ts +0 -76
  117. package/server/service/assistant/summarize.ts +0 -47
  118. package/server/service/assistant/tool-budget.test.ts +0 -246
  119. package/server/service/assistant/tool-budget.ts +0 -186
  120. package/server/service/assistant/tool-scope.test.ts +0 -123
  121. package/server/service/assistant/tool-scope.ts +0 -103
  122. package/server/service/capability.test.ts +0 -40
  123. package/server/service/capability.ts +0 -49
  124. package/server/service/decision/config.test.ts +0 -55
  125. package/server/service/decision/config.ts +0 -49
  126. package/server/service/decision/decision.test.ts +0 -94
  127. package/server/service/decision/decision.ts +0 -112
  128. package/server/service/decision/index.ts +0 -3
  129. package/server/service/decision/jev.ts +0 -40
  130. package/server/service/factory.ts +0 -28
  131. package/server/service/index.ts +0 -17
  132. package/server/service/providers/anthropic.ts +0 -274
  133. package/server/service/providers/gemini.ts +0 -396
  134. package/server/service/providers/index.ts +0 -8
  135. package/server/service/providers/json-answer.test.ts +0 -53
  136. package/server/service/providers/openai-models.test.ts +0 -30
  137. package/server/service/providers/openai.ts +0 -326
  138. package/server/service/providers/request-options.ts +0 -12
  139. package/server/service/providers/request-signal.test.ts +0 -77
  140. package/server/service/providers/transcribe.test.ts +0 -18
  141. package/server/service/testing/tool-call-context.ts +0 -38
  142. package/server/service/tool-registry/call-recorder.ts +0 -116
  143. package/server/service/tool-registry/index.ts +0 -50
  144. package/server/service/tool-registry/registry.test.ts +0 -319
  145. package/server/service/tool-registry/registry.ts +0 -248
  146. package/server/service/tool-registry/translate.ts +0 -12
  147. package/server/service/tool-registry/types.ts +0 -305
  148. package/server/service/types.ts +0 -221
  149. package/server/service/utils/grounding.test.ts +0 -119
  150. package/server/service/utils/grounding.ts +0 -131
  151. package/server/service/utils/index.ts +0 -3
  152. package/server/service/utils/parse-json.ts +0 -116
  153. package/server/service/utils/transient.test.ts +0 -92
  154. package/server/service/utils/transient.ts +0 -92
  155. package/tsconfig.json +0 -9
@@ -1 +0,0 @@
1
- export * from './agentic-loop.js'
@@ -1,83 +0,0 @@
1
- /*
2
- * What this guards: two different things the assistant proposes are two cards.
3
- *
4
- * The key folded on `tool|command|instanceId|args`, which fits a command proposal and nothing else.
5
- * Twin's other three (a declaration, a new twin draft, an analysis board) carry no command, so two
6
- * different value declarations for the same twin collapsed into one card — and pressing one marked
7
- * the other sent. The person then saw one card for two decisions [Twin lane found it, 2026-09-17].
8
- *
9
- * The chief architect ruled: the key comes from the proposal's content, and a shape the component
10
- * does not recognise is not folded at all (ADR-0053).
11
- */
12
- import { proposalEffectKey } from './agentic-loop'
13
-
14
- const command = (over: any = {}) => ({ tool: 'proposeAction', command: 'stop', instanceId: 'EQ-1', args: { reason: 'jam' }, label: 'stop it', ...over })
15
- const declaration = (over: any = {}) => ({ tool: 'proposeDeclaration', proposed: true, twinId: 'T-1', values: { capacity: 10 }, label: 'set capacity', ...over })
16
-
17
- it('★ the same command twice is one card', () => {
18
- expect(proposalEffectKey(command())).toBe(proposalEffectKey(command({ label: 'worded differently', reason: 'because' })))
19
- })
20
-
21
- it('a different target, or different arguments, is a different card', () => {
22
- expect(proposalEffectKey(command())).not.toBe(proposalEffectKey(command({ instanceId: 'EQ-2' })))
23
- expect(proposalEffectKey(command())).not.toBe(proposalEffectKey(command({ args: { reason: 'maintenance' } })))
24
- })
25
-
26
- it('★ two different declarations for the same twin are two cards — this is the defect', () => {
27
- const first = declaration({ values: { capacity: 10 } })
28
- const second = declaration({ values: { capacity: 25 } })
29
-
30
- expect(proposalEffectKey(first)).not.toBe(proposalEffectKey(second))
31
- })
32
-
33
- it('★ the same declaration proposed twice is still one card', () => {
34
- expect(proposalEffectKey(declaration())).toBe(proposalEffectKey(declaration({ label: 'reworded', reason: 'why' })))
35
- })
36
-
37
- it('★ proposals from different tools never share a card', () => {
38
- expect(proposalEffectKey(declaration())).not.toBe(proposalEffectKey({ tool: 'proposeTwin', proposed: true, twinId: 'T-1', values: { capacity: 10 } }))
39
- })
40
-
41
- it('wording does not make a new card — label, reason, icon and follow-ups are presentation', () => {
42
- const plain = declaration()
43
- const dressed = declaration({ label: 'x', reason: 'y', icon: 'bolt', choices: [{ label: 'more' }], key: 'ignored' })
44
-
45
- expect(proposalEffectKey(plain)).toBe(proposalEffectKey(dressed))
46
- })
47
-
48
- it('★ a scene edit with different ops is a different card', () => {
49
- const edit = (left: number) => ({ tool: 'proposeSceneEdit', proposed: true, kind: 'scene-edit', ops: [{ op: 'add', component: { tag: 'EQ-1', left } }] })
50
-
51
- expect(proposalEffectKey(edit(10))).not.toBe(proposalEffectKey(edit(880)))
52
- })
53
-
54
- /*
55
- * 이 키는 **사람이 읽는 자리로 나간다** — 호스트가 제안의 결말을 알리면 서버가 그것을 system 행으로
56
- * 적고 그 행이 대화에 남는다. 인자를 그대로 이어 붙이면 그 줄이 원형 JSON 이 된다.
57
- *
58
- * 2026-09-18 트윈 모델러에 이렇게 남아 있었다 — `proposal proposeSceneEdit({"kind":"scene-edit",
59
- * "ops":[{"component":{"height":180,"left":100,…`. 새로 고쳐도 그대로였다.
60
- */
61
- describe('the key is read by people', () => {
62
- const sceneEdit = {
63
- tool: 'proposeSceneEdit',
64
- kind: 'scene-edit',
65
- ops: [{ component: { height: 180, left: 100, top: 240, type: 'rect' }, refid: 'EQ-1' }]
66
- }
67
-
68
- it('★ 인자가 키에 그대로 실리지 않는다', () => {
69
- const key = proposalEffectKey(sceneEdit)
70
-
71
- expect(key).not.toContain('component')
72
- expect(key).not.toContain('180')
73
- expect(key).not.toContain('{')
74
- })
75
-
76
- it('★ 한 줄에 들어갈 만큼 짧다 — 대화에 남는 글이다', () => {
77
- expect(proposalEffectKey(sceneEdit).length).toBeLessThan(64)
78
- })
79
-
80
- it('도구 이름은 남는다 — 무엇에 대한 줄인지는 사람도 모델도 읽어야 한다', () => {
81
- expect(proposalEffectKey(sceneEdit).startsWith('proposeSceneEdit#')).toBe(true)
82
- })
83
- })
@@ -1,20 +0,0 @@
1
- import assert from 'node:assert/strict'
2
-
3
- import { isGroundedAnalysisContract } from './analysis-contract.ts'
4
-
5
- test('grounded analysis contract requires confidence, limitations, claims, and human approval', () => {
6
- assert.equal(isGroundedAnalysisContract({
7
- kind: 'example', scope: {}, window: {}, facts: {},
8
- confidence: { level: 'medium', reasons: ['sample-incomplete'] },
9
- limitations: [{ code: 'sample-incomplete' }],
10
- claims: [],
11
- approvalRequired: true,
12
- approval: { required: true, mode: 'review', reason: 'advisory' }
13
- }), true)
14
- })
15
-
16
- test('grounded analysis contract rejects an auto-executable response', () => {
17
- assert.equal(isGroundedAnalysisContract({
18
- kind: 'example', confidence: { level: 'high', reasons: [] }, limitations: [], claims: [], approvalRequired: false, approval: { required: false }
19
- }), false)
20
- })
@@ -1,77 +0,0 @@
1
- /**
2
- * Product-neutral contract for an AI conclusion that must be reviewed by a person.
3
- *
4
- * This is deliberately a vocabulary contract, not a domain model. Plant owns
5
- * execution facts, Twin owns engineering calculations, Figure owns rendering
6
- * checks, and Board owns edit patches. They can nevertheless expose the same
7
- * answer to a caller: what was observed, what was assumed, how certain it is,
8
- * what is missing, and whether a person must approve a proposed next step.
9
- */
10
-
11
- export type AIConfidenceLevel = 'high' | 'medium' | 'low'
12
-
13
- export interface AIAnalysisConfidence {
14
- level: AIConfidenceLevel
15
- /** Stable, machine-readable reasons. Do not put model prose here. */
16
- reasons: string[]
17
- }
18
-
19
- export interface AIAnalysisLimitation {
20
- code: string
21
- params?: Record<string, unknown>
22
- }
23
-
24
- export interface AIAnalysisClaim {
25
- code: string
26
- severity?: 'info' | 'warning' | 'critical'
27
- params?: Record<string, unknown>
28
- evidence: Record<string, unknown>
29
- method: string
30
- assumptions: string[]
31
- }
32
-
33
- export interface AIApprovalRequirement {
34
- /** AI output is advisory. A product authority must accept any state change. */
35
- required: true
36
- mode: 'review' | 'confirm'
37
- reason: string
38
- }
39
-
40
- /**
41
- * The portable part of a product AI response.
42
- *
43
- * `facts` and the specialized claim type intentionally remain generic. Moving
44
- * them here would make product-specific evidence look interchangeable and would
45
- * erase important operational, engineering, rendering, and board constraints.
46
- */
47
- export interface GroundedAnalysisContract<TFacts = unknown, TClaim extends AIAnalysisClaim = AIAnalysisClaim, TProposal = unknown> {
48
- kind: string
49
- scope: unknown
50
- window: unknown
51
- confidence: AIAnalysisConfidence
52
- limitations: AIAnalysisLimitation[]
53
- claims: TClaim[]
54
- facts: TFacts
55
- /** A domain-owned candidate. It is never an instruction to mutate canonical state. */
56
- proposal?: TProposal
57
- /** Convenient transport flag for docks and GraphQL clients. */
58
- approvalRequired: true
59
- approval: AIApprovalRequirement
60
- trace?: { source?: string; generatedAt?: string; version?: string }
61
- }
62
-
63
- /** A small runtime boundary for GraphQL/JSON consumers receiving untyped data. */
64
- export function isGroundedAnalysisContract(value: unknown): value is GroundedAnalysisContract {
65
- const one = value as any
66
- return !!one &&
67
- typeof one === 'object' &&
68
- typeof one.kind === 'string' &&
69
- !!one.confidence &&
70
- ['high', 'medium', 'low'].includes(one.confidence.level) &&
71
- Array.isArray(one.confidence.reasons) &&
72
- Array.isArray(one.limitations) &&
73
- Array.isArray(one.claims) &&
74
- one.approvalRequired === true &&
75
- !!one.approval && one.approval.required === true &&
76
- (one.approval.mode === 'review' || one.approval.mode === 'confirm')
77
- }
@@ -1,67 +0,0 @@
1
- /*
2
- * Why the loop stopped, said to the person who asked.
3
- *
4
- * ── Why this is here and not in a product (2026-09-10) ───────────────────────────
5
- * This came out of `board-ai`. It is not board's: every product that runs the agentic loop can
6
- * have it stop early, and a reply that was cut off looks exactly like a reply that finished.
7
- *
8
- * The loop already reports why it stopped — `AgenticLoopResult.abortReason`. Nothing forces the
9
- * caller to say so. A product that forgets prints a truncated answer as though it were complete,
10
- * and the person acts on half of it. That failure is silent by construction, which is why the
11
- * notice belongs beside the loop rather than beside each product's prose.
12
- *
13
- * ── The words are the reader's, and the caller owns the reader (2026-09-18) ────────
14
- * These lines were Korean literals in a framework package, so every product said them in Korean
15
- * whatever language the person was reading in (ADR-0049 ② · ADR-0054). The notice now names a key
16
- * and carries an English default; a caller that has the request's translator hands it in and the
17
- * person reads the line in their own language.
18
- */
19
- import type { AgenticLoopResult } from '../agentic-loop/index.js'
20
- import { isTransientAIError } from '../utils/index.js'
21
-
22
- /** Turns a key and its values into the reader's sentence. `ai-assistant` hands in the request's `context.t`. */
23
- export type TranslateNotice = (key: string, params?: Record<string, any>) => string
24
-
25
- /** The English sentence for each reason, used when the caller has no translator. */
26
- const NOTICE_DEFAULTS: Record<string, string> = {
27
- 'ai-assistant.notice.stopped': 'the request stopped partway, so only part of it was done.',
28
- 'ai-assistant.notice.provider-busy': 'the ai service did not answer just now. try again in a moment.',
29
- 'ai-assistant.notice.provider-error': 'something went wrong while handling this. tell an administrator if it keeps happening.',
30
- 'ai-assistant.notice.too-long': 'this stopped after {iter} lookups without an answer.',
31
- 'ai-assistant.notice.tool-kept-failing': '{tool} failed {count} times in a row, so it stopped. try saying it differently.'
32
- }
33
-
34
- function line(key: string, params: Record<string, any>, t?: TranslateNotice): string {
35
- const said = t
36
- ? t(key, { defaultValue: NOTICE_DEFAULTS[key], ...params })
37
- : Object.entries(params).reduce((text, [k, v]) => text.replaceAll(`{${k}}`, String(v)), NOTICE_DEFAULTS[key])
38
- return `\n\n_(${said})_`
39
- }
40
-
41
- /**
42
- * 중단 이유 → 답에 덧붙일 한 줄. 정상 종료면 빈 문자열이다.
43
- *
44
- * 답을 고치지 않고 **뒤에 붙인다** — 모델이 한 말을 우리가 다시 쓰지 않는다.
45
- */
46
- export function formatAbortNotice(
47
- abortReason: AgenticLoopResult<any>['abortReason'],
48
- t?: TranslateNotice
49
- ): string {
50
- if (!abortReason) return ''
51
- switch (abortReason.type) {
52
- case 'aborted':
53
- return line('ai-assistant.notice.stopped', {}, t)
54
- case 'provider_error':
55
- /* 남의 말(SDK 원문)을 사용자에게 보여주지 않는다 — "Error fetching from undefined: [503 …]" 은
56
- * 사용자가 할 수 있는 일을 알려주지 않는다. 일시 장애는 이미 몇 번 다시 시도한 뒤이므로,
57
- * 지금 필요한 안내는 "잠시 후 다시" 하나다. 원문은 서버 로그에 남는다. */
58
- return isTransientAIError({ message: abortReason.message })
59
- ? line('ai-assistant.notice.provider-busy', {}, t)
60
- : line('ai-assistant.notice.provider-error', {}, t)
61
- case 'max_iterations':
62
- /* A salvaged answer already says what it could not find. */
63
- return abortReason.salvaged ? '' : line('ai-assistant.notice.too-long', { iter: abortReason.iter }, t)
64
- case 'repeated_validation_failure':
65
- return line('ai-assistant.notice.tool-kept-failing', { tool: abortReason.toolName, count: abortReason.consecutive }, t)
66
- }
67
- }
@@ -1,240 +0,0 @@
1
- /*
2
- * What this guards: **the two things a product must not be able to skip.**
3
- *
4
- * The loop came out of board-ai on 2026-09-05 and the guards around it did not, so for four days
5
- * "run the loop" and "run the loop safely" were two different calls and only one of them was
6
- * reachable from a product without a board. The failure that made this urgent is recorded in
7
- * board-ai's grounding file: the twin's header route had the grounding guard and its dock route
8
- * did not, so the same question was verified on one side and not the other.
9
- *
10
- * So these tests are not about the loop's control flow — `agentic-loop.test.ts` covers that. They
11
- * assert that a caller who does nothing special still gets:
12
- *
13
- * ① the reason the loop stopped, in the reply
14
- * ② the reply checked against what the model was actually handed
15
- *
16
- * and that ② reads `groundedTexts`, never the display summaries.
17
- */
18
- import { assistantChat } from './assistant-chat'
19
- import type { AIToolCall, AIToolChatResult } from '../types.js'
20
- import type { ToolDispatchHelpers } from '../agentic-loop/index.js'
21
-
22
- /*
23
- * ⚠ 식별자 픽스처가 **소문자**인 이유: 접지 가드의 `ID_TOKEN` 이
24
- * `[a-z][a-z0-9]*(-[a-z0-9]+)+` 다. 대문자 식별자(`WO-99871`)는 애초에 추출되지 않아 경고가 나올
25
- * 수 없고, 그것으로 시험을 쓰면 **구현이 무엇을 하든 초록**이 된다(처음에 그렇게 썼다).
26
- *
27
- * 그 사정거리 자체가 별 문제다 — plant 의 오더(`WO-…`)와 트윈의 태그(`TAG-FUNC-…`)가 대문자라
28
- * **이 가드가 그 제품들에는 닿지 않는다.** 이 파일이 고칠 것은 아니고(9개 앱이 이 규칙을 쓴다),
29
- * `utils/grounding.ts` 의 `ID_TOKEN` 을 넓히는 별 판단이다.
30
- */
31
- const TC = (name: string, args: any = {}, id = 't1'): AIToolCall =>
32
- ({ id, name, arguments: args, type: 'tool_use' } as any)
33
-
34
- const okResult = (text?: string, toolCalls: AIToolCall[] = []): AIToolChatResult =>
35
- ({
36
- text,
37
- toolCalls,
38
- stopReason: toolCalls.length > 0 ? 'tool_use' : 'end_turn',
39
- usage: undefined
40
- } as any)
41
-
42
- const dispatch = (overrides: Partial<ToolDispatchHelpers> = {}): ToolDispatchHelpers => ({
43
- isReadTool: () => false,
44
- isWriteTool: () => false,
45
- isActionTool: () => false,
46
- executeReadTool: () => ({ stub: true }),
47
- validateWriteToolCall: () => ({ valid: true }),
48
- toolCallToOp: () => null,
49
- summarizeToolResult: v => v,
50
- ...overrides
51
- })
52
-
53
- const input = (overrides: any = {}, dispatchOverrides: Partial<ToolDispatchHelpers> = {}) => ({
54
- initialConversation: [{ role: 'user' as const, content: 'hi' }],
55
- tools: [],
56
- options: { systemPrompt: 'you are a bot' },
57
- chat: async () => okResult('done'),
58
- dispatch: dispatch(dispatchOverrides),
59
- context: {},
60
- ...overrides
61
- })
62
-
63
- describe('assistantChat — ① 중단 이유가 답에 닿는다', () => {
64
- it('정상 종료면 답이 모델의 말 그대로다 — 없는 통지를 붙이지 않는다', async () => {
65
- const r = await assistantChat(input({ chat: async () => okResult('열두 대입니다') }))
66
- expect(r.reply).toBe('열두 대입니다')
67
- expect(r.baseText).toBe('열두 대입니다')
68
- })
69
-
70
- it('공급자 오류로 멈추면 그 사실이 답에 붙는다 — 잘린 답이 완결로 보이지 않는다', async () => {
71
- const r = await assistantChat(
72
- input({
73
- chat: async () => {
74
- throw new Error('Error fetching from undefined: [503 Service Unavailable]')
75
- }
76
- })
77
- )
78
- expect(r.loop.abortReason?.type).toBe('provider_error')
79
- expect(r.reply).toMatch(/try again in a moment/)
80
- /* 남의 말(SDK 원문)을 사용자에게 보여주지 않는다. */
81
- expect(r.reply).not.toMatch(/503/)
82
- expect(r.reply).not.toMatch(/Error fetching/)
83
- })
84
-
85
- it('반복 한계로 멈추면 답이 그것을 말한다', async () => {
86
- /* 도구를 계속 부르게 해서 max_iterations 로 몰아넣는다. */
87
- const r = await assistantChat(
88
- input(
89
- {
90
- options: { systemPrompt: 's', maxIterations: 2 },
91
- chat: async () => okResult(undefined, [TC('read1')])
92
- },
93
- { isReadTool: () => true }
94
- )
95
- )
96
- expect(r.loop.abortReason?.type).toBe('max_iterations')
97
- /* No translator was handed in, so the line falls back to English. */
98
- expect(r.reply).toMatch(/stopped after 2 lookups/)
99
- })
100
-
101
- it('★ 통지의 말은 읽는 사람의 것이다 — 번역기를 주면 그것이 쓴 문장이 붙는다', async () => {
102
- const asked: any[] = []
103
- const r = await assistantChat(
104
- input(
105
- {
106
- options: { systemPrompt: 's', maxIterations: 2 },
107
- chat: async () => okResult(undefined, [TC('read1')]),
108
- t: (key: string, params: any) => {
109
- asked.push({ key, params })
110
- return `멈췄습니다(${params.iter}단계)`
111
- }
112
- },
113
- { isReadTool: () => true }
114
- )
115
- )
116
- expect(asked[0].key).toBe('ai-assistant.notice.too-long')
117
- expect(asked[0].params.iter).toBe(2)
118
- expect(asked[0].params.defaultValue).toMatch(/stopped after/)
119
- expect(r.reply).toContain('멈췄습니다(2단계)')
120
- })
121
-
122
- it('통지는 답을 고치지 않고 뒤에 붙는다', async () => {
123
- const r = await assistantChat(
124
- input(
125
- {
126
- options: { systemPrompt: 's', maxIterations: 1 },
127
- chat: async () => okResult('부분 결과', [TC('read1')])
128
- },
129
- { isReadTool: () => true }
130
- )
131
- )
132
- expect(r.baseText).toBe('부분 결과')
133
- expect(r.reply.startsWith('부분 결과')).toBe(true)
134
- expect(r.reply.length).toBeGreaterThan(r.baseText.length)
135
- })
136
- })
137
-
138
- describe('assistantChat — ② 접지 검사가 그냥 돈다', () => {
139
- it('아무 설정 없이도 근거 밖 식별자가 잡힌다 — 켜는 것을 잊을 수 없다', async () => {
140
- const r = await assistantChat(input({ chat: async () => okResult('wo-99871 이 밀렸습니다') }))
141
- expect(r.groundingWarnings).toBeDefined()
142
- expect(r.groundingWarnings!.join(' ')).toMatch(/wo-99871/)
143
- })
144
-
145
- it('도구가 준 원문 안의 식별자는 경고가 아니다', async () => {
146
- const r = await assistantChat(
147
- input(
148
- {
149
- chat: async (msgs: any[]) =>
150
- msgs.some(m => JSON.stringify(m.content).includes('wo-99871'))
151
- ? okResult('wo-99871 이 밀렸습니다')
152
- : okResult(undefined, [TC('findOrders')])
153
- },
154
- { isReadTool: () => true, executeReadTool: () => ({ orders: ['wo-99871'] }) }
155
- )
156
- )
157
- expect(r.baseText).toBe('wo-99871 이 밀렸습니다')
158
- expect(r.groundingWarnings).toBeUndefined()
159
- })
160
-
161
- it('★ 근거는 groundedTexts 다 — 화면용 요약이 잘라낸 식별자를 「근거 없음」으로 오판하지 않는다', async () => {
162
- /*
163
- * 이 시험이 이 파일의 이유다. `summarizeToolResult` 를 「전부 버린다」로 두면, 화면 요약을 근거로
164
- * 읽는 구현은 정상 답을 경고로 만든다. 모델은 원문을 받았기 때문이다.
165
- */
166
- const r = await assistantChat(
167
- input(
168
- {
169
- chat: async (msgs: any[]) =>
170
- msgs.some(m => JSON.stringify(m.content).includes('wo-99871'))
171
- ? okResult('wo-99871 이 밀렸습니다')
172
- : okResult(undefined, [TC('findOrders')])
173
- },
174
- {
175
- isReadTool: () => true,
176
- executeReadTool: () => ({ orders: ['wo-99871'] }),
177
- summarizeToolResult: () => '…(생략)'
178
- }
179
- )
180
- )
181
- expect(r.loop.toolUsages[0].result).toBe('…(생략)')
182
- expect(r.loop.groundedTexts.join(' ')).toMatch(/wo-99871/)
183
- expect(r.groundingWarnings).toBeUndefined()
184
- })
185
-
186
- it('호스트가 준 문맥도 근거다 — 안 주면 정상 답이 경고를 받는다', async () => {
187
- const reply = 'board-77 을 고쳤습니다'
188
-
189
- const without = await assistantChat(input({ chat: async () => okResult(reply) }))
190
- expect(without.groundingWarnings?.join(' ')).toMatch(/board-77/)
191
-
192
- const withContext = await assistantChat(
193
- input({ chat: async () => okResult(reply), groundingSources: { hostContext: 'current board: board-77' } })
194
- )
195
- expect(withContext.groundingWarnings).toBeUndefined()
196
- })
197
-
198
- it('명시로만 끌 수 있다 — 그리고 끈 것은 경고를 버린 것과 구별된다', async () => {
199
- const r = await assistantChat(
200
- input({ chat: async () => okResult('wo-99871 이 밀렸습니다'), skipGrounding: true })
201
- )
202
- expect(r.groundingWarnings).toBeUndefined()
203
- })
204
-
205
- it('경고가 없으면 undefined 다 — 빈 배열을 주지 않는다', async () => {
206
- const r = await assistantChat(input({ chat: async () => okResult('네') }))
207
- expect(r.groundingWarnings).toBeUndefined()
208
- })
209
- })
210
-
211
- describe('assistantChat — 말을 지어내지 않는다', () => {
212
- it('모델이 말을 안 하고 끝나면 답이 비어 있다 — 도메인을 모르는 자리에서 서술하지 않는다', async () => {
213
- const r = await assistantChat(
214
- input({ chat: async () => okResult(undefined) })
215
- )
216
- expect(r.baseText).toBe('')
217
- expect(r.reply).toBe('')
218
- /* 말이 없으면 검사할 것도 없다 — 빈 답에 대고 경고를 만들지 않는다. */
219
- expect(r.groundingWarnings).toBeUndefined()
220
- })
221
-
222
- it('루프 결과는 그대로 넘어온다 — 호스트가 자기 뜻으로 해석한다', async () => {
223
- /* 도구를 한 번만 부르게 한다 — 매번 같은 호출을 돌려주면 루프가 반복 한계까지 돈다. */
224
- let called = false
225
- const r = await assistantChat(
226
- input(
227
- {
228
- chat: async () => {
229
- if (called) return okResult('했습니다')
230
- called = true
231
- return okResult(undefined, [TC('write1')])
232
- }
233
- },
234
- { isWriteTool: () => true }
235
- )
236
- )
237
- expect(r.loop.accumulatedWriteCalls.map(c => c.name)).toEqual(['write1'])
238
- expect(r.baseText).toBe('했습니다')
239
- })
240
- })
@@ -1,104 +0,0 @@
1
- /*
2
- * One turn of an assistant — the loop **with the guards that must not be optional.**
3
- *
4
- * ── Why this exists (2026-09-10) ────────────────────────────────────────────────
5
- * `runAgenticLoop` is neutral and has been since 2026-09-05, when the same loop running in two
6
- * places was consolidated. The note on that change is the reason this file exists: it was "not a
7
- * duplication, a defect" — the two copies had **their safety measures set opposite ways**.
8
- *
9
- * The loop came out. The guards around it did not. They stayed in `board-ai`, wrapped around
10
- * `DefaultBoardAIAssistant.chat`, which meant a product with no board of its own could only get
11
- * them by going through the board editor. The plant lane read that correctly — it uses none of
12
- * board's session machinery — and asked whether it could call `runAgenticLoop` directly instead.
13
- *
14
- * The answer was no, and the reason is written in `board-ai`'s own grounding file: the twin's
15
- * header route had a grounding guard and its dock route did not, so **the same question was
16
- * verified on one side and not the other.** A per-product door makes that three ways. This file is
17
- * the door instead.
18
- *
19
- * ── What is guaranteed here, and what the host still owns ───────────────────────
20
- * Guaranteed, because a caller cannot skip it:
21
- * · the loop stops for a reason and the reason reaches the reply (`formatAbortNotice`)
22
- * · the reply is checked against what the model was actually given (`groundingWarnings`)
23
- *
24
- * Still the host's, because only the host knows the domain:
25
- * · which tools exist and what a write call means → `gate`, `dispatch`
26
- * · what counts as evidence beyond the tool results → `groundingSources`
27
- *
28
- * ── Grounding sources: leaving one out produces false warnings ──────────────────
29
- * The corpus is everything the model saw this turn. The tool results are added here, from
30
- * `groundedTexts` — the raw strings sent back as `tool_result`, never `toolUsages[].result`, which
31
- * is depth-limited for display. A check reading the display copy can pass while the model was
32
- * handed `{}`; an un-awaited async builder did exactly that.
33
- *
34
- * Anything else the host put in front of the model — a system prompt, a state summary, the user's
35
- * own words — has to be declared, or a correct answer quoting it gets warned about.
36
- */
37
- import { runAgenticLoop, type AgenticLoopInput, type AgenticLoopResult } from '../agentic-loop/index.js'
38
- import { buildGroundedCorpus, groundingWarnings, type GroundingSources } from '../utils/index.js'
39
- import { formatAbortNotice, type TranslateNotice } from './abort-notice.js'
40
-
41
- export interface AssistantChatInput<TCtx = unknown, TOp = unknown> extends AgenticLoopInput<TCtx, TOp> {
42
- /**
43
- * The request's translator, so a notice this function appends is in the reader's language
44
- * (ADR-0054). Without it the notice falls back to English.
45
- */
46
- t?: TranslateNotice
47
- /**
48
- * 이 턴에 모델이 본 것 — **도구 결과 말고** 전부. 도구 결과는 이 함수가 루프에서 받아 더한다.
49
- *
50
- * 빠뜨리면 정상 답이 경고를 받는다(오탐). 시스템 프롬프트에 적어 보낸 타입 이름을 모델이 말하는
51
- * 것은 근거 있는 발언이다.
52
- */
53
- groundingSources?: Omit<GroundingSources, 'toolResults'>
54
- /**
55
- * 접지 검사를 끈다 — **기본은 켜짐.**
56
- *
57
- * 끄는 것이 맞는 자리가 있다: 식별자를 다루지 않는 대화(문서 상담·개념 질문)는 근거집합에 식별자가
58
- * 없어 모든 고유명사가 경고로 나온다. 그때는 끄는 것이 정직하고, **켠 채로 경고를 버리는 것**이
59
- * 정직하지 않다.
60
- */
61
- skipGrounding?: boolean
62
- }
63
-
64
- export interface AssistantChatResult<TOp = unknown> {
65
- /**
66
- * 사용자에게 보일 답 — 모델의 마지막 말 + 중단 통지.
67
- *
68
- * 모델의 말을 고치지 않는다. 통지는 **뒤에 붙는다.**
69
- */
70
- reply: string
71
- /** 통지가 붙기 전의 답. 접지 검사가 본 것이고, 호스트가 다시 판정할 때 쓴다. */
72
- baseText: string
73
- /** 근거 밖의 식별자를 지목한 자리들. 없으면 undefined — 빈 배열을 주지 않는다. */
74
- groundingWarnings?: string[]
75
- /** 루프 결과 원본 — 쓰기 호출·조치·제안·도구 흔적. 호스트가 자기 뜻으로 해석한다. */
76
- loop: AgenticLoopResult<TOp>
77
- }
78
-
79
- /**
80
- * 한 턴을 돌린다.
81
- *
82
- * `lastText` 가 없을 수 있다(도구만 부르고 말을 안 한 턴). 그 경우 `baseText` 는 빈 문자열이고,
83
- * 무엇을 대신 말할지는 호스트가 정한다 — 여기서 「변경했습니다」 같은 말을 지어내지 않는다.
84
- * 도메인을 모르는 자리에서 결과를 서술하면 그것이 곧 지어낸 원인이 된다.
85
- */
86
- export async function assistantChat<TCtx = unknown, TOp = unknown>(
87
- input: AssistantChatInput<TCtx, TOp>
88
- ): Promise<AssistantChatResult<TOp>> {
89
- const { groundingSources, skipGrounding, ...loopInput } = input
90
-
91
- const loop = await runAgenticLoop<TCtx, TOp>(loopInput)
92
-
93
- const baseText = loop.lastText ?? ''
94
- const reply = baseText + formatAbortNotice(loop.abortReason, input.t)
95
-
96
- let warnings: string[] | undefined
97
- if (!skipGrounding && baseText) {
98
- const corpus = buildGroundedCorpus({ ...(groundingSources ?? {}), toolResults: loop.groundedTexts })
99
- const found = groundingWarnings(baseText, corpus)
100
- warnings = found.length > 0 ? found : undefined
101
- }
102
-
103
- return { reply, baseText, groundingWarnings: warnings, loop }
104
- }
@@ -1,13 +0,0 @@
1
- /*
2
- * The neutral assistant layer — the agentic loop plus the guards that must not be optional.
3
- *
4
- * See `assistant-chat.ts` for why this is not in a product package.
5
- */
6
- export * from './abort-notice.js'
7
- export * from './summarize.js'
8
- export * from './tool-scope.js'
9
- export * from './tool-budget.js'
10
- export * from './registry-gate.js'
11
- export * from './assistant-chat.js'
12
- export * from './registry-assistant.js'
13
- export * from './open-subject.js'