@things-factory/ai-client-base 10.1.278 → 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,240 +0,0 @@
1
- /*
2
- * A conversation for a product that has no editor of its own.
3
- *
4
- * ── What this is for ───────────────────────────────────────────────────────────
5
- * `board-ai` assembles its conversation from two sources: its own board editing tools, and
6
- * whatever other packages registered in the tool registry. The second half is the same work for
7
- * every product — read the specs, build the definitions, dispatch by name — but it only existed
8
- * inside the board assistant, so a product without a board had nowhere to ask a question from.
9
- * operato-figure hit exactly that: the dock was mounted, the tools were registered, and the only
10
- * mutation that could run them lived in a package figure does not load.
11
- *
12
- * ── Read only ──────────────────────────────────────────────────────────────────
13
- * A registry category may also carry `write` and `action` tools. Those produce edit ops for a
14
- * document the host owns, and a host with no document cannot apply them. Offering them here would
15
- * declare a door with no road behind it — the model would call one and the call would go nowhere.
16
- * `external` tools change something outside the conversation (board-import's
17
- * `materializeImportSession` creates a Board) and this door has no confirm-and-apply step, so they
18
- * are not offered either (A1, 2026-09-17). This runner offers, and dispatches, `read` only.
19
- *
20
- * The gate answers from the same list the definitions are built from, so what is offered and what
21
- * may be dispatched cannot drift apart.
22
- */
23
- import type { AIClient, AIMessage } from '../types.js'
24
- import { narrowToolScope, resolveToolScope, type ToolAccessCheck } from './tool-scope.js'
25
- import { assistantChat, type AssistantChatResult } from './assistant-chat.js'
26
- import { resultShapeOf } from './summarize.js'
27
- import type { GroundingSources } from '../utils/index.js'
28
- import type { ToolAttachment, ToolCallContext, UnattendedRunRef } from '../tool-registry/types.js'
29
- import { defaultValueTranslate } from '../tool-registry/translate.js'
30
- import { digestOf, recordToolCall, type ToolCallRecord, type ToolCallRun } from '../tool-registry/call-recorder.js'
31
- import { OPEN_TOOLS, TOOL_BUDGET_CATEGORY, toolOfferState, type ToolFront } from './tool-budget.js'
32
-
33
-
34
- /** Lookups a registry conversation may take before it answers from what it has (operato-twin's assistant takes 16 too). */
35
- export const REGISTRY_MAX_ITERATIONS = 16
36
-
37
- export interface RegistryAssistantInput {
38
- /** Provider client. Must implement `chatWithTools`. */
39
- client: AIClient
40
- /** The conversation so far, newest last. The caller owns history and truncation. */
41
- messages: AIMessage[]
42
- /** Who the assistant is and what this surface is. The host owns this prose. */
43
- systemPrompt: string
44
- /**
45
- * Categories this conversation may use. **Omitting it allows nothing** — the same as an empty
46
- * list, a plain conversation with no tools (A1, 2026-09-17). It used to mean every registered
47
- * category, which is how a Board-creating tool reached any conversation.
48
- */
49
- toolCategories?: string[]
50
- /**
51
- * What goes in front when the scope is larger than one call carries (ADR-0061 decision 9) - the screen's records,
52
- * the tools this conversation used. The rest the model opens with `openTools`. Without it, only `openTools` is in
53
- * front of a scope that does not fit.
54
- */
55
- front?: ToolFront
56
- /**
57
- * Answers whether the caller holds a tool's declared privilege. Without it, every tool that
58
- * declares a privilege stays closed. The host builds it from the request — this package does
59
- * not know auth.
60
- */
61
- toolAccess?: ToolAccessCheck
62
- /** Passed to tools as `context.host`. Client-supplied — never used for authorization. */
63
- hostContext?: any
64
- /**
65
- * Which conversation this is — `{ kind, target }` from the registered mode (ADR-0061 decision 3).
66
- *
67
- * Tools see it as `context.mode`. It is the server's value, resolved from the registry before the
68
- * turn runs, so a tool that behaves differently in two conversations reads it here and not from
69
- * `host`, which the client fills.
70
- */
71
- mode?: { kind: string; target?: string }
72
- /** Caller's koa state (domain, user, tx). Tools that read the database need it. */
73
- state: any
74
- model?: string
75
- temperature?: number
76
- maxTokens?: number
77
- /** Make the model call a tool before it may answer. For surfaces that report live state. */
78
- requireToolOnFirstTurn?: boolean
79
- /**
80
- * The request's translator — the stop notice is then in the reader's language, and tools write what a person
81
- * reads with it (`context.t`). Without it tools get `defaultValueTranslate`: the English default values.
82
- */
83
- t?: (key: string, params?: Record<string, any>) => string
84
- /**
85
- * The files sent with this turn, after the caller's server checked them — stored with this conversation, the
86
- * conversation the caller's to write, the mode's policy met (ADR-0061, 2026-10-16 decision 2). Tools see them as
87
- * `context.attachments`. Never built from the client's request: what a client puts in `hostContext` stays there.
88
- */
89
- attachments?: ToolAttachment[]
90
- /** Texts the answer is allowed to draw identifiers from, besides the tool results. */
91
- groundingSources?: Omit<GroundingSources, 'toolResults'>
92
- /** Stops the loop and the provider request - an unattended run's time limit. */
93
- signal?: AbortSignal
94
- /** Lookups before the answer; `REGISTRY_MAX_ITERATIONS` when absent. */
95
- maxIterations?: number
96
- /** At the lookup limit, one more call without tools to answer from what was read. On when absent. */
97
- salvageOnMaxIterations?: boolean
98
- /**
99
- * Each call as the recorders get it (`digestOf`, never its raw values) - an unattended run lists the reads its draft
100
- * rested on from the same digest the audit keeps, so the two cannot describe one call differently.
101
- */
102
- onToolCall?: (record: ToolCallRecord) => void
103
- /** Set for an unattended run; tools and recorders see it as `context.run`. */
104
- run?: UnattendedRunRef /** The stored conversation of this turn; tools see it as `context.conversation`. The caller's value, never the client's. */
105
- conversation?: { id: string }
106
- }
107
-
108
- export interface RegistryAssistantResult extends AssistantChatResult<unknown> {
109
- /** Tool names actually offered to the model this turn. The caller may log or return it. */
110
- offeredTools: string[]
111
- /** Tools of the scope the model could have opened and did not (ADR-0061 decision 9) - with `offeredTools`, all it may use. */
112
- openableTools: string[]
113
- }
114
-
115
- /**
116
- * Run one turn of a conversation whose only tools come from the registry.
117
- *
118
- * Throws when the client cannot use tools at all — a surface built on registered tools that
119
- * silently ran without them would answer from nothing and look like it had checked.
120
- */
121
- export async function registryAssistantChat(input: RegistryAssistantInput): Promise<RegistryAssistantResult> {
122
- const { client, messages, systemPrompt, toolCategories, hostContext, state } = input
123
-
124
- if (!client.chatWithTools) {
125
- throw new Error('[registry-assistant] the configured AI client cannot call tools, so this conversation cannot run')
126
- }
127
-
128
- /*
129
- * Only `read` is offered here. `external` means the tool changes something outside the
130
- * conversation (board-import's `materializeImportSession` creates a Board); this door answers
131
- * questions and has no confirm-and-apply step, so a tool with an effect does not go through it
132
- * even when the caller holds the privilege.
133
- */
134
- const scope = narrowToolScope(
135
- await resolveToolScope(toolCategories, input.toolAccess),
136
- spec => spec.kind === 'read'
137
- )
138
- /* What one call carries is within the budget; what is offered and what may run are the same set as it grows. */
139
- const offer = toolOfferState(scope, input.front)
140
- const categoryOf = new Map(scope.categories.flatMap(category => category.specs.map(spec => [spec.name, category.name] as [string, string])))
141
- categoryOf.set(OPEN_TOOLS, TOOL_BUDGET_CATEGORY)
142
-
143
- const tools = () =>
144
- offer.offered().map(spec => ({
145
- name: spec.name,
146
- description: spec.themeNote ? `${spec.description} ${spec.themeNote}` : spec.description,
147
- parameters: spec.schema
148
- }))
149
-
150
- /*
151
- * The rules for using a tool belong to whoever registered it. Collect only the offered ones, so
152
- * a surface never reads instructions for a category it cannot call - an opened tool brings its
153
- * category's with the opening.
154
- */
155
- const guidance = [...offer.frontGuidance(), offer.catalog()].filter(Boolean)
156
- const prompt = guidance.length > 0 ? `${systemPrompt}\n\n${guidance.join('\n\n')}` : systemPrompt
157
-
158
- /*
159
- * `mode` 는 서버의 값이다 — 등록된 모드에서 왔고, `host` 와 달리 클라이언트가 못 고친다. A2 가 서기
160
- * 전에는 채울 것이 없어 비워 두었다(ADR-0061 결정 3 의 주석). 이제 부르는 쪽이 들고 있다.
161
- */
162
- const toolContext: ToolCallContext = {
163
- state,
164
- host: hostContext ?? {},
165
- ...(input.mode ? { mode: input.mode } : {}),
166
- /* 번역기와 첨부는 서버의 값이다 — `host` 에서 받지 않는다(ADR-0061 2026-10-16 판정 1·2). */
167
- t: input.t ?? defaultValueTranslate,
168
- attachments: input.attachments ?? [],
169
- ...(input.run ? { run: input.run } : {}),
170
- ...(input.conversation?.id ? { conversation: { id: input.conversation.id } } : {})
171
- }
172
-
173
- const recorded = async (run: ToolCallRun, context: ToolCallContext) => {
174
- if (input.onToolCall) {
175
- try {
176
- input.onToolCall(digestOf(run))
177
- } catch (e) {
178
- console.warn(`[registry-assistant] onToolCall failed for ${run.tool}:`, (e as Error)?.message ?? e)
179
- }
180
- }
181
- await recordToolCall(run, context)
182
- }
183
-
184
- const result = await assistantChat<ToolCallContext, unknown>({
185
- initialConversation: messages,
186
- tools,
187
- options: {
188
- systemPrompt: prompt,
189
- model: input.model,
190
- temperature: input.temperature,
191
- maxTokens: input.maxTokens,
192
- requireToolOnFirstTurn: input.requireToolOnFirstTurn,
193
- /*
194
- * A question across a product's records takes many lookups. At the limit the model answers from
195
- * what it read and says what is missing — the person is never told to split the question.
196
- */
197
- maxIterations: input.maxIterations ?? REGISTRY_MAX_ITERATIONS,
198
- salvageOnMaxIterations: input.salvageOnMaxIterations ?? true,
199
- signal: input.signal
200
- },
201
- chat: (msgs, toolDefs, opts) => client.chatWithTools!(msgs, toolDefs, opts),
202
- context: toolContext,
203
- dispatch: {
204
- isReadTool: name => offer.isOffered(name) || offer.isOpenable(name),
205
- /*
206
- * This surface has no document, so nothing here can write. Saying so plainly makes the loop
207
- * report an unknown name back to the model instead of accepting a call and dropping it.
208
- */
209
- isWriteTool: () => false,
210
- isActionTool: () => false,
211
- /* Every call is handed to the recorders - an application's audit sees the tools other packages declared too. */
212
- executeReadTool: async (call, context) => {
213
- if (offer.isOpenable(call.name)) {
214
- return { rejected: true, error: 'tool-not-offered', message: `${call.name} is not open yet. Open it with ${OPEN_TOOLS} first, then call it.` }
215
- }
216
- const spec = offer.offered().find(one => one.name === call.name)
217
- if (!spec) return undefined
218
- const args = call.arguments ?? {}
219
- const started = Date.now()
220
- const record = { tool: spec.name, category: categoryOf.get(spec.name) ?? '', args }
221
- try {
222
- const result = await (spec.builder as any)(args, context)
223
- await recorded({ ...record, result, durationMs: Date.now() - started }, context)
224
- return result
225
- } catch (e) {
226
- await recorded({ ...record, error: e, durationMs: Date.now() - started }, context)
227
- throw e
228
- }
229
- },
230
- validateWriteToolCall: () => ({ valid: false, errors: ['this conversation has no document to write to'] }),
231
- toolCallToOp: () => null,
232
- /* The conversation row keeps the shape of each answer, as the audit does - never its values (ADR-0061 decision 8). */
233
- summarizeToolResult: resultShapeOf
234
- },
235
- groundingSources: input.groundingSources,
236
- t: input.t
237
- })
238
-
239
- return { ...result, offeredTools: offer.offered().map(spec => spec.name), openableTools: offer.openable() }
240
- }
@@ -1,76 +0,0 @@
1
- /*
2
- * Which tools this conversation may call — the registry half.
3
- *
4
- * ── Why a gate at all ───────────────────────────────────────────────────────────
5
- * One product grows several conversation surfaces (a board authoring dock, an operations dock, a
6
- * header assistant). Board edits can be reverted; an operations command reaches a real factory.
7
- * If both sets hang in one conversation, the boundary is a label on the screen.
8
- *
9
- * **Hiding the definitions is not enough.** A model can guess a name, and an older conversation
10
- * can be replayed with tool calls still in it. So the same gate has to decide *both* what is
11
- * offered and what may be dispatched. A name that fails the gate is reported back to the model as
12
- * unregistered — never a silent no-op, which the model would read as success.
13
- *
14
- * ── Why the registry half is here and the rest is not (2026-09-10) ──────────────
15
- * This came out of `board-ai`, where the gate answered from two sources at once: the tool registry
16
- * *and* board's own core tool-name sets. The first is neutral — any host asking "what kind of tool
17
- * is this name, and may this conversation see it" wants the same answer. The second is board's.
18
- *
19
- * So the registry half lives here and a host **extends** it with whatever it owns
20
- * (`extendToolGate`). Splitting it this way is what lets a product with no board of its own get
21
- * the same dispatch discipline, instead of each product writing its own gate and diverging — which
22
- * is what happened with the grounding guard: the twin's header route had it and the dock route did
23
- * not, so the same question was verified on one side and not the other.
24
- */
25
- import { findToolSpec, getToolKind, type ToolCategoryFilter, type ToolSpec } from '../tool-registry/index.js'
26
-
27
- /** 이름 하나에 대한 판정. 정의 조립과 dispatch 가 **같은 것**을 쓴다. */
28
- export interface ToolGate {
29
- /** 이 대화에 허용된 카테고리 목록. 없음 = 전부. */
30
- filter: ToolCategoryFilter
31
- isRead(name: string): boolean
32
- isWrite(name: string): boolean
33
- isAction(name: string): boolean
34
- spec(name: string): ToolSpec | undefined
35
- }
36
-
37
- /** 호스트가 자기 도구를 더할 때 주는 것. 준 것만 더해지고, 안 준 축은 레지스트리 판정 그대로다. */
38
- export interface ToolGateExtension {
39
- isRead?(name: string): boolean
40
- isWrite?(name: string): boolean
41
- isAction?(name: string): boolean
42
- spec?(name: string): ToolSpec | undefined
43
- }
44
-
45
- /**
46
- * 레지스트리만 보고 답하는 게이트.
47
- *
48
- * `external` 은 읽기로 본다 — 등록한 쪽이 「밖에서 값을 가져온다」고 말한 것이고, 그것은 쓰지 않는다.
49
- */
50
- export function registryToolGate(filter?: ToolCategoryFilter): ToolGate {
51
- const kind = (name: string) => getToolKind(name, filter)
52
- return {
53
- filter,
54
- isRead: name => kind(name) === 'read' || kind(name) === 'external',
55
- isWrite: name => kind(name) === 'write',
56
- isAction: name => kind(name) === 'action',
57
- spec: name => findToolSpec(name, filter)
58
- }
59
- }
60
-
61
- /**
62
- * 호스트의 판정을 **더한다.** 겹치면 어느 쪽이든 참이면 참이다 — 게이트는 「이 이름을 다룰 수 있나」를
63
- * 묻고, 두 출처 중 하나가 안다고 하면 다룰 수 있다.
64
- *
65
- * 한쪽으로 덮지 않는 이유: 덮으면 호스트가 자기 이름집합에 없는 등록 도구를 **조용히 잠근다.** 그러면
66
- * 대화면이 카테고리를 허용했는데 호출이 미등록으로 회신되고, 원인이 두 자리에 나뉘어 있어 못 찾는다.
67
- */
68
- export function extendToolGate(base: ToolGate, extension: ToolGateExtension): ToolGate {
69
- return {
70
- filter: base.filter,
71
- isRead: name => base.isRead(name) || !!extension.isRead?.(name),
72
- isWrite: name => base.isWrite(name) || !!extension.isWrite?.(name),
73
- isAction: name => base.isAction(name) || !!extension.isAction?.(name),
74
- spec: name => base.spec(name) ?? extension.spec?.(name)
75
- }
76
- }
@@ -1,47 +0,0 @@
1
- /*
2
- * A tool result as it is kept - its shape, never its values (ADR-0061 decision 8, ruled 2026-10-17).
3
- *
4
- * Two records keep what a tool answered: the conversation row (`toolUsages`, the dock's tool panel) and the AI audit
5
- * (the call recorder's digest). Both keep the same thing, through this one function: how big the answer was, how many
6
- * rows it carried, the names of its fields, and the code it failed with. The values - pay, shareholdings, a person's
7
- * name - stay in their own tables; copying them into a conversation row puts them in its backups and exports too,
8
- * whoever may read the row.
9
- *
10
- * ── ⚠ This is for the panel and the audit, never for a judgement ─────────────────
11
- * What the model actually received is `AgenticLoopResult.groundedTexts`. Grounding uses it, and anything that judges
12
- * correctness must use it too.
13
- */
14
-
15
- /** Field names kept of an object answer - its first ones; an answer with more says how many. */
16
- const MAX_KEYS = 20
17
-
18
- export interface ResultShape {
19
- /** Characters of the answer as JSON. */
20
- size: number
21
- /** Rows it carried - `read` of a list read, else the length of the answer or of its first list. */
22
- count?: number
23
- /** The field names of an object answer - names only. */
24
- keys?: string[]
25
- /** More field names than `keys` holds. */
26
- moreKeys?: number
27
- /** The code it failed with - a refusal's `error`, or the `error` code of a failure. */
28
- errorCode?: string
29
- }
30
-
31
- export function resultShapeOf(value: unknown): ResultShape {
32
- const size = JSON.stringify(value ?? null).length
33
- if (Array.isArray(value)) return { size, count: value.length }
34
- if (!value || typeof value !== 'object') return { size }
35
- const answer = value as Record<string, any>
36
- const names = Object.keys(answer)
37
- const lists = Object.values(answer).filter(Array.isArray)
38
- const count = typeof answer.read === 'number' ? answer.read : lists.length ? lists[0].length : undefined
39
- const errorCode = answer.rejected === true ? String(answer.error ?? 'rejected') : typeof answer.error === 'string' ? answer.error : undefined
40
- return {
41
- size,
42
- ...(count === undefined ? {} : { count }),
43
- keys: names.slice(0, MAX_KEYS),
44
- ...(names.length > MAX_KEYS ? { moreKeys: names.length - MAX_KEYS } : {}),
45
- ...(errorCode ? { errorCode } : {})
46
- }
47
- }
@@ -1,246 +0,0 @@
1
- /*
2
- * What this guards: **no model call carries more than MAX_OFFERED_TOOLS tools, and nothing a person may do is lost by
3
- * it** (ADR-0061 decision 9, operato-application design/ai/tool-budget.md).
4
- *
5
- * Office's conversation opened 165 tools and OpenAI refuses more than 128, so every turn of a person who may read
6
- * everything failed. A scope that fits is offered whole as before. A larger one starts with what the caller puts in
7
- * front and `openTools`; the rest is listed in the prompt, opened for the rest of the turn, and run through the same
8
- * doors and recorders as any tool.
9
- */
10
- import { registryAssistantChat } from './registry-assistant'
11
- import { MAX_OFFERED_TOOLS, OPEN_TOOLS, TOOL_BUDGET_CATEGORY, ToolBudgetError, planToolOffer } from './tool-budget'
12
- import { resolveToolScope } from './tool-scope'
13
- import { clearToolCallRecorders, clearToolRegistry, registerToolCallRecorder, registerToolCategory, type ToolCallRecord } from '../tool-registry/index.js'
14
- import type { AIToolCall, AIToolChatResult } from '../types.js'
15
-
16
- const TC = (name: string, args: any = {}, id = `t-${name}`): AIToolCall => ({ id, name, arguments: args, type: 'tool_use' } as any)
17
- const reply = (text?: string, toolCalls: AIToolCall[] = []): AIToolChatResult =>
18
- ({ text, toolCalls, stopReason: toolCalls.length > 0 ? 'tool_use' : 'end_turn', usage: undefined } as any)
19
-
20
- function recordingClient(replies: AIToolChatResult[] = [reply('answered')]) {
21
- const seen: Array<{ tools: any[]; options: any; messages: any[] }> = []
22
- let turn = 0
23
- return {
24
- seen,
25
- client: {
26
- chatWithTools: async (messages: any[], tools: any[], options: any) => {
27
- seen.push({ tools: [...tools], options, messages: [...messages] })
28
- return replies[Math.min(turn++, replies.length - 1)]
29
- }
30
- } as any
31
- }
32
- }
33
-
34
- const ran: string[] = []
35
-
36
- /** `count` categories of one read tool each - `list-0` … - behind the door `Query.<name>`. */
37
- function registerLists(count: number, prefix = 'list') {
38
- for (let i = 0; i < count; i++) {
39
- const name = `read${prefix[0].toUpperCase()}${prefix.slice(1)}${i}`
40
- registerToolCategory({
41
- name: `${prefix}-${i}`,
42
- guidance: `- To answer from ${prefix} ${i}, call ${name}.`,
43
- specs: [
44
- {
45
- kind: 'read',
46
- name,
47
- description: `Read ${prefix} ${i}. Every number comes from its result.`,
48
- doors: [`Query.${name}`],
49
- schema: { type: 'object', properties: { from: { type: 'string' } } },
50
- builder: () => {
51
- ran.push(name)
52
- return { rows: [{ i }] }
53
- }
54
- }
55
- ]
56
- } as any)
57
- }
58
- return Array.from({ length: count }, (_, i) => `${prefix}-${i}`)
59
- }
60
-
61
- const input = (over: any = {}) => ({
62
- client: recordingClient().client,
63
- messages: [{ role: 'user' as const, content: 'how much came in this month' }],
64
- systemPrompt: 'you read the books',
65
- state: { domain: { id: 'dom-1' }, user: { id: 'u-1' } },
66
- toolAccess: async () => true,
67
- ...over
68
- })
69
-
70
- const names = (tools: any[]) => tools.map(tool => tool.name)
71
-
72
- beforeEach(() => {
73
- clearToolRegistry()
74
- clearToolCallRecorders()
75
- ran.length = 0
76
- })
77
- afterAll(() => clearToolCallRecorders())
78
-
79
- describe('a scope that fits is offered whole, as before', () => {
80
- it('★ every tool, no openTools, no list to open from', async () => {
81
- const categories = registerLists(MAX_OFFERED_TOOLS)
82
- const { client, seen } = recordingClient()
83
- await registryAssistantChat(input({ client, toolCategories: categories }))
84
-
85
- expect(seen[0].tools).toHaveLength(MAX_OFFERED_TOOLS)
86
- expect(names(seen[0].tools)).not.toContain(OPEN_TOOLS)
87
- expect(seen[0].options.systemPrompt).not.toContain(`Tools you can open with ${OPEN_TOOLS}`)
88
- expect(seen[0].options.systemPrompt).toContain('- To answer from list 63, call readList63.')
89
- })
90
- })
91
-
92
- describe('a scope larger than one call carries', () => {
93
- it('★ the first call carries the front and openTools - never more than the budget', async () => {
94
- const categories = registerLists(165)
95
- const { client, seen } = recordingClient()
96
- await registryAssistantChat(input({ client, toolCategories: categories, front: { categories: ['list-3', 'list-150'] } }))
97
-
98
- expect(names(seen[0].tools)).toEqual(['readList3', 'readList150', OPEN_TOOLS])
99
- expect(seen[0].tools.length).toBeLessThanOrEqual(MAX_OFFERED_TOOLS)
100
- })
101
-
102
- it('★ the rest is listed once in the prompt, the opening tool says only how to open', async () => {
103
- const categories = registerLists(165)
104
- const { client, seen } = recordingClient()
105
- await registryAssistantChat(input({ client, toolCategories: categories, front: { categories: ['list-3'] } }))
106
-
107
- const prompt = seen[0].options.systemPrompt
108
- expect(prompt).toContain(`Tools you can open with ${OPEN_TOOLS}`)
109
- expect(prompt).toContain('- readList150: Read list 150.')
110
- expect(prompt).not.toContain('- readList3:')
111
- /* Only the front's guidance - an unopened list's rules are not read to the model. */
112
- expect(prompt).toContain('- To answer from list 3, call readList3.')
113
- expect(prompt).not.toContain('call readList150.')
114
- const opening = seen[0].tools.find(tool => tool.name === OPEN_TOOLS)
115
- expect(opening.description).not.toContain('readList150')
116
- expect(opening.description.length).toBeLessThan(1024)
117
- })
118
-
119
- it('★ an opened tool is offered from the next call on, with its guidance, and runs', async () => {
120
- const categories = registerLists(165)
121
- const { client, seen } = recordingClient([
122
- reply(undefined, [TC(OPEN_TOOLS, { names: ['readList150'] })]),
123
- reply(undefined, [TC('readList150', { from: '2026-10-01' })]),
124
- reply('42 came in')
125
- ])
126
- const result = await registryAssistantChat(input({ client, toolCategories: categories, front: { categories: ['list-3'] } }))
127
-
128
- expect(names(seen[0].tools)).not.toContain('readList150')
129
- expect(names(seen[1].tools)).toContain('readList150')
130
- const opened = JSON.parse(seen[1].messages.at(-1).content[0].content)
131
- expect(opened).toMatchObject({ opened: ['readList150'], guidance: '- To answer from list 150, call readList150.' })
132
- expect(ran).toEqual(['readList150'])
133
- expect(result.offeredTools).toContain('readList150')
134
- /* What it could still have opened - with the offered ones, all this person may use here. */
135
- expect(result.openableTools).toHaveLength(165 - 2)
136
- expect(result.openableTools).not.toContain('readList150')
137
- })
138
-
139
- it('★ the list says its tools are the model\'s to use - not something to tell the person is missing', async () => {
140
- const categories = registerLists(165)
141
- const { client, seen } = recordingClient()
142
- await registryAssistantChat(input({ client, toolCategories: categories, front: { categories: ['list-3'] } }))
143
-
144
- const prompt = seen[0].options.systemPrompt
145
- expect(prompt).toMatch(/never tell the person a tool on this list is missing/)
146
- expect(prompt).toMatch(/never ask the person to choose instead of opening it/)
147
- })
148
-
149
- it('★ opening a tool that is already offered says so - call it now', async () => {
150
- const categories = registerLists(165)
151
- const { client, seen } = recordingClient([reply(undefined, [TC(OPEN_TOOLS, { names: ['readList3', 'readList150'] })]), reply('done')])
152
- await registryAssistantChat(input({ client, toolCategories: categories, front: { categories: ['list-3'] } }))
153
-
154
- expect(JSON.parse(seen[1].messages.at(-1).content[0].content)).toMatchObject({ opened: ['readList150'], alreadyOffered: ['readList3'] })
155
- })
156
-
157
- it('★ a wrong name among right ones opens the right ones, and says what the wrong one most likely meant', async () => {
158
- const categories = registerLists(165)
159
- const { client, seen } = recordingClient([reply(undefined, [TC(OPEN_TOOLS, { names: ['readList150', 'queryList151'] })]), reply(undefined, [TC(OPEN_TOOLS, { names: ['queryList151'] })]), reply('done')])
160
- await registryAssistantChat(input({ client, toolCategories: categories, front: { categories: ['list-3'] } }))
161
-
162
- expect(JSON.parse(seen[1].messages.at(-1).content[0].content)).toMatchObject({ opened: ['readList150'], notOffered: ['queryList151'], suggestions: { queryList151: ['readList151'] } })
163
- expect(names(seen[1].tools)).toContain('readList150')
164
- /* Only wrong names: refused, still with what each most likely meant. */
165
- expect(JSON.parse(seen[2].messages.at(-1).content[0].content)).toMatchObject({ rejected: true, error: 'tool-not-offered', suggestions: { queryList151: ['readList151'] } })
166
- })
167
-
168
- it('★ a tool called before it is opened does not run - the model is told to open it', async () => {
169
- const categories = registerLists(165)
170
- const { client, seen } = recordingClient([reply(undefined, [TC('readList150')]), reply('done')])
171
- await registryAssistantChat(input({ client, toolCategories: categories, front: { categories: ['list-3'] } }))
172
-
173
- expect(ran).toEqual([])
174
- expect(JSON.parse(seen[1].messages.at(-1).content[0].content)).toMatchObject({ error: 'tool-not-offered' })
175
- })
176
-
177
- it('★ a tool whose door the person cannot pass is not in the list, cannot be opened and never runs', async () => {
178
- const categories = registerLists(165)
179
- const { client, seen } = recordingClient([reply(undefined, [TC(OPEN_TOOLS, { names: ['readList150'] })]), reply(undefined, [TC('readList150')]), reply('done')])
180
- await registryAssistantChat(
181
- input({ client, toolCategories: categories, front: { categories: ['list-3'] }, toolAccess: async (door: string) => door !== 'Query.readList150' })
182
- )
183
-
184
- expect(seen[0].options.systemPrompt).not.toContain('readList150')
185
- expect(JSON.parse(seen[1].messages.at(-1).content[0].content)).toMatchObject({ error: 'tool-not-offered', names: ['readList150'] })
186
- expect(names(seen[1].tools)).not.toContain('readList150')
187
- expect(ran).toEqual([])
188
- })
189
-
190
- it('★ opening past the budget is refused with the room left - no call ever carries more', async () => {
191
- const categories = registerLists(165)
192
- const many = Array.from({ length: 70 }, (_, i) => `readList${i + 10}`)
193
- const { client, seen } = recordingClient([
194
- reply(undefined, [TC(OPEN_TOOLS, { names: many })]),
195
- reply(undefined, [TC(OPEN_TOOLS, { names: many.slice(0, 20) })]),
196
- reply('done')
197
- ])
198
- await registryAssistantChat(input({ client, toolCategories: categories, front: { categories: ['list-3'] } }))
199
-
200
- expect(JSON.parse(seen[1].messages.at(-1).content[0].content)).toMatchObject({ error: 'tool-budget-exceeded', room: MAX_OFFERED_TOOLS - 2 })
201
- expect(seen[2].tools).toHaveLength(22)
202
- for (const call of seen) expect(call.tools.length).toBeLessThanOrEqual(MAX_OFFERED_TOOLS)
203
- })
204
-
205
- it('★ the front tools fill only the room the categories leave', async () => {
206
- const categories = registerLists(165)
207
- const scope = await resolveToolScope(categories, async () => true)
208
- const front = Array.from({ length: 100 }, (_, i) => `readList${i}`)
209
- const plan = planToolOffer(scope, { categories: ['list-150'], tools: front })
210
-
211
- expect(plan.offered).toHaveLength(MAX_OFFERED_TOOLS - 1)
212
- expect(plan.offered[0].name).toBe('readList150')
213
- expect(plan.openable).toHaveLength(165 - (MAX_OFFERED_TOOLS - 1))
214
- })
215
-
216
- it('★ front categories that do not fit are refused loudly, never cut', async () => {
217
- const categories = registerLists(165)
218
- const scope = await resolveToolScope(categories, async () => true)
219
-
220
- expect(() => planToolOffer(scope, { categories: categories.slice(0, MAX_OFFERED_TOOLS) })).toThrow(ToolBudgetError)
221
- await expect(registryAssistantChat(input({ toolCategories: categories, front: { categories: categories.slice(0, 80) } }))).rejects.toMatchObject({
222
- code: 'tool-budget-exceeded'
223
- })
224
- })
225
- })
226
-
227
- describe('opening and the opened tool are recorded like any call (ADR-0061 decision 8, ADR-0141)', () => {
228
- it('★ the recorders get the opening, under its own category, and the opened tool under its own', async () => {
229
- const recorded: ToolCallRecord[] = []
230
- registerToolCallRecorder(record => {
231
- recorded.push(record)
232
- })
233
- const categories = registerLists(165)
234
- const { client } = recordingClient([
235
- reply(undefined, [TC(OPEN_TOOLS, { names: ['readList150'] })]),
236
- reply(undefined, [TC('readList150', { from: '2026-10-01' })]),
237
- reply('done')
238
- ])
239
- await registryAssistantChat(input({ client, toolCategories: categories, front: { categories: ['list-3'] }, mode: { kind: 'office.finance' } }))
240
-
241
- expect(recorded.map(record => [record.tool, record.category, record.ok])).toEqual([
242
- [OPEN_TOOLS, TOOL_BUDGET_CATEGORY, true],
243
- ['readList150', 'list-150', true]
244
- ])
245
- })
246
- })