@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.
- package/dist-server/service/agent/ai-client-for.js +2 -0
- package/dist-server/service/agent/ai-model-price.d.ts +22 -0
- package/dist-server/service/agent/ai-model-price.js +81 -0
- package/dist-server/service/agent/ai-usage-summary.d.ts +8 -1
- package/dist-server/service/agent/ai-usage-summary.js +17 -4
- package/dist-server/service/agent/ai-usage.d.ts +2 -0
- package/dist-server/service/agent/ai-usage.js +12 -2
- package/dist-server/service/agent/index.d.ts +2 -0
- package/dist-server/service/agent/index.js +4 -1
- package/dist-server/service/agent/model-price-boot.d.ts +1 -0
- package/dist-server/service/agent/model-price-boot.js +14 -0
- package/dist-server/service/agent/model-price.d.ts +77 -0
- package/dist-server/service/agent/model-price.js +214 -0
- package/dist-server/service/index.d.ts +3 -1
- package/dist-server/service/index.js +3 -1
- package/dist-server/service/providers/anthropic.js +2 -5
- package/dist-server/service/providers/gemini.js +2 -6
- package/dist-server/service/providers/openai.js +2 -5
- package/dist-server/service/providers/usage.d.ts +18 -0
- package/dist-server/service/providers/usage.js +50 -0
- package/dist-server/service/types.d.ts +6 -0
- package/package.json +20 -6
- package/translations/en.json +5 -1
- package/translations/es.json +5 -1
- package/translations/ja.json +5 -1
- package/translations/ko.json +5 -1
- package/translations/ms.json +5 -1
- package/translations/zh.json +5 -1
- package/dist-server/index.js.map +0 -1
- package/dist-server/service/agent/agent-directory.js.map +0 -1
- package/dist-server/service/agent/agent-settings-save.js.map +0 -1
- package/dist-server/service/agent/agent-spec.js.map +0 -1
- package/dist-server/service/agent/ai-client-for.js.map +0 -1
- package/dist-server/service/agent/ai-usage-summary.js.map +0 -1
- package/dist-server/service/agent/ai-usage.js.map +0 -1
- package/dist-server/service/agent/index.js.map +0 -1
- package/dist-server/service/agent/provider-models.js.map +0 -1
- package/dist-server/service/agentic-loop/agentic-loop.js.map +0 -1
- package/dist-server/service/agentic-loop/index.js.map +0 -1
- package/dist-server/service/analysis-contract.js.map +0 -1
- package/dist-server/service/assistant/abort-notice.js.map +0 -1
- package/dist-server/service/assistant/assistant-chat.js.map +0 -1
- package/dist-server/service/assistant/index.js.map +0 -1
- package/dist-server/service/assistant/open-subject.js.map +0 -1
- package/dist-server/service/assistant/registry-assistant.js.map +0 -1
- package/dist-server/service/assistant/registry-gate.js.map +0 -1
- package/dist-server/service/assistant/summarize.js.map +0 -1
- package/dist-server/service/assistant/tool-budget.js.map +0 -1
- package/dist-server/service/assistant/tool-scope.js.map +0 -1
- package/dist-server/service/capability.js.map +0 -1
- package/dist-server/service/decision/config.js.map +0 -1
- package/dist-server/service/decision/decision.js.map +0 -1
- package/dist-server/service/decision/index.js.map +0 -1
- package/dist-server/service/decision/jev.js.map +0 -1
- package/dist-server/service/factory.js.map +0 -1
- package/dist-server/service/index.js.map +0 -1
- package/dist-server/service/providers/anthropic.js.map +0 -1
- package/dist-server/service/providers/gemini.js.map +0 -1
- package/dist-server/service/providers/index.js.map +0 -1
- package/dist-server/service/providers/openai.js.map +0 -1
- package/dist-server/service/providers/request-options.js.map +0 -1
- package/dist-server/service/testing/tool-call-context.js.map +0 -1
- package/dist-server/service/tool-registry/call-recorder.js.map +0 -1
- package/dist-server/service/tool-registry/index.js.map +0 -1
- package/dist-server/service/tool-registry/registry.js.map +0 -1
- package/dist-server/service/tool-registry/translate.js.map +0 -1
- package/dist-server/service/tool-registry/types.js.map +0 -1
- package/dist-server/service/types.js.map +0 -1
- package/dist-server/service/utils/grounding.js.map +0 -1
- package/dist-server/service/utils/index.js.map +0 -1
- package/dist-server/service/utils/parse-json.js.map +0 -1
- package/dist-server/service/utils/transient.js.map +0 -1
- package/dist-server/tsconfig.tsbuildinfo +0 -1
- package/docs/grounded-analysis-contract.md +0 -54
- package/experiments/entity360/README.md +0 -224
- package/experiments/entity360/apps.cjs +0 -103
- package/experiments/entity360/apps.test.cjs +0 -24
- package/experiments/entity360/baseline-apps-results.json +0 -3357
- package/experiments/entity360/baseline-expanded-results.json +0 -5952
- package/experiments/entity360/baseline-results.json +0 -1507
- package/experiments/entity360/expanded.cjs +0 -65
- package/experiments/entity360/fixtures.json +0 -100
- package/experiments/entity360/index.html +0 -44
- package/experiments/entity360/jev-apps-results.json +0 -3440
- package/experiments/entity360/jev-expanded-results.json +0 -6095
- package/experiments/entity360/jev-results.json +0 -1542
- package/experiments/entity360/run.cjs +0 -100
- package/server/index.ts +0 -19
- package/server/service/agent/agent-directory.test.ts +0 -206
- package/server/service/agent/agent-directory.ts +0 -198
- package/server/service/agent/agent-settings-save.test.ts +0 -151
- package/server/service/agent/agent-settings-save.ts +0 -205
- package/server/service/agent/agent-spec.ts +0 -103
- package/server/service/agent/ai-client-for.test.ts +0 -170
- package/server/service/agent/ai-client-for.ts +0 -215
- package/server/service/agent/ai-usage-summary.test.ts +0 -65
- package/server/service/agent/ai-usage-summary.ts +0 -146
- package/server/service/agent/ai-usage.ts +0 -97
- package/server/service/agent/index.ts +0 -7
- package/server/service/agent/one-door.test.ts +0 -57
- package/server/service/agent/provider-models.ts +0 -43
- package/server/service/agentic-loop/agentic-loop.test.ts +0 -1118
- package/server/service/agentic-loop/agentic-loop.ts +0 -745
- package/server/service/agentic-loop/index.ts +0 -1
- package/server/service/agentic-loop/proposal-key.test.ts +0 -83
- package/server/service/analysis-contract.test.ts +0 -20
- package/server/service/analysis-contract.ts +0 -77
- package/server/service/assistant/abort-notice.ts +0 -67
- package/server/service/assistant/assistant-chat.test.ts +0 -240
- package/server/service/assistant/assistant-chat.ts +0 -104
- package/server/service/assistant/index.ts +0 -13
- package/server/service/assistant/open-subject.test.ts +0 -91
- package/server/service/assistant/open-subject.ts +0 -140
- package/server/service/assistant/registry-assistant.test.ts +0 -627
- package/server/service/assistant/registry-assistant.ts +0 -240
- package/server/service/assistant/registry-gate.ts +0 -76
- package/server/service/assistant/summarize.ts +0 -47
- package/server/service/assistant/tool-budget.test.ts +0 -246
- package/server/service/assistant/tool-budget.ts +0 -186
- package/server/service/assistant/tool-scope.test.ts +0 -123
- package/server/service/assistant/tool-scope.ts +0 -103
- package/server/service/capability.test.ts +0 -40
- package/server/service/capability.ts +0 -49
- package/server/service/decision/config.test.ts +0 -55
- package/server/service/decision/config.ts +0 -49
- package/server/service/decision/decision.test.ts +0 -94
- package/server/service/decision/decision.ts +0 -112
- package/server/service/decision/index.ts +0 -3
- package/server/service/decision/jev.ts +0 -40
- package/server/service/factory.ts +0 -28
- package/server/service/index.ts +0 -17
- package/server/service/providers/anthropic.ts +0 -274
- package/server/service/providers/gemini.ts +0 -396
- package/server/service/providers/index.ts +0 -8
- package/server/service/providers/json-answer.test.ts +0 -53
- package/server/service/providers/openai-models.test.ts +0 -30
- package/server/service/providers/openai.ts +0 -326
- package/server/service/providers/request-options.ts +0 -12
- package/server/service/providers/request-signal.test.ts +0 -77
- package/server/service/providers/transcribe.test.ts +0 -18
- package/server/service/testing/tool-call-context.ts +0 -38
- package/server/service/tool-registry/call-recorder.ts +0 -116
- package/server/service/tool-registry/index.ts +0 -50
- package/server/service/tool-registry/registry.test.ts +0 -319
- package/server/service/tool-registry/registry.ts +0 -248
- package/server/service/tool-registry/translate.ts +0 -12
- package/server/service/tool-registry/types.ts +0 -305
- package/server/service/types.ts +0 -221
- package/server/service/utils/grounding.test.ts +0 -119
- package/server/service/utils/grounding.ts +0 -131
- package/server/service/utils/index.ts +0 -3
- package/server/service/utils/parse-json.ts +0 -116
- package/server/service/utils/transient.test.ts +0 -92
- package/server/service/utils/transient.ts +0 -92
- package/tsconfig.json +0 -9
|
@@ -1,215 +0,0 @@
|
|
|
1
|
-
import { Domain, getRepository, Refusal } from '@things-factory/shell'
|
|
2
|
-
|
|
3
|
-
import { createAIClient } from '../factory.js'
|
|
4
|
-
import type { AIChatOptions, AIClient, AIProviderUsage } from '../types.js'
|
|
5
|
-
import { type AiAgentEntry, readAiAgentDirectory } from './agent-directory.js'
|
|
6
|
-
import type { AiUsage } from './ai-usage.js'
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* **The one door to a model** (design/ai/agent-settings.md §4).
|
|
10
|
-
*
|
|
11
|
-
* Every call that reaches a provider gets its client here, for a domain: the agent is the one asked for, or the
|
|
12
|
-
* domain's default, and its key is the closest one on the domain chain. There is no deployment-wide client - a domain
|
|
13
|
-
* with no usable agent has no AI (user decision 2026-10-12).
|
|
14
|
-
*
|
|
15
|
-
* The client handed back is metered: each provider request writes one AiUsage row with the domain, the person, the
|
|
16
|
-
* agent and what was used (ADR-0061 decision 6).
|
|
17
|
-
*/
|
|
18
|
-
export interface AiClientRequest {
|
|
19
|
-
domain: Domain
|
|
20
|
-
/** The person calling. Empty for a call with no person, such as a webhook. */
|
|
21
|
-
user?: { id: string } | null
|
|
22
|
-
/** The agent the person picked. Empty takes the domain's default. */
|
|
23
|
-
agentId?: string | null
|
|
24
|
-
/** The conversation mode, when the call is part of a conversation. */
|
|
25
|
-
modeKind?: string | null
|
|
26
|
-
/** The conversation, by id. */
|
|
27
|
-
sessionId?: string | null
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
/** The client of one agent, as a call got it. */
|
|
31
|
-
export interface AgentClient extends AIClient {
|
|
32
|
-
readonly agent: { id: string; name: string; provider: string; model: string }
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
/* The usage rows still being written: a request's answer does not wait for its row. */
|
|
36
|
-
const recording = new Set<Promise<unknown>>()
|
|
37
|
-
|
|
38
|
-
/**
|
|
39
|
-
* Once every usage row asked for so far is written (or failed and said so). For a process that closes its database
|
|
40
|
-
* after its last call -- a script running scenarios -- so the last rows are not lost to a closed handle.
|
|
41
|
-
*/
|
|
42
|
-
export async function aiUsageRecorded(): Promise<void> {
|
|
43
|
-
while (recording.size) await Promise.allSettled([...recording])
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
export async function aiClientFor(request: AiClientRequest): Promise<AgentClient> {
|
|
47
|
-
if (_testing) return _testing(request)
|
|
48
|
-
if (!request.domain) throw new Error('aiClientFor needs the domain the call is made in')
|
|
49
|
-
|
|
50
|
-
const directory = await readAiAgentDirectory(request.domain)
|
|
51
|
-
const entry = pickAgent(directory.entries, request.agentId, directory.defaultAgentId)
|
|
52
|
-
return meter(providerClientOf(entry), entry, request)
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
/**
|
|
56
|
-
* The agent a request is answered by. A named agent that this domain cannot use is refused, never swapped for
|
|
57
|
-
* another; no agent at all is "not configured".
|
|
58
|
-
*/
|
|
59
|
-
export function pickAgent(entries: AiAgentEntry[], agentId: string | null | undefined, defaultAgentId?: string): AiAgentEntry {
|
|
60
|
-
if (agentId) {
|
|
61
|
-
const named = entries.find(one => one.spec.id === agentId)
|
|
62
|
-
if (!named?.usable) {
|
|
63
|
-
throw new Refusal('ai-agent-not-available', { agentId }, 'The AI agent you picked is not available here.')
|
|
64
|
-
}
|
|
65
|
-
return named
|
|
66
|
-
}
|
|
67
|
-
const fallback = entries.find(one => one.spec.id === defaultAgentId && one.usable)
|
|
68
|
-
if (!fallback) {
|
|
69
|
-
throw new Refusal('ai-not-configured', {}, 'AI is not set up for this domain.')
|
|
70
|
-
}
|
|
71
|
-
return fallback
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
/* Provider clients are kept per agent and rebuilt when its definition or its key changes. */
|
|
75
|
-
const _clients = new Map<string, { version: string; client: AIClient }>()
|
|
76
|
-
|
|
77
|
-
function providerClientOf(entry: AiAgentEntry): AIClient {
|
|
78
|
-
const { spec } = entry
|
|
79
|
-
const version = JSON.stringify([spec.provider, spec.model, spec.baseURL, spec.organization, entry.keyVersion])
|
|
80
|
-
const cached = _clients.get(spec.id)
|
|
81
|
-
if (cached?.version === version) return cached.client
|
|
82
|
-
|
|
83
|
-
const client = createAIClient({
|
|
84
|
-
provider: spec.provider,
|
|
85
|
-
model: spec.model,
|
|
86
|
-
apiKey: entry.apiKey!,
|
|
87
|
-
...(spec.baseURL && { baseURL: spec.baseURL }),
|
|
88
|
-
...(spec.organization && { organization: spec.organization })
|
|
89
|
-
})
|
|
90
|
-
_clients.set(spec.id, { version, client })
|
|
91
|
-
return client
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
function meter(client: AIClient, entry: AiAgentEntry, request: AiClientRequest): AgentClient {
|
|
95
|
-
const { spec } = entry
|
|
96
|
-
|
|
97
|
-
async function measured<T>(operation: string, options: AIChatOptions | undefined, call: (options: AIChatOptions) => Promise<T>): Promise<T> {
|
|
98
|
-
const started = new Date()
|
|
99
|
-
const reported: AIProviderUsage[] = []
|
|
100
|
-
const withUsage: AIChatOptions = {
|
|
101
|
-
...options,
|
|
102
|
-
onUsage: usage => {
|
|
103
|
-
reported.push(usage)
|
|
104
|
-
options?.onUsage?.(usage)
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
try {
|
|
108
|
-
const result = await call(withUsage)
|
|
109
|
-
record(operation, started, reported, 'ok')
|
|
110
|
-
return result
|
|
111
|
-
} catch (error: any) {
|
|
112
|
-
record(operation, started, reported, outcomeOf(error))
|
|
113
|
-
/* A failure must say why somewhere: the loop above turns it into a sentence for the person, and the usage row
|
|
114
|
-
keeps only its code. The provider's own message names no key. */
|
|
115
|
-
console.error(
|
|
116
|
-
`[ai-client-base] ${spec.provider}:${spec.model} (${spec.name}) ${operation} failed:`,
|
|
117
|
-
error?.status ?? '',
|
|
118
|
-
error?.message ?? error
|
|
119
|
-
)
|
|
120
|
-
throw error
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
function record(operation: string, started: Date, reported: AIProviderUsage[], outcome: string) {
|
|
125
|
-
const durationMs = Date.now() - started.valueOf()
|
|
126
|
-
/* A failed request reports nothing, and is still one row - a failure costs time and often money. */
|
|
127
|
-
const rows = (reported.length ? reported : [{ model: spec.model } as AIProviderUsage]).map((usage, index, all) => ({
|
|
128
|
-
domain: { id: request.domain.id },
|
|
129
|
-
...(request.user?.id && { creator: { id: request.user.id } }),
|
|
130
|
-
agentId: spec.id,
|
|
131
|
-
agentDomainId: entry.ownerDomainId,
|
|
132
|
-
keyDomainId: entry.keyDomainId,
|
|
133
|
-
provider: spec.provider,
|
|
134
|
-
model: usage.model || spec.model,
|
|
135
|
-
modeKind: request.modeKind ?? undefined,
|
|
136
|
-
operation,
|
|
137
|
-
sessionId: request.sessionId ?? undefined,
|
|
138
|
-
inputTokens: usage.inputTokens,
|
|
139
|
-
outputTokens: usage.outputTokens,
|
|
140
|
-
/* The whole call's time goes on its last request; the rows of one call still add up to it. */
|
|
141
|
-
durationMs: index === all.length - 1 ? durationMs : 0,
|
|
142
|
-
outcome: index === all.length - 1 ? outcome : 'ok',
|
|
143
|
-
hourStart: hourOf(started)
|
|
144
|
-
}))
|
|
145
|
-
/* Outside the caller's transaction: a rolled-back write still spent the tokens. By name, so the decorated entity
|
|
146
|
-
stays out of this module's imports. */
|
|
147
|
-
const written: Promise<unknown> = getRepository<AiUsage>('AiUsage')
|
|
148
|
-
.save(rows as any)
|
|
149
|
-
.catch(error => console.error('[ai-client-base] could not record AI usage:', error?.message ?? error))
|
|
150
|
-
.finally(() => recording.delete(written))
|
|
151
|
-
recording.add(written)
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
const metered: AgentClient = {
|
|
155
|
-
id: `${spec.provider}:${spec.model}`,
|
|
156
|
-
agent: { id: spec.id, name: spec.name, provider: spec.provider, model: spec.model },
|
|
157
|
-
chat: (messages, options) => measured('chat', options, o => client.chat(messages, o)),
|
|
158
|
-
generateJSON: (prompt, options) => measured('generateJSON', options, o => client.generateJSON(prompt, o)),
|
|
159
|
-
...(client.transcribe && { transcribe: (audio, options) => measured('transcribe', options, o => client.transcribe!(audio, o)) }),
|
|
160
|
-
...(client.vision && {
|
|
161
|
-
vision: (image, prompt, options) => measured('vision', options, o => client.vision!(image, prompt, o))
|
|
162
|
-
}),
|
|
163
|
-
...(client.chatWithTools && {
|
|
164
|
-
chatWithTools: (messages, tools, options) =>
|
|
165
|
-
measured('chatWithTools', options, o => client.chatWithTools!(messages, tools, o))
|
|
166
|
-
}),
|
|
167
|
-
listModels: () => client.listModels()
|
|
168
|
-
}
|
|
169
|
-
return metered
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
/** The UTC hour a moment falls in. */
|
|
173
|
-
export function hourOf(moment: Date): Date {
|
|
174
|
-
const hour = new Date(moment)
|
|
175
|
-
hour.setUTCMinutes(0, 0, 0)
|
|
176
|
-
return hour
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
/** Why a provider request failed, as the usage row keeps it. */
|
|
180
|
-
export function outcomeOf(error: any): string {
|
|
181
|
-
const status = Number(error?.status ?? error?.statusCode ?? error?.response?.status)
|
|
182
|
-
if (status === 401 || status === 403) return 'key-rejected'
|
|
183
|
-
if (status === 429) return 'rate-limited'
|
|
184
|
-
return 'provider-error'
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
type TestClientResolver = (request: AiClientRequest) => AgentClient
|
|
188
|
-
|
|
189
|
-
let _testing: TestClientResolver | undefined
|
|
190
|
-
|
|
191
|
-
export function isAIClientForTesting(): boolean {
|
|
192
|
-
return !!_testing
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
/**
|
|
196
|
-
* Tests answer aiClientFor with a client of their own - no database, no provider, no usage rows. A client is wrapped
|
|
197
|
-
* as an agent named after it; a function decides per request. `undefined` puts the real door back.
|
|
198
|
-
*/
|
|
199
|
-
export function setAIClientForTesting(client: AIClient | TestClientResolver | undefined): void {
|
|
200
|
-
if (!client) {
|
|
201
|
-
_testing = undefined
|
|
202
|
-
} else if (typeof client === 'function') {
|
|
203
|
-
_testing = client
|
|
204
|
-
} else {
|
|
205
|
-
/* The test's own object answers - its counters and `this` stay its own; it only gains the agent it is named as. */
|
|
206
|
-
if (!(client as AgentClient).agent) {
|
|
207
|
-
const [provider, model] = String(client.id ?? 'test:test').split(':')
|
|
208
|
-
Object.defineProperty(client, 'agent', {
|
|
209
|
-
value: { id: 'test-agent', name: client.id ?? 'test', provider, model },
|
|
210
|
-
configurable: true
|
|
211
|
-
})
|
|
212
|
-
}
|
|
213
|
-
_testing = () => client as AgentClient
|
|
214
|
-
}
|
|
215
|
-
}
|
|
@@ -1,65 +0,0 @@
|
|
|
1
|
-
/*
|
|
2
|
-
* What this guards: **usage is counted per bucket × agent × person in the domain's own time zone, and a domain above
|
|
3
|
-
* never sees the people of a domain below** (design/ai/agent-settings.md §6-2).
|
|
4
|
-
*/
|
|
5
|
-
import { rollUp } from './ai-usage-summary'
|
|
6
|
-
|
|
7
|
-
const hour = (iso: string, extra: any = {}) => ({
|
|
8
|
-
hourStart: iso,
|
|
9
|
-
agentId: 'a1',
|
|
10
|
-
provider: 'openai',
|
|
11
|
-
model: 'gpt-4o',
|
|
12
|
-
domainId: 'hq',
|
|
13
|
-
domainName: '본사',
|
|
14
|
-
userId: 'u1',
|
|
15
|
-
userName: '김철수',
|
|
16
|
-
calls: '2',
|
|
17
|
-
inputTokens: '100',
|
|
18
|
-
outputTokens: '10',
|
|
19
|
-
failures: '0',
|
|
20
|
-
...extra
|
|
21
|
-
})
|
|
22
|
-
|
|
23
|
-
const names = new Map([['a1', 'GPT-4o']])
|
|
24
|
-
|
|
25
|
-
it('★ hours roll up into the domain\'s days - 15:00Z on the 11th is the 12th in Seoul', () => {
|
|
26
|
-
const rows = rollUp(
|
|
27
|
-
[hour('2026-10-11T14:00:00.000Z'), hour('2026-10-11T15:00:00.000Z'), hour('2026-10-12T03:00:00.000Z', { failures: '1' })],
|
|
28
|
-
'day',
|
|
29
|
-
'Asia/Seoul',
|
|
30
|
-
'hq',
|
|
31
|
-
names
|
|
32
|
-
)
|
|
33
|
-
expect(rows.map(one => [one.bucket, one.calls, one.inputTokens, one.failures])).toEqual([
|
|
34
|
-
['2026-10-12', 4, 200, 1],
|
|
35
|
-
['2026-10-11', 2, 100, 0]
|
|
36
|
-
])
|
|
37
|
-
expect(rows[0]).toMatchObject({ agentName: 'GPT-4o', userName: '김철수', domainName: '본사' })
|
|
38
|
-
})
|
|
39
|
-
|
|
40
|
-
it('hour and month buckets are named in the domain\'s time zone too', () => {
|
|
41
|
-
expect(rollUp([hour('2026-10-31T15:00:00.000Z')], 'hour', 'Asia/Seoul', 'hq', names)[0].bucket).toBe('2026-11-01 00:00')
|
|
42
|
-
expect(rollUp([hour('2026-10-31T15:00:00.000Z')], 'month', 'Asia/Seoul', 'hq', names)[0].bucket).toBe('2026-11')
|
|
43
|
-
})
|
|
44
|
-
|
|
45
|
-
it('★ a domain below is one line per domain - its people are not named above', () => {
|
|
46
|
-
const rows = rollUp(
|
|
47
|
-
[
|
|
48
|
-
hour('2026-10-12T01:00:00.000Z', { domainId: 'plant', domainName: '서울공장', userId: 'p1', userName: '이영희' }),
|
|
49
|
-
hour('2026-10-12T02:00:00.000Z', { domainId: 'plant', domainName: '서울공장', userId: 'p2', userName: '박민수' })
|
|
50
|
-
],
|
|
51
|
-
'day',
|
|
52
|
-
'Asia/Seoul',
|
|
53
|
-
'hq',
|
|
54
|
-
names
|
|
55
|
-
)
|
|
56
|
-
expect(rows).toEqual([expect.objectContaining({ domainName: '서울공장', calls: 4 })])
|
|
57
|
-
expect(rows[0].userId).toBeUndefined()
|
|
58
|
-
expect(rows[0].userName).toBeUndefined()
|
|
59
|
-
})
|
|
60
|
-
|
|
61
|
-
it('a deleted agent keeps its usage, without a name', () => {
|
|
62
|
-
const [row] = rollUp([hour('2026-10-12T01:00:00.000Z', { agentId: 'gone' })], 'day', 'Asia/Seoul', 'hq', names)
|
|
63
|
-
expect(row).toMatchObject({ agentId: 'gone', calls: 2 })
|
|
64
|
-
expect(row.agentName).toBeUndefined()
|
|
65
|
-
})
|
|
@@ -1,146 +0,0 @@
|
|
|
1
|
-
import { Domain, getRepository } from '@things-factory/shell'
|
|
2
|
-
|
|
3
|
-
import { fullDomain, readAiAgentDirectory, readDescendantDomains } from './agent-directory.js'
|
|
4
|
-
import type { AiUsage } from './ai-usage.js'
|
|
5
|
-
|
|
6
|
-
export type AiUsageBucketSize = 'hour' | 'day' | 'month'
|
|
7
|
-
|
|
8
|
-
export interface AiUsageFilter {
|
|
9
|
-
from: Date
|
|
10
|
-
to: Date
|
|
11
|
-
bucket: AiUsageBucketSize
|
|
12
|
-
agentIds?: string[]
|
|
13
|
-
userIds?: string[]
|
|
14
|
-
/** Also count what domains below did with this domain's agents - per domain, without their people. */
|
|
15
|
-
includeDescendants?: boolean
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
export interface AiUsageBucketRow {
|
|
19
|
-
/** The bucket in the domain's time zone: `2026-10-12 14:00`, `2026-10-12` or `2026-10`. */
|
|
20
|
-
bucket: string
|
|
21
|
-
agentId?: string
|
|
22
|
-
agentName?: string
|
|
23
|
-
provider: string
|
|
24
|
-
model: string
|
|
25
|
-
/** The domain the calls were made in. */
|
|
26
|
-
domainId: string
|
|
27
|
-
domainName: string
|
|
28
|
-
/** Empty on a row of a domain below, and for calls with no person. */
|
|
29
|
-
userId?: string
|
|
30
|
-
userName?: string
|
|
31
|
-
calls: number
|
|
32
|
-
inputTokens: number
|
|
33
|
-
outputTokens: number
|
|
34
|
-
failures: number
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
/**
|
|
38
|
-
* Usage per bucket × agent × person (design/ai/agent-settings.md §6-2).
|
|
39
|
-
*
|
|
40
|
-
* The database groups by the stored UTC hour, which every database can do; the hours are then rolled up into the
|
|
41
|
-
* domain's days or months here. People of a domain below are never named to the domain above.
|
|
42
|
-
*/
|
|
43
|
-
export async function summarizeAiUsage(given: Domain, filter: AiUsageFilter): Promise<AiUsageBucketRow[]> {
|
|
44
|
-
/* The time zone and the chain are the domain row's. */
|
|
45
|
-
const domain = await fullDomain(given)
|
|
46
|
-
const below = filter.includeDescendants ? await readDescendantDomains(domain) : []
|
|
47
|
-
|
|
48
|
-
const query = getRepository<AiUsage>('AiUsage')
|
|
49
|
-
.createQueryBuilder('usage')
|
|
50
|
-
.leftJoin('usage.domain', 'domain')
|
|
51
|
-
.leftJoin('usage.creator', 'creator')
|
|
52
|
-
.select('usage.hourStart', 'hourStart')
|
|
53
|
-
.addSelect('usage.agentId', 'agentId')
|
|
54
|
-
.addSelect('usage.provider', 'provider')
|
|
55
|
-
.addSelect('usage.model', 'model')
|
|
56
|
-
.addSelect('domain.id', 'domainId')
|
|
57
|
-
.addSelect('domain.name', 'domainName')
|
|
58
|
-
.addSelect('creator.id', 'userId')
|
|
59
|
-
.addSelect('creator.name', 'userName')
|
|
60
|
-
.addSelect('COUNT(*)', 'calls')
|
|
61
|
-
.addSelect('SUM(COALESCE(usage.inputTokens, 0))', 'inputTokens')
|
|
62
|
-
.addSelect('SUM(COALESCE(usage.outputTokens, 0))', 'outputTokens')
|
|
63
|
-
.addSelect(`SUM(CASE WHEN usage.outcome = 'ok' THEN 0 ELSE 1 END)`, 'failures')
|
|
64
|
-
.where('usage.hourStart >= :from AND usage.hourStart < :to', { from: filter.from, to: filter.to })
|
|
65
|
-
.groupBy('usage.hourStart')
|
|
66
|
-
.addGroupBy('usage.agentId')
|
|
67
|
-
.addGroupBy('usage.provider')
|
|
68
|
-
.addGroupBy('usage.model')
|
|
69
|
-
.addGroupBy('domain.id')
|
|
70
|
-
.addGroupBy('domain.name')
|
|
71
|
-
.addGroupBy('creator.id')
|
|
72
|
-
.addGroupBy('creator.name')
|
|
73
|
-
|
|
74
|
-
if (below.length) {
|
|
75
|
-
query.andWhere('(domain.id = :here OR (domain.id IN (:...below) AND usage.agentDomainId = :here))', {
|
|
76
|
-
here: domain.id,
|
|
77
|
-
below: below.map(one => one.id)
|
|
78
|
-
})
|
|
79
|
-
} else {
|
|
80
|
-
query.andWhere('domain.id = :here', { here: domain.id })
|
|
81
|
-
}
|
|
82
|
-
if (filter.agentIds?.length) query.andWhere('usage.agentId IN (:...agentIds)', { agentIds: filter.agentIds })
|
|
83
|
-
if (filter.userIds?.length) query.andWhere('creator.id IN (:...userIds)', { userIds: filter.userIds })
|
|
84
|
-
|
|
85
|
-
const [hours, directory] = await Promise.all([query.getRawMany(), readAiAgentDirectory(domain)])
|
|
86
|
-
const agentNameOf = new Map(directory.entries.map(one => [one.spec.id, one.spec.name]))
|
|
87
|
-
return rollUp(hours, filter.bucket, domain.timezone, domain.id, agentNameOf)
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
export function rollUp(
|
|
91
|
-
hours: any[],
|
|
92
|
-
bucket: AiUsageBucketSize,
|
|
93
|
-
timezone: string | undefined,
|
|
94
|
-
hereId: string,
|
|
95
|
-
agentNameOf: Map<string, string>
|
|
96
|
-
): AiUsageBucketRow[] {
|
|
97
|
-
const label = bucketLabeller(bucket, timezone)
|
|
98
|
-
const rows = new Map<string, AiUsageBucketRow>()
|
|
99
|
-
|
|
100
|
-
for (const hour of hours) {
|
|
101
|
-
const below = hour.domainId !== hereId
|
|
102
|
-
const userId = below ? undefined : hour.userId ?? undefined
|
|
103
|
-
const key = [label(new Date(hour.hourStart)), hour.agentId, hour.provider, hour.model, hour.domainId, userId].join('\u0000')
|
|
104
|
-
const row =
|
|
105
|
-
rows.get(key) ??
|
|
106
|
-
rows
|
|
107
|
-
.set(key, {
|
|
108
|
-
bucket: label(new Date(hour.hourStart)),
|
|
109
|
-
...(hour.agentId && { agentId: hour.agentId, agentName: agentNameOf.get(hour.agentId) }),
|
|
110
|
-
provider: hour.provider,
|
|
111
|
-
model: hour.model,
|
|
112
|
-
domainId: hour.domainId,
|
|
113
|
-
domainName: hour.domainName,
|
|
114
|
-
...(userId && { userId, userName: hour.userName }),
|
|
115
|
-
calls: 0,
|
|
116
|
-
inputTokens: 0,
|
|
117
|
-
outputTokens: 0,
|
|
118
|
-
failures: 0
|
|
119
|
-
})
|
|
120
|
-
.get(key)!
|
|
121
|
-
row.calls += Number(hour.calls) || 0
|
|
122
|
-
row.inputTokens += Number(hour.inputTokens) || 0
|
|
123
|
-
row.outputTokens += Number(hour.outputTokens) || 0
|
|
124
|
-
row.failures += Number(hour.failures) || 0
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
return [...rows.values()].sort((a, b) => b.bucket.localeCompare(a.bucket) || b.calls - a.calls)
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
/** Names the bucket a UTC moment falls in, in the domain's time zone (the server's when the domain has none). */
|
|
131
|
-
function bucketLabeller(bucket: AiUsageBucketSize, timezone?: string): (moment: Date) => string {
|
|
132
|
-
const format = new Intl.DateTimeFormat('en-CA', {
|
|
133
|
-
timeZone: timezone || undefined,
|
|
134
|
-
year: 'numeric',
|
|
135
|
-
month: '2-digit',
|
|
136
|
-
day: '2-digit',
|
|
137
|
-
hour: '2-digit',
|
|
138
|
-
hourCycle: 'h23'
|
|
139
|
-
})
|
|
140
|
-
return moment => {
|
|
141
|
-
const part = Object.fromEntries(format.formatToParts(moment).map(one => [one.type, one.value]))
|
|
142
|
-
if (bucket === 'month') return `${part.year}-${part.month}`
|
|
143
|
-
if (bucket === 'day') return `${part.year}-${part.month}-${part.day}`
|
|
144
|
-
return `${part.year}-${part.month}-${part.day} ${part.hour}:00`
|
|
145
|
-
}
|
|
146
|
-
}
|
|
@@ -1,97 +0,0 @@
|
|
|
1
|
-
import { Column, CreateDateColumn, Entity, Index, ManyToOne, PrimaryGeneratedColumn, RelationId } from 'typeorm'
|
|
2
|
-
import { Field, ID, Int, ObjectType } from 'type-graphql'
|
|
3
|
-
|
|
4
|
-
import { User } from '@things-factory/auth-base'
|
|
5
|
-
import { Domain } from '@things-factory/shell'
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
* One provider request - the metering boundary writes a row each time a model is called (ADR-0061 decision 6,
|
|
9
|
-
* design/ai/agent-settings.md §6).
|
|
10
|
-
*
|
|
11
|
-
* A turn that loops through tools makes several rows. The row is joined to a conversation by id only and is never
|
|
12
|
-
* copied onto a message. It is written once and never changed, so it has no updater.
|
|
13
|
-
*/
|
|
14
|
-
@Entity()
|
|
15
|
-
@Index('ix_ai_usage_0', (usage: AiUsage) => [usage.domain, usage.hourStart])
|
|
16
|
-
@Index('ix_ai_usage_1', (usage: AiUsage) => [usage.agentDomainId, usage.hourStart])
|
|
17
|
-
@ObjectType({ description: 'One request an AI agent sent to its provider, with what it used.' })
|
|
18
|
-
export class AiUsage {
|
|
19
|
-
@PrimaryGeneratedColumn('uuid')
|
|
20
|
-
@Field(type => ID, { description: 'Row id.' })
|
|
21
|
-
readonly id: string
|
|
22
|
-
|
|
23
|
-
@ManyToOne(type => Domain)
|
|
24
|
-
@Field(type => Domain, { nullable: true, description: 'The domain the call was made in.' })
|
|
25
|
-
domain?: Domain
|
|
26
|
-
|
|
27
|
-
@RelationId((usage: AiUsage) => usage.domain)
|
|
28
|
-
domainId?: string
|
|
29
|
-
|
|
30
|
-
@Column({ nullable: true })
|
|
31
|
-
@Field(type => String, { nullable: true, description: 'The agent that answered.' })
|
|
32
|
-
agentId?: string
|
|
33
|
-
|
|
34
|
-
@Column({ nullable: true })
|
|
35
|
-
@Field(type => String, { nullable: true, description: 'The domain that declared the agent - a domain above when the agent was inherited.' })
|
|
36
|
-
agentDomainId?: string
|
|
37
|
-
|
|
38
|
-
@Column({ nullable: true })
|
|
39
|
-
@Field(type => String, { nullable: true, description: 'The domain whose API key answered - whose cost the call is.' })
|
|
40
|
-
keyDomainId?: string
|
|
41
|
-
|
|
42
|
-
@Column()
|
|
43
|
-
@Field(type => String, { description: 'openai, anthropic or gemini.' })
|
|
44
|
-
provider: string
|
|
45
|
-
|
|
46
|
-
@Column()
|
|
47
|
-
@Field(type => String, { description: 'The model the provider reported answering.' })
|
|
48
|
-
model: string
|
|
49
|
-
|
|
50
|
-
@Column({ nullable: true })
|
|
51
|
-
@Field(type => String, { nullable: true, description: 'The conversation mode kind, when the call was part of a conversation.' })
|
|
52
|
-
modeKind?: string
|
|
53
|
-
|
|
54
|
-
@Column()
|
|
55
|
-
@Field(type => String, { description: 'chat, chatWithTools, generateJSON, vision or transcribe.' })
|
|
56
|
-
operation: string
|
|
57
|
-
|
|
58
|
-
@Column({ nullable: true })
|
|
59
|
-
@Field(type => String, { nullable: true, description: 'The conversation the call belongs to, by id only.' })
|
|
60
|
-
sessionId?: string
|
|
61
|
-
|
|
62
|
-
@Column({ type: 'int', nullable: true })
|
|
63
|
-
@Field(type => Int, { nullable: true, description: 'Input tokens the provider reported.' })
|
|
64
|
-
inputTokens?: number
|
|
65
|
-
|
|
66
|
-
@Column({ type: 'int', nullable: true })
|
|
67
|
-
@Field(type => Int, { nullable: true, description: 'Output tokens the provider reported.' })
|
|
68
|
-
outputTokens?: number
|
|
69
|
-
|
|
70
|
-
@Column({ type: 'int' })
|
|
71
|
-
@Field(type => Int, { description: 'How long the request took, in milliseconds.' })
|
|
72
|
-
durationMs: number
|
|
73
|
-
|
|
74
|
-
/** `ok`, or why it failed: key-rejected · rate-limited · provider-error. */
|
|
75
|
-
@Column()
|
|
76
|
-
@Field(type => String, { description: 'ok, or why the request failed: key-rejected, rate-limited or provider-error.' })
|
|
77
|
-
outcome: string
|
|
78
|
-
|
|
79
|
-
/**
|
|
80
|
-
* The UTC hour the call started in. Usage is grouped by this column, which every database can do; days and months
|
|
81
|
-
* are rolled up from it in the domain's time zone.
|
|
82
|
-
*/
|
|
83
|
-
@Column()
|
|
84
|
-
@Field(type => Date, { description: 'The UTC hour the call started in.' })
|
|
85
|
-
hourStart: Date
|
|
86
|
-
|
|
87
|
-
@ManyToOne(type => User, { nullable: true })
|
|
88
|
-
@Field(type => User, { nullable: true, description: 'The person who made the call. Empty for a call with no person, such as a webhook.' })
|
|
89
|
-
creator?: User
|
|
90
|
-
|
|
91
|
-
@RelationId((usage: AiUsage) => usage.creator)
|
|
92
|
-
creatorId?: string
|
|
93
|
-
|
|
94
|
-
@CreateDateColumn()
|
|
95
|
-
@Field(type => Date, { description: 'When the call was made.' })
|
|
96
|
-
createdAt: Date
|
|
97
|
-
}
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
export * from './agent-spec.js'
|
|
2
|
-
export * from './agent-directory.js'
|
|
3
|
-
export * from './ai-client-for.js'
|
|
4
|
-
export * from './provider-models.js'
|
|
5
|
-
export * from './agent-settings-save.js'
|
|
6
|
-
export * from './ai-usage-summary.js'
|
|
7
|
-
export { AiUsage } from './ai-usage.js'
|
|
@@ -1,57 +0,0 @@
|
|
|
1
|
-
/*
|
|
2
|
-
* What this guards: **every call that reaches a model goes through aiClientFor** - the door that picks the domain's
|
|
3
|
-
* agent and writes the usage row (ADR-0061 decision 6, design/ai/agent-settings.md §4).
|
|
4
|
-
*
|
|
5
|
-
* A module that imports a provider SDK, or builds a client of its own, reaches a provider with no domain, no agent and
|
|
6
|
-
* no usage row - and with a key from somewhere other than the domain's settings. So this counts, across the
|
|
7
|
-
* framework's sources, what does either: only this package's adapters and its own door may.
|
|
8
|
-
*/
|
|
9
|
-
import { readdirSync, readFileSync, statSync } from 'fs'
|
|
10
|
-
import path from 'path'
|
|
11
|
-
|
|
12
|
-
const PACKAGES = path.resolve(__dirname, '../../../..')
|
|
13
|
-
const HOME = path.join(PACKAGES, 'ai-client-base')
|
|
14
|
-
|
|
15
|
-
function sources(dir: string, out: string[] = []): string[] {
|
|
16
|
-
for (const entry of readdirSync(dir)) {
|
|
17
|
-
if (entry === 'node_modules' || entry.startsWith('dist') || entry.startsWith('.')) continue
|
|
18
|
-
const full = path.join(dir, entry)
|
|
19
|
-
if (statSync(full).isDirectory()) sources(full, out)
|
|
20
|
-
else if (/\.ts$/.test(entry) && !/\.(test|spec)\.ts$/.test(entry) && !entry.endsWith('.d.ts')) out.push(full)
|
|
21
|
-
}
|
|
22
|
-
return out
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
const files = readdirSync(PACKAGES)
|
|
26
|
-
.flatMap(name => ['server', 'client'].map(part => path.join(PACKAGES, name, part)))
|
|
27
|
-
.filter(dir => {
|
|
28
|
-
try {
|
|
29
|
-
return statSync(dir).isDirectory()
|
|
30
|
-
} catch {
|
|
31
|
-
return false
|
|
32
|
-
}
|
|
33
|
-
})
|
|
34
|
-
.flatMap(dir => sources(dir))
|
|
35
|
-
|
|
36
|
-
const SDK = /from ['"](openai|@anthropic-ai\/sdk|@google\/generative-ai)['"]|require\(['"](openai|@anthropic-ai\/sdk|@google\/generative-ai)['"]\)/
|
|
37
|
-
const OWN_CLIENT = /\bcreateAIClient\s*\(/
|
|
38
|
-
|
|
39
|
-
it('reads the framework\'s sources', () => {
|
|
40
|
-
expect(files.length).toBeGreaterThan(1000)
|
|
41
|
-
})
|
|
42
|
-
|
|
43
|
-
it('★ only ai-client-base\'s adapters import a provider SDK', () => {
|
|
44
|
-
const outside = files.filter(file => SDK.test(readFileSync(file, 'utf8')) && !file.startsWith(path.join(HOME, 'server/service/providers')))
|
|
45
|
-
expect(outside.map(file => path.relative(PACKAGES, file))).toEqual([])
|
|
46
|
-
})
|
|
47
|
-
|
|
48
|
-
it('★ no module builds a provider client of its own - it asks aiClientFor for the domain\'s agent', () => {
|
|
49
|
-
const outside = files.filter(file => OWN_CLIENT.test(readFileSync(file, 'utf8')) && !file.startsWith(HOME))
|
|
50
|
-
expect(outside.map(file => path.relative(PACKAGES, file))).toEqual([])
|
|
51
|
-
})
|
|
52
|
-
|
|
53
|
-
it('★ nothing reads a deployment-wide AI configuration any more', () => {
|
|
54
|
-
const global = /config\.get\(\s*['"](aiClient|openai)['"]|getDefaultAIClient|setDefaultAIClient/
|
|
55
|
-
const readers = files.filter(file => global.test(readFileSync(file, 'utf8')))
|
|
56
|
-
expect(readers.map(file => path.relative(PACKAGES, file))).toEqual([])
|
|
57
|
-
})
|
|
@@ -1,43 +0,0 @@
|
|
|
1
|
-
import { Refusal } from '@things-factory/shell'
|
|
2
|
-
|
|
3
|
-
import { createAIClient } from '../factory.js'
|
|
4
|
-
import { type AiAgentProvider, isAiAgentProvider } from './agent-spec.js'
|
|
5
|
-
import { outcomeOf } from './ai-client-for.js'
|
|
6
|
-
|
|
7
|
-
export interface ProviderModelsRequest {
|
|
8
|
-
provider: string
|
|
9
|
-
apiKey: string
|
|
10
|
-
baseURL?: string
|
|
11
|
-
organization?: string
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
/**
|
|
15
|
-
* The conversation models a key may call, read from the provider (design/ai/agent-settings.md §3-4). A model is only
|
|
16
|
-
* ever picked from this list. Reading it also proves the key: a refused key and an unreachable provider come back as
|
|
17
|
-
* reasons, never as an empty list.
|
|
18
|
-
*/
|
|
19
|
-
export async function listProviderModels(request: ProviderModelsRequest): Promise<string[]> {
|
|
20
|
-
if (!isAiAgentProvider(request.provider)) {
|
|
21
|
-
throw new Refusal('ai-agent-provider-unknown', { provider: request.provider }, `"${request.provider}" is not a provider an agent can use.`)
|
|
22
|
-
}
|
|
23
|
-
if (!request.apiKey?.trim()) {
|
|
24
|
-
throw new Refusal('ai-agent-key-required', {}, 'Enter the API key first.')
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
const client = createAIClient({
|
|
28
|
-
provider: request.provider as AiAgentProvider,
|
|
29
|
-
apiKey: request.apiKey.trim(),
|
|
30
|
-
...(request.baseURL && { baseURL: request.baseURL }),
|
|
31
|
-
...(request.organization && { organization: request.organization })
|
|
32
|
-
})
|
|
33
|
-
|
|
34
|
-
try {
|
|
35
|
-
return await client.listModels()
|
|
36
|
-
} catch (error) {
|
|
37
|
-
/* Gemini answers a wrong key with 400 ("API key not valid"); a list request has no other input to be wrong. */
|
|
38
|
-
if (outcomeOf(error) === 'key-rejected' || Number((error as any)?.status) === 400) {
|
|
39
|
-
throw new Refusal('ai-provider-key-rejected', { provider: request.provider }, 'The provider did not accept this API key.')
|
|
40
|
-
}
|
|
41
|
-
throw new Refusal('ai-provider-unreachable', { provider: request.provider }, 'The provider could not be reached.')
|
|
42
|
-
}
|
|
43
|
-
}
|