@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,326 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* OpenAI AI Client adapter.
|
|
3
|
-
*
|
|
4
|
-
* 기본 모델: gpt-4o (구성에서 override 가능).
|
|
5
|
-
* SDK: openai
|
|
6
|
-
*
|
|
7
|
-
* organization 필드 지원.
|
|
8
|
-
*/
|
|
9
|
-
import OpenAI from 'openai'
|
|
10
|
-
import { toFile } from 'openai/uploads'
|
|
11
|
-
import type {
|
|
12
|
-
AIChatOptions,
|
|
13
|
-
AIClient,
|
|
14
|
-
AIClientConfig,
|
|
15
|
-
AIContentPart,
|
|
16
|
-
AIJSONOptions,
|
|
17
|
-
AIMessage,
|
|
18
|
-
AITool,
|
|
19
|
-
AIToolCall,
|
|
20
|
-
AIToolChatOptions,
|
|
21
|
-
AIToolChatResult,
|
|
22
|
-
AIVisionOptions
|
|
23
|
-
} from '../types.js'
|
|
24
|
-
import { registerAIProvider } from '../factory.js'
|
|
25
|
-
import { parseJSONResponse } from '../utils/parse-json.js'
|
|
26
|
-
import { requestOptionsOf } from './request-options.js'
|
|
27
|
-
|
|
28
|
-
const DEFAULT_MODEL = 'gpt-4o'
|
|
29
|
-
const DEFAULT_MAX_TOKENS = 4096
|
|
30
|
-
|
|
31
|
-
export class OpenAIAIClient implements AIClient {
|
|
32
|
-
readonly id: string
|
|
33
|
-
private sdk: OpenAI
|
|
34
|
-
private defaultModel: string
|
|
35
|
-
|
|
36
|
-
constructor(config: AIClientConfig) {
|
|
37
|
-
this.sdk = new OpenAI({
|
|
38
|
-
apiKey: config.apiKey,
|
|
39
|
-
...(config.organization && { organization: config.organization }),
|
|
40
|
-
...(config.baseURL && { baseURL: config.baseURL })
|
|
41
|
-
})
|
|
42
|
-
this.defaultModel = config.model ?? DEFAULT_MODEL
|
|
43
|
-
this.id = `openai:${this.defaultModel}`
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
/** Whisper accepts the small MP3 prepared by the material reader and returns speech timestamps. */
|
|
47
|
-
async transcribe(audio: Buffer, options: AIChatOptions = {}) {
|
|
48
|
-
const model = 'whisper-1'
|
|
49
|
-
const answer = await this.sdk.audio.transcriptions.create({
|
|
50
|
-
file: await toFile(audio, 'speech.mp3', { type: 'audio/mpeg' }),
|
|
51
|
-
model, response_format: 'verbose_json', timestamp_granularities: ['segment']
|
|
52
|
-
}, requestOptionsOf(options))
|
|
53
|
-
options.onUsage?.({ model }) // Speech billing does not report text token counts.
|
|
54
|
-
return { text: answer.text, segments: (answer.segments ?? []).map(s => ({ start: s.start, end: s.end, text: s.text })) }
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
async chat(messages: AIMessage[], options: AIChatOptions = {}): Promise<string> {
|
|
58
|
-
const sdkMessages = buildSDKMessages(messages, options.systemPrompt)
|
|
59
|
-
const response = await this.sdk.chat.completions.create({
|
|
60
|
-
model: options.model ?? this.defaultModel,
|
|
61
|
-
/* `max_tokens` is refused by the gpt-5 and o-series models; every chat model takes this one. */
|
|
62
|
-
max_completion_tokens: options.maxTokens ?? DEFAULT_MAX_TOKENS,
|
|
63
|
-
...(options.temperature !== undefined && { temperature: options.temperature }),
|
|
64
|
-
...(options.stopSequences && { stop: options.stopSequences }),
|
|
65
|
-
messages: sdkMessages as any
|
|
66
|
-
}, requestOptionsOf(options))
|
|
67
|
-
reportUsage(response, options, options.model ?? this.defaultModel)
|
|
68
|
-
return response.choices[0]?.message?.content ?? ''
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
async generateJSON<T = unknown>(
|
|
72
|
-
prompt: string | AIMessage[],
|
|
73
|
-
options: AIJSONOptions = {}
|
|
74
|
-
): Promise<T> {
|
|
75
|
-
const messages: AIMessage[] =
|
|
76
|
-
typeof prompt === 'string' ? [{ role: 'user', content: prompt }] : prompt
|
|
77
|
-
|
|
78
|
-
const schemaHint = options.schema
|
|
79
|
-
? `\n\nResponse MUST conform to this JSON schema:\n${JSON.stringify(options.schema)}`
|
|
80
|
-
: ''
|
|
81
|
-
const enforcedSystem =
|
|
82
|
-
(options.systemPrompt ? options.systemPrompt + '\n\n' : '') +
|
|
83
|
-
'Return only valid JSON. No markdown code fences, no commentary.' +
|
|
84
|
-
schemaHint
|
|
85
|
-
|
|
86
|
-
const sdkMessages = buildSDKMessages(messages, enforcedSystem)
|
|
87
|
-
const response = await this.sdk.chat.completions.create({
|
|
88
|
-
model: options.model ?? this.defaultModel,
|
|
89
|
-
/* `max_tokens` is refused by the gpt-5 and o-series models; every chat model takes this one. */
|
|
90
|
-
max_completion_tokens: options.maxTokens ?? DEFAULT_MAX_TOKENS,
|
|
91
|
-
...(options.temperature !== undefined && { temperature: options.temperature }),
|
|
92
|
-
response_format: { type: 'json_object' },
|
|
93
|
-
messages: sdkMessages as any
|
|
94
|
-
}, requestOptionsOf(options))
|
|
95
|
-
reportUsage(response, options, options.model ?? this.defaultModel)
|
|
96
|
-
const text = response.choices[0]?.message?.content ?? '{}'
|
|
97
|
-
return parseJSONResponse<T>(text, { cutShort: response.choices[0]?.finish_reason === 'length' })
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
async vision(
|
|
101
|
-
image: Buffer | Uint8Array | { url: string },
|
|
102
|
-
prompt: string,
|
|
103
|
-
options: AIVisionOptions = {}
|
|
104
|
-
): Promise<string> {
|
|
105
|
-
const imagePart: AIContentPart =
|
|
106
|
-
typeof image === 'object' && 'url' in image
|
|
107
|
-
? { type: 'image', source: { kind: 'url', url: image.url } }
|
|
108
|
-
: {
|
|
109
|
-
type: 'image',
|
|
110
|
-
source: { kind: 'base64', data: image as Buffer | Uint8Array, mediaType: 'image/png' }
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
return this.chat(
|
|
114
|
-
[{ role: 'user', content: [imagePart, { type: 'text', text: prompt }] }],
|
|
115
|
-
options
|
|
116
|
-
)
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
async chatWithTools(
|
|
120
|
-
messages: AIMessage[],
|
|
121
|
-
tools: AITool[],
|
|
122
|
-
options: AIToolChatOptions = {}
|
|
123
|
-
): Promise<AIToolChatResult> {
|
|
124
|
-
const sdkMessages = buildSDKMessages(messages, options.systemPrompt)
|
|
125
|
-
|
|
126
|
-
const sdkTools = tools.map(t => ({
|
|
127
|
-
type: 'function' as const,
|
|
128
|
-
function: {
|
|
129
|
-
name: t.name,
|
|
130
|
-
description: t.description,
|
|
131
|
-
parameters: t.parameters
|
|
132
|
-
}
|
|
133
|
-
}))
|
|
134
|
-
|
|
135
|
-
const toolChoice = buildOpenAIToolChoice(options)
|
|
136
|
-
|
|
137
|
-
const response = await this.sdk.chat.completions.create({
|
|
138
|
-
model: options.model ?? this.defaultModel,
|
|
139
|
-
/* `max_tokens` is refused by the gpt-5 and o-series models; every chat model takes this one. */
|
|
140
|
-
max_completion_tokens: options.maxTokens ?? DEFAULT_MAX_TOKENS,
|
|
141
|
-
...(options.temperature !== undefined && { temperature: options.temperature }),
|
|
142
|
-
...(options.stopSequences && { stop: options.stopSequences }),
|
|
143
|
-
messages: sdkMessages as any,
|
|
144
|
-
tools: sdkTools,
|
|
145
|
-
...(toolChoice !== undefined && { tool_choice: toolChoice as any }),
|
|
146
|
-
...(options.allowParallelToolCalls === false && { parallel_tool_calls: false })
|
|
147
|
-
}, requestOptionsOf(options))
|
|
148
|
-
reportUsage(response, options, options.model ?? this.defaultModel)
|
|
149
|
-
|
|
150
|
-
const choice = response.choices?.[0]
|
|
151
|
-
const message = choice?.message
|
|
152
|
-
const text = message?.content || undefined
|
|
153
|
-
|
|
154
|
-
const toolCalls: AIToolCall[] = (message?.tool_calls || []).map((tc: any) => {
|
|
155
|
-
const fn = tc.function
|
|
156
|
-
let args: Record<string, any> = {}
|
|
157
|
-
try {
|
|
158
|
-
args = fn?.arguments ? JSON.parse(fn.arguments) : {}
|
|
159
|
-
} catch {
|
|
160
|
-
args = {}
|
|
161
|
-
}
|
|
162
|
-
return {
|
|
163
|
-
id: typeof tc.id === 'string' && tc.id ? tc.id : `call_${Math.random().toString(36).slice(2, 12)}`,
|
|
164
|
-
name: fn?.name ?? '',
|
|
165
|
-
arguments: args
|
|
166
|
-
}
|
|
167
|
-
})
|
|
168
|
-
|
|
169
|
-
return {
|
|
170
|
-
text,
|
|
171
|
-
toolCalls,
|
|
172
|
-
stopReason: normalizeOpenAIStopReason(choice?.finish_reason)
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
async listModels(): Promise<string[]> {
|
|
177
|
-
const ids: string[] = []
|
|
178
|
-
for await (const model of this.sdk.models.list()) ids.push(model.id)
|
|
179
|
-
return ids.filter(isOpenAIChatModel).sort()
|
|
180
|
-
}
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
/**
|
|
184
|
-
* OpenAI's model list has no capability field, so the conversation models are told apart by name: the GPT and
|
|
185
|
-
* o-series families, without their audio, realtime, speech, image, search and instruct variants. One rule, kept by a test.
|
|
186
|
-
*/
|
|
187
|
-
export function isOpenAIChatModel(id: string): boolean {
|
|
188
|
-
if (!/^(gpt-|chatgpt-|o\d)/.test(id)) return false
|
|
189
|
-
return !/(audio|realtime|tts|transcribe|image|search|instruct|embedding|moderation)/.test(id)
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
function reportUsage(response: any, options: AIChatOptions, requested: string): void {
|
|
193
|
-
options.onUsage?.({
|
|
194
|
-
model: response?.model ?? requested,
|
|
195
|
-
inputTokens: response?.usage?.prompt_tokens,
|
|
196
|
-
outputTokens: response?.usage?.completion_tokens
|
|
197
|
-
})
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
// ── 변환 유틸 ─────────────────────────────────────────────────────────
|
|
201
|
-
|
|
202
|
-
function buildSDKMessages(messages: AIMessage[], externalSystem?: string): any[] {
|
|
203
|
-
const out: any[] = []
|
|
204
|
-
|
|
205
|
-
const systemFromMessages = messages
|
|
206
|
-
.filter(m => m.role === 'system')
|
|
207
|
-
.map(extractTextContent)
|
|
208
|
-
.filter(Boolean)
|
|
209
|
-
.join('\n\n')
|
|
210
|
-
const combinedSystem = [externalSystem, systemFromMessages].filter(Boolean).join('\n\n')
|
|
211
|
-
if (combinedSystem) {
|
|
212
|
-
out.push({ role: 'system', content: combinedSystem })
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
for (const msg of messages) {
|
|
216
|
-
if (msg.role === 'system') continue
|
|
217
|
-
const sdkMsgs = toSDKMessages(msg)
|
|
218
|
-
out.push(...sdkMsgs)
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
return out
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
/**
|
|
225
|
-
* 한 AIMessage 가 다중 tool_result 를 가지면 OpenAI 측에서 여러 role:'tool' 메시지로
|
|
226
|
-
* 분리해야 함 (OpenAI 는 메시지당 tool_call_id 하나만 매핑). 따라서 array 를 반환.
|
|
227
|
-
*/
|
|
228
|
-
export function toSDKMessages(msg: AIMessage): any[] {
|
|
229
|
-
if (typeof msg.content === 'string') {
|
|
230
|
-
return [{ role: msg.role, content: msg.content }]
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
const parts = msg.content
|
|
234
|
-
const toolUseParts = parts.filter(p => p.type === 'tool_use') as any[]
|
|
235
|
-
const toolResultParts = parts.filter(p => p.type === 'tool_result') as any[]
|
|
236
|
-
const otherParts = parts.filter(p => p.type !== 'tool_use' && p.type !== 'tool_result')
|
|
237
|
-
|
|
238
|
-
// tool_result 가 있으면 각각을 role='tool' 메시지로 분리 (OpenAI 요구사항).
|
|
239
|
-
if (toolResultParts.length > 0) {
|
|
240
|
-
const results = toolResultParts.map((r: any) => ({
|
|
241
|
-
role: 'tool',
|
|
242
|
-
tool_call_id: r.toolUseId,
|
|
243
|
-
content: r.content
|
|
244
|
-
}))
|
|
245
|
-
/* A tool message holds text only - pictures a read tool returned follow as one user message (agentic-loop takeToolImages). */
|
|
246
|
-
const images = otherParts.filter(p => p.type === 'image')
|
|
247
|
-
return images.length ? [...results, { role: 'user', content: images.map(toSDKContentPart) }] : results
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
// assistant 측 tool_use 가 있으면 message.tool_calls 로
|
|
251
|
-
const out: any = { role: msg.role }
|
|
252
|
-
if (otherParts.length > 0) {
|
|
253
|
-
out.content = otherParts.map(toSDKContentPart)
|
|
254
|
-
} else {
|
|
255
|
-
out.content = null
|
|
256
|
-
}
|
|
257
|
-
if (toolUseParts.length > 0) {
|
|
258
|
-
out.tool_calls = toolUseParts.map(p => ({
|
|
259
|
-
id: p.id,
|
|
260
|
-
type: 'function',
|
|
261
|
-
function: { name: p.name, arguments: JSON.stringify(p.arguments) }
|
|
262
|
-
}))
|
|
263
|
-
}
|
|
264
|
-
return [out]
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
function toSDKContentPart(part: AIContentPart): any {
|
|
268
|
-
if (part.type === 'text') {
|
|
269
|
-
return { type: 'text', text: part.text }
|
|
270
|
-
}
|
|
271
|
-
if (part.type === 'tool_use' || part.type === 'tool_result') {
|
|
272
|
-
// 처리는 toSDKMessage 가 함 — 도달하면 버그.
|
|
273
|
-
return { type: 'text', text: '' }
|
|
274
|
-
}
|
|
275
|
-
// image
|
|
276
|
-
if (part.source.kind === 'url') {
|
|
277
|
-
return { type: 'image_url', image_url: { url: part.source.url } }
|
|
278
|
-
}
|
|
279
|
-
const b64 = Buffer.isBuffer(part.source.data)
|
|
280
|
-
? part.source.data.toString('base64')
|
|
281
|
-
: Buffer.from(part.source.data).toString('base64')
|
|
282
|
-
return {
|
|
283
|
-
type: 'image_url',
|
|
284
|
-
image_url: { url: `data:${part.source.mediaType};base64,${b64}` }
|
|
285
|
-
}
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
function extractTextContent(msg: AIMessage): string {
|
|
289
|
-
if (typeof msg.content === 'string') return msg.content
|
|
290
|
-
return msg.content
|
|
291
|
-
.filter(p => p.type === 'text')
|
|
292
|
-
.map(p => (p as { type: 'text'; text: string }).text)
|
|
293
|
-
.join('\n')
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
function buildOpenAIToolChoice(options: AIToolChatOptions): any {
|
|
297
|
-
const choice = options.toolChoice ?? 'auto'
|
|
298
|
-
if (choice === 'none') return 'none'
|
|
299
|
-
if (choice === 'required') {
|
|
300
|
-
if (options.forceTool) {
|
|
301
|
-
return { type: 'function', function: { name: options.forceTool } }
|
|
302
|
-
}
|
|
303
|
-
return 'required'
|
|
304
|
-
}
|
|
305
|
-
return 'auto'
|
|
306
|
-
}
|
|
307
|
-
|
|
308
|
-
function normalizeOpenAIStopReason(raw: any): AIToolChatResult['stopReason'] {
|
|
309
|
-
switch (raw) {
|
|
310
|
-
case 'tool_calls':
|
|
311
|
-
return 'tool_use'
|
|
312
|
-
case 'function_call':
|
|
313
|
-
return 'tool_use'
|
|
314
|
-
case 'stop':
|
|
315
|
-
return 'end_turn'
|
|
316
|
-
case 'length':
|
|
317
|
-
return 'max_tokens'
|
|
318
|
-
case 'content_filter':
|
|
319
|
-
return 'stop_sequence'
|
|
320
|
-
default:
|
|
321
|
-
return raw ?? 'end_turn'
|
|
322
|
-
}
|
|
323
|
-
}
|
|
324
|
-
|
|
325
|
-
// Auto-register at module load
|
|
326
|
-
registerAIProvider('openai', config => new OpenAIAIClient(config))
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
/*
|
|
2
|
-
* What a provider SDK is handed per request besides the body - the caller's abort signal (types.ts `signal`).
|
|
3
|
-
*
|
|
4
|
-
* The three adapters each take it the same way, so it is said once. Aborting stops our wait and frees the loop; the
|
|
5
|
-
* provider may still finish the request on its side and bill it, which is why a run's spend is capped by its token
|
|
6
|
-
* limit and not by its clock.
|
|
7
|
-
*/
|
|
8
|
-
import type { AIChatOptions } from '../types.js'
|
|
9
|
-
|
|
10
|
-
export function requestOptionsOf(options: AIChatOptions | undefined): { signal: AbortSignal } | undefined {
|
|
11
|
-
return options?.signal ? { signal: options.signal } : undefined
|
|
12
|
-
}
|
|
@@ -1,77 +0,0 @@
|
|
|
1
|
-
/*
|
|
2
|
-
* What this guards: a stop reaches the provider request.
|
|
3
|
-
*
|
|
4
|
-
* The loop passed `signal` on every request and no adapter handed it to its SDK, so a person's stop and an unattended
|
|
5
|
-
* run's time limit ended our side while the request kept running (2026-10-20). Each adapter's SDK is replaced with a
|
|
6
|
-
* stand-in that keeps what it was handed per request, for every call that sends one.
|
|
7
|
-
*/
|
|
8
|
-
import { AnthropicAIClient } from './anthropic'
|
|
9
|
-
import { OpenAIAIClient } from './openai'
|
|
10
|
-
import { GeminiAIClient } from './gemini'
|
|
11
|
-
|
|
12
|
-
type Seen = Array<{ body: any; request: any }>
|
|
13
|
-
|
|
14
|
-
function anthropic(seen: Seen) {
|
|
15
|
-
const client: any = new AnthropicAIClient({ provider: 'anthropic', apiKey: 'test-key' } as any)
|
|
16
|
-
client.sdk = {
|
|
17
|
-
messages: {
|
|
18
|
-
create: async (body: any, request: any) => {
|
|
19
|
-
seen.push({ body, request })
|
|
20
|
-
return { model: 'm', content: [{ type: 'text', text: '{"ok":true}' }], stop_reason: 'end_turn', usage: {} }
|
|
21
|
-
}
|
|
22
|
-
}
|
|
23
|
-
}
|
|
24
|
-
return client
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
function openai(seen: Seen) {
|
|
28
|
-
const client: any = new OpenAIAIClient({ provider: 'openai', apiKey: 'test-key' } as any)
|
|
29
|
-
client.sdk = {
|
|
30
|
-
chat: {
|
|
31
|
-
completions: {
|
|
32
|
-
create: async (body: any, request: any) => {
|
|
33
|
-
seen.push({ body, request })
|
|
34
|
-
return { model: 'm', choices: [{ message: { content: '{"ok":true}' }, finish_reason: 'stop' }], usage: {} }
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
return client
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
function gemini(seen: Seen) {
|
|
43
|
-
const client: any = new GeminiAIClient({ provider: 'gemini', apiKey: 'test-key' } as any)
|
|
44
|
-
client.sdk = {
|
|
45
|
-
getGenerativeModel: () => ({
|
|
46
|
-
generateContent: async (body: any, request: any) => {
|
|
47
|
-
seen.push({ body, request })
|
|
48
|
-
const response = { candidates: [{ content: { parts: [{ text: '{"ok":true}' }] }, finishReason: 'STOP' }], text: () => '{"ok":true}' }
|
|
49
|
-
return { response }
|
|
50
|
-
}
|
|
51
|
-
})
|
|
52
|
-
}
|
|
53
|
-
return client
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
const ADAPTERS = { anthropic, openai, gemini }
|
|
57
|
-
const tools = [{ name: 'readGoals', description: 'goals', parameters: { type: 'object', properties: {} } }]
|
|
58
|
-
const user = [{ role: 'user' as const, content: 'hello' }]
|
|
59
|
-
|
|
60
|
-
describe.each(Object.entries(ADAPTERS))('%s', (_name, make) => {
|
|
61
|
-
it('★ chat, generateJSON and chatWithTools hand the signal to the SDK request', async () => {
|
|
62
|
-
const seen: Seen = []
|
|
63
|
-
const client = make(seen)
|
|
64
|
-
const { signal } = new AbortController()
|
|
65
|
-
await client.chat(user, { signal })
|
|
66
|
-
await client.generateJSON('give json', { signal })
|
|
67
|
-
await client.chatWithTools(user, tools, { signal })
|
|
68
|
-
expect(seen).toHaveLength(3)
|
|
69
|
-
expect(seen.every(one => one.request?.signal === signal)).toBe(true)
|
|
70
|
-
})
|
|
71
|
-
|
|
72
|
-
it('without a signal the SDK is handed nothing extra', async () => {
|
|
73
|
-
const seen: Seen = []
|
|
74
|
-
await make(seen).chatWithTools(user, tools, {})
|
|
75
|
-
expect(seen[0].request).toBeUndefined()
|
|
76
|
-
})
|
|
77
|
-
})
|
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
import { OpenAIAIClient } from './openai'
|
|
2
|
-
|
|
3
|
-
it('transcribes speech with timestamps, cancellation and usage reporting through the configured SDK', async () => {
|
|
4
|
-
const client: any = new OpenAIAIClient({ provider: 'openai', apiKey: 'test-only' })
|
|
5
|
-
const calls: any[] = []
|
|
6
|
-
client.sdk = { audio: { transcriptions: { create: async (body: any, request: any) => {
|
|
7
|
-
calls.push({ body, request })
|
|
8
|
-
return { text: 'Hello', segments: [{ start: 0, end: 1.5, text: 'Hello' }] }
|
|
9
|
-
} } } }
|
|
10
|
-
const usage: any[] = []
|
|
11
|
-
const { signal } = new AbortController()
|
|
12
|
-
const answer = await client.transcribe(Buffer.from('test audio'), { signal, onUsage: (u: any) => usage.push(u) })
|
|
13
|
-
expect(answer).toEqual({ text: 'Hello', segments: [{ start: 0, end: 1.5, text: 'Hello' }] })
|
|
14
|
-
expect(calls[0].body.model).toBe('whisper-1')
|
|
15
|
-
expect(calls[0].body.response_format).toBe('verbose_json')
|
|
16
|
-
expect(calls[0].request.signal).toBe(signal)
|
|
17
|
-
expect(usage).toEqual([{ model: 'whisper-1' }])
|
|
18
|
-
})
|
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
/*
|
|
2
|
-
* The one way a test builds what a registered tool is handed (A3, 2026-09-17).
|
|
3
|
-
*
|
|
4
|
-
* The twin's space tools read `ctx.state.host` while the door passed `ctx.host`, and their tests
|
|
5
|
-
* stayed green because each test wrote its own context in the shape the tool expected. A fixture
|
|
6
|
-
* owned by each test agrees with its tool by construction. This one is owned by the package that
|
|
7
|
-
* defines the neutral door, and that door's tests check it hands tools exactly this shape — so a tool
|
|
8
|
-
* test built on it fails when the tool reads a field no door fills.
|
|
9
|
-
*/
|
|
10
|
-
import type { ToolAttachment, ToolCallContext, ToolCallMode, ToolTranslate, UnattendedRunRef } from '../tool-registry/types.js'
|
|
11
|
-
import { defaultValueTranslate } from '../tool-registry/translate.js'
|
|
12
|
-
|
|
13
|
-
export interface ToolCallContextFixtureInput {
|
|
14
|
-
domainId?: string
|
|
15
|
-
userId?: string
|
|
16
|
-
/** Extra request-state fields a tool reads (e.g. `tx`). Merged after domain and user. */
|
|
17
|
-
state?: Record<string, any>
|
|
18
|
-
host?: Record<string, any>
|
|
19
|
-
mode?: ToolCallMode
|
|
20
|
-
/** The request translator. Absent: the one the door hands when it was given none. */
|
|
21
|
-
t?: ToolTranslate
|
|
22
|
-
/** The checked files of the turn. Absent: none. */
|
|
23
|
-
attachments?: ToolAttachment[]
|
|
24
|
-
/** The unattended run the call belongs to. Absent: a turn of a conversation. */
|
|
25
|
-
run?: UnattendedRunRef
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
export function toolCallContextFixture(input: ToolCallContextFixtureInput = {}): ToolCallContext {
|
|
29
|
-
const context: ToolCallContext = {
|
|
30
|
-
state: { domain: { id: input.domainId ?? 'domain-test' }, user: { id: input.userId ?? 'user-test' }, ...(input.state ?? {}) },
|
|
31
|
-
host: input.host ?? {},
|
|
32
|
-
t: input.t ?? defaultValueTranslate,
|
|
33
|
-
attachments: input.attachments ?? []
|
|
34
|
-
}
|
|
35
|
-
if (input.mode) context.mode = input.mode
|
|
36
|
-
if (input.run) context.run = input.run
|
|
37
|
-
return context
|
|
38
|
-
}
|
|
@@ -1,116 +0,0 @@
|
|
|
1
|
-
/*
|
|
2
|
-
* Every tool call of a registry conversation, handed to whoever writes them down (ADR-0061 decision 8).
|
|
3
|
-
*
|
|
4
|
-
* An application that keeps an AI audit (operato-office's AI 감사 기록) needs each call - which tool, about what,
|
|
5
|
-
* how much came back or why it failed - whoever registered the tool: its own tools, a read target's list query, a
|
|
6
|
-
* data entry target's proposal. Wrapping each tool in the application left out the tools other packages declare,
|
|
7
|
-
* so the audit missed the reads that mattered most (2026-10-16). The registry conversation runs every tool at one
|
|
8
|
-
* place and calls the recorders there.
|
|
9
|
-
*
|
|
10
|
-
* A recorder is handed a digest: the tool, its category, the ids its arguments name, the size and hash of what came
|
|
11
|
-
* back, an error code. The arguments and the result themselves - pay, shareholdings - are not copied into an audit
|
|
12
|
-
* by default; a recorder that must keep them names the categories it keeps them for (`raw`).
|
|
13
|
-
*
|
|
14
|
-
* A recorder that fails is said in the log and the call goes on - an audit that cannot be written never stops an
|
|
15
|
-
* answer. A recorder decides for itself which conversations it writes down (`context.mode.kind`).
|
|
16
|
-
*/
|
|
17
|
-
import { createHash } from 'crypto'
|
|
18
|
-
|
|
19
|
-
import { resultShapeOf } from '../assistant/summarize'
|
|
20
|
-
import type { ToolCallContext } from './types'
|
|
21
|
-
|
|
22
|
-
export interface ToolCallRecord {
|
|
23
|
-
tool: string
|
|
24
|
-
/** The category the tool was offered from. */
|
|
25
|
-
category: string
|
|
26
|
-
/** The ids the arguments name - `id`, `…Id`, `ids`, `…Ids` - and nothing else of them. */
|
|
27
|
-
targetIds: string[]
|
|
28
|
-
/** sha256 of the arguments - the same call is the same hash. */
|
|
29
|
-
argsHash: string
|
|
30
|
-
/** Characters of the result as JSON; 0 when the tool threw. */
|
|
31
|
-
resultSize: number
|
|
32
|
-
/** How many rows it carried - `read` of a list read, else the length of its first list; absent when it says none. */
|
|
33
|
-
resultCount?: number
|
|
34
|
-
resultHash?: string
|
|
35
|
-
/** Why it failed: the code a refusal returned (`{ rejected: true, error }`), the thrown error's code, or `tool-threw`. */
|
|
36
|
-
errorCode?: string
|
|
37
|
-
ok: boolean
|
|
38
|
-
durationMs: number
|
|
39
|
-
/** The arguments and the result as they were - only for a category the recorder named in `raw`. */
|
|
40
|
-
raw?: { args: unknown; result?: unknown; error?: string }
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
export type ToolCallRecorder = (record: ToolCallRecord, context: ToolCallContext) => void | Promise<void>
|
|
44
|
-
|
|
45
|
-
export interface ToolCallRecorderOptions {
|
|
46
|
-
/** Categories whose calls the recorder is handed with their arguments and result as they were. */
|
|
47
|
-
raw?: string[]
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
/** A call as it ran - the registry door's side, before it is cut down for a recorder. */
|
|
51
|
-
export interface ToolCallRun {
|
|
52
|
-
tool: string
|
|
53
|
-
category: string
|
|
54
|
-
args: unknown
|
|
55
|
-
result?: unknown
|
|
56
|
-
error?: unknown
|
|
57
|
-
durationMs: number
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
const recorders: { recorder: ToolCallRecorder; raw: Set<string> }[] = []
|
|
61
|
-
|
|
62
|
-
export function registerToolCallRecorder(recorder: ToolCallRecorder, options: ToolCallRecorderOptions = {}): void {
|
|
63
|
-
if (recorders.some(one => one.recorder === recorder)) return
|
|
64
|
-
recorders.push({ recorder, raw: new Set(options.raw ?? []) })
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
export function clearToolCallRecorders(): void {
|
|
68
|
-
recorders.length = 0
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
const hash = (value: unknown) => createHash('sha256').update(JSON.stringify(value ?? null)).digest('hex')
|
|
72
|
-
|
|
73
|
-
/** The ids an argument object names, by its keys - a value under any other key is not carried. */
|
|
74
|
-
function idsOf(args: unknown): string[] {
|
|
75
|
-
if (!args || typeof args !== 'object') return []
|
|
76
|
-
const ids: string[] = []
|
|
77
|
-
for (const [key, value] of Object.entries(args as Record<string, unknown>)) {
|
|
78
|
-
if (!/^(id|ids)$|[a-z](Id|Ids)$/.test(key)) continue
|
|
79
|
-
for (const one of Array.isArray(value) ? value : [value]) if (typeof one === 'string' || typeof one === 'number') ids.push(String(one))
|
|
80
|
-
}
|
|
81
|
-
return ids
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
/** A run as a recorder sees it - the digest, and the raw text when its category was asked for. */
|
|
85
|
-
export function digestOf(run: ToolCallRun, raw = false): ToolCallRecord {
|
|
86
|
-
const threw = run.error !== undefined
|
|
87
|
-
const result: any = run.result
|
|
88
|
-
/* The same shape the conversation row keeps (resultShapeOf) - one reading of an answer. */
|
|
89
|
-
const shape = threw ? undefined : resultShapeOf(result)
|
|
90
|
-
const errorCode = threw ? String((run.error as any)?.code ?? 'tool-threw') : shape!.errorCode
|
|
91
|
-
const resultSize = shape?.size ?? 0
|
|
92
|
-
const resultCount = shape?.count
|
|
93
|
-
return {
|
|
94
|
-
tool: run.tool,
|
|
95
|
-
category: run.category,
|
|
96
|
-
targetIds: idsOf(run.args),
|
|
97
|
-
argsHash: hash(run.args),
|
|
98
|
-
resultSize,
|
|
99
|
-
...(resultCount === undefined ? {} : { resultCount }),
|
|
100
|
-
...(threw ? {} : { resultHash: hash(result) }),
|
|
101
|
-
...(errorCode ? { errorCode } : {}),
|
|
102
|
-
ok: !errorCode,
|
|
103
|
-
durationMs: run.durationMs,
|
|
104
|
-
...(raw ? { raw: { args: run.args, ...(threw ? { error: String((run.error as any)?.message ?? run.error) } : { result }) } } : {})
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
export async function recordToolCall(run: ToolCallRun, context: ToolCallContext): Promise<void> {
|
|
109
|
-
for (const { recorder, raw } of recorders) {
|
|
110
|
-
try {
|
|
111
|
-
await recorder(digestOf(run, raw.has(run.category)), context)
|
|
112
|
-
} catch (e) {
|
|
113
|
-
console.warn(`[ai-client-base] a tool call recorder failed for ${run.tool}:`, (e as Error)?.message ?? e)
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
}
|
|
@@ -1,50 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Tool Registry — board-ai 의 외부 도메인 LLM tool 노출 plugin point.
|
|
3
|
-
*
|
|
4
|
-
* 자세한 설계는 ./types 와 ./registry 의 헤더 주석 참조.
|
|
5
|
-
*/
|
|
6
|
-
export {
|
|
7
|
-
registerToolCategory,
|
|
8
|
-
getToolCategories,
|
|
9
|
-
getAllToolSpecs,
|
|
10
|
-
getToolSpecsFor,
|
|
11
|
-
getCategoryGuidance,
|
|
12
|
-
findToolSpec,
|
|
13
|
-
getToolKind,
|
|
14
|
-
hasTool,
|
|
15
|
-
getCategorySpecs,
|
|
16
|
-
clearToolRegistry,
|
|
17
|
-
getToolRegistryWarnings
|
|
18
|
-
} from './registry'
|
|
19
|
-
|
|
20
|
-
export { defaultValueTranslate } from './translate'
|
|
21
|
-
|
|
22
|
-
export { registerToolCallRecorder, clearToolCallRecorders, recordToolCall, digestOf } from './call-recorder'
|
|
23
|
-
export type { ToolCallRecord, ToolCallRecorder, ToolCallRecorderOptions, ToolCallRun } from './call-recorder'
|
|
24
|
-
|
|
25
|
-
/* 대화별 노출 제한 타입은 registry 소유(정의가 거기 있다). */
|
|
26
|
-
export type { ToolCategoryFilter, ToolRegistryWarning } from './registry'
|
|
27
|
-
|
|
28
|
-
export type {
|
|
29
|
-
ToolSpec,
|
|
30
|
-
ToolSpecBase,
|
|
31
|
-
ReadToolSpec,
|
|
32
|
-
WriteToolSpec,
|
|
33
|
-
ActionToolSpec,
|
|
34
|
-
ExternalToolSpec,
|
|
35
|
-
ToolCategory,
|
|
36
|
-
ReadToolBuilder,
|
|
37
|
-
WriteToolBuilder,
|
|
38
|
-
ActionToolBuilder,
|
|
39
|
-
ExternalToolBuilder,
|
|
40
|
-
ReadToolContext,
|
|
41
|
-
WriteToolContext,
|
|
42
|
-
ExternalToolContext,
|
|
43
|
-
ToolCallContext,
|
|
44
|
-
ToolCallMode,
|
|
45
|
-
UnattendedRunRef,
|
|
46
|
-
ToolTranslate,
|
|
47
|
-
ToolAttachment,
|
|
48
|
-
ToolImageAttachment,
|
|
49
|
-
ToolTextAttachment
|
|
50
|
-
} from './types'
|