@things-factory/ai-client-base 10.1.280 → 10.1.282

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 (34) hide show
  1. package/dist-server/service/agent/agent-directory.js +1 -1
  2. package/dist-server/service/agent/agent-settings-save.js +3 -2
  3. package/dist-server/service/agent/agent-spec.d.ts +11 -2
  4. package/dist-server/service/agent/agent-spec.js +23 -2
  5. package/dist-server/service/agent/ai-client-for.js +4 -1
  6. package/dist-server/service/agent/ai-usage.d.ts +1 -1
  7. package/dist-server/service/agent/ai-usage.js +1 -1
  8. package/dist-server/service/agent/provider-models.js +5 -2
  9. package/dist-server/service/agentic-loop/agentic-loop.d.ts +9 -3
  10. package/dist-server/service/agentic-loop/agentic-loop.js +9 -2
  11. package/dist-server/service/assistant/abort-notice.d.ts +5 -0
  12. package/dist-server/service/assistant/abort-notice.js +10 -1
  13. package/dist-server/service/assistant/assistant-chat.js +1 -1
  14. package/dist-server/service/assistant/registry-assistant.d.ts +1 -1
  15. package/dist-server/service/assistant/registry-assistant.js +2 -24
  16. package/dist-server/service/providers/anthropic.d.ts +4 -1
  17. package/dist-server/service/providers/anthropic.js +16 -61
  18. package/dist-server/service/providers/claude-code-tools-mcp.d.ts +3 -0
  19. package/dist-server/service/providers/claude-code-tools-mcp.js +56 -0
  20. package/dist-server/service/providers/claude-code.d.ts +38 -0
  21. package/dist-server/service/providers/claude-code.js +322 -0
  22. package/dist-server/service/providers/common.d.ts +20 -0
  23. package/dist-server/service/providers/common.js +52 -0
  24. package/dist-server/service/providers/gemini.js +4 -26
  25. package/dist-server/service/providers/index.d.ts +2 -0
  26. package/dist-server/service/providers/index.js +6 -1
  27. package/dist-server/service/providers/openai.js +37 -48
  28. package/dist-server/service/tool-registry/index.d.ts +2 -1
  29. package/dist-server/service/tool-registry/index.js +4 -1
  30. package/dist-server/service/tool-registry/registry.d.ts +2 -0
  31. package/dist-server/service/tool-registry/registry.js +9 -0
  32. package/dist-server/service/tool-registry/run-tool.d.ts +15 -0
  33. package/dist-server/service/tool-registry/run-tool.js +37 -0
  34. package/package.json +6 -6
@@ -0,0 +1,322 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.startClaudeCode = startClaudeCode;
4
+ exports.claudeCodeAvailable = claudeCodeAvailable;
5
+ exports.createClaudeCodeClient = createClaudeCodeClient;
6
+ /**
7
+ * Claude Code, logged in on this machine, as a provider (2026-11-13, the person: an option to use Claude logged in
8
+ * locally, picked in the AI assistant like any other model). For development: the dev server only, on the account of
9
+ * whoever logged in the `claude` CLI here -- never a product's server, which has neither (aiProviderAvailable).
10
+ *
11
+ * Called as an API is: our system prompt alone (Claude Code's own replaced), no Claude Code tools, no settings, no
12
+ * memory, a fresh empty folder, no session kept -- one stateless request per call. Pictures are not carried.
13
+ *
14
+ * ── How a tool is called (2026-11-14) ──────────────────────────────────────────────────────────────────────────────
15
+ * The CLI has no request with tools in it, as an API has. Two ways stand in for it, and the loop sees no difference:
16
+ *
17
+ * native (the default) The turn's tools are listed to the CLI by an MCP server that runs none of them
18
+ * (claude-code-tools-mcp.ts). The model calls them as it calls any tool; its first turn is read from the
19
+ * stream and the request ends there (--max-turns 1). What a call does is the loop's business.
20
+ * schema Without MCP -- chosen (toolCalls: 'schema', or AI_CLAUDE_CODE_TOOL_CALLS=schema), or when the tool server
21
+ * does not connect. The answer is held to a JSON schema: the calls to make and the words to say.
22
+ *
23
+ * Measured on the dock's own prompt and tools, opus, sonnet and haiku, 8 requests each (2026-11-14): native 24 of 24,
24
+ * 3-4 s a turn; schema 17 of 24, 8-16 s -- held to the schema, the model still tried to call the listed tools itself,
25
+ * was told there were none, and answered that it could not look. Asked for JSON in the prompt alone (the way before),
26
+ * it wrote its calls in prose, in tags, as a bare list: each one a call lost and an empty bubble.
27
+ */
28
+ const child_process_1 = require("child_process");
29
+ const fs_1 = require("fs");
30
+ const os_1 = require("os");
31
+ const path_1 = require("path");
32
+ const factory_js_1 = require("../factory.js");
33
+ const parse_json_js_1 = require("../utils/parse-json.js");
34
+ const usage_js_1 = require("./usage.js");
35
+ /** The models a subscription offers by alias; Claude Code resolves each to the current one. */
36
+ const MODELS = ['opus', 'sonnet', 'haiku'];
37
+ /** The MCP server that lists a turn's tools; built next to this file. */
38
+ const TOOLS_SERVER = (0, path_1.join)(__dirname, 'claude-code-tools-mcp.js');
39
+ const SERVER_NAME = 'app';
40
+ const TOOL_PREFIX = `mcp__${SERVER_NAME}__`;
41
+ const bin = () => process.env.AI_CLAUDE_CODE_BIN || 'claude';
42
+ /**
43
+ * The `claude` CLI started in a folder, as every caller on this server starts it -- this provider, and the figure agent
44
+ * that runs it with the figure MCP server (figure-service).
45
+ */
46
+ function startClaudeCode(args, cwd) {
47
+ /*
48
+ MCP servers named by --mcp-config connect without blocking in print mode, and the first turn could start before
49
+ the tools were listed: the model wrote a call as words and ended (2026-11-14). Waiting costs nothing without one.
50
+ */
51
+ return (0, child_process_1.spawn)(bin(), args, { cwd, stdio: ['pipe', 'pipe', 'pipe'], env: { ...process.env, MCP_CONNECTION_NONBLOCKING: 'false' } });
52
+ }
53
+ const run = (args, input, cwd, signal) => new Promise((resolve, reject) => {
54
+ const child = startClaudeCode(args, cwd);
55
+ let out = '';
56
+ let err = '';
57
+ const stop = () => child.kill('SIGTERM');
58
+ signal?.addEventListener('abort', stop, { once: true });
59
+ child.stdout.on('data', d => (out += d));
60
+ child.stderr.on('data', d => (err += d));
61
+ child.on('error', reject);
62
+ child.on('close', code => {
63
+ signal?.removeEventListener('abort', stop);
64
+ if (signal?.aborted)
65
+ reject(Object.assign(new Error('aborted'), { name: 'AbortError' }));
66
+ else if (out)
67
+ resolve(out);
68
+ else
69
+ reject(new Error(`claude exited ${code}: ${err.slice(0, 500)}`));
70
+ });
71
+ child.stdin.end(input);
72
+ });
73
+ let availability;
74
+ /**
75
+ * Offered only where it can answer and where it belongs: a development server whose machine has the `claude` CLI
76
+ * logged in. A production server is never one (NODE_ENV production), and has no logged-in CLI either.
77
+ */
78
+ function claudeCodeAvailable() {
79
+ if (process.env.NODE_ENV !== 'development' || process.env.AI_CLAUDE_CODE === 'off')
80
+ return false;
81
+ if (availability && Date.now() - availability.at < 60_000)
82
+ return availability.ok;
83
+ let ok = false;
84
+ try {
85
+ const status = (0, child_process_1.spawnSync)(bin(), ['auth', 'status'], { encoding: 'utf-8', timeout: 10_000 });
86
+ ok = status.status === 0 && /"loggedIn":\s*true/.test(status.stdout ?? '');
87
+ }
88
+ catch {
89
+ ok = false;
90
+ }
91
+ availability = { at: Date.now(), ok };
92
+ return ok;
93
+ }
94
+ function textOf(content) {
95
+ if (typeof content === 'string')
96
+ return content;
97
+ return content
98
+ .map(part => part.type === 'text'
99
+ ? part.text
100
+ : part.type === 'image'
101
+ ? '[a picture was attached here; it is not carried by this provider]'
102
+ : part.type === 'tool_use'
103
+ ? `[called ${part.name} ${JSON.stringify(part.arguments ?? {})} as call ${part.id}]`
104
+ : `<tool_result id="${part.toolUseId}"${part.isError ? ' error="true"' : ''}>${part.content}</tool_result>`)
105
+ .join('\n');
106
+ }
107
+ /**
108
+ * The conversation as one request: a stateless call carries the turns before it, as an API request does. An earlier
109
+ * call is told as a plain record -- "[called x {...} as call id]" -- in neither way's answer shape: a record the model
110
+ * could copy as its answer was copied (tags, 2026-11-13).
111
+ */
112
+ function transcriptOf(messages) {
113
+ const system = messages.filter(m => m.role === 'system').map(m => textOf(m.content));
114
+ const turns = messages.filter(m => m.role !== 'system');
115
+ const text = turns.length === 1 && turns[0].role === 'user'
116
+ ? textOf(turns[0].content)
117
+ : turns.map(m => `<${m.role}>\n${textOf(m.content)}\n</${m.role}>`).join('\n\n') + '\n\nAnswer the last user turn.';
118
+ return { system: system.join('\n\n'), text };
119
+ }
120
+ /** The model that answered: among those a request used (Claude Code also asks a small model on its own), the one that wrote most. */
121
+ function answeringModel(modelUsage, fallback) {
122
+ const used = Object.entries(modelUsage ?? {});
123
+ if (!used.length)
124
+ return fallback;
125
+ return used.reduce((a, b) => ((b[1]?.outputTokens ?? 0) > (a[1]?.outputTokens ?? 0) ? b : a))[0];
126
+ }
127
+ /** A tool server that did not connect: the request is made again without MCP. */
128
+ class ToolServerUnavailable extends Error {
129
+ }
130
+ /** The schema an answer with tools is held to when tools are not offered natively. */
131
+ function toolAnswerSchema(options) {
132
+ const choice = options.toolChoice ?? 'auto';
133
+ return {
134
+ type: 'object',
135
+ additionalProperties: false,
136
+ properties: {
137
+ tool_calls: {
138
+ type: 'array',
139
+ description: 'The tools to call now, in order. Empty when you only answer the person.',
140
+ ...(choice === 'none' ? { maxItems: 0 } : choice === 'required' ? { minItems: 1 } : {}),
141
+ items: {
142
+ type: 'object',
143
+ additionalProperties: false,
144
+ properties: {
145
+ name: { type: 'string', description: 'A tool name from the list.', ...(choice === 'required' && options.forceTool ? { enum: [options.forceTool] } : {}) },
146
+ arguments: { type: 'object', description: "The tool's arguments, following its parameters." }
147
+ },
148
+ required: ['name', 'arguments']
149
+ }
150
+ },
151
+ text: { type: 'string', description: 'What you say to the person, in their language. Never a tool call.' }
152
+ },
153
+ required: ['tool_calls']
154
+ };
155
+ }
156
+ /** What the model is told of calling tools: the same for both ways, but how a call is made. */
157
+ function toolRules(options) {
158
+ const choice = options.toolChoice ?? 'auto';
159
+ return [
160
+ choice === 'required' ? `Call at least one tool now${options.forceTool ? `: ${options.forceTool}` : ''}.` : choice === 'none' ? 'Call no tool now: answer with text.' : 'Call tools when they are needed; answer with text when you are done.',
161
+ options.allowParallelToolCalls === false ? 'Call one tool at a time.' : '',
162
+ 'A tool result comes back in a later turn as <tool_result id="...">; read it before deciding what to do next.'
163
+ ].filter(Boolean);
164
+ }
165
+ class ClaudeCodeAIClient {
166
+ constructor(config, runner = run) {
167
+ this.config = config;
168
+ this.runner = runner;
169
+ this.id = `claude-code:${config.model ?? 'default'}`;
170
+ }
171
+ get toolCalls() {
172
+ return (this.config.toolCalls ?? process.env.AI_CLAUDE_CODE_TOOL_CALLS) === 'schema' ? 'schema' : 'native';
173
+ }
174
+ /** One stateless request; the usage told, a failure the CLI reports thrown. */
175
+ async request(messages, options, request = {}) {
176
+ const { system, text } = transcriptOf(messages);
177
+ const model = options.model ?? this.config.model;
178
+ const cwd = (0, fs_1.mkdtempSync)((0, path_1.join)((0, os_1.tmpdir)(), 'ai-claude-code-'));
179
+ try {
180
+ const systemFile = (0, path_1.join)(cwd, '.system-prompt');
181
+ (0, fs_1.writeFileSync)(systemFile, [options.systemPrompt, system, request.system].filter(Boolean).join('\n\n') || 'You are a helpful assistant.');
182
+ /* "{cwd}" in a file or an argument is this request's own folder. */
183
+ const here = (value) => value.split('{cwd}').join(cwd);
184
+ for (const [name, content] of Object.entries(request.files ?? {}))
185
+ (0, fs_1.writeFileSync)((0, path_1.join)(cwd, name), here(content));
186
+ const args = [
187
+ '-p',
188
+ '--output-format',
189
+ ...(request.stream ? ['stream-json', '--verbose'] : ['json']),
190
+ '--system-prompt-file',
191
+ systemFile,
192
+ '--tools',
193
+ '',
194
+ '--setting-sources',
195
+ '',
196
+ '--no-session-persistence',
197
+ ...(model ? ['--model', model] : []),
198
+ ...(request.args ?? []).map(here)
199
+ ];
200
+ const raw = await this.runner(args, text, cwd, options.signal);
201
+ const events = request.stream
202
+ ? raw
203
+ .split('\n')
204
+ .filter(Boolean)
205
+ .flatMap(line => {
206
+ try {
207
+ return [JSON.parse(line)];
208
+ }
209
+ catch {
210
+ return [];
211
+ }
212
+ })
213
+ : [JSON.parse(raw)];
214
+ const result = events.find(e => e?.type === 'result') ?? (request.stream ? undefined : events[0]);
215
+ const init = events.find(e => e?.type === 'system' && e.subtype === 'init');
216
+ const server = init?.mcp_servers?.find((s) => s?.name === SERVER_NAME);
217
+ if (server && server.status !== 'connected')
218
+ throw new ToolServerUnavailable(`the tool server is ${server.status}`);
219
+ if (!result)
220
+ throw new Error('Claude Code: no answer');
221
+ /* The CLI reports Anthropic's usage, so it is read as Anthropic's: the cache apart, inside the input (providers/usage.ts). */
222
+ options.onUsage?.((0, usage_js_1.anthropicUsageOf)(answeringModel(result.modelUsage, model ?? 'claude-code'), result.usage));
223
+ /* A turn stopped after its calls ends at the turn limit by design; any other error is one. */
224
+ if (result.is_error && result.subtype !== 'error_max_turns')
225
+ throw Object.assign(new Error(`Claude Code: ${result.result ?? result.subtype ?? 'error'}`), { status: /401|authenticate/i.test(String(result.result)) ? 401 : undefined });
226
+ return { events, result };
227
+ }
228
+ finally {
229
+ (0, fs_1.rmSync)(cwd, { recursive: true, force: true });
230
+ }
231
+ }
232
+ async chat(messages, options = {}) {
233
+ return String((await this.request(messages, options)).result.result ?? '');
234
+ }
235
+ async generateJSON(prompt, options = {}) {
236
+ const messages = typeof prompt === 'string' ? [{ role: 'user', content: prompt }] : prompt;
237
+ const { result } = await this.request(messages, options, { system: 'Answer with one JSON value only: no prose, no code fences.' });
238
+ return (0, parse_json_js_1.parseJSONResponse)(String(result.result ?? ''), { cutShort: result.stop_reason === 'max_tokens' });
239
+ }
240
+ async chatWithTools(messages, tools, options = {}) {
241
+ if ((options.toolChoice ?? 'auto') === 'none' || !tools.length) {
242
+ const { result } = await this.request(messages, options, { system: toolRules({ ...options, toolChoice: 'none' }).join('\n') });
243
+ return { ...(result.result ? { text: String(result.result) } : {}), toolCalls: [], stopReason: result.stop_reason === 'max_tokens' ? 'max_tokens' : 'end_turn' };
244
+ }
245
+ if (this.toolCalls === 'native') {
246
+ try {
247
+ return await this.nativeTools(messages, tools, options);
248
+ }
249
+ catch (e) {
250
+ if (!(e instanceof ToolServerUnavailable))
251
+ throw e;
252
+ console.warn(`[claude-code] ${e.message}; answering without MCP`);
253
+ }
254
+ }
255
+ return this.schemaTools(messages, tools, options);
256
+ }
257
+ /** The tools listed by an MCP server that runs none; the model's first turn read from the stream. */
258
+ async nativeTools(messages, tools, options) {
259
+ const offered = options.toolChoice === 'required' && options.forceTool ? tools.filter(t => t.name === options.forceTool) : tools;
260
+ const mcp = { mcpServers: { [SERVER_NAME]: { type: 'stdio', command: process.execPath, args: [TOOLS_SERVER], env: { CLAUDE_CODE_TOOLS: '{cwd}/tools.json' } } } };
261
+ const { events, result } = await this.request(messages, options, {
262
+ system: toolRules(options).join('\n'),
263
+ stream: true,
264
+ files: { 'tools.json': JSON.stringify(offered), 'mcp.json': JSON.stringify(mcp) },
265
+ args: ['--strict-mcp-config', '--mcp-config', '{cwd}/mcp.json', '--allowedTools', `mcp__${SERVER_NAME}`, '--max-turns', '1']
266
+ });
267
+ /* The first turn is what the model said before anything answered it: every assistant event before the first user event. */
268
+ const firstTurn = [];
269
+ for (const event of events) {
270
+ if (event?.type === 'user')
271
+ break;
272
+ if (event?.type === 'assistant')
273
+ firstTurn.push(...(event.message?.content ?? []));
274
+ }
275
+ const text = firstTurn
276
+ .filter(p => p?.type === 'text' && typeof p.text === 'string')
277
+ .map(p => p.text)
278
+ .join('');
279
+ const toolCalls = firstTurn
280
+ .filter(p => p?.type === 'tool_use' && typeof p.name === 'string')
281
+ .map(p => ({ id: String(p.id), name: p.name.startsWith(TOOL_PREFIX) ? p.name.slice(TOOL_PREFIX.length) : p.name, arguments: p.input && typeof p.input === 'object' ? p.input : {} }));
282
+ const answered = text || (toolCalls.length ? '' : String(result.result ?? ''));
283
+ return {
284
+ ...(answered ? { text: answered } : {}),
285
+ toolCalls,
286
+ stopReason: toolCalls.length ? 'tool_use' : result.stop_reason === 'max_tokens' ? 'max_tokens' : 'end_turn'
287
+ };
288
+ }
289
+ /** Without MCP: the answer held to a schema of the calls to make and the words to say. */
290
+ async schemaTools(messages, tools, options) {
291
+ const system = [
292
+ 'You can call these tools. Each takes arguments that follow its JSON schema:',
293
+ JSON.stringify(tools.map(t => ({ name: t.name, description: t.description, parameters: t.parameters }))),
294
+ '',
295
+ 'These tools are not functions you can call yourself, and nothing else is: you call a tool by writing it in "tool_calls" of your answer. It runs after you answer.',
296
+ 'Your answer is the structured output: "tool_calls" lists the tools to call now, in order (empty when you only answer the person); "text" is what you say to the person.',
297
+ ...toolRules(options)
298
+ ].join('\n');
299
+ const { result } = await this.request(messages, options, { system, args: ['--json-schema', JSON.stringify(toolAnswerSchema(options))] });
300
+ const answer = result.structured_output;
301
+ if (!answer || typeof answer !== 'object') {
302
+ const words = String(result.result ?? '');
303
+ return { ...(words ? { text: words } : {}), toolCalls: [], stopReason: result.stop_reason === 'max_tokens' ? 'max_tokens' : 'end_turn' };
304
+ }
305
+ const ts = Date.now().toString(36);
306
+ const toolCalls = (Array.isArray(answer.tool_calls) ? answer.tool_calls : [])
307
+ .filter((c) => c && typeof c.name === 'string' && c.name)
308
+ .map((c, i) => ({ id: `cc_${ts}_${i}`, name: c.name, arguments: c.arguments && typeof c.arguments === 'object' ? c.arguments : {} }));
309
+ const text = typeof answer.text === 'string' && answer.text ? answer.text : undefined;
310
+ return { ...(text ? { text } : {}), toolCalls, stopReason: toolCalls.length ? 'tool_use' : 'end_turn' };
311
+ }
312
+ async listModels() {
313
+ if (!claudeCodeAvailable())
314
+ throw Object.assign(new Error('Claude Code is not logged in on this server'), { status: 401 });
315
+ return MODELS;
316
+ }
317
+ }
318
+ function createClaudeCodeClient(config, runner) {
319
+ return new ClaudeCodeAIClient(config, runner);
320
+ }
321
+ (0, factory_js_1.registerAIProvider)('claude-code', config => new ClaudeCodeAIClient(config));
322
+ //# sourceMappingURL=claude-code.js.map
@@ -0,0 +1,20 @@
1
+ /**
2
+ * What every adapter does the same way, said once (2026-11-14). Each adapter keeps only how its provider is spoken to:
3
+ * the request shape, the tool shape, how an answer is read back. These pieces were copied into each one, and a copy
4
+ * changed in one adapter was a provider answering differently without anyone deciding it.
5
+ */
6
+ import type { AIJSONOptions, AIMessage } from '../types.js';
7
+ /** The system prompt a request carries: the caller's own, then the system messages of the conversation. */
8
+ export declare function systemPromptOf(messages: AIMessage[], systemPrompt?: string): string;
9
+ /** The conversation without its system messages, which every provider takes apart from the turns. */
10
+ export declare function turnsOf(messages: AIMessage[]): AIMessage[];
11
+ /** One user turn holding a picture and the question about it -- a picture without a type is taken for a PNG. */
12
+ export declare function visionTurn(image: Buffer | Uint8Array | {
13
+ url: string;
14
+ }, prompt: string): AIMessage[];
15
+ /** The system prompt that asks for JSON where a provider has no way to hold an answer to a schema itself. */
16
+ export declare function jsonSystemPrompt(options: AIJSONOptions): string;
17
+ /** An id for a tool call the provider gave none: the loop pairs each result with its call by id. */
18
+ export declare function madeCallId(): string;
19
+ /** A picture's bytes as base64. */
20
+ export declare function base64Of(data: Buffer | Uint8Array): string;
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.systemPromptOf = systemPromptOf;
4
+ exports.turnsOf = turnsOf;
5
+ exports.visionTurn = visionTurn;
6
+ exports.jsonSystemPrompt = jsonSystemPrompt;
7
+ exports.madeCallId = madeCallId;
8
+ exports.base64Of = base64Of;
9
+ /** The words of a message, its pictures and tool parts left out. */
10
+ function textOfMessage(message) {
11
+ if (typeof message.content === 'string')
12
+ return message.content;
13
+ return message.content
14
+ .filter(part => part.type === 'text')
15
+ .map(part => part.text)
16
+ .join('\n');
17
+ }
18
+ /** The system prompt a request carries: the caller's own, then the system messages of the conversation. */
19
+ function systemPromptOf(messages, systemPrompt) {
20
+ const fromMessages = messages
21
+ .filter(m => m.role === 'system')
22
+ .map(textOfMessage)
23
+ .filter(Boolean)
24
+ .join('\n\n');
25
+ return [systemPrompt, fromMessages].filter(Boolean).join('\n\n');
26
+ }
27
+ /** The conversation without its system messages, which every provider takes apart from the turns. */
28
+ function turnsOf(messages) {
29
+ return messages.filter(m => m.role !== 'system');
30
+ }
31
+ /** One user turn holding a picture and the question about it -- a picture without a type is taken for a PNG. */
32
+ function visionTurn(image, prompt) {
33
+ const picture = typeof image === 'object' && 'url' in image
34
+ ? { type: 'image', source: { kind: 'url', url: image.url } }
35
+ : { type: 'image', source: { kind: 'base64', data: image, mediaType: 'image/png' } };
36
+ return [{ role: 'user', content: [picture, { type: 'text', text: prompt }] }];
37
+ }
38
+ /** The system prompt that asks for JSON where a provider has no way to hold an answer to a schema itself. */
39
+ function jsonSystemPrompt(options) {
40
+ return ((options.systemPrompt ? options.systemPrompt + '\n\n' : '') +
41
+ 'Return only valid JSON. No markdown code fences, no commentary.' +
42
+ (options.schema ? `\n\nResponse MUST conform to this JSON schema:\n${JSON.stringify(options.schema)}` : ''));
43
+ }
44
+ /** An id for a tool call the provider gave none: the loop pairs each result with its call by id. */
45
+ function madeCallId() {
46
+ return `call_${Math.random().toString(36).slice(2, 12)}`;
47
+ }
48
+ /** A picture's bytes as base64. */
49
+ function base64Of(data) {
50
+ return Buffer.isBuffer(data) ? data.toString('base64') : Buffer.from(data).toString('base64');
51
+ }
52
+ //# sourceMappingURL=common.js.map
@@ -13,6 +13,7 @@ exports.ProviderListError = exports.GeminiAIClient = void 0;
13
13
  const generative_ai_1 = require("@google/generative-ai");
14
14
  const factory_js_1 = require("../factory.js");
15
15
  const parse_json_js_1 = require("../utils/parse-json.js");
16
+ const common_js_1 = require("./common.js");
16
17
  const request_options_js_1 = require("./request-options.js");
17
18
  const usage_js_1 = require("./usage.js");
18
19
  // `gemini-3-pro` 는 2026-03-09 종료됨. 후속 권장 모델로 변경.
@@ -53,13 +54,7 @@ class GeminiAIClient {
53
54
  return (0, parse_json_js_1.parseJSONResponse)(text, { cutShort: result.response.candidates?.[0]?.finishReason === 'MAX_TOKENS' });
54
55
  }
55
56
  async vision(image, prompt, options = {}) {
56
- const imagePart = typeof image === 'object' && 'url' in image
57
- ? { type: 'image', source: { kind: 'url', url: image.url } }
58
- : {
59
- type: 'image',
60
- source: { kind: 'base64', data: image, mediaType: 'image/png' }
61
- };
62
- return this.chat([{ role: 'user', content: [imagePart, { type: 'text', text: prompt }] }], options);
57
+ return this.chat((0, common_js_1.visionTurn)(image, prompt), options);
63
58
  }
64
59
  buildModel(options, systemInstruction) {
65
60
  return this.sdk.getGenerativeModel({
@@ -175,21 +170,7 @@ function baseGenerationConfig(options) {
175
170
  };
176
171
  }
177
172
  function splitMessages(messages, externalSystem) {
178
- const systemMessages = messages
179
- .filter(m => m.role === 'system')
180
- .map(extractTextContent)
181
- .filter(Boolean);
182
- const conversation = messages.filter(m => m.role !== 'system');
183
- const systemPrompt = [externalSystem, ...systemMessages].filter(Boolean).join('\n\n');
184
- return { systemPrompt, contents: conversation.map(toGeminiContent) };
185
- }
186
- function extractTextContent(msg) {
187
- if (typeof msg.content === 'string')
188
- return msg.content;
189
- return msg.content
190
- .filter(p => p.type === 'text')
191
- .map(p => p.text)
192
- .join('\n');
173
+ return { systemPrompt: (0, common_js_1.systemPromptOf)(messages, externalSystem), contents: (0, common_js_1.turnsOf)(messages).map(toGeminiContent) };
193
174
  }
194
175
  function toGeminiContent(msg) {
195
176
  // Our 'assistant' role → Gemini's 'model' role
@@ -237,11 +218,8 @@ function toGeminiPart(part) {
237
218
  // Gemini SDK 는 inlineData(base64) 만 지원. URL 은 호출 전에 fetch 필요.
238
219
  throw new Error('Gemini adapter: image URL is not supported directly. Fetch the URL and pass as Buffer.');
239
220
  }
240
- const data = Buffer.isBuffer(part.source.data)
241
- ? part.source.data.toString('base64')
242
- : Buffer.from(part.source.data).toString('base64');
243
221
  return {
244
- inlineData: { data, mimeType: part.source.mediaType }
222
+ inlineData: { data: (0, common_js_1.base64Of)(part.source.data), mimeType: part.source.mediaType }
245
223
  };
246
224
  }
247
225
  /**
@@ -1,6 +1,8 @@
1
1
  import './anthropic.js';
2
+ import './claude-code.js';
2
3
  import './gemini.js';
3
4
  import './openai.js';
4
5
  export { AnthropicAIClient } from './anthropic.js';
6
+ export { claudeCodeAvailable, createClaudeCodeClient, startClaudeCode, type ClaudeCodeRunner } from './claude-code.js';
5
7
  export { GeminiAIClient } from './gemini.js';
6
8
  export { OpenAIAIClient } from './openai.js';
@@ -1,12 +1,17 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.OpenAIAIClient = exports.GeminiAIClient = exports.AnthropicAIClient = void 0;
3
+ exports.OpenAIAIClient = exports.GeminiAIClient = exports.startClaudeCode = exports.createClaudeCodeClient = exports.claudeCodeAvailable = exports.AnthropicAIClient = void 0;
4
4
  // Auto-register providers on module load
5
5
  require("./anthropic.js");
6
+ require("./claude-code.js");
6
7
  require("./gemini.js");
7
8
  require("./openai.js");
8
9
  var anthropic_js_1 = require("./anthropic.js");
9
10
  Object.defineProperty(exports, "AnthropicAIClient", { enumerable: true, get: function () { return anthropic_js_1.AnthropicAIClient; } });
11
+ var claude_code_js_1 = require("./claude-code.js");
12
+ Object.defineProperty(exports, "claudeCodeAvailable", { enumerable: true, get: function () { return claude_code_js_1.claudeCodeAvailable; } });
13
+ Object.defineProperty(exports, "createClaudeCodeClient", { enumerable: true, get: function () { return claude_code_js_1.createClaudeCodeClient; } });
14
+ Object.defineProperty(exports, "startClaudeCode", { enumerable: true, get: function () { return claude_code_js_1.startClaudeCode; } });
10
15
  var gemini_js_1 = require("./gemini.js");
11
16
  Object.defineProperty(exports, "GeminiAIClient", { enumerable: true, get: function () { return gemini_js_1.GeminiAIClient; } });
12
17
  var openai_js_1 = require("./openai.js");
@@ -16,10 +16,23 @@ const openai_1 = tslib_1.__importDefault(require("openai"));
16
16
  const uploads_1 = require("openai/uploads");
17
17
  const factory_js_1 = require("../factory.js");
18
18
  const parse_json_js_1 = require("../utils/parse-json.js");
19
+ const common_js_1 = require("./common.js");
19
20
  const request_options_js_1 = require("./request-options.js");
20
21
  const usage_js_1 = require("./usage.js");
21
22
  const DEFAULT_MODEL = 'gpt-4o';
22
23
  const DEFAULT_MAX_TOKENS = 4096;
24
+ /*
25
+ * Models that take function tools on chat/completions only with reasoning off (2026-11-14: gpt-6.1-terra answered 400
26
+ * "Function tools with reasoning_effort are not supported ... set reasoning_effort to 'none'"). Nothing is sent by
27
+ * default -- a model that takes tools as it is stays as it is, and one that does not know the field is never sent it.
28
+ * A model is put here when it refuses that way, by the endpoint it was asked at, and asked again at once.
29
+ */
30
+ const toolsNeedReasoningOff = new Set();
31
+ /** The refusal of tools while reasoning is on, which says to set reasoning_effort to 'none'. */
32
+ function refusesToolsWhileReasoning(error) {
33
+ const message = String(error?.message ?? '');
34
+ return Number(error?.status) === 400 && /reasoning_effort/.test(message) && /\bnone\b/.test(message);
35
+ }
23
36
  class OpenAIAIClient {
24
37
  constructor(config) {
25
38
  this.sdk = new openai_1.default({
@@ -55,13 +68,7 @@ class OpenAIAIClient {
55
68
  }
56
69
  async generateJSON(prompt, options = {}) {
57
70
  const messages = typeof prompt === 'string' ? [{ role: 'user', content: prompt }] : prompt;
58
- const schemaHint = options.schema
59
- ? `\n\nResponse MUST conform to this JSON schema:\n${JSON.stringify(options.schema)}`
60
- : '';
61
- const enforcedSystem = (options.systemPrompt ? options.systemPrompt + '\n\n' : '') +
62
- 'Return only valid JSON. No markdown code fences, no commentary.' +
63
- schemaHint;
64
- const sdkMessages = buildSDKMessages(messages, enforcedSystem);
71
+ const sdkMessages = buildSDKMessages(messages, (0, common_js_1.jsonSystemPrompt)(options));
65
72
  const response = await this.sdk.chat.completions.create({
66
73
  model: options.model ?? this.defaultModel,
67
74
  /* `max_tokens` is refused by the gpt-5 and o-series models; every chat model takes this one. */
@@ -75,13 +82,7 @@ class OpenAIAIClient {
75
82
  return (0, parse_json_js_1.parseJSONResponse)(text, { cutShort: response.choices[0]?.finish_reason === 'length' });
76
83
  }
77
84
  async vision(image, prompt, options = {}) {
78
- const imagePart = typeof image === 'object' && 'url' in image
79
- ? { type: 'image', source: { kind: 'url', url: image.url } }
80
- : {
81
- type: 'image',
82
- source: { kind: 'base64', data: image, mediaType: 'image/png' }
83
- };
84
- return this.chat([{ role: 'user', content: [imagePart, { type: 'text', text: prompt }] }], options);
85
+ return this.chat((0, common_js_1.visionTurn)(image, prompt), options);
85
86
  }
86
87
  async chatWithTools(messages, tools, options = {}) {
87
88
  const sdkMessages = buildSDKMessages(messages, options.systemPrompt);
@@ -94,8 +95,10 @@ class OpenAIAIClient {
94
95
  }
95
96
  }));
96
97
  const toolChoice = buildOpenAIToolChoice(options);
97
- const response = await this.sdk.chat.completions.create({
98
- model: options.model ?? this.defaultModel,
98
+ const model = options.model ?? this.defaultModel;
99
+ const known = `${this.sdk.baseURL} ${model}`;
100
+ const ask = (reasoningOff) => this.sdk.chat.completions.create({
101
+ model,
99
102
  /* `max_tokens` is refused by the gpt-5 and o-series models; every chat model takes this one. */
100
103
  max_completion_tokens: options.maxTokens ?? DEFAULT_MAX_TOKENS,
101
104
  ...(options.temperature !== undefined && { temperature: options.temperature }),
@@ -103,9 +106,21 @@ class OpenAIAIClient {
103
106
  messages: sdkMessages,
104
107
  tools: sdkTools,
105
108
  ...(toolChoice !== undefined && { tool_choice: toolChoice }),
106
- ...(options.allowParallelToolCalls === false && { parallel_tool_calls: false })
109
+ ...(options.allowParallelToolCalls === false && { parallel_tool_calls: false }),
110
+ /* The SDK's types predate 'none'; the API takes it. */
111
+ ...(reasoningOff && { reasoning_effort: 'none' })
107
112
  }, (0, request_options_js_1.requestOptionsOf)(options));
108
- reportUsage(response, options, options.model ?? this.defaultModel);
113
+ let response;
114
+ try {
115
+ response = await ask(toolsNeedReasoningOff.has(known));
116
+ }
117
+ catch (error) {
118
+ if (toolsNeedReasoningOff.has(known) || !refusesToolsWhileReasoning(error))
119
+ throw error;
120
+ toolsNeedReasoningOff.add(known);
121
+ response = await ask(true);
122
+ }
123
+ reportUsage(response, options, model);
109
124
  const choice = response.choices?.[0];
110
125
  const message = choice?.message;
111
126
  const text = message?.content || undefined;
@@ -119,7 +134,7 @@ class OpenAIAIClient {
119
134
  args = {};
120
135
  }
121
136
  return {
122
- id: typeof tc.id === 'string' && tc.id ? tc.id : `call_${Math.random().toString(36).slice(2, 12)}`,
137
+ id: typeof tc.id === 'string' && tc.id ? tc.id : (0, common_js_1.madeCallId)(),
123
138
  name: fn?.name ?? '',
124
139
  arguments: args
125
140
  };
@@ -152,23 +167,8 @@ function reportUsage(response, options, requested) {
152
167
  }
153
168
  // ── 변환 유틸 ─────────────────────────────────────────────────────────
154
169
  function buildSDKMessages(messages, externalSystem) {
155
- const out = [];
156
- const systemFromMessages = messages
157
- .filter(m => m.role === 'system')
158
- .map(extractTextContent)
159
- .filter(Boolean)
160
- .join('\n\n');
161
- const combinedSystem = [externalSystem, systemFromMessages].filter(Boolean).join('\n\n');
162
- if (combinedSystem) {
163
- out.push({ role: 'system', content: combinedSystem });
164
- }
165
- for (const msg of messages) {
166
- if (msg.role === 'system')
167
- continue;
168
- const sdkMsgs = toSDKMessages(msg);
169
- out.push(...sdkMsgs);
170
- }
171
- return out;
170
+ const system = (0, common_js_1.systemPromptOf)(messages, externalSystem);
171
+ return [...(system ? [{ role: 'system', content: system }] : []), ...(0, common_js_1.turnsOf)(messages).flatMap(toSDKMessages)];
172
172
  }
173
173
  /**
174
174
  * 한 AIMessage 가 다중 tool_result 를 가지면 OpenAI 측에서 여러 role:'tool' 메시지로
@@ -222,22 +222,11 @@ function toSDKContentPart(part) {
222
222
  if (part.source.kind === 'url') {
223
223
  return { type: 'image_url', image_url: { url: part.source.url } };
224
224
  }
225
- const b64 = Buffer.isBuffer(part.source.data)
226
- ? part.source.data.toString('base64')
227
- : Buffer.from(part.source.data).toString('base64');
228
225
  return {
229
226
  type: 'image_url',
230
- image_url: { url: `data:${part.source.mediaType};base64,${b64}` }
227
+ image_url: { url: `data:${part.source.mediaType};base64,${(0, common_js_1.base64Of)(part.source.data)}` }
231
228
  };
232
229
  }
233
- function extractTextContent(msg) {
234
- if (typeof msg.content === 'string')
235
- return msg.content;
236
- return msg.content
237
- .filter(p => p.type === 'text')
238
- .map(p => p.text)
239
- .join('\n');
240
- }
241
230
  function buildOpenAIToolChoice(options) {
242
231
  const choice = options.toolChoice ?? 'auto';
243
232
  if (choice === 'none')
@@ -3,9 +3,10 @@
3
3
  *
4
4
  * 자세한 설계는 ./types 와 ./registry 의 헤더 주석 참조.
5
5
  */
6
- export { registerToolCategory, getToolCategories, getAllToolSpecs, getToolSpecsFor, getCategoryGuidance, findToolSpec, getToolKind, hasTool, getCategorySpecs, clearToolRegistry, getToolRegistryWarnings } from './registry';
6
+ export { registerToolCategory, getToolCategories, getAllToolSpecs, getToolSpecsFor, getCategoryGuidance, findToolSpec, findToolCategory, getToolKind, hasTool, getCategorySpecs, clearToolRegistry, getToolRegistryWarnings } from './registry';
7
7
  export { defaultValueTranslate } from './translate';
8
8
  export { registerToolCallRecorder, clearToolCallRecorders, recordToolCall, digestOf } from './call-recorder';
9
+ export { runRegisteredTool } from './run-tool';
9
10
  export type { ToolCallRecord, ToolCallRecorder, ToolCallRecorderOptions, ToolCallRun } from './call-recorder';
10
11
  export type { ToolCategoryFilter, ToolRegistryWarning } from './registry';
11
12
  export type { ToolSpec, ToolSpecBase, ReadToolSpec, WriteToolSpec, ActionToolSpec, ExternalToolSpec, ToolCategory, ReadToolBuilder, WriteToolBuilder, ActionToolBuilder, ExternalToolBuilder, ReadToolContext, WriteToolContext, ExternalToolContext, ToolCallContext, ToolCallMode, UnattendedRunRef, ToolTranslate, ToolAttachment, ToolImageAttachment, ToolTextAttachment } from './types';