@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,186 +0,0 @@
1
- /*
2
- * How many tools one model call carries (ADR-0061 decision 9, operato-application design/ai/tool-budget.md).
3
- *
4
- * A conversation used to send every tool its mode opened on every call. Office's conversation opened 165, and OpenAI
5
- * refuses more than 128 - every turn of a person who may read everything failed. The tools also went with their
6
- * guidance, some 140,000 characters a call.
7
- *
8
- * Now a call carries at most `MAX_OFFERED_TOOLS`. When the scope is larger, the caller names what goes in front (the
9
- * screen's records, the tools this conversation used); the rest is listed once in the prompt and the model opens what
10
- * it needs with `openTools` for the rest of the turn. Whether a person may use a tool is decided as before - the list
11
- * holds only the tools of their scope, and opening runs no tool.
12
- */
13
- import type { ToolSpec } from '../tool-registry/types.js'
14
- import type { ScopedCategory, ToolScope } from './tool-scope.js'
15
-
16
- /** Half the smallest provider limit known (OpenAI, 128). One constant - an application or a mode does not change it. */
17
- export const MAX_OFFERED_TOOLS = 64
18
-
19
- export const OPEN_TOOLS = 'openTools'
20
-
21
- /** The category the opening tool is recorded under - it is not registered; no mode names it. */
22
- export const TOOL_BUDGET_CATEGORY = 'tool-budget'
23
-
24
- /** What the caller puts in front when the scope does not fit: whole categories first, then single tools while there is room. */
25
- export interface ToolFront {
26
- categories?: string[]
27
- tools?: string[]
28
- }
29
-
30
- export class ToolBudgetError extends Error {
31
- code = 'tool-budget-exceeded'
32
- constructor(public front: number) {
33
- super(`[tool-budget] the tools put in front (${front}) and openTools do not fit in ${MAX_OFFERED_TOOLS} - narrow the mode's own categories`)
34
- }
35
- }
36
-
37
- export interface ToolOffer {
38
- /** What the first call carries, openTools last when anything is left to open. */
39
- offered: ToolSpec[]
40
- /** In the scope and not offered - what openTools may open. */
41
- openable: ToolSpec[]
42
- }
43
-
44
- /**
45
- * What a turn starts with. The whole scope when it fits; otherwise the front categories (all of them, or it throws),
46
- * the front tools while there is room, and openTools.
47
- */
48
- export function planToolOffer(scope: ToolScope, front: ToolFront = {}): ToolOffer {
49
- if (scope.specs.length <= MAX_OFFERED_TOOLS) return { offered: [...scope.specs], openable: [] }
50
-
51
- const room = MAX_OFFERED_TOOLS - 1
52
- const picked = new Map<string, ToolSpec>()
53
- for (const name of front.categories ?? []) {
54
- for (const spec of scope.categories.find(category => category.name === name)?.specs ?? []) picked.set(spec.name, spec)
55
- }
56
- if (picked.size > room) throw new ToolBudgetError(picked.size)
57
-
58
- const byName = new Map(scope.specs.map(spec => [spec.name, spec]))
59
- for (const name of front.tools ?? []) {
60
- if (picked.size >= room) break
61
- const spec = byName.get(name)
62
- if (spec) picked.set(name, spec)
63
- }
64
-
65
- const offered = [...picked.values()]
66
- return { offered, openable: scope.specs.filter(spec => !picked.has(spec.name)) }
67
- }
68
-
69
- const ONE_LINE = 160
70
-
71
- /** The first sentence of a description, on one line - what the list says of a tool. */
72
- function oneLine(description: string | undefined): string {
73
- const flat = String(description ?? '').replace(/\s+/g, ' ').trim()
74
- const sentence = /^(.+?[.!?])(\s|$)/.exec(flat)?.[1] ?? flat
75
- return sentence.length > ONE_LINE ? `${sentence.slice(0, ONE_LINE - 1)}…` : sentence
76
- }
77
-
78
- /**
79
- * The list of tools the model may open - one function builds it, wherever it goes. It goes in the prompt: OpenAI is
80
- * reported to refuse a tool description over 1024 characters, and Office's list runs to some 150 lines.
81
- */
82
- export function openableToolCatalog(openable: ReadonlyArray<ToolSpec>): string {
83
- if (openable.length === 0) return ''
84
- return [
85
- /*
86
- * Office's model, offered a bank lines' total it could open, told the person that read was not open and asked them
87
- * to pick a range (2026-10-22) - an app's prompt said a missing tool means a missing permission. What is on this
88
- * list is the model's to use.
89
- */
90
- `Tools you can open with ${OPEN_TOOLS} (name: what it does). They are yours to use in this conversation, only not loaded yet. ` +
91
- `When the question needs one, open it with ${OPEN_TOOLS} and call it: never tell the person a tool on this list is missing, ` +
92
- 'and never ask the person to choose instead of opening it.',
93
- ...openable.map(spec => `- ${spec.name}: ${oneLine(spec.description)}`)
94
- ].join('\n')
95
- }
96
-
97
- /** The opening tool's definition. */
98
- export function openToolsSpec(open: (names: string[]) => unknown): ToolSpec {
99
- return {
100
- kind: 'read',
101
- name: OPEN_TOOLS,
102
- description:
103
- `Open more tools for the rest of this answer. Pass the exact names from the list of tools you can open; they are offered from your next step on, with how to use them. At most ${MAX_OFFERED_TOOLS} tools are open at once.`,
104
- schema: {
105
- type: 'object',
106
- required: ['names'],
107
- properties: { names: { type: 'array', items: { type: 'string' }, description: 'Names from the list of tools you can open.' } }
108
- },
109
- builder: (args: any) => open(Array.isArray(args?.names) ? args.names.map(String) : [])
110
- } as ToolSpec
111
- }
112
-
113
- /**
114
- * The offer of one turn, as it grows. `open` adds tools to what the next call carries; it never runs one.
115
- */
116
- export function toolOfferState(scope: ToolScope, front: ToolFront = {}) {
117
- const plan = planToolOffer(scope, front)
118
- const openable = new Map(plan.openable.map(spec => [spec.name, spec]))
119
- const opening = openable.size > 0 ? openToolsSpec(names => open(names)) : undefined
120
- const offered = new Map<string, ToolSpec>([...plan.offered, ...(opening ? [opening] : [])].map(spec => [spec.name, spec]))
121
- const categoryOf = new Map<string, ScopedCategory>(scope.categories.flatMap(category => category.specs.map(spec => [spec.name, category] as [string, ScopedCategory])))
122
-
123
- /*
124
- * The tools of this scope a wrong name most likely meant - the same name after its verb (`readOfficeExpenditureRequest`
125
- * for `queryOfficeExpenditureRequest`). Only this scope's: a tool the person may not use is never named.
126
- */
127
- const meant = (name: string) => {
128
- const stem = name.replace(/^[a-z]+/, '')
129
- return stem ? [...openable.keys(), ...offered.keys()].filter(one => one !== name && one.replace(/^[a-z]+/, '') === stem) : []
130
- }
131
-
132
- /*
133
- * A wrong name among right ones does not hold the right ones back: asked for a card, the model opened the card tool with
134
- * a read it named wrong, got nothing open, and told the person the tools were not there (2026-10-25). The right ones
135
- * open; each wrong one is said with what it most likely meant.
136
- */
137
- function open(names: string[]) {
138
- const unknown = [...new Set(names.filter(name => !openable.has(name) && !offered.has(name)))]
139
- const suggestions = Object.fromEntries(unknown.map(name => [name, meant(name)]).filter(([, near]) => near.length))
140
- const notInList = unknown.length
141
- ? `${unknown.join(', ')} ${unknown.length > 1 ? 'are' : 'is'} not in the list of tools you can open` +
142
- (Object.keys(suggestions).length ? ` - ${Object.entries(suggestions).map(([name, near]) => `for ${name} use ${(near as string[]).join(' or ')}`).join('; ')}` : '') +
143
- '. Use the exact names from the list.'
144
- : ''
145
- if (unknown.length && unknown.length === new Set(names).size) {
146
- return { rejected: true, error: 'tool-not-offered', names: unknown, ...(Object.keys(suggestions).length ? { suggestions } : {}), message: `${notInList} Call ${OPEN_TOOLS} again now.` }
147
- }
148
- names = names.filter(name => !unknown.includes(name))
149
- const fresh = [...new Set(names)].filter(name => !offered.has(name))
150
- const already = [...new Set(names)].filter(name => offered.has(name) && name !== OPEN_TOOLS)
151
- const room = MAX_OFFERED_TOOLS - offered.size
152
- if (fresh.length > room) {
153
- return {
154
- rejected: true,
155
- error: 'tool-budget-exceeded',
156
- room,
157
- message: `only ${room} more tools fit in this answer. Open fewer - the ones this question needs - or answer from what you have read.`
158
- }
159
- }
160
- for (const name of fresh) offered.set(name, openable.get(name)!)
161
- const guidance = [...new Set(fresh.map(name => categoryOf.get(name)?.guidance).filter(Boolean))]
162
- const said = already.length
163
- ? `${already.join(', ')} ${already.length > 1 ? 'are' : 'is'} already open - call ${already.length > 1 ? 'them' : 'it'} now. ${fresh.length ? 'The others are open from your next step on.' : ''}`.trim()
164
- : 'these tools are open from your next step on. Call them as the question needs.'
165
- return {
166
- opened: fresh,
167
- ...(already.length ? { alreadyOffered: already } : {}),
168
- ...(unknown.length ? { notOffered: unknown, ...(Object.keys(suggestions).length ? { suggestions } : {}) } : {}),
169
- ...(guidance.length ? { guidance: guidance.join('\n') } : {}),
170
- message: notInList ? `${said} ${notInList} Open it now and go on.` : said
171
- }
172
- }
173
-
174
- return {
175
- /** What a call carries now. */
176
- offered: () => [...offered.values()],
177
- isOffered: (name: string) => offered.has(name),
178
- /** In the scope and still to be opened - a call to one is answered with how to open it. */
179
- isOpenable: (name: string) => openable.has(name) && !offered.has(name),
180
- /** In the scope and not offered now. */
181
- openable: () => [...openable.keys()].filter(name => !offered.has(name)),
182
- /** The guidance of the categories in front - opened ones bring theirs with the result. */
183
- frontGuidance: () => [...new Set(plan.offered.map(spec => categoryOf.get(spec.name)?.guidance).filter(Boolean) as string[])],
184
- catalog: () => openableToolCatalog(plan.openable)
185
- }
186
- }
@@ -1,123 +0,0 @@
1
- /**
2
- * What this guards: which tools one conversation is offered, now that the **doors** decide it
3
- * (ADR-0071 decision 2, added to 2026-09-18).
4
- *
5
- * The three states of `doors` are three different answers, and the interesting one is the third:
6
- * a tool that says nothing is **left out**, not opened. Reading an absent declaration as "nothing
7
- * to check" is how the board-import tool reached every conversation once already.
8
- */
9
- import { registerToolCategory, clearToolRegistry } from '../tool-registry/registry'
10
- import type { ToolCategory, ToolSpec } from '../tool-registry/types'
11
- import { resolveToolScope, narrowToolScope, EMPTY_TOOL_SCOPE } from './tool-scope'
12
-
13
- afterEach(() => clearToolRegistry())
14
-
15
- function category(name: string, specs: Partial<ToolSpec>[]): ToolCategory {
16
- return {
17
- name,
18
- guidance: `- fixture guidance for ${name}`,
19
- specs: specs.map(s => ({
20
- kind: 'read' as const,
21
- name: 'unnamed',
22
- description: 'desc',
23
- schema: {},
24
- builder: () => ({}),
25
- ...s
26
- })) as ToolSpec[]
27
- }
28
- }
29
-
30
- const names = (scope: { specs: ReadonlyArray<ToolSpec> }) => scope.specs.map(s => s.name)
31
-
32
- /** A caller holding these doors and no others. */
33
- const holding = (...doors: string[]) => jest.fn(async (door: string) => doors.includes(door))
34
-
35
- describe('resolveToolScope — the doors decide', () => {
36
- test('★ a tool that names no doors at all is left out, not let through', async () => {
37
- registerToolCategory(category('mixed', [{ name: 'undeclared' }, { name: 'declared', doors: ['Query.a'] }]))
38
-
39
- const scope = await resolveToolScope(['mixed'], holding('Query.a'))
40
-
41
- expect(names(scope)).toEqual(['declared'])
42
- })
43
-
44
- test('★ `doors: []` passes without asking — it reaches nothing to ask about', async () => {
45
- const access = holding()
46
- registerToolCategory(category('surface', [{ name: 'getOpenScene', doors: [] }]))
47
-
48
- expect(names(await resolveToolScope(['surface'], access))).toEqual(['getOpenScene'])
49
- expect(access).not.toHaveBeenCalled()
50
- })
51
-
52
- test('★ several doors are AND — half of them is not enough', async () => {
53
- registerToolCategory(
54
- category('plant', [
55
- { name: 'overview', doors: ['Query.jobOrders', 'Query.productionReports'] },
56
- { name: 'findJobOrders', doors: ['Query.jobOrders'] }
57
- ])
58
- )
59
-
60
- const scope = await resolveToolScope(['plant'], holding('Query.jobOrders'))
61
-
62
- expect(names(scope)).toEqual(['findJobOrders'])
63
- })
64
-
65
- test('each door is asked once however many tools reach it', async () => {
66
- const access = holding('Query.jobOrders', 'Query.productionReports')
67
- registerToolCategory(
68
- category('plant', [
69
- { name: 'overview', doors: ['Query.jobOrders', 'Query.productionReports'] },
70
- { name: 'findJobOrders', doors: ['Query.jobOrders'] },
71
- { name: 'attention', doors: ['Query.jobOrders', 'Query.productionReports'] }
72
- ])
73
- )
74
-
75
- await resolveToolScope(['plant'], access)
76
-
77
- expect(access.mock.calls.map(c => c[0]).sort()).toEqual(['Query.jobOrders', 'Query.productionReports'])
78
- })
79
-
80
- test('★ no access check closes every tool that reaches a door', async () => {
81
- registerToolCategory(category('plant', [{ name: 'findJobOrders', doors: ['Query.jobOrders'] }, { name: 'getOpenScene', doors: [] }]))
82
-
83
- expect(names(await resolveToolScope(['plant']))).toEqual(['getOpenScene'])
84
- })
85
-
86
- test('a door check that throws closes that door', async () => {
87
- const access = jest.fn(async () => {
88
- throw new Error('auth is down')
89
- })
90
- registerToolCategory(category('plant', [{ name: 'findJobOrders', doors: ['Query.jobOrders'] }]))
91
-
92
- expect(await resolveToolScope(['plant'], access)).toEqual(EMPTY_TOOL_SCOPE)
93
- })
94
-
95
- test('a category left with no usable tool drops out, so its guidance is not read to the model', async () => {
96
- registerToolCategory(category('plant', [{ name: 'findJobOrders', doors: ['Query.jobOrders'] }]))
97
- registerToolCategory(category('twin', [{ name: 'queryState', doors: ['Query.twinReplay'] }]))
98
-
99
- const scope = await resolveToolScope(['plant', 'twin'], holding('Query.twinReplay'))
100
-
101
- expect(scope.categories.map(c => c.name)).toEqual(['twin'])
102
- })
103
-
104
- test('nothing asked for is nothing offered', async () => {
105
- registerToolCategory(category('plant', [{ name: 'findJobOrders', doors: [] }]))
106
-
107
- expect(await resolveToolScope([], holding())).toEqual(EMPTY_TOOL_SCOPE)
108
- expect(await resolveToolScope(undefined as any, holding())).toEqual(EMPTY_TOOL_SCOPE)
109
- })
110
-
111
- test('narrowing keeps the same reading — a surface that runs only reads', async () => {
112
- registerToolCategory(
113
- category('twin', [
114
- { name: 'queryState', doors: ['Query.twinReplay'] },
115
- { name: 'bindEntity', kind: 'write', doors: ['Query.twinReplay'] }
116
- ])
117
- )
118
-
119
- const scope = await resolveToolScope(['twin'], holding('Query.twinReplay'))
120
-
121
- expect(names(narrowToolScope(scope, spec => spec.kind === 'read'))).toEqual(['queryState'])
122
- })
123
- })
@@ -1,103 +0,0 @@
1
- /*
2
- * Which registered tools one conversation may use — decided once per request, before anything is
3
- * offered, so offering and dispatch read the same list.
4
- *
5
- * ── Two questions, one list ───────────────────────────────────────────────────────
6
- * Which categories did this surface ask for? `toolCategories`
7
- * Which of their tools may this caller use? each spec's `doors`, asked of `access`
8
- *
9
- * **Nothing asked means nothing offered.** Omitting the category list used to mean "every
10
- * registered category"; that default is the one that opened board-import's Board-creating tool to
11
- * any conversation. An absent answer leans to the closed side (ADR-0047 ② · ADR-0053).
12
- *
13
- * **The doors are the gate** (ADR-0071 decision 2). A tool used to declare its own copy of what its
14
- * door asks, and this asked that copy. Two declarations of one fact drift, and the looser one wins;
15
- * plant's hand-written read check and its `doors` list were that pair. Now a tool names the doors it
16
- * reaches and the host resolves each one against the door's own declaration, so what passes here is
17
- * what passes at the door.
18
- *
19
- * **All the doors, not one of them.** A tool that answers from two doors hands back what is behind
20
- * both, so the caller holds both (AND, the same reading as AUTH's `requiresAll`).
21
- *
22
- * **No access check means a tool that reaches a door stays closed.** A caller that cannot say who is
23
- * asking gets only the tools that reach nothing.
24
- *
25
- * The permission check itself belongs to auth, which this package does not depend on, so the host
26
- * hands it in (`ai-assistant` builds it from the request state and AUTH's field table).
27
- */
28
- import { getToolCategories, type ToolCategoryFilter } from '../tool-registry/index.js'
29
- import type { ToolSpec } from '../tool-registry/types.js'
30
-
31
- /** Answers "may this caller pass this door" — `'Query.jobOrders'`. */
32
- export type ToolAccessCheck = (door: string) => Promise<boolean>
33
-
34
- export interface ScopedCategory {
35
- readonly name: string
36
- readonly guidance: string
37
- /** The tools of this category this caller may use. Never empty — a category with none is left out. */
38
- readonly specs: ReadonlyArray<ToolSpec>
39
- }
40
-
41
- export interface ToolScope {
42
- /** Categories with at least one usable tool, in registration order. */
43
- readonly categories: ReadonlyArray<ScopedCategory>
44
- /** Every usable tool, flat. Offering and dispatch both read this. */
45
- readonly specs: ReadonlyArray<ToolSpec>
46
- }
47
-
48
- export const EMPTY_TOOL_SCOPE: ToolScope = Object.freeze({ categories: [], specs: [] })
49
-
50
- export async function resolveToolScope(requested: ToolCategoryFilter, access?: ToolAccessCheck): Promise<ToolScope> {
51
- if (!requested || requested.length === 0) return EMPTY_TOOL_SCOPE
52
-
53
- /* One check per distinct door — five tools behind `Query.jobOrders` ask once. */
54
- const answers = new Map<string, Promise<boolean>>()
55
- const passes = (door: string): Promise<boolean> => {
56
- if (!answers.has(door)) answers.set(door, access!(door).catch(() => false))
57
- return answers.get(door)!
58
- }
59
-
60
- const mayUse = async (spec: ToolSpec): Promise<boolean> => {
61
- /*
62
- * Said nothing. Not open — left out, and the boot report names it. An answer this tool built
63
- * would be readable by no one (ADR-0073), so offering it would only produce dead answers.
64
- */
65
- if (!Array.isArray(spec.doors)) return false
66
- /* Reaches no door: it hands back what the surface itself sent. There is nothing to gate. */
67
- if (spec.doors.length === 0) return true
68
- if (!access) return false
69
-
70
- const held = await Promise.all(spec.doors.map(passes))
71
- return held.every(Boolean)
72
- }
73
-
74
- const categories: ScopedCategory[] = []
75
- for (const category of getToolCategories()) {
76
- if (!requested.includes(category.name)) continue
77
- const allowed = await Promise.all(category.specs.map(mayUse))
78
- const specs = category.specs.filter((_, i) => allowed[i])
79
- if (specs.length > 0) categories.push({ name: category.name, guidance: String(category.guidance ?? '').trim(), specs })
80
- }
81
- return fromCategories(categories)
82
- }
83
-
84
- /**
85
- * Keep only the tools a surface can run — e.g. a surface with no document keeps `read`. A category
86
- * left with nothing drops out, so its guidance is not read to a model that cannot call it.
87
- */
88
- export function narrowToolScope(scope: ToolScope, keep: (spec: ToolSpec) => boolean): ToolScope {
89
- return fromCategories(
90
- scope.categories
91
- .map(category => ({ ...category, specs: category.specs.filter(keep) }))
92
- .filter(category => category.specs.length > 0)
93
- )
94
- }
95
-
96
- /** The rules of the categories in scope, for the system prompt. */
97
- export function toolScopeGuidance(scope: ToolScope): string[] {
98
- return scope.categories.map(category => category.guidance).filter(Boolean)
99
- }
100
-
101
- function fromCategories(categories: ScopedCategory[]): ToolScope {
102
- return { categories, specs: categories.flatMap(category => category.specs) }
103
- }
@@ -1,40 +0,0 @@
1
- /*
2
- * What this guards: a screen can ask whether this domain has an AI, instead of finding out by pressing a button that
3
- * fails.
4
- *
5
- * The defect this replaces: twin decided the same question from whether a mutation had thrown once. The mutation
6
- * stopped being called, the flag stayed true, and deployments with no provider showed the button anyway (standard A7-a).
7
- * Agents are set per domain now, so the answer is read from the domain's agents.
8
- */
9
- import { capabilityOf } from './capability'
10
-
11
- const entry = (id: string, extra: any = {}) => ({
12
- spec: { id, name: id, provider: 'anthropic', model: 'claude-sonnet-5', active: true },
13
- turnedOff: false,
14
- usable: true,
15
- ...extra
16
- })
17
-
18
- it('★ a domain with a usable default says so, and names what answers', () => {
19
- expect(capabilityOf({ entries: [entry('a')] as any, defaultAgentId: 'a' })).toEqual({
20
- state: 'configured',
21
- provider: 'anthropic',
22
- model: 'claude-sonnet-5'
23
- })
24
- })
25
-
26
- it('★ no agent at all is "not configured", with the reason - never silence', () => {
27
- expect(capabilityOf({ entries: [] })).toEqual({ state: 'not-configured', reason: 'no-agent' })
28
- })
29
-
30
- it('★ agents with no key are their own reason - every request would fail at the provider', () => {
31
- expect(capabilityOf({ entries: [entry('a', { usable: false, keyState: 'missing' })] as any })).toEqual({
32
- state: 'not-configured',
33
- reason: 'no-agent-key'
34
- })
35
- })
36
-
37
- it('agents that are all off are their own reason', () => {
38
- const entries = [entry('a', { usable: false, spec: { id: 'a', active: false } }), entry('b', { usable: false, turnedOff: true })]
39
- expect(capabilityOf({ entries: entries as any })).toEqual({ state: 'not-configured', reason: 'no-usable-agent' })
40
- })
@@ -1,49 +0,0 @@
1
- /**
2
- * Is there an AI for this domain, and what is missing — asked before anything is tried.
3
- *
4
- * The twin had a button that asked the assistant, and whether to show it was decided by whether a
5
- * now-dead mutation had failed once. When the dock moved to the neutral door nothing called that
6
- * mutation any more, so the answer was "configured" forever: the button appeared on deployments
7
- * with no provider at all and failed when pressed (standard A7-a).
8
- *
9
- * A capability is read, not discovered by failing (ADR-0042 decision ②). It lives here because the
10
- * agents do, and the answer has three states — the third is the one a screen must not fold away:
11
- * **not asked yet** is not "configured". Since agents are set per domain (design/ai/agent-settings.md),
12
- * so is the answer.
13
- */
14
- import type { Domain } from '@things-factory/shell'
15
-
16
- import { type AiAgentDirectory, readAiAgentDirectory } from './agent/agent-directory.js'
17
- import { isAIClientForTesting } from './agent/ai-client-for.js'
18
-
19
- export type AiCapabilityState = 'configured' | 'not-configured'
20
-
21
- export interface AiCapability {
22
- state: AiCapabilityState
23
- /** The provider of the agent a request without a choice gets. */
24
- provider?: string
25
- /** That agent's model. */
26
- model?: string
27
- /** Why it is not configured, as a code: no-agent · no-agent-key · no-usable-agent. */
28
- reason?: string
29
- }
30
-
31
- /** What this domain can do, as of now. It never throws: a domain with no AI is a normal domain. */
32
- export async function aiCapability(domain: Domain): Promise<AiCapability> {
33
- if (isAIClientForTesting()) return { state: 'configured' }
34
- try {
35
- return capabilityOf(await readAiAgentDirectory(domain))
36
- } catch (error) {
37
- console.error('[ai-client-base] could not read the AI agents of a domain:', (error as Error)?.message)
38
- return { state: 'not-configured', reason: 'no-agent' }
39
- }
40
- }
41
-
42
- export function capabilityOf(directory: Pick<AiAgentDirectory, 'entries' | 'defaultAgentId'>): AiCapability {
43
- const chosen = directory.entries.find(one => one.spec.id === directory.defaultAgentId && one.usable)
44
- if (chosen) return { state: 'configured', provider: chosen.spec.provider, model: chosen.spec.model }
45
-
46
- const live = directory.entries.filter(one => one.spec.active && !one.turnedOff)
47
- if (!live.length) return { state: 'not-configured', reason: directory.entries.length ? 'no-usable-agent' : 'no-agent' }
48
- return { state: 'not-configured', reason: 'no-agent-key' }
49
- }
@@ -1,55 +0,0 @@
1
- const mockGet = jest.fn()
2
- jest.mock('@things-factory/env', () => ({ config: { get: (...args: any[]) => mockGet(...args) } }))
3
- import { createConfiguredDecisionClient, getDefaultDecisionClient } from './config'
4
-
5
- beforeEach(() => mockGet.mockReset())
6
-
7
- test('absent and disabled config do not require a key or produce a client', () => {
8
- expect(createConfiguredDecisionClient(null)).toBeUndefined()
9
- expect(createConfiguredDecisionClient({ enabled: false })).toBeUndefined()
10
- })
11
-
12
- test('reads only aiDecision and exposes policy without exposing credentials', () => {
13
- mockGet.mockReturnValue({ enabled: true, provider: 'typesafe', apiKey: 'test-credential' })
14
- const client = getDefaultDecisionClient()!
15
- expect(mockGet).toHaveBeenCalledWith('aiDecision', null)
16
- expect(client.model).toBe('jev-1.13.0')
17
- expect(client.timeoutMs).toBe(300)
18
- expect(JSON.stringify(client)).not.toContain('test-credential')
19
- })
20
-
21
- test.each([
22
- { enabled: 'true' }, { provider: 'unknown' }, { model: 'jev-latest' },
23
- { timeoutMs: 0 }, { timeoutMs: NaN }, { timeoutMs: 10001 }, { apiKey: ' ' }
24
- ])('invalid enabled config fails explicitly without logging supplied values', change => {
25
- expect(() => createConfiguredDecisionClient({ enabled: true, provider: 'typesafe', apiKey: 'test-credential', ...change } as any)).toThrow(/^aiDecision\./)
26
- })
27
-
28
- test('configured deadline governs recommendation even if caller tries to override it', async () => {
29
- const client = createConfiguredDecisionClient({ enabled: true, provider: 'typesafe', apiKey: 'test-credential', timeoutMs: 5 })!
30
- const result = await client.recommend({
31
- query: 'order', candidates: [{ key: '1', label: 'order', description: '' }],
32
- mayRead: () => new Promise<boolean>(() => {}), isCurrent: () => true, timeoutMs: 10000
33
- } as any)
34
- expect(result.reason).toBe('timeout')
35
- expect(result.provider).toBe('jev-1.13.0')
36
- })
37
-
38
- test('host explicitly selects action classification; default stays entity and unknown purpose fails closed', async () => {
39
- const transport = jest.spyOn(globalThis, 'fetch').mockImplementation(async (_url, options) => {
40
- const body = JSON.parse(options!.body as string)
41
- const purpose = Object.keys(body.questions)[0]
42
- return { ok: true, json: async () => ({ model: 'jev-1.13.0', answers: { [purpose]: {
43
- type: 'choice', choice: 'read', confidence: 1, probabilities: { read: 1, __none__: 0 }
44
- } } }) } as Response
45
- })
46
- try {
47
- const client = createConfiguredDecisionClient({ enabled: true, provider: 'typesafe', apiKey: 'test-credential' })!
48
- const request = { query: 'read', candidates: [{ key: 'read', label: 'read', description: 'Read only' }], mayRead: async () => true, isCurrent: () => true }
49
- expect((await client.recommend({ ...request, purpose: 'action' })).candidateKey).toBe('read')
50
- expect((await client.recommend(request)).candidateKey).toBe('read')
51
- expect(transport.mock.calls.map(([, options]) => Object.keys(JSON.parse(options!.body as string).questions)[0])).toEqual(['action', 'entity'])
52
- await expect(client.recommend({ ...request, purpose: 'other' as any })).rejects.toThrow('Unsupported decision purpose')
53
- expect(transport).toHaveBeenCalledTimes(2)
54
- } finally { transport.mockRestore() }
55
- })
@@ -1,49 +0,0 @@
1
- import { config as envConfig } from '@things-factory/env'
2
- import { recommendCandidate, type DecisionResult } from './decision'
3
- import { createJevDecisionProvider, JEV_DECISION_MODEL, type JevDecisionPurpose } from './jev'
4
-
5
- export interface AIDecisionConfig {
6
- enabled: boolean
7
- provider?: 'typesafe'
8
- model?: string
9
- apiKey?: string
10
- timeoutMs?: number
11
- }
12
-
13
- export type DecisionRequest = Omit<Parameters<typeof recommendCandidate>[0], 'provider' | 'timeoutMs'> & {
14
- /** Trusted host contract, not a model-selected mode. Defaults to entity selection. */
15
- purpose?: JevDecisionPurpose
16
- }
17
-
18
- export interface DecisionClient {
19
- readonly provider: 'typesafe'
20
- readonly model: string
21
- readonly timeoutMs: number
22
- recommend(request: DecisionRequest): Promise<DecisionResult>
23
- }
24
-
25
- /** Validate once on construction. Errors never include supplied values or secrets. */
26
- export function createConfiguredDecisionClient(config: AIDecisionConfig | null | undefined): DecisionClient | undefined {
27
- if (!config || config.enabled === false) return undefined
28
- if (config.enabled !== true) throw new Error('aiDecision.enabled must be a boolean')
29
- if (config.provider !== 'typesafe') throw new Error('aiDecision.provider is not supported')
30
- const model = config.model ?? JEV_DECISION_MODEL
31
- if (model !== JEV_DECISION_MODEL) throw new Error('aiDecision.model must use the supported pinned version')
32
- const timeoutMs = config.timeoutMs ?? 300
33
- if (!Number.isFinite(timeoutMs) || timeoutMs < 1 || timeoutMs > 10000) throw new Error('aiDecision.timeoutMs must be between 1 and 10000')
34
- if (typeof config.apiKey !== 'string' || !config.apiKey.trim()) throw new Error('aiDecision.apiKey is required when enabled')
35
- const provider = createJevDecisionProvider(config.apiKey.trim())
36
- const actionProvider = createJevDecisionProvider(config.apiKey.trim(), fetch, 'action')
37
- return Object.freeze({
38
- provider: 'typesafe' as const, model, timeoutMs,
39
- recommend: async ({ purpose = 'entity', ...request }: DecisionRequest) => {
40
- if (purpose !== 'entity' && purpose !== 'action') throw new Error('Unsupported decision purpose')
41
- return recommendCandidate({ ...request, provider: purpose === 'action' ? actionProvider : provider, timeoutMs })
42
- }
43
- })
44
- }
45
-
46
- /** Server configuration only; constructing this client performs no network request and does not cache credentials. */
47
- export function getDefaultDecisionClient(): DecisionClient | undefined {
48
- return createConfiguredDecisionClient(envConfig.get('aiDecision', null) as AIDecisionConfig | null)
49
- }