@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
@@ -49,7 +49,7 @@ async function readAiAgentDirectory(given) {
49
49
  keyState,
50
50
  ...(key?.value && { keyDomainId: key.domainId, apiKey: key.value, keyVersion: `${key.domainId}:${key.updatedAt?.valueOf() ?? ''}` }),
51
51
  ...(keyHere && key?.value && { keyHint: (0, shell_1.secretHint)(key.value) }),
52
- usable: spec.active && !off && keyState !== 'missing'
52
+ usable: spec.active && !off && ((0, agent_spec_js_1.aiProviderNeedsKey)(spec.provider) ? keyState !== 'missing' : (0, agent_spec_js_1.aiProviderAvailable)(spec.provider))
53
53
  };
54
54
  });
55
55
  const nameOf = new Map(domains.map(one => [one.id, one.name]));
@@ -22,8 +22,9 @@ async function saveAiAgents(write, { tx, domain, user }) {
22
22
  const storedKeyOf = new Map(directory.entries.filter(one => !one.inherited && one.keyState === 'own').map(one => [one.spec.id, one.apiKey]));
23
23
  for (const [index, agent] of agents.entries()) {
24
24
  const newKey = write.agents[index].apiKey?.trim();
25
- const key = newKey || storedKeyOf.get(agent.id);
26
- if (!key)
25
+ const keyless = !(0, agent_spec_js_1.aiProviderNeedsKey)(agent.provider);
26
+ const key = keyless ? '' : newKey || storedKeyOf.get(agent.id);
27
+ if (!keyless && !key)
27
28
  throw new shell_1.Refusal('ai-agent-key-required', { agent: agent.name }, `Enter the API key of "${agent.name}".`);
28
29
  if (needsModelCheck(agent, storedById.get(agent.id), !!newKey)) {
29
30
  const offered = await (0, provider_models_js_1.listProviderModels)({ provider: agent.provider, apiKey: key, baseURL: agent.baseURL, organization: agent.organization });
@@ -5,9 +5,18 @@
5
5
  * definition and the secret live where the framework already keeps domain settings and secrets (ADR-0112).
6
6
  * This file is the shape and its parsing - no database.
7
7
  */
8
- /** The providers an agent may name. Three, by decision (2026-10-12). */
9
- export declare const AI_AGENT_PROVIDERS: readonly ["openai", "anthropic", "gemini"];
8
+ /**
9
+ * The providers an agent may name. Three, by decision (2026-10-12); and claude-code (2026-11-13): Claude Code logged in
10
+ * on the server's own machine, for development -- it needs no key, and is offered only where it can answer.
11
+ */
12
+ export declare const AI_AGENT_PROVIDERS: readonly ["openai", "anthropic", "gemini", "claude-code"];
10
13
  export type AiAgentProvider = (typeof AI_AGENT_PROVIDERS)[number];
14
+ /** A provider whose agent needs no API key: it answers on what the server's machine is logged in to. */
15
+ export declare function aiProviderNeedsKey(provider: string): boolean;
16
+ /** Whether this server can use the provider at all: claude-code only on a development server with the CLI logged in. */
17
+ export declare function aiProviderAvailable(provider: string): boolean;
18
+ /** The providers this server offers, for the settings screen. */
19
+ export declare function aiProvidersOffered(): AiAgentProvider[];
11
20
  /** The Setting row that holds a domain's agents. */
12
21
  export declare const AI_AGENTS_SETTING = "ai-agents";
13
22
  export declare const AI_AGENTS_SETTING_CATEGORY = "ai";
@@ -8,12 +8,33 @@
8
8
  */
9
9
  Object.defineProperty(exports, "__esModule", { value: true });
10
10
  exports.AI_AGENT_KEY_PREFIX = exports.AI_AGENTS_SETTING_CATEGORY = exports.AI_AGENTS_SETTING = exports.AI_AGENT_PROVIDERS = void 0;
11
+ exports.aiProviderNeedsKey = aiProviderNeedsKey;
12
+ exports.aiProviderAvailable = aiProviderAvailable;
13
+ exports.aiProvidersOffered = aiProvidersOffered;
11
14
  exports.aiAgentKeyName = aiAgentKeyName;
12
15
  exports.isAiAgentProvider = isAiAgentProvider;
13
16
  exports.parseAiAgentsSetting = parseAiAgentsSetting;
14
17
  exports.stringifyAiAgentsSetting = stringifyAiAgentsSetting;
15
- /** The providers an agent may name. Three, by decision (2026-10-12). */
16
- exports.AI_AGENT_PROVIDERS = ['openai', 'anthropic', 'gemini'];
18
+ /**
19
+ * The providers an agent may name. Three, by decision (2026-10-12); and claude-code (2026-11-13): Claude Code logged in
20
+ * on the server's own machine, for development -- it needs no key, and is offered only where it can answer.
21
+ */
22
+ exports.AI_AGENT_PROVIDERS = ['openai', 'anthropic', 'gemini', 'claude-code'];
23
+ /** A provider whose agent needs no API key: it answers on what the server's machine is logged in to. */
24
+ function aiProviderNeedsKey(provider) {
25
+ return provider !== 'claude-code';
26
+ }
27
+ /** Whether this server can use the provider at all: claude-code only on a development server with the CLI logged in. */
28
+ function aiProviderAvailable(provider) {
29
+ if (provider !== 'claude-code')
30
+ return true;
31
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
32
+ return require('../providers/claude-code.js').claudeCodeAvailable();
33
+ }
34
+ /** The providers this server offers, for the settings screen. */
35
+ function aiProvidersOffered() {
36
+ return exports.AI_AGENT_PROVIDERS.filter(aiProviderAvailable);
37
+ }
17
38
  /** The Setting row that holds a domain's agents. */
18
39
  exports.AI_AGENTS_SETTING = 'ai-agents';
19
40
  exports.AI_AGENTS_SETTING_CATEGORY = 'ai';
@@ -58,7 +58,7 @@ function providerClientOf(entry) {
58
58
  const client = (0, factory_js_1.createAIClient)({
59
59
  provider: spec.provider,
60
60
  model: spec.model,
61
- apiKey: entry.apiKey,
61
+ apiKey: entry.apiKey ?? '',
62
62
  ...(spec.baseURL && { baseURL: spec.baseURL }),
63
63
  ...(spec.organization && { organization: spec.organization })
64
64
  });
@@ -145,6 +145,9 @@ function hourOf(moment) {
145
145
  }
146
146
  /** Why a provider request failed, as the usage row keeps it. */
147
147
  function outcomeOf(error) {
148
+ /* A request stopped on our side -- a person's stop, a run's time limit -- is not the provider failing. */
149
+ if (error?.name === 'AbortError')
150
+ return 'stopped';
148
151
  const status = Number(error?.status ?? error?.statusCode ?? error?.response?.status);
149
152
  if (status === 401 || status === 403)
150
153
  return 'key-rejected';
@@ -24,7 +24,7 @@ export declare class AiUsage {
24
24
  cacheWriteTokens?: number;
25
25
  outputTokens?: number;
26
26
  durationMs: number;
27
- /** `ok`, or why it failed: key-rejected · rate-limited · provider-error. */
27
+ /** `ok`, or why it failed: key-rejected · rate-limited · provider-error · stopped (on our side). */
28
28
  outcome: string;
29
29
  /**
30
30
  * The UTC hour the call started in. Usage is grouped by this column, which every database can do; days and months
@@ -97,7 +97,7 @@ tslib_1.__decorate([
97
97
  ], AiUsage.prototype, "durationMs", void 0);
98
98
  tslib_1.__decorate([
99
99
  (0, typeorm_1.Column)(),
100
- (0, type_graphql_1.Field)(type => String, { description: 'ok, or why the request failed: key-rejected, rate-limited or provider-error.' }),
100
+ (0, type_graphql_1.Field)(type => String, { description: 'ok, or why the request failed: key-rejected, rate-limited, provider-error, or stopped on our side.' }),
101
101
  tslib_1.__metadata("design:type", String)
102
102
  ], AiUsage.prototype, "outcome", void 0);
103
103
  tslib_1.__decorate([
@@ -14,12 +14,15 @@ async function listProviderModels(request) {
14
14
  if (!(0, agent_spec_js_1.isAiAgentProvider)(request.provider)) {
15
15
  throw new shell_1.Refusal('ai-agent-provider-unknown', { provider: request.provider }, `"${request.provider}" is not a provider an agent can use.`);
16
16
  }
17
- if (!request.apiKey?.trim()) {
17
+ if (!(0, agent_spec_js_1.aiProviderAvailable)(request.provider)) {
18
+ throw new shell_1.Refusal('ai-provider-unreachable', { provider: request.provider }, 'This provider is not available on this server.');
19
+ }
20
+ if ((0, agent_spec_js_1.aiProviderNeedsKey)(request.provider) && !request.apiKey?.trim()) {
18
21
  throw new shell_1.Refusal('ai-agent-key-required', {}, 'Enter the API key first.');
19
22
  }
20
23
  const client = (0, factory_js_1.createAIClient)({
21
24
  provider: request.provider,
22
- apiKey: request.apiKey.trim(),
25
+ apiKey: request.apiKey?.trim() ?? '',
23
26
  ...(request.baseURL && { baseURL: request.baseURL }),
24
27
  ...(request.organization && { organization: request.organization })
25
28
  });
@@ -1,4 +1,4 @@
1
- import type { AIImagePart, AIMessage, AIToolCall, AIToolChatResult } from '../types.js';
1
+ import type { AIImagePart, AIMessage, AITool, AIToolCall, AIToolChatOptions, AIToolChatResult } from '../types.js';
2
2
  /**
3
3
  * AI 가 응답을 만드는 동안 호출한 도구의 시간순 trace.
4
4
  *
@@ -116,10 +116,10 @@ export interface AgenticLoopInput<TCtx = unknown, TOp = unknown> {
116
116
  * The tools the model is offered. A function is asked before every call, so a conversation that opens tools in a
117
117
  * turn (ADR-0061 decision 9, `openTools`) offers them from its next call on.
118
118
  */
119
- tools: any[] | (() => any[]);
119
+ tools: AITool[] | (() => AITool[]);
120
120
  options: AgenticLoopOptions;
121
121
  /** LLM provider 의 chatWithTools 위임. provider-specific 구현. */
122
- chat: (messages: AIMessage[], tools: any[], options: any) => Promise<AIToolChatResult>;
122
+ chat: (messages: AIMessage[], tools: AITool[], options: AIToolChatOptions) => Promise<AIToolChatResult>;
123
123
  dispatch: ToolDispatchHelpers<TCtx, TOp>;
124
124
  /** 도구가 알아야 하는 것 한 뭉치 — 루프는 들여다보지 않고 나른다. */
125
125
  context: TCtx;
@@ -146,6 +146,12 @@ export interface AgenticLoopResult<TOp = unknown> {
146
146
  proposals: any[];
147
147
  /** LLM 마지막 응답의 stopReason. provider-specific 문자열. */
148
148
  stopReason: string;
149
+ /**
150
+ * The words handed back (lastText) are the model's last answer, and it stopped at the output limit before it ended
151
+ * (stopReason `max_tokens`, no call in it) -- the turn's own answer, or the wrap-up's. Not a stop of the loop -- the
152
+ * words are what the model said -- but a reader must not take them for the whole answer.
153
+ */
154
+ cutShort?: boolean;
149
155
  /**
150
156
  * 비정상 종료 사유 — 정상 종료 시 undefined.
151
157
  * 호출자 (assistant.ts) 가 사용자 메시지에 반영 (예: '시도 중 오류가 발생했어요').
@@ -79,6 +79,8 @@ async function runAgenticLoop(input) {
79
79
  const proposals = [];
80
80
  let lastText;
81
81
  let stopReason = 'end_turn';
82
+ /* Set where the words handed back are the model's last answer, and that answer hit the output limit. */
83
+ let cutShort = false;
82
84
  let abortReason;
83
85
  // 같은 tool 의 validation 실패 연속 카운터 — 다른 tool 호출 시 reset
84
86
  let lastFailedToolName;
@@ -132,8 +134,10 @@ async function runAgenticLoop(input) {
132
134
  lastText = result.text || lastText;
133
135
  stopReason = result.stopReason;
134
136
  log('iter %d: text=%s, toolCalls=%d, stopReason=%s', iter, result.text ? `"${result.text.slice(0, 60)}..."` : '(none)', result.toolCalls.length, result.stopReason);
135
- if (result.toolCalls.length === 0)
137
+ if (result.toolCalls.length === 0) {
138
+ cutShort = result.stopReason === 'max_tokens' && !!result.text;
136
139
  break;
140
+ }
137
141
  // (1b) 삭제: chat() 직후 abort 는 다음 iter 시작 시 (1) 에서 감지.
138
142
  // 현재 iter tool 실행을 중단하면 read tool 결과도 버려져 테스트/동작 불일치.
139
143
  // tool 결과 빌드 — read 는 즉시 실행, write 는 누적, action 은 별도 채널
@@ -198,6 +202,7 @@ async function runAgenticLoop(input) {
198
202
  });
199
203
  if (salvaged?.text) {
200
204
  lastText = salvaged.text;
205
+ cutShort = salvaged.stopReason === 'max_tokens';
201
206
  /* The wrap-up answered from what was found and says what is missing; no notice need follow it. */
202
207
  abortReason = { type: 'max_iterations', iter, salvaged: true };
203
208
  stopReason = salvaged.stopReason ?? stopReason;
@@ -218,6 +223,7 @@ async function runAgenticLoop(input) {
218
223
  groundedTexts,
219
224
  proposals,
220
225
  stopReason,
226
+ ...(cutShort ? { cutShort: true } : {}),
221
227
  abortReason
222
228
  };
223
229
  }
@@ -369,7 +375,8 @@ iter) {
369
375
  toolResultParts.push({
370
376
  type: 'tool_result',
371
377
  toolUseId: tc.id,
372
- content: JSON.stringify(value)
378
+ /* Always a text: a tool that gave nothing back says so as null, never as no content at all. */
379
+ content: JSON.stringify(value ?? null)
373
380
  });
374
381
  toolUsages.push({
375
382
  name: tc.name,
@@ -7,3 +7,8 @@ export type TranslateNotice = (key: string, params?: Record<string, any>) => str
7
7
  * 답을 고치지 않고 **뒤에 붙인다** — 모델이 한 말을 우리가 다시 쓰지 않는다.
8
8
  */
9
9
  export declare function formatAbortNotice(abortReason: AgenticLoopResult<any>['abortReason'], t?: TranslateNotice): string;
10
+ /**
11
+ * The line for an answer cut at the output limit (`AgenticLoopResult.cutShort`), or nothing. Apart from the stop
12
+ * notice: the loop did not stop, the answer did -- an unattended run keeps its draft, and a person is told it is not all.
13
+ */
14
+ export declare function formatCutShortNotice(cutShort: boolean | undefined, t?: TranslateNotice): string;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.formatAbortNotice = formatAbortNotice;
4
+ exports.formatCutShortNotice = formatCutShortNotice;
4
5
  const index_js_1 = require("../utils/index.js");
5
6
  /** The English sentence for each reason, used when the caller has no translator. */
6
7
  const NOTICE_DEFAULTS = {
@@ -8,7 +9,8 @@ const NOTICE_DEFAULTS = {
8
9
  'ai-assistant.notice.provider-busy': 'the ai service did not answer just now. try again in a moment.',
9
10
  'ai-assistant.notice.provider-error': 'something went wrong while handling this. tell an administrator if it keeps happening.',
10
11
  'ai-assistant.notice.too-long': 'this stopped after {iter} lookups without an answer.',
11
- 'ai-assistant.notice.tool-kept-failing': '{tool} failed {count} times in a row, so it stopped. try saying it differently.'
12
+ 'ai-assistant.notice.tool-kept-failing': '{tool} failed {count} times in a row, so it stopped. try saying it differently.',
13
+ 'ai-assistant.notice.cut-short': 'this answer reached its length limit and was cut off.'
12
14
  };
13
15
  function line(key, params, t) {
14
16
  const said = t
@@ -41,4 +43,11 @@ function formatAbortNotice(abortReason, t) {
41
43
  return line('ai-assistant.notice.tool-kept-failing', { tool: abortReason.toolName, count: abortReason.consecutive }, t);
42
44
  }
43
45
  }
46
+ /**
47
+ * The line for an answer cut at the output limit (`AgenticLoopResult.cutShort`), or nothing. Apart from the stop
48
+ * notice: the loop did not stop, the answer did -- an unattended run keeps its draft, and a person is told it is not all.
49
+ */
50
+ function formatCutShortNotice(cutShort, t) {
51
+ return cutShort ? line('ai-assistant.notice.cut-short', {}, t) : '';
52
+ }
44
53
  //# sourceMappingURL=abort-notice.js.map
@@ -51,7 +51,7 @@ async function assistantChat(input) {
51
51
  const { groundingSources, skipGrounding, ...loopInput } = input;
52
52
  const loop = await (0, index_js_1.runAgenticLoop)(loopInput);
53
53
  const baseText = loop.lastText ?? '';
54
- const reply = baseText + (0, abort_notice_js_1.formatAbortNotice)(loop.abortReason, input.t);
54
+ const reply = baseText + (0, abort_notice_js_1.formatAbortNotice)(loop.abortReason, input.t) + (0, abort_notice_js_1.formatCutShortNotice)(loop.cutShort, input.t);
55
55
  let warnings;
56
56
  if (!skipGrounding && baseText) {
57
57
  const corpus = (0, index_js_2.buildGroundedCorpus)({ ...(groundingSources ?? {}), toolResults: loop.groundedTexts });
@@ -3,7 +3,7 @@ import { type ToolAccessCheck } from './tool-scope.js';
3
3
  import { type AssistantChatResult } from './assistant-chat.js';
4
4
  import type { GroundingSources } from '../utils/index.js';
5
5
  import type { ToolAttachment, UnattendedRunRef } from '../tool-registry/types.js';
6
- import { type ToolCallRecord } from '../tool-registry/call-recorder.js';
6
+ import type { ToolCallRecord } from '../tool-registry/call-recorder.js';
7
7
  import { type ToolFront } from './tool-budget.js';
8
8
  /** Lookups a registry conversation may take before it answers from what it has (operato-twin's assistant takes 16 too). */
9
9
  export declare const REGISTRY_MAX_ITERATIONS = 16;
@@ -6,7 +6,7 @@ const tool_scope_js_1 = require("./tool-scope.js");
6
6
  const assistant_chat_js_1 = require("./assistant-chat.js");
7
7
  const summarize_js_1 = require("./summarize.js");
8
8
  const translate_js_1 = require("../tool-registry/translate.js");
9
- const call_recorder_js_1 = require("../tool-registry/call-recorder.js");
9
+ const run_tool_js_1 = require("../tool-registry/run-tool.js");
10
10
  const tool_budget_js_1 = require("./tool-budget.js");
11
11
  /** Lookups a registry conversation may take before it answers from what it has (operato-twin's assistant takes 16 too). */
12
12
  exports.REGISTRY_MAX_ITERATIONS = 16;
@@ -58,17 +58,6 @@ async function registryAssistantChat(input) {
58
58
  ...(input.run ? { run: input.run } : {}),
59
59
  ...(input.conversation?.id ? { conversation: { id: input.conversation.id } } : {})
60
60
  };
61
- const recorded = async (run, context) => {
62
- if (input.onToolCall) {
63
- try {
64
- input.onToolCall((0, call_recorder_js_1.digestOf)(run));
65
- }
66
- catch (e) {
67
- console.warn(`[registry-assistant] onToolCall failed for ${run.tool}:`, e?.message ?? e);
68
- }
69
- }
70
- await (0, call_recorder_js_1.recordToolCall)(run, context);
71
- };
72
61
  const result = await (0, assistant_chat_js_1.assistantChat)({
73
62
  initialConversation: messages,
74
63
  tools,
@@ -104,18 +93,7 @@ async function registryAssistantChat(input) {
104
93
  const spec = offer.offered().find(one => one.name === call.name);
105
94
  if (!spec)
106
95
  return undefined;
107
- const args = call.arguments ?? {};
108
- const started = Date.now();
109
- const record = { tool: spec.name, category: categoryOf.get(spec.name) ?? '', args };
110
- try {
111
- const result = await spec.builder(args, context);
112
- await recorded({ ...record, result, durationMs: Date.now() - started }, context);
113
- return result;
114
- }
115
- catch (e) {
116
- await recorded({ ...record, error: e, durationMs: Date.now() - started }, context);
117
- throw e;
118
- }
96
+ return (0, run_tool_js_1.runRegisteredTool)({ spec, category: categoryOf.get(spec.name) ?? '', args: call.arguments ?? {}, context, onToolCall: input.onToolCall });
119
97
  },
120
98
  validateWriteToolCall: () => ({ valid: false, errors: ['this conversation has no document to write to'] }),
121
99
  toolCallToOp: () => null,
@@ -5,7 +5,10 @@ export declare class AnthropicAIClient implements AIClient {
5
5
  private defaultModel;
6
6
  constructor(config: AIClientConfig);
7
7
  chat(messages: AIMessage[], options?: AIChatOptions): Promise<string>;
8
- /** One request, the provider's response as it came: `generateJSON` reads whether it stopped at the output limit. */
8
+ /**
9
+ * One request, the provider's response as it came: `generateJSON` reads whether it stopped at the output limit, and
10
+ * `chatWithTools` adds its tools to the same body.
11
+ */
9
12
  private send;
10
13
  generateJSON<T = unknown>(prompt: string | AIMessage[], options?: AIJSONOptions): Promise<T>;
11
14
  vision(image: Buffer | Uint8Array | {
@@ -11,6 +11,7 @@ const tslib_1 = require("tslib");
11
11
  const sdk_1 = tslib_1.__importDefault(require("@anthropic-ai/sdk"));
12
12
  const factory_js_1 = require("../factory.js");
13
13
  const parse_json_js_1 = require("../utils/parse-json.js");
14
+ const common_js_1 = require("./common.js");
14
15
  const request_options_js_1 = require("./request-options.js");
15
16
  const usage_js_1 = require("./usage.js");
16
17
  const DEFAULT_MODEL = 'claude-sonnet-4-6';
@@ -27,79 +28,44 @@ class AnthropicAIClient {
27
28
  async chat(messages, options = {}) {
28
29
  return extractResponseText(await this.send(messages, options));
29
30
  }
30
- /** One request, the provider's response as it came: `generateJSON` reads whether it stopped at the output limit. */
31
- async send(messages, options) {
32
- const systemFromMessages = messages
33
- .filter(m => m.role === 'system')
34
- .map(extractTextContent)
35
- .filter(Boolean)
36
- .join('\n\n');
37
- const system = [options.systemPrompt, systemFromMessages].filter(Boolean).join('\n\n');
38
- const conversation = messages
39
- .filter(m => m.role !== 'system')
40
- .map(toAnthropicMessage);
31
+ /**
32
+ * One request, the provider's response as it came: `generateJSON` reads whether it stopped at the output limit, and
33
+ * `chatWithTools` adds its tools to the same body.
34
+ */
35
+ async send(messages, options, extra = {}) {
36
+ const system = (0, common_js_1.systemPromptOf)(messages, options.systemPrompt);
41
37
  const response = await this.sdk.messages.create({
42
38
  model: options.model ?? this.defaultModel,
43
39
  max_tokens: options.maxTokens ?? DEFAULT_MAX_TOKENS,
44
40
  ...(options.temperature !== undefined && { temperature: options.temperature }),
45
41
  ...(system && { system }),
46
42
  ...(options.stopSequences && { stop_sequences: options.stopSequences }),
47
- messages: conversation
43
+ messages: (0, common_js_1.turnsOf)(messages).map(toAnthropicMessage),
44
+ ...extra
48
45
  }, (0, request_options_js_1.requestOptionsOf)(options));
49
46
  reportUsage(response, options, options.model ?? this.defaultModel);
50
47
  return response;
51
48
  }
52
49
  async generateJSON(prompt, options = {}) {
53
50
  const messages = typeof prompt === 'string' ? [{ role: 'user', content: prompt }] : prompt;
54
- const schemaHint = options.schema
55
- ? `\n\nResponse MUST conform to this JSON schema:\n${JSON.stringify(options.schema)}`
56
- : '';
57
- const enforcedSystem = (options.systemPrompt ? options.systemPrompt + '\n\n' : '') +
58
- 'Return only valid JSON. No markdown code fences, no commentary.' +
59
- schemaHint;
60
- const response = await this.send(messages, { ...options, systemPrompt: enforcedSystem });
51
+ const response = await this.send(messages, { ...options, systemPrompt: (0, common_js_1.jsonSystemPrompt)(options) });
61
52
  return (0, parse_json_js_1.parseJSONResponse)(extractResponseText(response), { cutShort: response?.stop_reason === 'max_tokens' });
62
53
  }
63
54
  async vision(image, prompt, options = {}) {
64
- const imagePart = typeof image === 'object' && 'url' in image
65
- ? { type: 'image', source: { kind: 'url', url: image.url } }
66
- : {
67
- type: 'image',
68
- source: { kind: 'base64', data: image, mediaType: 'image/png' }
69
- };
70
- return this.chat([{ role: 'user', content: [imagePart, { type: 'text', text: prompt }] }], options);
55
+ return this.chat((0, common_js_1.visionTurn)(image, prompt), options);
71
56
  }
72
57
  async chatWithTools(messages, tools, options = {}) {
73
- const systemFromMessages = messages
74
- .filter(m => m.role === 'system')
75
- .map(extractTextContent)
76
- .filter(Boolean)
77
- .join('\n\n');
78
- const system = [options.systemPrompt, systemFromMessages].filter(Boolean).join('\n\n');
79
- const conversation = messages.filter(m => m.role !== 'system').map(toAnthropicMessage);
80
- const sdkTools = tools.map(t => ({
81
- name: t.name,
82
- description: t.description,
83
- input_schema: t.parameters
84
- }));
85
58
  const toolChoice = buildAnthropicToolChoice(options);
86
- const response = await this.sdk.messages.create({
87
- model: options.model ?? this.defaultModel,
88
- max_tokens: options.maxTokens ?? DEFAULT_MAX_TOKENS,
89
- ...(options.temperature !== undefined && { temperature: options.temperature }),
90
- ...(system && { system }),
91
- ...(options.stopSequences && { stop_sequences: options.stopSequences }),
92
- messages: conversation,
93
- tools: sdkTools,
59
+ const response = await this.send(messages, options, {
60
+ tools: tools.map(t => ({ name: t.name, description: t.description, input_schema: t.parameters })),
94
61
  ...(toolChoice && { tool_choice: toolChoice })
95
- }, (0, request_options_js_1.requestOptionsOf)(options));
96
- reportUsage(response, options, options.model ?? this.defaultModel);
62
+ });
97
63
  const text = extractResponseText(response) || undefined;
98
64
  const toolCalls = Array.isArray(response.content)
99
65
  ? response.content
100
66
  .filter((b) => b && b.type === 'tool_use')
101
67
  .map((b) => ({
102
- id: typeof b.id === 'string' && b.id ? b.id : `call_${Math.random().toString(36).slice(2, 12)}`,
68
+ id: typeof b.id === 'string' && b.id ? b.id : (0, common_js_1.madeCallId)(),
103
69
  name: b.name,
104
70
  arguments: (b.input && typeof b.input === 'object' ? b.input : {})
105
71
  }))
@@ -123,14 +89,6 @@ function reportUsage(response, options, requested) {
123
89
  options.onUsage?.((0, usage_js_1.anthropicUsageOf)(response?.model ?? requested, response?.usage));
124
90
  }
125
91
  // ── 변환 유틸 ─────────────────────────────────────────────────────────
126
- function extractTextContent(msg) {
127
- if (typeof msg.content === 'string')
128
- return msg.content;
129
- return msg.content
130
- .filter(p => p.type === 'text')
131
- .map(p => p.text)
132
- .join('\n');
133
- }
134
92
  function toAnthropicMessage(msg) {
135
93
  if (typeof msg.content === 'string') {
136
94
  return { role: msg.role, content: msg.content };
@@ -159,12 +117,9 @@ function toAnthropicContentBlock(part) {
159
117
  if (part.source.kind === 'url') {
160
118
  return { type: 'image', source: { type: 'url', url: part.source.url } };
161
119
  }
162
- const data = Buffer.isBuffer(part.source.data)
163
- ? part.source.data.toString('base64')
164
- : Buffer.from(part.source.data).toString('base64');
165
120
  return {
166
121
  type: 'image',
167
- source: { type: 'base64', media_type: part.source.mediaType, data }
122
+ source: { type: 'base64', media_type: part.source.mediaType, data: (0, common_js_1.base64Of)(part.source.data) }
168
123
  };
169
124
  }
170
125
  function extractResponseText(response) {
@@ -0,0 +1,3 @@
1
+ import type { AITool } from '../types.js';
2
+ /** What the server answers one JSON-RPC message; undefined for a notification. */
3
+ export declare function answerOf(message: any, tools: AITool[]): object | undefined;
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.answerOf = answerOf;
4
+ /**
5
+ * The tools of one Claude Code request, listed as an MCP server that runs none of them (2026-11-14).
6
+ *
7
+ * The claude-code provider offers a turn's tools to the CLI this way so the model calls them as it calls any tool --
8
+ * natively, as tool_use -- and the provider reads those calls from the turn and stops it there. What a call does is the
9
+ * assistant loop's business, as with every other provider: here a call only answers that its result comes later.
10
+ *
11
+ * Run as `node claude-code-tools-mcp.js` with CLAUDE_CODE_TOOLS naming a JSON file of AITool.
12
+ */
13
+ const fs_1 = require("fs");
14
+ const readline_1 = require("readline");
15
+ /** What the server answers one JSON-RPC message; undefined for a notification. */
16
+ function answerOf(message, tools) {
17
+ if (!message || message.id === undefined)
18
+ return undefined;
19
+ const reply = (result) => ({ jsonrpc: '2.0', id: message.id, result });
20
+ switch (message.method) {
21
+ case 'initialize':
22
+ return reply({
23
+ protocolVersion: message.params?.protocolVersion ?? '2025-06-18',
24
+ capabilities: { tools: {} },
25
+ serverInfo: { name: 'app', version: '1' }
26
+ });
27
+ case 'tools/list':
28
+ return reply({
29
+ tools: tools.map(tool => ({
30
+ name: tool.name,
31
+ description: tool.description,
32
+ inputSchema: tool.parameters?.type === 'object' ? tool.parameters : { type: 'object', properties: {} }
33
+ }))
34
+ });
35
+ case 'tools/call':
36
+ return reply({ content: [{ type: 'text', text: 'Deferred: the result comes back in the next turn.' }] });
37
+ default:
38
+ return reply({});
39
+ }
40
+ }
41
+ if (require.main === module) {
42
+ const tools = JSON.parse((0, fs_1.readFileSync)(process.env.CLAUDE_CODE_TOOLS, 'utf-8'));
43
+ (0, readline_1.createInterface)({ input: process.stdin }).on('line', line => {
44
+ let message;
45
+ try {
46
+ message = JSON.parse(line);
47
+ }
48
+ catch {
49
+ return;
50
+ }
51
+ const answer = answerOf(message, tools);
52
+ if (answer)
53
+ process.stdout.write(JSON.stringify(answer) + '\n');
54
+ });
55
+ }
56
+ //# sourceMappingURL=claude-code-tools-mcp.js.map
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Claude Code, logged in on this machine, as a provider (2026-11-13, the person: an option to use Claude logged in
3
+ * locally, picked in the AI assistant like any other model). For development: the dev server only, on the account of
4
+ * whoever logged in the `claude` CLI here -- never a product's server, which has neither (aiProviderAvailable).
5
+ *
6
+ * Called as an API is: our system prompt alone (Claude Code's own replaced), no Claude Code tools, no settings, no
7
+ * memory, a fresh empty folder, no session kept -- one stateless request per call. Pictures are not carried.
8
+ *
9
+ * ── How a tool is called (2026-11-14) ──────────────────────────────────────────────────────────────────────────────
10
+ * 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:
11
+ *
12
+ * native (the default) The turn's tools are listed to the CLI by an MCP server that runs none of them
13
+ * (claude-code-tools-mcp.ts). The model calls them as it calls any tool; its first turn is read from the
14
+ * stream and the request ends there (--max-turns 1). What a call does is the loop's business.
15
+ * schema Without MCP -- chosen (toolCalls: 'schema', or AI_CLAUDE_CODE_TOOL_CALLS=schema), or when the tool server
16
+ * does not connect. The answer is held to a JSON schema: the calls to make and the words to say.
17
+ *
18
+ * Measured on the dock's own prompt and tools, opus, sonnet and haiku, 8 requests each (2026-11-14): native 24 of 24,
19
+ * 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,
20
+ * was told there were none, and answered that it could not look. Asked for JSON in the prompt alone (the way before),
21
+ * it wrote its calls in prose, in tags, as a bare list: each one a call lost and an empty bubble.
22
+ */
23
+ import { type ChildProcessWithoutNullStreams } from 'child_process';
24
+ import type { AIClient, AIClientConfig } from '../types.js';
25
+ export interface ClaudeCodeRunner {
26
+ (args: string[], input: string, cwd: string, signal?: AbortSignal): Promise<string>;
27
+ }
28
+ /**
29
+ * The `claude` CLI started in a folder, as every caller on this server starts it -- this provider, and the figure agent
30
+ * that runs it with the figure MCP server (figure-service).
31
+ */
32
+ export declare function startClaudeCode(args: string[], cwd: string): ChildProcessWithoutNullStreams;
33
+ /**
34
+ * Offered only where it can answer and where it belongs: a development server whose machine has the `claude` CLI
35
+ * logged in. A production server is never one (NODE_ENV production), and has no logged-in CLI either.
36
+ */
37
+ export declare function claudeCodeAvailable(): boolean;
38
+ export declare function createClaudeCodeClient(config: AIClientConfig, runner?: ClaudeCodeRunner): AIClient;