@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,205 +0,0 @@
1
- import { randomUUID } from 'crypto'
2
- import { EntityManager, In } from 'typeorm'
3
-
4
- import { Domain, EnvVar, getRepository, Refusal } from '@things-factory/shell'
5
- import { Setting } from '@things-factory/setting-base'
6
-
7
- import { readAiAgentDirectory, readDescendantDomains } from './agent-directory.js'
8
- import {
9
- AI_AGENTS_SETTING,
10
- AI_AGENTS_SETTING_CATEGORY,
11
- aiAgentKeyName,
12
- type AiAgentSpec,
13
- isAiAgentProvider,
14
- parseAiAgentsSetting,
15
- stringifyAiAgentsSetting
16
- } from './agent-spec.js'
17
- import { listProviderModels } from './provider-models.js'
18
-
19
- /** One of this domain's own agents as the settings card sends it. No id means a new agent. */
20
- export interface AiAgentWrite {
21
- id?: string
22
- name: string
23
- provider: string
24
- model: string
25
- baseURL?: string
26
- organization?: string
27
- active: boolean
28
- /** A new key. Left out, the stored key stays (ADR-0112 decision 3). */
29
- apiKey?: string
30
- }
31
-
32
- /** This domain's key for an agent it inherits - set one, or clear it to go back to the key above. */
33
- export interface InheritedKeyWrite {
34
- agentId: string
35
- apiKey?: string
36
- clear?: boolean
37
- }
38
-
39
- export interface AiAgentsWrite {
40
- /** The whole list of this domain's own agents. One that is left out is deleted. */
41
- agents: AiAgentWrite[]
42
- defaultAgentId?: string
43
- turnedOff?: string[]
44
- inheritedKeys?: InheritedKeyWrite[]
45
- }
46
-
47
- /**
48
- * Saves a domain's agents and their keys in one transaction, touching only the request domain's rows - except that
49
- * deleting an agent also removes the keys domains below had set for it (design/ai/agent-settings.md §3-2, §3-3).
50
- */
51
- export async function saveAiAgents(
52
- write: AiAgentsWrite,
53
- { tx, domain, user }: { tx: EntityManager; domain: Domain; user?: { id: string } }
54
- ): Promise<void> {
55
- const directory = await readAiAgentDirectory(domain)
56
- const storedById = new Map(directory.own.agents.map(one => [one.id, one]))
57
- const inheritedIds = new Set(directory.entries.filter(one => one.inherited).map(one => one.spec.id))
58
-
59
- const agents = write.agents.map(one => normalize(one, storedById))
60
- refuseDuplicateNames(agents)
61
- await refuseNamesTakenAround(domain, agents, directory.entries.filter(one => one.inherited).map(one => one.spec))
62
-
63
- const storedKeyOf = new Map(
64
- directory.entries.filter(one => !one.inherited && one.keyState === 'own').map(one => [one.spec.id, one.apiKey!])
65
- )
66
- for (const [index, agent] of agents.entries()) {
67
- const newKey = write.agents[index].apiKey?.trim()
68
- const key = newKey || storedKeyOf.get(agent.id)
69
- if (!key) throw new Refusal('ai-agent-key-required', { agent: agent.name }, `Enter the API key of "${agent.name}".`)
70
- if (needsModelCheck(agent, storedById.get(agent.id), !!newKey)) {
71
- const offered = await listProviderModels({ provider: agent.provider, apiKey: key, baseURL: agent.baseURL, organization: agent.organization })
72
- if (!offered.includes(agent.model)) {
73
- throw new Refusal(
74
- 'ai-agent-model-not-offered',
75
- { agent: agent.name, model: agent.model },
76
- `The provider does not offer "${agent.model}" to this key.`
77
- )
78
- }
79
- }
80
- }
81
-
82
- const ownIds = new Set(agents.map(one => one.id))
83
- const defaultAgentId = write.defaultAgentId && (ownIds.has(write.defaultAgentId) || inheritedIds.has(write.defaultAgentId))
84
- ? write.defaultAgentId
85
- : undefined
86
- if (write.defaultAgentId && !defaultAgentId) {
87
- throw new Refusal('ai-agent-not-available', { agentId: write.defaultAgentId }, 'The default agent is not one this domain can use.')
88
- }
89
- const turnedOff = (write.turnedOff ?? []).filter(id => inheritedIds.has(id))
90
-
91
- await upsertSetting(tx, domain, user, stringifyAiAgentsSetting({ agents, defaultAgentId, turnedOff }))
92
-
93
- for (const [index, agent] of agents.entries()) {
94
- const newKey = write.agents[index].apiKey?.trim()
95
- if (newKey) await upsertKey(tx, domain, agent, newKey)
96
- }
97
-
98
- for (const one of write.inheritedKeys ?? []) {
99
- if (!inheritedIds.has(one.agentId)) {
100
- throw new Refusal('ai-agent-not-available', { agentId: one.agentId }, 'That agent is not inherited by this domain.')
101
- }
102
- if (one.clear) {
103
- await tx.getRepository(EnvVar).delete({ domain: { id: domain.id }, name: aiAgentKeyName(one.agentId) })
104
- } else if (one.apiKey?.trim()) {
105
- const spec = directory.entries.find(entry => entry.spec.id === one.agentId)!.spec
106
- await upsertKey(tx, domain, spec, one.apiKey.trim())
107
- }
108
- }
109
-
110
- const deleted = directory.own.agents.filter(one => !ownIds.has(one.id)).map(one => aiAgentKeyName(one.id))
111
- if (deleted.length) {
112
- const below = await readDescendantDomains(domain)
113
- await tx.getRepository(EnvVar).delete({
114
- domain: { id: In([domain.id, ...below.map(one => one.id)]) },
115
- name: In(deleted)
116
- })
117
- }
118
- }
119
-
120
- function normalize(write: AiAgentWrite, storedById: Map<string, AiAgentSpec>): AiAgentSpec {
121
- const name = write.name?.trim()
122
- if (!name) throw new Refusal('ai-agent-name-required', {}, 'Every agent needs a name.')
123
- if (!isAiAgentProvider(write.provider)) {
124
- throw new Refusal('ai-agent-provider-unknown', { provider: String(write.provider) }, `"${write.provider}" is not a provider an agent can use.`)
125
- }
126
- const model = write.model?.trim()
127
- if (!model) throw new Refusal('ai-agent-model-required', { agent: name }, `Pick the model of "${name}".`)
128
- if (write.id && !storedById.has(write.id)) {
129
- throw new Refusal('ai-agent-not-in-domain', { agentId: write.id }, 'That agent does not belong to this domain.')
130
- }
131
- return {
132
- id: write.id || randomUUID(),
133
- name,
134
- provider: write.provider,
135
- model,
136
- ...(write.baseURL?.trim() && { baseURL: write.baseURL.trim() }),
137
- ...(write.provider === 'openai' && write.organization?.trim() && { organization: write.organization.trim() }),
138
- active: write.active !== false
139
- }
140
- }
141
-
142
- /** The model is checked against the provider's list when anything that decides the list, or the model, changed. */
143
- function needsModelCheck(agent: AiAgentSpec, stored: AiAgentSpec | undefined, newKey: boolean): boolean {
144
- if (!stored || newKey) return true
145
- return stored.provider !== agent.provider || stored.model !== agent.model || stored.baseURL !== agent.baseURL || stored.organization !== agent.organization
146
- }
147
-
148
- function refuseDuplicateNames(agents: AiAgentSpec[]) {
149
- const seen = new Set<string>()
150
- for (const agent of agents) {
151
- const key = agent.name.toLowerCase()
152
- if (seen.has(key)) throw new Refusal('ai-agent-name-taken', { name: agent.name, domain: '' }, `There is already an agent named "${agent.name}".`)
153
- seen.add(key)
154
- }
155
- }
156
-
157
- /**
158
- * A name is one across the chain, so a picker never shows two agents of the same name: not the name of an agent
159
- * inherited from above, nor of an agent a domain below declared.
160
- */
161
- async function refuseNamesTakenAround(domain: Domain, agents: AiAgentSpec[], inherited: AiAgentSpec[]) {
162
- const taken = new Map<string, string>()
163
- for (const spec of inherited) taken.set(spec.name.toLowerCase(), '')
164
- const below = await readDescendantDomains(domain)
165
- if (below.length) {
166
- const settings = await getRepository(Setting).find({
167
- where: { domain: { id: In(below.map(one => one.id)) }, name: AI_AGENTS_SETTING }
168
- })
169
- const nameOf = new Map(below.map(one => [one.id, one.name]))
170
- for (const setting of settings) {
171
- for (const spec of parseAiAgentsSetting(setting.value).agents) taken.set(spec.name.toLowerCase(), nameOf.get(setting.domainId) ?? '')
172
- }
173
- }
174
- for (const agent of agents) {
175
- if (taken.has(agent.name.toLowerCase())) {
176
- throw new Refusal(
177
- 'ai-agent-name-taken',
178
- { name: agent.name, domain: taken.get(agent.name.toLowerCase()) ?? '' },
179
- `There is already an agent named "${agent.name}".`
180
- )
181
- }
182
- }
183
- }
184
-
185
- async function upsertSetting(tx: EntityManager, domain: Domain, user: { id: string } | undefined, value: string) {
186
- const repository = tx.getRepository(Setting)
187
- const stored = await repository.findOne({ where: { domain: { id: domain.id }, name: AI_AGENTS_SETTING } })
188
- await repository.save({
189
- ...(stored ?? { domain: { id: domain.id }, name: AI_AGENTS_SETTING, category: AI_AGENTS_SETTING_CATEGORY, creator: user }),
190
- value,
191
- updater: user
192
- } as any)
193
- }
194
-
195
- async function upsertKey(tx: EntityManager, domain: Domain, agent: AiAgentSpec, apiKey: string) {
196
- const repository = tx.getRepository(EnvVar)
197
- const name = aiAgentKeyName(agent.id)
198
- const stored = await repository.findOne({ where: { domain: { id: domain.id }, name } })
199
- await repository.save({
200
- ...(stored ?? { domain: { id: domain.id }, name }),
201
- value: apiKey,
202
- description: `API key of the AI agent "${agent.name}"`,
203
- active: true
204
- } as any)
205
- }
@@ -1,103 +0,0 @@
1
- /**
2
- * An AI agent - a provider, a model and a key that together can answer (design/ai/agent-settings.md §3).
3
- *
4
- * A domain keeps its agents in one Setting row (`ai-agents`) and each key in an EnvVar of its own, so the
5
- * definition and the secret live where the framework already keeps domain settings and secrets (ADR-0112).
6
- * This file is the shape and its parsing - no database.
7
- */
8
-
9
- /** The providers an agent may name. Three, by decision (2026-10-12). */
10
- export const AI_AGENT_PROVIDERS = ['openai', 'anthropic', 'gemini'] as const
11
- export type AiAgentProvider = (typeof AI_AGENT_PROVIDERS)[number]
12
-
13
- /** The Setting row that holds a domain's agents. */
14
- export const AI_AGENTS_SETTING = 'ai-agents'
15
- export const AI_AGENTS_SETTING_CATEGORY = 'ai'
16
-
17
- export interface AiAgentSpec {
18
- id: string
19
- name: string
20
- provider: AiAgentProvider
21
- model: string
22
- baseURL?: string
23
- /** OpenAI only. */
24
- organization?: string
25
- /** Off takes the agent out of this domain and every domain below it. */
26
- active: boolean
27
- }
28
-
29
- /** What the `ai-agents` Setting row holds for one domain. */
30
- export interface AiAgentsSetting {
31
- agents: AiAgentSpec[]
32
- /** This domain's default - one of its own agents or an inherited one. */
33
- defaultAgentId?: string
34
- /** Inherited agents this domain does not use. */
35
- turnedOff?: string[]
36
- }
37
-
38
- /** The EnvVar that holds an agent's key. Named by the agent id, so renaming an agent keeps its key. */
39
- export function aiAgentKeyName(agentId: string): string {
40
- return `AiAgent::${agentId}::apiKey`
41
- }
42
-
43
- export const AI_AGENT_KEY_PREFIX = 'AiAgent::'
44
-
45
- export function isAiAgentProvider(value: unknown): value is AiAgentProvider {
46
- return typeof value === 'string' && (AI_AGENT_PROVIDERS as readonly string[]).includes(value)
47
- }
48
-
49
- const EMPTY: AiAgentsSetting = { agents: [] }
50
-
51
- /**
52
- * Reads a stored `ai-agents` value. The row can also be written through the generic setting doors, so a value that
53
- * does not parse reads as no agents, and an entry without an id, a name, a known provider or a model is left out -
54
- * a broken row never becomes an agent that fails at the provider.
55
- */
56
- export function parseAiAgentsSetting(value: string | null | undefined): AiAgentsSetting {
57
- if (!value) return EMPTY
58
- let raw: any
59
- try {
60
- raw = JSON.parse(value)
61
- } catch {
62
- return EMPTY
63
- }
64
- if (!raw || typeof raw !== 'object' || !Array.isArray(raw.agents)) return EMPTY
65
-
66
- const agents: AiAgentSpec[] = raw.agents.flatMap((one: any) => {
67
- if (!one || typeof one !== 'object') return []
68
- const id = text(one.id)
69
- const name = text(one.name)
70
- const model = text(one.model)
71
- if (!id || !name || !model || !isAiAgentProvider(one.provider)) return []
72
- return [
73
- {
74
- id,
75
- name,
76
- provider: one.provider,
77
- model,
78
- ...(text(one.baseURL) && { baseURL: text(one.baseURL) }),
79
- ...(one.provider === 'openai' && text(one.organization) && { organization: text(one.organization) }),
80
- active: one.active !== false
81
- }
82
- ]
83
- })
84
-
85
- const turnedOff = Array.isArray(raw.turnedOff) ? raw.turnedOff.filter((id: unknown) => typeof id === 'string') : []
86
- return {
87
- agents,
88
- ...(text(raw.defaultAgentId) && { defaultAgentId: text(raw.defaultAgentId) }),
89
- ...(turnedOff.length && { turnedOff })
90
- }
91
- }
92
-
93
- export function stringifyAiAgentsSetting(setting: AiAgentsSetting): string {
94
- return JSON.stringify({
95
- agents: setting.agents,
96
- ...(setting.defaultAgentId && { defaultAgentId: setting.defaultAgentId }),
97
- ...(setting.turnedOff?.length && { turnedOff: setting.turnedOff })
98
- })
99
- }
100
-
101
- function text(value: unknown): string {
102
- return typeof value === 'string' ? value.trim() : ''
103
- }
@@ -1,170 +0,0 @@
1
- /*
2
- * What this guards: **the one door to a model picks the agent the person asked for or the domain's default, refuses
3
- * anything else, and writes a usage row for every provider request** (ADR-0061 decision 6,
4
- * design/ai/agent-settings.md §4).
5
- */
6
- const saved: any[] = []
7
- /* How long a usage row takes to write: 0, or slower than the answer it records. */
8
- const mockWrite = { ms: 0 }
9
-
10
- jest.mock('@things-factory/shell', () => ({
11
- ...jest.requireActual('@things-factory/shell'),
12
- getRepository: jest.fn(() => ({
13
- save: async (rows: any[]) => {
14
- if (mockWrite.ms) await new Promise(resolve => setTimeout(resolve, mockWrite.ms))
15
- saved.push(...rows)
16
- }
17
- }))
18
- }))
19
- jest.mock('./agent-directory', () => ({ readAiAgentDirectory: jest.fn() }))
20
-
21
- import { readAiAgentDirectory } from './agent-directory'
22
- import { aiClientFor, aiUsageRecorded, hourOf, outcomeOf, pickAgent } from './ai-client-for'
23
- import { registerAIProvider } from '../factory'
24
-
25
- const entry = (id: string, extra: any = {}) => ({
26
- spec: { id, name: id.toUpperCase(), provider: 'fake', model: 'fake-1', active: true },
27
- ownerDomainId: 'hq',
28
- inherited: true,
29
- turnedOff: false,
30
- keyState: 'inherited',
31
- keyDomainId: 'hq',
32
- apiKey: 'k',
33
- keyVersion: 'hq:0',
34
- usable: true,
35
- ...extra
36
- })
37
-
38
- let replies: Array<(options: any) => any> = []
39
- registerAIProvider('fake', config => ({
40
- id: `fake:${config.model}`,
41
- chat: async (_messages, options: any) => {
42
- const reply = replies.shift()!
43
- return reply(options)
44
- },
45
- generateJSON: async () => ({}),
46
- chatWithTools: async (_messages, _tools, options: any) => {
47
- options.onUsage?.({ model: 'fake-1-0607', inputTokens: 100, outputTokens: 20 })
48
- options.onUsage?.({ model: 'fake-1-0607', inputTokens: 300, outputTokens: 5 })
49
- return { toolCalls: [], stopReason: 'end_turn' }
50
- },
51
- transcribe: async (_audio, options: any) => { options.onUsage?.({ model: 'fake-speech' }); return { text: 'spoken', segments: [{ start: 0, end: 1, text: 'spoken' }] } },
52
- listModels: async () => ['fake-1']
53
- }))
54
-
55
- const flush = () => new Promise(resolve => setImmediate(resolve))
56
-
57
- beforeEach(() => {
58
- saved.length = 0
59
- replies = []
60
- mockWrite.ms = 0
61
- })
62
-
63
- describe('which agent answers', () => {
64
- it('★ the agent the person picked, when this domain can use it', () => {
65
- expect(pickAgent([entry('a'), entry('b')] as any, 'b', 'a').spec.id).toBe('b')
66
- })
67
-
68
- it('★ the domain default when nobody picked', () => {
69
- expect(pickAgent([entry('a'), entry('b')] as any, undefined, 'a').spec.id).toBe('a')
70
- })
71
-
72
- it('★ a picked agent this domain cannot use is refused - never swapped for another', () => {
73
- const entries = [entry('a'), entry('b', { usable: false })] as any
74
- expect(() => pickAgent(entries, 'b', 'a')).toThrow(expect.objectContaining({ code: 'ai-agent-not-available' }))
75
- expect(() => pickAgent(entries, 'nonesuch', 'a')).toThrow(expect.objectContaining({ code: 'ai-agent-not-available' }))
76
- })
77
-
78
- it('★ no usable agent is "not configured"', () => {
79
- expect(() => pickAgent([entry('a', { usable: false })] as any, undefined, 'a')).toThrow(
80
- expect.objectContaining({ code: 'ai-not-configured' })
81
- )
82
- })
83
- })
84
-
85
- describe('usage', () => {
86
- beforeEach(() => {
87
- ;(readAiAgentDirectory as jest.Mock).mockResolvedValue({ entries: [entry('a')], defaultAgentId: 'a' })
88
- })
89
-
90
- it('★ every provider request of a call is one row, with the domain, the person, the agent and who paid', async () => {
91
- const client = await aiClientFor({ domain: { id: 'plant' } as any, user: { id: 'u1' }, modeKind: 'twin.space', sessionId: 's1' })
92
- await client.chatWithTools!([], [], {})
93
- await flush()
94
-
95
- expect(saved).toHaveLength(2)
96
- expect(saved[0]).toMatchObject({
97
- domain: { id: 'plant' },
98
- creator: { id: 'u1' },
99
- agentId: 'a',
100
- agentDomainId: 'hq',
101
- keyDomainId: 'hq',
102
- provider: 'fake',
103
- model: 'fake-1-0607',
104
- modeKind: 'twin.space',
105
- operation: 'chatWithTools',
106
- sessionId: 's1',
107
- inputTokens: 100,
108
- outputTokens: 20,
109
- outcome: 'ok'
110
- })
111
- expect(saved[1]).toMatchObject({ inputTokens: 300, outputTokens: 5 })
112
- })
113
-
114
- it('★ a failed request is still a row, with why it failed', async () => {
115
- replies.push(() => {
116
- throw Object.assign(new Error('nope'), { status: 429 })
117
- })
118
- const client = await aiClientFor({ domain: { id: 'plant' } as any })
119
-
120
- await expect(client.chat([])).rejects.toThrow('nope')
121
- await flush()
122
-
123
- expect(saved).toEqual([expect.objectContaining({ operation: 'chat', outcome: 'rate-limited', model: 'fake-1' })])
124
- expect(saved[0].creator).toBeUndefined()
125
- })
126
-
127
- /* A script closing its database after its last call (figure-ai-scenarios-agent.cjs) waits for the rows first. */
128
- it('the rows still being written are waited for: none is left to a database closed after the last answer', async () => {
129
- mockWrite.ms = 30
130
- const client = await aiClientFor({ domain: { id: 'plant' } as any })
131
- await client.chatWithTools!([], [], {})
132
- expect(saved).toHaveLength(0)
133
- await aiUsageRecorded()
134
- expect(saved).toHaveLength(2)
135
- })
136
-
137
- it('the caller\'s own usage listener still hears every request', async () => {
138
- const heard: any[] = []
139
- const client = await aiClientFor({ domain: { id: 'plant' } as any })
140
- await client.chatWithTools!([], [], { onUsage: usage => heard.push(usage) })
141
- expect(heard).toHaveLength(2)
142
- })
143
-
144
- it('the client names the agent that answered', async () => {
145
- const client = await aiClientFor({ domain: { id: 'plant' } as any })
146
- expect(client.agent).toEqual({ id: 'a', name: 'A', provider: 'fake', model: 'fake-1' })
147
- expect(client.id).toBe('fake:fake-1')
148
- })
149
- })
150
-
151
- it('a failure is named by what the provider said', () => {
152
- expect(outcomeOf({ status: 401 })).toBe('key-rejected')
153
- expect(outcomeOf({ status: 403 })).toBe('key-rejected')
154
- expect(outcomeOf({ status: 429 })).toBe('rate-limited')
155
- expect(outcomeOf(new Error('socket hang up'))).toBe('provider-error')
156
- })
157
-
158
- it('a call is grouped by the UTC hour it started in', () => {
159
- expect(hourOf(new Date('2026-10-12T05:47:13.120Z')).toISOString()).toBe('2026-10-12T05:00:00.000Z')
160
- })
161
-
162
- it('speech transcription uses the same tenant usage boundary without fabricated token counts', async () => {
163
- ;(readAiAgentDirectory as jest.Mock).mockResolvedValue({ entries: [entry('speech')], defaultAgentId: 'speech' })
164
- const client = await aiClientFor({ domain: { id: 'office' } as any, user: { id: 'manager' }, modeKind: 'learning.material-transcription' })
165
- expect(await client.transcribe!(Buffer.from('audio'))).toEqual({ text: 'spoken', segments: [{ start: 0, end: 1, text: 'spoken' }] })
166
- await aiUsageRecorded()
167
- expect(saved).toHaveLength(1)
168
- expect(saved[0]).toMatchObject({ operation: 'transcribe', model: 'fake-speech', domain: { id: 'office' }, creator: { id: 'manager' } })
169
- expect(saved[0].inputTokens).toBeUndefined()
170
- })