clanka 0.16.0 → 0.17.0

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 (65) hide show
  1. package/README.md +61 -0
  2. package/dist/Agent.d.ts.map +1 -1
  3. package/dist/Agent.js +5 -1
  4. package/dist/Agent.js.map +1 -1
  5. package/dist/ClaudeAgent.d.ts +111 -0
  6. package/dist/ClaudeAgent.d.ts.map +1 -0
  7. package/dist/ClaudeAgent.js +772 -0
  8. package/dist/ClaudeAgent.js.map +1 -0
  9. package/dist/ClaudeAgent.test.d.ts +2 -0
  10. package/dist/ClaudeAgent.test.d.ts.map +1 -0
  11. package/dist/ClaudeAgent.test.js +416 -0
  12. package/dist/ClaudeAgent.test.js.map +1 -0
  13. package/dist/ModelLayer.d.ts +2 -2
  14. package/dist/ModelLayer.d.ts.map +1 -1
  15. package/dist/ModelLayer.js +13 -7
  16. package/dist/ModelLayer.js.map +1 -1
  17. package/dist/ModelLayer.test.js +3 -0
  18. package/dist/ModelLayer.test.js.map +1 -1
  19. package/dist/ModelsRepo.d.ts +7 -4
  20. package/dist/ModelsRepo.d.ts.map +1 -1
  21. package/dist/ModelsRepo.js +44 -19
  22. package/dist/ModelsRepo.js.map +1 -1
  23. package/dist/ModelsRepo.test.js +86 -9
  24. package/dist/ModelsRepo.test.js.map +1 -1
  25. package/dist/bin/{Effect-4B1lzxy4.mjs → Effect-On-1ks2z.mjs} +50 -2
  26. package/dist/bin/Effect-On-1ks2z.mjs.map +1 -0
  27. package/dist/bin/{McpClient-DMfHHEx3.mjs → McpClient-iwrW83Si.mjs} +3 -3
  28. package/dist/bin/{McpClient-DMfHHEx3.mjs.map → McpClient-iwrW83Si.mjs.map} +1 -1
  29. package/dist/bin/{OutputFormatter-DRycCEdr.mjs → OutputFormatter-DeNaqhQM.mjs} +3 -3
  30. package/dist/bin/{OutputFormatter-DRycCEdr.mjs.map → OutputFormatter-DeNaqhQM.mjs.map} +1 -1
  31. package/dist/bin/{Schema-D4fxUgEU.mjs → Schema-B3pFcw4E.mjs} +2 -2
  32. package/dist/bin/{Schema-D4fxUgEU.mjs.map → Schema-B3pFcw4E.mjs.map} +1 -1
  33. package/dist/bin/{SemanticSearch-BcLFv9qz.mjs → SemanticSearch-BZIXkWYz.mjs} +4 -4
  34. package/dist/bin/{SemanticSearch-BcLFv9qz.mjs.map → SemanticSearch-BZIXkWYz.mjs.map} +1 -1
  35. package/dist/bin/{Stream-i37nF1ep.mjs → Stream-DCB3_nIX.mjs} +91 -12
  36. package/dist/bin/Stream-DCB3_nIX.mjs.map +1 -0
  37. package/dist/bin/cli.mjs +1255 -12860
  38. package/dist/bin/cli.mjs.map +1 -1
  39. package/dist/bin/helpers-BPLUsjsL.mjs +7191 -0
  40. package/dist/bin/helpers-BPLUsjsL.mjs.map +1 -0
  41. package/dist/bin/{rolldown-runtime-zY4HT0JA.mjs → rolldown-runtime-Cjv6nE1W.mjs} +14 -1
  42. package/dist/bin/server-CBmuybpI.mjs +321 -0
  43. package/dist/bin/server-CBmuybpI.mjs.map +1 -0
  44. package/dist/bin/{turndown.cjs-LntFxFyd.mjs → turndown.cjs-cie0BXQQ.mjs} +2 -2
  45. package/dist/bin/{turndown.cjs-LntFxFyd.mjs.map → turndown.cjs-cie0BXQQ.mjs.map} +1 -1
  46. package/dist/bin/types-RT_9fFNm.mjs +5278 -0
  47. package/dist/bin/types-RT_9fFNm.mjs.map +1 -0
  48. package/dist/cli.js +4 -0
  49. package/dist/cli.js.map +1 -1
  50. package/dist/index.d.ts +4 -0
  51. package/dist/index.d.ts.map +1 -1
  52. package/dist/index.js +4 -0
  53. package/dist/index.js.map +1 -1
  54. package/package.json +9 -1
  55. package/src/Agent.ts +7 -1
  56. package/src/ClaudeAgent.test.ts +526 -0
  57. package/src/ClaudeAgent.ts +1113 -0
  58. package/src/ModelLayer.test.ts +4 -0
  59. package/src/ModelLayer.ts +21 -15
  60. package/src/ModelsRepo.test.ts +123 -9
  61. package/src/ModelsRepo.ts +53 -26
  62. package/src/cli.ts +4 -0
  63. package/src/index.ts +5 -0
  64. package/dist/bin/Effect-4B1lzxy4.mjs.map +0 -1
  65. package/dist/bin/Stream-i37nF1ep.mjs.map +0 -1
@@ -0,0 +1,772 @@
1
+ import * as Array from "effect/Array";
2
+ import * as Effect from "effect/Effect";
3
+ import * as Base64 from "effect/encoding/Base64";
4
+ import * as Exit from "effect/Exit";
5
+ import * as Layer from "effect/Layer";
6
+ import * as Option from "effect/Option";
7
+ import * as Queue from "effect/Queue";
8
+ import * as Scope from "effect/Scope";
9
+ import * as Stream from "effect/Stream";
10
+ import * as AiError from "effect/ai/AiError";
11
+ import * as LanguageModel from "effect/ai/LanguageModel";
12
+ import * as Model from "effect/ai/Model";
13
+ import * as Prompt from "effect/ai/Prompt";
14
+ import * as Tool from "effect/ai/Tool";
15
+ import * as Fs from "node:fs";
16
+ import * as Path from "node:path";
17
+ import { isDeepStrictEqual } from "node:util";
18
+ import packageJson from "../package.json" with { type: "json" };
19
+ import { AgentModelConfig } from "./Agent.js";
20
+ import * as Image from "./Image.js";
21
+ /**
22
+ * The oldest Claude Code release clanka runs: the first to honour
23
+ * `verbatimPrompts`.
24
+ *
25
+ * @since 1.0.0
26
+ * @category Claude Code
27
+ */
28
+ export const minimumClaudeCodeVersion = "2.1.248";
29
+ const serverName = "clanka";
30
+ const toolPrefix = `mcp__${serverName}__`;
31
+ // Claude Code features that duplicate clanka's, or would hide its tool.
32
+ const isolationEnv = {
33
+ CLAUDE_CODE_DISABLE_CLAUDE_MDS: "1",
34
+ CLAUDE_CODE_DISABLE_AUTO_MEMORY: "1",
35
+ // clanka compacts its own history.
36
+ DISABLE_AUTO_COMPACT: "1",
37
+ CLAUDE_CODE_ENABLE_AWAY_SUMMARY: "0",
38
+ // Tool search would defer clanka's only tool.
39
+ ENABLE_TOOL_SEARCH: "false",
40
+ CLAUDE_CODE_DISABLE_ADVISOR_TOOL: "1",
41
+ // clanka caps tool output itself.
42
+ MAX_MCP_OUTPUT_TOKENS: "200000",
43
+ // Skips OAuth, so a subscription login would not be used.
44
+ CLAUDE_CODE_SIMPLE: undefined,
45
+ // Would override the effort clanka sends.
46
+ CLAUDE_CODE_EFFORT_LEVEL: undefined,
47
+ // Would cap every `execute` call.
48
+ MCP_TOOL_TIMEOUT: undefined,
49
+ };
50
+ /**
51
+ * The Claude Agent SDK options for a session: Claude Code runs with none of
52
+ * its own tools, settings, hooks, memory, skills or transcripts, and with the
53
+ * system prompt from `prompt`.
54
+ *
55
+ * @since 1.0.0
56
+ * @category Claude Code
57
+ */
58
+ export const queryOptions = (options) => ({
59
+ pathToClaudeCodeExecutable: options.pathToClaudeCodeExecutable,
60
+ cwd: options.cwd,
61
+ model: options.model,
62
+ ...effortOptions(options.effort),
63
+ systemPrompt: { type: "custom", prompt: systemText(options.prompt) },
64
+ env: {
65
+ ...process.env,
66
+ ...isolationEnv,
67
+ CLAUDE_AGENT_SDK_CLIENT_APP: `clanka/${packageJson.version}`,
68
+ },
69
+ settingSources: [],
70
+ settings: { disableAllHooks: true },
71
+ strictMcpConfig: true,
72
+ skills: [],
73
+ tools: [],
74
+ permissionMode: "dontAsk",
75
+ allowedTools: [`${toolPrefix}*`],
76
+ verbatimPrompts: true,
77
+ includePartialMessages: true,
78
+ persistSession: false,
79
+ });
80
+ const efforts = new Set([
81
+ "low",
82
+ "medium",
83
+ "high",
84
+ "xhigh",
85
+ "max",
86
+ ]);
87
+ const effortOptions = (effort) => {
88
+ if (effort === "none")
89
+ return { thinking: { type: "disabled" } };
90
+ const thinking = { type: "adaptive", display: "summarized" };
91
+ if (effort === "minimal")
92
+ return { thinking, effort: "low" };
93
+ return effort !== null && effort !== undefined && efforts.has(effort)
94
+ ? { thinking, effort: effort }
95
+ : { thinking };
96
+ };
97
+ const systemText = (prompt) => prompt.content
98
+ .flatMap((message) => (message.role === "system" ? [message.content] : []))
99
+ .join("\n\n");
100
+ const render = (value) => typeof value === "string" ? value : JSON.stringify(value);
101
+ const renderParams = (params) => typeof params === "object" && params !== null && !Array.isArray(params)
102
+ ? Object.entries(params)
103
+ .map(([key, value]) => `<${key}>\n${render(value)}\n</${key}>`)
104
+ .join("\n")
105
+ : render(params);
106
+ /**
107
+ * A prompt as the content of one Claude Code user message. A `query()` takes
108
+ * no assistant history, so when the prompt has earlier turns each message is
109
+ * wrapped in a `<role>` tag. Images become image blocks; the system message
110
+ * is left out, it goes in `queryOptions`.
111
+ *
112
+ * @since 1.0.0
113
+ * @category Messages
114
+ */
115
+ export const toUserContent = (prompt) => {
116
+ const blocks = [];
117
+ let text = [];
118
+ const flush = () => {
119
+ if (text.length === 0)
120
+ return;
121
+ blocks.push({ type: "text", text: text.join("\n") });
122
+ text = [];
123
+ };
124
+ const history = prompt.content.some((message) => message.role === "assistant" || message.role === "tool");
125
+ for (const message of prompt.content) {
126
+ if (message.role === "system")
127
+ continue;
128
+ if (history)
129
+ text.push(`<${message.role}>`);
130
+ for (const part of message.content) {
131
+ switch (part.type) {
132
+ case "text":
133
+ text.push(part.text);
134
+ break;
135
+ case "file": {
136
+ const bytes = Image.isImageMediaType(part.mediaType)
137
+ ? Image.partBytes(part)
138
+ : Option.none();
139
+ if (Option.isNone(bytes)) {
140
+ text.push(`[file ${part.fileName ?? ""} (${part.mediaType}) omitted]`);
141
+ break;
142
+ }
143
+ flush();
144
+ blocks.push({
145
+ type: "image",
146
+ source: {
147
+ type: "base64",
148
+ media_type: part.mediaType,
149
+ data: Base64.encode(bytes.value),
150
+ },
151
+ });
152
+ break;
153
+ }
154
+ case "tool-call":
155
+ text.push(`<tool-call id="${part.id}" name="${part.name}">\n${renderParams(part.params)}\n</tool-call>`);
156
+ break;
157
+ case "tool-result":
158
+ text.push(`<tool-result id="${part.id}" name="${part.name}"${part.isFailure ? ' failed="true"' : ""}>\n${render(part.result)}\n</tool-result>`);
159
+ break;
160
+ }
161
+ }
162
+ if (history)
163
+ text.push(`</${message.role}>`);
164
+ }
165
+ flush();
166
+ return blocks;
167
+ };
168
+ // Claude Code reports the same API message several times, so each count
169
+ // keeps its maximum per message. Context size is the last call's input.
170
+ const makeUsage = () => {
171
+ const messages = new Map();
172
+ let last;
173
+ return {
174
+ update(id, usage) {
175
+ if (usage === null || usage === undefined)
176
+ return;
177
+ let counts = messages.get(id);
178
+ if (counts === undefined) {
179
+ counts = { input: 0, read: 0, write: 0, output: 0 };
180
+ messages.set(id, counts);
181
+ last = id;
182
+ }
183
+ counts.input = Math.max(counts.input, usage.input_tokens ?? 0);
184
+ counts.read = Math.max(counts.read, usage.cache_read_input_tokens ?? 0);
185
+ counts.write = Math.max(counts.write, usage.cache_creation_input_tokens ?? 0);
186
+ counts.output = Math.max(counts.output, usage.output_tokens ?? 0);
187
+ },
188
+ // The result's usage sums the whole Claude Code turn, so it only counts
189
+ // when this step saw no API message.
190
+ result(usage) {
191
+ if (messages.size === 0)
192
+ this.update("result", usage);
193
+ },
194
+ snapshot() {
195
+ let output = 0;
196
+ for (const counts of messages.values())
197
+ output += counts.output;
198
+ const lastCall = last === undefined ? undefined : messages.get(last);
199
+ return {
200
+ inputTokens: {
201
+ uncached: lastCall?.input,
202
+ total: lastCall === undefined
203
+ ? undefined
204
+ : lastCall.input + lastCall.read + lastCall.write,
205
+ cacheRead: lastCall?.read,
206
+ cacheWrite: lastCall?.write,
207
+ },
208
+ outputTokens: { total: output },
209
+ };
210
+ },
211
+ };
212
+ };
213
+ const aiError = (reason) => AiError.make({ module: "ClaudeAgent", method: "streamText", reason });
214
+ const unknownError = (description) => aiError(new AiError.UnknownError({ description }));
215
+ const resultError = (message, code) => {
216
+ const status = message.subtype === "success" ? message.api_error_status : undefined;
217
+ if (message.subtype === "success" &&
218
+ !message.is_error &&
219
+ (status === undefined || status === null || status < 400)) {
220
+ return undefined;
221
+ }
222
+ const description = (message.subtype === "success"
223
+ ? message.result
224
+ : message.errors.join("\n")).replaceAll("Please run /login", "Run `claude auth login`") ||
225
+ `Claude Code could not finish its reply${status ? ` (HTTP ${status})` : ""}`;
226
+ switch (code) {
227
+ case "authentication_failed":
228
+ case "oauth_org_not_allowed":
229
+ return aiError(new AiError.AuthenticationError({ kind: "Unknown", description }));
230
+ case "invalid_request":
231
+ return aiError(new AiError.InvalidRequestError({ description }));
232
+ }
233
+ // Claude Code has already retried, so nothing here is retryable.
234
+ return aiError(/prompt is too long/i.test(description)
235
+ ? new AiError.InvalidRequestError({ description })
236
+ : new AiError.UnknownError({ description }));
237
+ };
238
+ const makeConverter = () => {
239
+ const usage = makeUsage();
240
+ const streamed = new Set();
241
+ const blocks = new Map();
242
+ let messageId = "";
243
+ let calledTools = false;
244
+ let errorCode;
245
+ return (message) => {
246
+ const parts = [];
247
+ if (message.type === "stream_event" &&
248
+ message.parent_tool_use_id === null) {
249
+ const event = message.event;
250
+ switch (event.type) {
251
+ case "message_start":
252
+ messageId = event.message.id;
253
+ streamed.add(messageId);
254
+ usage.update(messageId, event.message.usage);
255
+ break;
256
+ case "content_block_start": {
257
+ const id = `${messageId}:${event.index}`;
258
+ const block = event.content_block;
259
+ if (block.type === "text") {
260
+ blocks.set(event.index, "text");
261
+ parts.push({ type: "text-start", id });
262
+ if (block.text)
263
+ parts.push({ type: "text-delta", id, delta: block.text });
264
+ }
265
+ else if (block.type === "thinking") {
266
+ blocks.set(event.index, "reasoning");
267
+ parts.push({ type: "reasoning-start", id });
268
+ if (block.thinking) {
269
+ parts.push({ type: "reasoning-delta", id, delta: block.thinking });
270
+ }
271
+ }
272
+ break;
273
+ }
274
+ case "content_block_delta": {
275
+ const id = `${messageId}:${event.index}`;
276
+ const delta = event.delta;
277
+ if (delta.type === "text_delta") {
278
+ parts.push({ type: "text-delta", id, delta: delta.text });
279
+ }
280
+ else if (delta.type === "thinking_delta" && delta.thinking) {
281
+ parts.push({ type: "reasoning-delta", id, delta: delta.thinking });
282
+ }
283
+ break;
284
+ }
285
+ case "content_block_stop": {
286
+ const kind = blocks.get(event.index);
287
+ if (kind !== undefined) {
288
+ parts.push({
289
+ type: `${kind}-end`,
290
+ id: `${messageId}:${event.index}`,
291
+ });
292
+ blocks.delete(event.index);
293
+ }
294
+ break;
295
+ }
296
+ case "message_delta":
297
+ usage.update(messageId, event.usage);
298
+ break;
299
+ case "message_stop":
300
+ // The step ends once Claude has called clanka's tool: its handler
301
+ // waits for the result of the next step.
302
+ if (calledTools) {
303
+ parts.push({
304
+ type: "finish",
305
+ reason: "tool-calls",
306
+ usage: usage.snapshot(),
307
+ });
308
+ }
309
+ break;
310
+ }
311
+ }
312
+ else if (message.type === "assistant" &&
313
+ message.parent_tool_use_id === null) {
314
+ // Synthetic API error messages are diagnostics; the result reports
315
+ // the failure.
316
+ if (message.error !== undefined) {
317
+ errorCode = message.error;
318
+ return Effect.succeed(parts);
319
+ }
320
+ usage.update(message.message.id, message.message.usage);
321
+ // Assistant messages repeat streamed content, so only use their text
322
+ // when nothing was streamed.
323
+ const replay = !streamed.has(message.message.id);
324
+ message.message.content.forEach((block, index) => {
325
+ const id = `${message.uuid}:${index}`;
326
+ if (block.type === "tool_use") {
327
+ // Claude Code answers calls to tools clanka did not offer itself.
328
+ if (!block.name.startsWith(toolPrefix))
329
+ return;
330
+ calledTools = true;
331
+ parts.push({
332
+ type: "tool-call",
333
+ id: block.id,
334
+ name: block.name.slice(toolPrefix.length),
335
+ params: block.input,
336
+ providerExecuted: false,
337
+ });
338
+ }
339
+ else if (replay && block.type === "text") {
340
+ parts.push({ type: "text-start", id }, { type: "text-delta", id, delta: block.text }, { type: "text-end", id });
341
+ }
342
+ else if (replay && block.type === "thinking") {
343
+ parts.push({ type: "reasoning-start", id }, { type: "reasoning-delta", id, delta: block.thinking }, { type: "reasoning-end", id });
344
+ }
345
+ });
346
+ }
347
+ else if (message.type === "result") {
348
+ const error = resultError(message, errorCode);
349
+ if (error !== undefined)
350
+ return Effect.fail(error);
351
+ usage.result(message.usage);
352
+ parts.push({
353
+ type: "finish",
354
+ reason: message.stop_reason === "max_tokens" ? "length" : "stop",
355
+ usage: usage.snapshot(),
356
+ });
357
+ }
358
+ return Effect.succeed(parts);
359
+ };
360
+ };
361
+ /**
362
+ * Converts the Claude Agent SDK messages of one model step to response
363
+ * parts, ending at the step's `finish` part. A step ends when Claude Code
364
+ * finishes its turn, or after an API message that called clanka's tools.
365
+ *
366
+ * @since 1.0.0
367
+ * @category Messages
368
+ */
369
+ export const toStreamParts = (self) => Stream.suspend(() => {
370
+ const convert = makeConverter();
371
+ return self.pipe(Stream.mapEffect(convert), Stream.flattenIterable, Stream.takeUntil((part) => part.type === "finish"));
372
+ });
373
+ // =============================================================================
374
+ // Sessions
375
+ // =============================================================================
376
+ const userMessage = (content, priority) => ({
377
+ type: "user",
378
+ message: { role: "user", content: content },
379
+ parent_tool_use_id: null,
380
+ ...(priority === undefined ? {} : { priority }),
381
+ });
382
+ const errorResult = (text) => ({
383
+ isError: true,
384
+ content: [{ type: "text", text }],
385
+ });
386
+ // The parked tool calls, keyed by the tool use id Claude Code tags each MCP
387
+ // call with. `onCall` reports each request as it arrives, `undefined` for an
388
+ // untagged one. A handler waits until the next step resolves its call with
389
+ // clanka's result.
390
+ const makeToolBridge = (onCall) => {
391
+ const calls = new Map();
392
+ const entry = (id) => {
393
+ let call = calls.get(id);
394
+ if (call === undefined) {
395
+ call = Promise.withResolvers();
396
+ calls.set(id, call);
397
+ }
398
+ return call;
399
+ };
400
+ return {
401
+ async call(id) {
402
+ onCall(id);
403
+ // Never guess which call an untagged request is.
404
+ if (id === undefined)
405
+ return errorResult("Missing tool use id");
406
+ const result = await entry(id).promise;
407
+ calls.delete(id);
408
+ return result;
409
+ },
410
+ resolve(id, result) {
411
+ entry(id).resolve(result);
412
+ },
413
+ cancel() {
414
+ for (const call of calls.values())
415
+ call.resolve(errorResult("Cancelled"));
416
+ calls.clear();
417
+ },
418
+ };
419
+ };
420
+ const makeToolServer = (tools, bridge) => Effect.tryPromise({
421
+ try: async () => {
422
+ // Loaded on first use, like the SDK.
423
+ const [{ Server }, { CallToolRequestSchema, ListToolsRequestSchema }] = await Promise.all([
424
+ import("@modelcontextprotocol/sdk/server/index.js"),
425
+ import("@modelcontextprotocol/sdk/types.js"),
426
+ ]);
427
+ const server = new Server({ name: serverName, version: packageJson.version }, { capabilities: { tools: {} } });
428
+ const definitions = tools.map((tool) => ({
429
+ name: tool.name,
430
+ description: Tool.getDescription(tool) ?? "",
431
+ inputSchema: Tool.getJsonSchema(tool),
432
+ annotations: { readOnlyHint: false },
433
+ _meta: { "anthropic/alwaysLoad": true },
434
+ }));
435
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
436
+ tools: definitions,
437
+ }));
438
+ server.setRequestHandler(CallToolRequestSchema, (request) => {
439
+ const toolUseId = request.params._meta?.["claudecode/toolUseId"];
440
+ return bridge.call(typeof toolUseId === "string" ? toolUseId : undefined);
441
+ });
442
+ return {
443
+ type: "sdk",
444
+ name: serverName,
445
+ // The SDK names the high-level McpServer, but connects any server.
446
+ instance: server,
447
+ };
448
+ },
449
+ catch: (cause) => unknownError(`Failed to start the clanka MCP server: ${String(cause)}`),
450
+ });
451
+ const loadSdk = Effect.tryPromise({
452
+ try: () => import("@anthropic-ai/claude-agent-sdk"),
453
+ catch: () => unknownError("The claude provider needs @anthropic-ai/claude-agent-sdk. Install it next to clanka."),
454
+ });
455
+ const executableNames = process.platform === "win32" ? ["claude.exe", "claude.cmd"] : ["claude"];
456
+ const isExecutable = (path) => {
457
+ try {
458
+ Fs.accessSync(path, Fs.constants.X_OK);
459
+ return true;
460
+ }
461
+ catch {
462
+ return false;
463
+ }
464
+ };
465
+ const findExecutable = Effect.suspend(() => {
466
+ const found = process.env.CLANKA_CLAUDE_PATH ||
467
+ (process.env.PATH ?? "")
468
+ .split(Path.delimiter)
469
+ .flatMap((dir) => executableNames.map((name) => Path.join(dir, name)))
470
+ .find(isExecutable);
471
+ return found === undefined
472
+ ? Effect.fail(unknownError("Claude Code was not found. Install Claude Code and run `claude auth login`, or set CLANKA_CLAUDE_PATH."))
473
+ : Effect.succeed(found);
474
+ });
475
+ const compareVersions = (a, b) => {
476
+ const left = a.split(/[.-]/).map(Number);
477
+ const right = b.split(/[.-]/).map(Number);
478
+ for (let i = 0; i < 3; i++) {
479
+ const diff = (left[i] ?? 0) - (right[i] ?? 0);
480
+ if (diff !== 0)
481
+ return diff;
482
+ }
483
+ return 0;
484
+ };
485
+ const closeSession = (session) => Effect.suspend(() => {
486
+ session.bridge.cancel();
487
+ session.query.close();
488
+ return Queue.end(session.input).pipe(Effect.andThen(Scope.close(session.scope, Exit.void)));
489
+ });
490
+ const startSession = Effect.fnUntraced(function* (model, options, provider, withTools) {
491
+ const query = options?.query ?? (yield* loadSdk).query;
492
+ const executable = options?.executable ?? (yield* findExecutable);
493
+ const messages = yield* Queue.make();
494
+ const bridge = makeToolBridge((id) => {
495
+ Queue.offerUnsafe(messages, { type: "clanka_parked", id });
496
+ });
497
+ const mcpServers = withTools
498
+ ? { [serverName]: yield* makeToolServer(provider.tools, bridge) }
499
+ : {};
500
+ const input = yield* Queue.make();
501
+ Queue.offerUnsafe(input, userMessage(toUserContent(provider.prompt)));
502
+ if (!withTools)
503
+ yield* Queue.end(input);
504
+ const session = query({
505
+ prompt: Stream.toAsyncIterable(Stream.fromQueue(input)),
506
+ options: {
507
+ ...queryOptions({
508
+ model,
509
+ prompt: provider.prompt,
510
+ cwd: options?.cwd ?? process.cwd(),
511
+ pathToClaudeCodeExecutable: executable,
512
+ effort: options?.effort,
513
+ }),
514
+ mcpServers,
515
+ },
516
+ });
517
+ const scope = yield* Scope.make();
518
+ yield* Stream.fromAsyncIterable(session, (cause) => unknownError(`Claude Code failed: ${String(cause)}`)).pipe(Stream.runForEach((message) => Queue.offer(messages, message)), Effect.matchCauseEffect({
519
+ onSuccess: () => Queue.end(messages),
520
+ onFailure: (cause) => Queue.failCause(messages, cause),
521
+ }), Effect.forkIn(scope));
522
+ const live = {
523
+ query: session,
524
+ input,
525
+ bridge,
526
+ messages,
527
+ scope,
528
+ toolNames: provider.tools.map((tool) => tool.name).join(","),
529
+ seen: provider.prompt.content,
530
+ outcome: undefined,
531
+ };
532
+ yield* Effect.tryPromise({
533
+ try: () => session.initializationResult(),
534
+ catch: (cause) => unknownError(`Claude Code failed to start: ${String(cause)}`),
535
+ }).pipe(Effect.flatMap((init) => init.claude_code_version !== undefined &&
536
+ compareVersions(init.claude_code_version, minimumClaudeCodeVersion) < 0
537
+ ? Effect.fail(unknownError(`Claude Code ${init.claude_code_version} is too old, clanka needs ${minimumClaudeCodeVersion} or later. Run \`claude update\`.`))
538
+ : Effect.void), Effect.onError(() => closeSession(live)));
539
+ return live;
540
+ });
541
+ const toolResult = (part) => ({
542
+ content: [{ type: "text", text: render(part.result) }],
543
+ isError: part.isFailure,
544
+ });
545
+ const isImageOnly = (message) => message.role === "user" &&
546
+ message.content.length > 0 &&
547
+ message.content.every((part) => part.type === "file");
548
+ // What a step emitted, as its assistant message in the history must hold.
549
+ const emitted = (outcome) => ({
550
+ text: outcome.text,
551
+ calls: outcome.calls.map(({ id, name, params }) => ({ id, name, params })),
552
+ });
553
+ const appended = (message) => ({
554
+ text: message.content
555
+ .flatMap((part) => (part.type === "text" ? [part.text] : []))
556
+ .join(""),
557
+ calls: message.content.flatMap((part) => part.type === "tool-call" && !part.providerExecuted
558
+ ? [{ id: part.id, name: part.name, params: part.params }]
559
+ : []),
560
+ });
561
+ // How `prompt` continues the live session: the messages of the last step,
562
+ // then its response as emitted, then a result for each of its tool calls,
563
+ // then user messages (at least one after a `Stop`). `undefined` when it does
564
+ // not, and the session has to start over with the full history.
565
+ const continuation = (session, provider) => {
566
+ const outcome = session.outcome;
567
+ const messages = provider.prompt.content;
568
+ const seen = session.seen;
569
+ const response = messages[seen.length];
570
+ if (outcome === undefined ||
571
+ session.toolNames !== provider.tools.map((tool) => tool.name).join(",") ||
572
+ response?.role !== "assistant" ||
573
+ !seen.every((message, i) => messages[i] === message) ||
574
+ !isDeepStrictEqual(appended(response), emitted(outcome))) {
575
+ return undefined;
576
+ }
577
+ const [toolMessages, users] = Array.span(messages.slice(seen.length + 1), (message) => message.role === "tool");
578
+ const results = new Map(toolMessages.flatMap((message) => message.content.flatMap((part) => part.type === "tool-result" ? [[part.id, part]] : [])));
579
+ const ids = outcome.calls.map((call) => call.id);
580
+ if (results.size !== ids.length ||
581
+ !ids.every((id) => results.has(id)) ||
582
+ !users.every((message) => message.role === "user") ||
583
+ (outcome._tag === "Stop" && users.length === 0)) {
584
+ return undefined;
585
+ }
586
+ return { ids, results, users };
587
+ };
588
+ const continueSession = (session, plan) => {
589
+ const results = plan.ids.map((id) => toolResult(plan.results.get(id)));
590
+ // Images attached by the tool calls follow their results; they go back
591
+ // with the last result.
592
+ const last = results.at(-1);
593
+ let users = plan.users;
594
+ if (last !== undefined) {
595
+ while (users[0] !== undefined && isImageOnly(users[0])) {
596
+ for (const block of toUserContent(Prompt.fromMessages([users[0]]))) {
597
+ if (block.type === "image") {
598
+ last.content.push({
599
+ type: "image",
600
+ data: block.source.data,
601
+ mimeType: block.source.media_type,
602
+ });
603
+ }
604
+ }
605
+ users = users.slice(1);
606
+ }
607
+ }
608
+ if (users.length > 0) {
609
+ Queue.offerUnsafe(session.input, userMessage(toUserContent(Prompt.fromMessages(users)), last === undefined ? undefined : "next"));
610
+ }
611
+ plan.ids.forEach((id, i) => session.bridge.resolve(id, results[i]));
612
+ };
613
+ // The ids of the tool results in an SDK user message.
614
+ const toolResultIds = (message) => typeof message.message.content === "string"
615
+ ? []
616
+ : message.message.content.flatMap((block) => block.type === "tool_result" ? [block.tool_use_id] : []);
617
+ // Reads one step from the session, recording how it ended. A step that does
618
+ // not finish leaves the session in an unknown state, so it is closed.
619
+ //
620
+ // A tool step holds back its tool calls and its finish until Claude Code has
621
+ // parked an MCP request for every call. Effect runs a call's handler as soon
622
+ // as more parts follow it, so emitting a call earlier could run a script
623
+ // that Claude Code never waits for. An untagged request, or Claude Code
624
+ // answering a call itself, fails the step before any script runs.
625
+ const readStep = (session, onAbandon) => Stream.suspend(() => {
626
+ const convert = makeConverter();
627
+ const calls = [];
628
+ const parked = new Set();
629
+ let finish;
630
+ let text = "";
631
+ // Once the tool message's `message_stop` is read, every call it made is
632
+ // known, so a park for any other id can never be released.
633
+ const release = () => {
634
+ if (finish === undefined)
635
+ return Effect.succeed([]);
636
+ const unknown = [...parked].find((id) => !calls.some((call) => call.id === id));
637
+ if (unknown !== undefined) {
638
+ return Effect.fail(unknownError(`Claude Code called clanka for tool call ${unknown}, which it never made.`));
639
+ }
640
+ if (!calls.every((call) => parked.has(call.id)))
641
+ return Effect.succeed([]);
642
+ session.outcome = { _tag: "Tools", calls, text };
643
+ return Effect.succeed([...calls, finish]);
644
+ };
645
+ const handle = (event) => {
646
+ if (event.type === "clanka_parked") {
647
+ if (event.id === undefined) {
648
+ return Effect.fail(unknownError("Claude Code sent a tool call without its tool use id. This Claude Code version is not supported."));
649
+ }
650
+ parked.add(event.id);
651
+ return release();
652
+ }
653
+ if (event.type === "user" && event.parent_tool_use_id === null) {
654
+ const answered = toolResultIds(event).find((id) => !parked.has(id) && calls.some((call) => call.id === id));
655
+ if (answered !== undefined) {
656
+ return Effect.fail(unknownError(`Claude Code answered the tool call ${answered} itself instead of calling clanka.`));
657
+ }
658
+ }
659
+ return Effect.flatMap(convert(event), (parts) => {
660
+ const out = [];
661
+ for (const part of parts) {
662
+ switch (part.type) {
663
+ case "tool-call":
664
+ calls.push(part);
665
+ break;
666
+ case "text-delta":
667
+ text += part.delta;
668
+ out.push(part);
669
+ break;
670
+ case "finish":
671
+ if (part.reason === "tool-calls") {
672
+ finish = part;
673
+ break;
674
+ }
675
+ session.outcome = { _tag: "Stop", calls: [], text };
676
+ out.push(part);
677
+ break;
678
+ default:
679
+ out.push(part);
680
+ }
681
+ }
682
+ return Effect.map(release(), (released) => [...out, ...released]);
683
+ });
684
+ };
685
+ return Stream.fromQueue(session.messages).pipe(Stream.mapEffect(handle), Stream.flattenIterable,
686
+ // The queue ends when Claude Code exits, so reaching this means it
687
+ // stopped mid-step.
688
+ Stream.concat(Stream.fail(unknownError("Claude Code stopped before finishing its reply"))), Stream.takeUntil((part) => part.type === "finish"), Stream.onExit(() => session.outcome === undefined ? onAbandon : Effect.void));
689
+ });
690
+ // A call without tools, such as a compaction summary, runs on its own
691
+ // short-lived Claude Code.
692
+ const oneShot = (model, options, provider) => Stream.unwrap(Effect.map(Effect.acquireRelease(startSession(model, options, provider, false), closeSession), (session) => readStep(session, Effect.void))).pipe(Stream.scoped);
693
+ const layerLanguageModel = (model, options) => Layer.effect(LanguageModel.LanguageModel, Effect.gen(function* () {
694
+ // The live session of the conversation, one per model layer.
695
+ let current;
696
+ const closeCurrent = Effect.suspend(() => {
697
+ const session = current;
698
+ current = undefined;
699
+ return session === undefined ? Effect.void : closeSession(session);
700
+ });
701
+ yield* Effect.addFinalizer(() => closeCurrent);
702
+ const step = (provider) => Stream.unwrap(Effect.gen(function* () {
703
+ const plan = current === undefined
704
+ ? undefined
705
+ : continuation(current, provider);
706
+ if (current !== undefined && plan !== undefined) {
707
+ continueSession(current, plan);
708
+ current.seen = provider.prompt.content;
709
+ current.outcome = undefined;
710
+ return readStep(current, closeCurrent);
711
+ }
712
+ yield* closeCurrent;
713
+ current = yield* startSession(model, options, provider, true);
714
+ return readStep(current, closeCurrent);
715
+ }));
716
+ const streamText = (provider) => provider.tools.length === 0
717
+ ? oneShot(model, options, provider)
718
+ : step(provider);
719
+ return yield* LanguageModel.make({
720
+ streamText,
721
+ generateText: (provider) => streamText(provider).pipe(Stream.runCollect, Effect.map(toParts)),
722
+ });
723
+ }));
724
+ // Stream parts as the parts of a whole response.
725
+ const toParts = (parts) => {
726
+ const result = [];
727
+ const texts = new Map();
728
+ for (const part of parts) {
729
+ switch (part.type) {
730
+ case "text-start":
731
+ case "reasoning-start":
732
+ texts.set(part.id, {
733
+ type: part.type === "text-start" ? "text" : "reasoning",
734
+ text: "",
735
+ });
736
+ break;
737
+ case "text-delta":
738
+ case "reasoning-delta": {
739
+ const text = texts.get(part.id);
740
+ if (text !== undefined)
741
+ text.text += part.delta;
742
+ break;
743
+ }
744
+ case "text-end":
745
+ case "reasoning-end": {
746
+ const text = texts.get(part.id);
747
+ if (text !== undefined)
748
+ result.push({ type: text.type, text: text.text });
749
+ break;
750
+ }
751
+ case "tool-call":
752
+ case "finish":
753
+ result.push(part);
754
+ break;
755
+ }
756
+ }
757
+ return result;
758
+ };
759
+ /**
760
+ * A Claude model run by the user's installed Claude Code, with whatever
761
+ * login it has: a Claude subscription, an API key, or Bedrock, Vertex or
762
+ * Foundry credentials.
763
+ *
764
+ * @since 1.0.0
765
+ * @category Layers
766
+ */
767
+ export const model = (model, options) => Model.make("claude", model, Layer.merge(layerLanguageModel(model, options),
768
+ // The system prompt stays in the Prompt, where `queryOptions` reads
769
+ // it. No Compaction.SummarizerTransform: Claude Code takes no
770
+ // per-request output cap.
771
+ AgentModelConfig.layer({ supportsImages: options?.supportsImages })));
772
+ //# sourceMappingURL=ClaudeAgent.js.map