clanka 0.16.1 → 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.
- package/README.md +61 -0
- package/dist/Agent.d.ts.map +1 -1
- package/dist/Agent.js +5 -1
- package/dist/Agent.js.map +1 -1
- package/dist/ClaudeAgent.d.ts +111 -0
- package/dist/ClaudeAgent.d.ts.map +1 -0
- package/dist/ClaudeAgent.js +772 -0
- package/dist/ClaudeAgent.js.map +1 -0
- package/dist/ClaudeAgent.test.d.ts +2 -0
- package/dist/ClaudeAgent.test.d.ts.map +1 -0
- package/dist/ClaudeAgent.test.js +416 -0
- package/dist/ClaudeAgent.test.js.map +1 -0
- package/dist/ModelLayer.d.ts +2 -2
- package/dist/ModelLayer.d.ts.map +1 -1
- package/dist/ModelLayer.js +13 -7
- package/dist/ModelLayer.js.map +1 -1
- package/dist/ModelLayer.test.js +3 -0
- package/dist/ModelLayer.test.js.map +1 -1
- package/dist/ModelsRepo.d.ts +7 -6
- package/dist/ModelsRepo.d.ts.map +1 -1
- package/dist/ModelsRepo.js +44 -27
- package/dist/ModelsRepo.js.map +1 -1
- package/dist/ModelsRepo.test.js +47 -3
- package/dist/ModelsRepo.test.js.map +1 -1
- package/dist/bin/{Effect-4B1lzxy4.mjs → Effect-On-1ks2z.mjs} +50 -2
- package/dist/bin/Effect-On-1ks2z.mjs.map +1 -0
- package/dist/bin/{McpClient-DMfHHEx3.mjs → McpClient-iwrW83Si.mjs} +3 -3
- package/dist/bin/{McpClient-DMfHHEx3.mjs.map → McpClient-iwrW83Si.mjs.map} +1 -1
- package/dist/bin/{OutputFormatter-DRycCEdr.mjs → OutputFormatter-DeNaqhQM.mjs} +3 -3
- package/dist/bin/{OutputFormatter-DRycCEdr.mjs.map → OutputFormatter-DeNaqhQM.mjs.map} +1 -1
- package/dist/bin/{Schema-D4fxUgEU.mjs → Schema-B3pFcw4E.mjs} +2 -2
- package/dist/bin/{Schema-D4fxUgEU.mjs.map → Schema-B3pFcw4E.mjs.map} +1 -1
- package/dist/bin/{SemanticSearch-BcLFv9qz.mjs → SemanticSearch-BZIXkWYz.mjs} +4 -4
- package/dist/bin/{SemanticSearch-BcLFv9qz.mjs.map → SemanticSearch-BZIXkWYz.mjs.map} +1 -1
- package/dist/bin/{Stream-i37nF1ep.mjs → Stream-DCB3_nIX.mjs} +91 -12
- package/dist/bin/Stream-DCB3_nIX.mjs.map +1 -0
- package/dist/bin/cli.mjs +1256 -12867
- package/dist/bin/cli.mjs.map +1 -1
- package/dist/bin/helpers-BPLUsjsL.mjs +7191 -0
- package/dist/bin/helpers-BPLUsjsL.mjs.map +1 -0
- package/dist/bin/{rolldown-runtime-zY4HT0JA.mjs → rolldown-runtime-Cjv6nE1W.mjs} +14 -1
- package/dist/bin/server-CBmuybpI.mjs +321 -0
- package/dist/bin/server-CBmuybpI.mjs.map +1 -0
- package/dist/bin/{turndown.cjs-LntFxFyd.mjs → turndown.cjs-cie0BXQQ.mjs} +2 -2
- package/dist/bin/{turndown.cjs-LntFxFyd.mjs.map → turndown.cjs-cie0BXQQ.mjs.map} +1 -1
- package/dist/bin/types-RT_9fFNm.mjs +5278 -0
- package/dist/bin/types-RT_9fFNm.mjs.map +1 -0
- package/dist/cli.js +4 -0
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -1
- package/package.json +9 -1
- package/src/Agent.ts +7 -1
- package/src/ClaudeAgent.test.ts +526 -0
- package/src/ClaudeAgent.ts +1113 -0
- package/src/ModelLayer.test.ts +4 -0
- package/src/ModelLayer.ts +21 -15
- package/src/ModelsRepo.test.ts +69 -3
- package/src/ModelsRepo.ts +24 -8
- package/src/cli.ts +4 -0
- package/src/index.ts +5 -0
- package/dist/bin/Effect-4B1lzxy4.mjs.map +0 -1
- package/dist/bin/Stream-i37nF1ep.mjs.map +0 -1
|
@@ -0,0 +1,1113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runs Claude models through the Claude Agent SDK and the user's own
|
|
3
|
+
* installed Claude Code. clanka keeps its agent loop, `execute` tool, system
|
|
4
|
+
* prompt and history; Claude Code only makes the model calls.
|
|
5
|
+
*
|
|
6
|
+
* See `.specs/claude-agent.md`.
|
|
7
|
+
*
|
|
8
|
+
* @since 1.0.0
|
|
9
|
+
*/
|
|
10
|
+
import type * as Sdk from "@anthropic-ai/claude-agent-sdk"
|
|
11
|
+
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"
|
|
12
|
+
import * as Array from "effect/Array"
|
|
13
|
+
import type * as Cause from "effect/Cause"
|
|
14
|
+
import * as Effect from "effect/Effect"
|
|
15
|
+
import * as Base64 from "effect/encoding/Base64"
|
|
16
|
+
import * as Exit from "effect/Exit"
|
|
17
|
+
import * as Layer from "effect/Layer"
|
|
18
|
+
import * as Option from "effect/Option"
|
|
19
|
+
import * as Queue from "effect/Queue"
|
|
20
|
+
import * as Scope from "effect/Scope"
|
|
21
|
+
import * as Stream from "effect/Stream"
|
|
22
|
+
import * as AiError from "effect/ai/AiError"
|
|
23
|
+
import * as LanguageModel from "effect/ai/LanguageModel"
|
|
24
|
+
import * as Model from "effect/ai/Model"
|
|
25
|
+
import * as Prompt from "effect/ai/Prompt"
|
|
26
|
+
import type * as Response from "effect/ai/Response"
|
|
27
|
+
import * as Tool from "effect/ai/Tool"
|
|
28
|
+
import * as Fs from "node:fs"
|
|
29
|
+
import * as Path from "node:path"
|
|
30
|
+
import { isDeepStrictEqual } from "node:util"
|
|
31
|
+
import packageJson from "../package.json" with { type: "json" }
|
|
32
|
+
import { AgentModelConfig } from "./Agent.ts"
|
|
33
|
+
import * as Image from "./Image.ts"
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The oldest Claude Code release clanka runs: the first to honour
|
|
37
|
+
* `verbatimPrompts`.
|
|
38
|
+
*
|
|
39
|
+
* @since 1.0.0
|
|
40
|
+
* @category Claude Code
|
|
41
|
+
*/
|
|
42
|
+
export const minimumClaudeCodeVersion = "2.1.248"
|
|
43
|
+
|
|
44
|
+
const serverName = "clanka"
|
|
45
|
+
const toolPrefix = `mcp__${serverName}__`
|
|
46
|
+
|
|
47
|
+
// Claude Code features that duplicate clanka's, or would hide its tool.
|
|
48
|
+
const isolationEnv = {
|
|
49
|
+
CLAUDE_CODE_DISABLE_CLAUDE_MDS: "1",
|
|
50
|
+
CLAUDE_CODE_DISABLE_AUTO_MEMORY: "1",
|
|
51
|
+
// clanka compacts its own history.
|
|
52
|
+
DISABLE_AUTO_COMPACT: "1",
|
|
53
|
+
CLAUDE_CODE_ENABLE_AWAY_SUMMARY: "0",
|
|
54
|
+
// Tool search would defer clanka's only tool.
|
|
55
|
+
ENABLE_TOOL_SEARCH: "false",
|
|
56
|
+
CLAUDE_CODE_DISABLE_ADVISOR_TOOL: "1",
|
|
57
|
+
// clanka caps tool output itself.
|
|
58
|
+
MAX_MCP_OUTPUT_TOKENS: "200000",
|
|
59
|
+
// Skips OAuth, so a subscription login would not be used.
|
|
60
|
+
CLAUDE_CODE_SIMPLE: undefined,
|
|
61
|
+
// Would override the effort clanka sends.
|
|
62
|
+
CLAUDE_CODE_EFFORT_LEVEL: undefined,
|
|
63
|
+
// Would cap every `execute` call.
|
|
64
|
+
MCP_TOOL_TIMEOUT: undefined,
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Options for a model. `effort: null` sends no effort, for models that
|
|
69
|
+
* accept none; `"none"` turns thinking off.
|
|
70
|
+
*
|
|
71
|
+
* @since 1.0.0
|
|
72
|
+
* @category Models
|
|
73
|
+
*/
|
|
74
|
+
export interface ModelOptions {
|
|
75
|
+
readonly effort?: string | null | undefined
|
|
76
|
+
/**
|
|
77
|
+
* The Claude Code executable. Defaults to `CLANKA_CLAUDE_PATH`, then
|
|
78
|
+
* `claude` on the `PATH`.
|
|
79
|
+
*/
|
|
80
|
+
readonly executable?: string | undefined
|
|
81
|
+
/**
|
|
82
|
+
* Claude Code's working directory. Defaults to `process.cwd()`.
|
|
83
|
+
*/
|
|
84
|
+
readonly cwd?: string | undefined
|
|
85
|
+
readonly supportsImages?: boolean | undefined
|
|
86
|
+
/**
|
|
87
|
+
* The SDK's `query` function. Defaults to the one from
|
|
88
|
+
* `@anthropic-ai/claude-agent-sdk`, loaded on first use.
|
|
89
|
+
*/
|
|
90
|
+
readonly query?: typeof Sdk.query | undefined
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* The Claude Agent SDK options for a session: Claude Code runs with none of
|
|
95
|
+
* its own tools, settings, hooks, memory, skills or transcripts, and with the
|
|
96
|
+
* system prompt from `prompt`.
|
|
97
|
+
*
|
|
98
|
+
* @since 1.0.0
|
|
99
|
+
* @category Claude Code
|
|
100
|
+
*/
|
|
101
|
+
export const queryOptions = (options: {
|
|
102
|
+
readonly model: string
|
|
103
|
+
readonly prompt: Prompt.Prompt
|
|
104
|
+
readonly cwd: string
|
|
105
|
+
readonly pathToClaudeCodeExecutable: string
|
|
106
|
+
readonly effort?: string | null | undefined
|
|
107
|
+
}): Sdk.Options => ({
|
|
108
|
+
pathToClaudeCodeExecutable: options.pathToClaudeCodeExecutable,
|
|
109
|
+
cwd: options.cwd,
|
|
110
|
+
model: options.model,
|
|
111
|
+
...effortOptions(options.effort),
|
|
112
|
+
systemPrompt: { type: "custom", prompt: systemText(options.prompt) },
|
|
113
|
+
env: {
|
|
114
|
+
...process.env,
|
|
115
|
+
...isolationEnv,
|
|
116
|
+
CLAUDE_AGENT_SDK_CLIENT_APP: `clanka/${packageJson.version}`,
|
|
117
|
+
},
|
|
118
|
+
settingSources: [],
|
|
119
|
+
settings: { disableAllHooks: true },
|
|
120
|
+
strictMcpConfig: true,
|
|
121
|
+
skills: [],
|
|
122
|
+
tools: [],
|
|
123
|
+
permissionMode: "dontAsk",
|
|
124
|
+
allowedTools: [`${toolPrefix}*`],
|
|
125
|
+
verbatimPrompts: true,
|
|
126
|
+
includePartialMessages: true,
|
|
127
|
+
persistSession: false,
|
|
128
|
+
})
|
|
129
|
+
|
|
130
|
+
const efforts: ReadonlySet<string> = new Set([
|
|
131
|
+
"low",
|
|
132
|
+
"medium",
|
|
133
|
+
"high",
|
|
134
|
+
"xhigh",
|
|
135
|
+
"max",
|
|
136
|
+
])
|
|
137
|
+
|
|
138
|
+
const effortOptions = (
|
|
139
|
+
effort: string | null | undefined,
|
|
140
|
+
): Pick<Sdk.Options, "effort" | "thinking"> => {
|
|
141
|
+
if (effort === "none") return { thinking: { type: "disabled" } }
|
|
142
|
+
const thinking = { type: "adaptive", display: "summarized" } as const
|
|
143
|
+
if (effort === "minimal") return { thinking, effort: "low" }
|
|
144
|
+
return effort !== null && effort !== undefined && efforts.has(effort)
|
|
145
|
+
? { thinking, effort: effort as Sdk.EffortLevel }
|
|
146
|
+
: { thinking }
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const systemText = (prompt: Prompt.Prompt) =>
|
|
150
|
+
prompt.content
|
|
151
|
+
.flatMap((message) => (message.role === "system" ? [message.content] : []))
|
|
152
|
+
.join("\n\n")
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* A content block of a Claude Code user message.
|
|
156
|
+
*
|
|
157
|
+
* @since 1.0.0
|
|
158
|
+
* @category Messages
|
|
159
|
+
*/
|
|
160
|
+
export type ContentBlock =
|
|
161
|
+
| { readonly type: "text"; readonly text: string }
|
|
162
|
+
| {
|
|
163
|
+
readonly type: "image"
|
|
164
|
+
readonly source: {
|
|
165
|
+
readonly type: "base64"
|
|
166
|
+
readonly media_type: Image.ImageMediaType
|
|
167
|
+
readonly data: string
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const render = (value: unknown) =>
|
|
172
|
+
typeof value === "string" ? value : JSON.stringify(value)
|
|
173
|
+
|
|
174
|
+
const renderParams = (params: unknown) =>
|
|
175
|
+
typeof params === "object" && params !== null && !Array.isArray(params)
|
|
176
|
+
? Object.entries(params)
|
|
177
|
+
.map(([key, value]) => `<${key}>\n${render(value)}\n</${key}>`)
|
|
178
|
+
.join("\n")
|
|
179
|
+
: render(params)
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* A prompt as the content of one Claude Code user message. A `query()` takes
|
|
183
|
+
* no assistant history, so when the prompt has earlier turns each message is
|
|
184
|
+
* wrapped in a `<role>` tag. Images become image blocks; the system message
|
|
185
|
+
* is left out, it goes in `queryOptions`.
|
|
186
|
+
*
|
|
187
|
+
* @since 1.0.0
|
|
188
|
+
* @category Messages
|
|
189
|
+
*/
|
|
190
|
+
export const toUserContent = (prompt: Prompt.Prompt): Array<ContentBlock> => {
|
|
191
|
+
const blocks: Array<ContentBlock> = []
|
|
192
|
+
let text: Array<string> = []
|
|
193
|
+
const flush = () => {
|
|
194
|
+
if (text.length === 0) return
|
|
195
|
+
blocks.push({ type: "text", text: text.join("\n") })
|
|
196
|
+
text = []
|
|
197
|
+
}
|
|
198
|
+
const history = prompt.content.some(
|
|
199
|
+
(message) => message.role === "assistant" || message.role === "tool",
|
|
200
|
+
)
|
|
201
|
+
for (const message of prompt.content) {
|
|
202
|
+
if (message.role === "system") continue
|
|
203
|
+
if (history) text.push(`<${message.role}>`)
|
|
204
|
+
for (const part of message.content) {
|
|
205
|
+
switch (part.type) {
|
|
206
|
+
case "text":
|
|
207
|
+
text.push(part.text)
|
|
208
|
+
break
|
|
209
|
+
case "file": {
|
|
210
|
+
const bytes = Image.isImageMediaType(part.mediaType)
|
|
211
|
+
? Image.partBytes(part)
|
|
212
|
+
: Option.none()
|
|
213
|
+
if (Option.isNone(bytes)) {
|
|
214
|
+
text.push(
|
|
215
|
+
`[file ${part.fileName ?? ""} (${part.mediaType}) omitted]`,
|
|
216
|
+
)
|
|
217
|
+
break
|
|
218
|
+
}
|
|
219
|
+
flush()
|
|
220
|
+
blocks.push({
|
|
221
|
+
type: "image",
|
|
222
|
+
source: {
|
|
223
|
+
type: "base64",
|
|
224
|
+
media_type: part.mediaType as Image.ImageMediaType,
|
|
225
|
+
data: Base64.encode(bytes.value),
|
|
226
|
+
},
|
|
227
|
+
})
|
|
228
|
+
break
|
|
229
|
+
}
|
|
230
|
+
case "tool-call":
|
|
231
|
+
text.push(
|
|
232
|
+
`<tool-call id="${part.id}" name="${part.name}">\n${renderParams(part.params)}\n</tool-call>`,
|
|
233
|
+
)
|
|
234
|
+
break
|
|
235
|
+
case "tool-result":
|
|
236
|
+
text.push(
|
|
237
|
+
`<tool-result id="${part.id}" name="${part.name}"${part.isFailure ? ' failed="true"' : ""}>\n${render(part.result)}\n</tool-result>`,
|
|
238
|
+
)
|
|
239
|
+
break
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
if (history) text.push(`</${message.role}>`)
|
|
243
|
+
}
|
|
244
|
+
flush()
|
|
245
|
+
return blocks
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// =============================================================================
|
|
249
|
+
// Stream conversion
|
|
250
|
+
// =============================================================================
|
|
251
|
+
|
|
252
|
+
interface UsageCounts {
|
|
253
|
+
input: number
|
|
254
|
+
read: number
|
|
255
|
+
write: number
|
|
256
|
+
output: number
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
interface ApiUsage {
|
|
260
|
+
readonly input_tokens?: number | null | undefined
|
|
261
|
+
readonly cache_read_input_tokens?: number | null | undefined
|
|
262
|
+
readonly cache_creation_input_tokens?: number | null | undefined
|
|
263
|
+
readonly output_tokens?: number | null | undefined
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// Claude Code reports the same API message several times, so each count
|
|
267
|
+
// keeps its maximum per message. Context size is the last call's input.
|
|
268
|
+
const makeUsage = () => {
|
|
269
|
+
const messages = new Map<string, UsageCounts>()
|
|
270
|
+
let last: string | undefined
|
|
271
|
+
return {
|
|
272
|
+
update(id: string, usage: ApiUsage | null | undefined) {
|
|
273
|
+
if (usage === null || usage === undefined) return
|
|
274
|
+
let counts = messages.get(id)
|
|
275
|
+
if (counts === undefined) {
|
|
276
|
+
counts = { input: 0, read: 0, write: 0, output: 0 }
|
|
277
|
+
messages.set(id, counts)
|
|
278
|
+
last = id
|
|
279
|
+
}
|
|
280
|
+
counts.input = Math.max(counts.input, usage.input_tokens ?? 0)
|
|
281
|
+
counts.read = Math.max(counts.read, usage.cache_read_input_tokens ?? 0)
|
|
282
|
+
counts.write = Math.max(
|
|
283
|
+
counts.write,
|
|
284
|
+
usage.cache_creation_input_tokens ?? 0,
|
|
285
|
+
)
|
|
286
|
+
counts.output = Math.max(counts.output, usage.output_tokens ?? 0)
|
|
287
|
+
},
|
|
288
|
+
// The result's usage sums the whole Claude Code turn, so it only counts
|
|
289
|
+
// when this step saw no API message.
|
|
290
|
+
result(usage: ApiUsage) {
|
|
291
|
+
if (messages.size === 0) this.update("result", usage)
|
|
292
|
+
},
|
|
293
|
+
snapshot(): typeof Response.Usage.Encoded {
|
|
294
|
+
let output = 0
|
|
295
|
+
for (const counts of messages.values()) output += counts.output
|
|
296
|
+
const lastCall = last === undefined ? undefined : messages.get(last)
|
|
297
|
+
return {
|
|
298
|
+
inputTokens: {
|
|
299
|
+
uncached: lastCall?.input,
|
|
300
|
+
total:
|
|
301
|
+
lastCall === undefined
|
|
302
|
+
? undefined
|
|
303
|
+
: lastCall.input + lastCall.read + lastCall.write,
|
|
304
|
+
cacheRead: lastCall?.read,
|
|
305
|
+
cacheWrite: lastCall?.write,
|
|
306
|
+
},
|
|
307
|
+
outputTokens: { total: output },
|
|
308
|
+
}
|
|
309
|
+
},
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
const aiError = (reason: AiError.AiErrorReason) =>
|
|
314
|
+
AiError.make({ module: "ClaudeAgent", method: "streamText", reason })
|
|
315
|
+
|
|
316
|
+
const unknownError = (description: string) =>
|
|
317
|
+
aiError(new AiError.UnknownError({ description }))
|
|
318
|
+
|
|
319
|
+
const resultError = (
|
|
320
|
+
message: Sdk.SDKResultMessage,
|
|
321
|
+
code: Sdk.SDKAssistantMessageError | undefined,
|
|
322
|
+
): AiError.AiError | undefined => {
|
|
323
|
+
const status =
|
|
324
|
+
message.subtype === "success" ? message.api_error_status : undefined
|
|
325
|
+
if (
|
|
326
|
+
message.subtype === "success" &&
|
|
327
|
+
!message.is_error &&
|
|
328
|
+
(status === undefined || status === null || status < 400)
|
|
329
|
+
) {
|
|
330
|
+
return undefined
|
|
331
|
+
}
|
|
332
|
+
const description =
|
|
333
|
+
(message.subtype === "success"
|
|
334
|
+
? message.result
|
|
335
|
+
: message.errors.join("\n")
|
|
336
|
+
).replaceAll("Please run /login", "Run `claude auth login`") ||
|
|
337
|
+
`Claude Code could not finish its reply${status ? ` (HTTP ${status})` : ""}`
|
|
338
|
+
switch (code) {
|
|
339
|
+
case "authentication_failed":
|
|
340
|
+
case "oauth_org_not_allowed":
|
|
341
|
+
return aiError(
|
|
342
|
+
new AiError.AuthenticationError({ kind: "Unknown", description }),
|
|
343
|
+
)
|
|
344
|
+
case "invalid_request":
|
|
345
|
+
return aiError(new AiError.InvalidRequestError({ description }))
|
|
346
|
+
}
|
|
347
|
+
// Claude Code has already retried, so nothing here is retryable.
|
|
348
|
+
return aiError(
|
|
349
|
+
/prompt is too long/i.test(description)
|
|
350
|
+
? new AiError.InvalidRequestError({ description })
|
|
351
|
+
: new AiError.UnknownError({ description }),
|
|
352
|
+
)
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
const makeConverter = () => {
|
|
356
|
+
const usage = makeUsage()
|
|
357
|
+
const streamed = new Set<string>()
|
|
358
|
+
const blocks = new Map<number, "text" | "reasoning">()
|
|
359
|
+
let messageId = ""
|
|
360
|
+
let calledTools = false
|
|
361
|
+
let errorCode: Sdk.SDKAssistantMessageError | undefined
|
|
362
|
+
|
|
363
|
+
return (
|
|
364
|
+
message: Sdk.SDKMessage,
|
|
365
|
+
): Effect.Effect<Array<Response.StreamPartEncoded>, AiError.AiError> => {
|
|
366
|
+
const parts: Array<Response.StreamPartEncoded> = []
|
|
367
|
+
if (
|
|
368
|
+
message.type === "stream_event" &&
|
|
369
|
+
message.parent_tool_use_id === null
|
|
370
|
+
) {
|
|
371
|
+
const event = message.event
|
|
372
|
+
switch (event.type) {
|
|
373
|
+
case "message_start":
|
|
374
|
+
messageId = event.message.id
|
|
375
|
+
streamed.add(messageId)
|
|
376
|
+
usage.update(messageId, event.message.usage)
|
|
377
|
+
break
|
|
378
|
+
case "content_block_start": {
|
|
379
|
+
const id = `${messageId}:${event.index}`
|
|
380
|
+
const block = event.content_block
|
|
381
|
+
if (block.type === "text") {
|
|
382
|
+
blocks.set(event.index, "text")
|
|
383
|
+
parts.push({ type: "text-start", id })
|
|
384
|
+
if (block.text)
|
|
385
|
+
parts.push({ type: "text-delta", id, delta: block.text })
|
|
386
|
+
} else if (block.type === "thinking") {
|
|
387
|
+
blocks.set(event.index, "reasoning")
|
|
388
|
+
parts.push({ type: "reasoning-start", id })
|
|
389
|
+
if (block.thinking) {
|
|
390
|
+
parts.push({ type: "reasoning-delta", id, delta: block.thinking })
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
break
|
|
394
|
+
}
|
|
395
|
+
case "content_block_delta": {
|
|
396
|
+
const id = `${messageId}:${event.index}`
|
|
397
|
+
const delta = event.delta
|
|
398
|
+
if (delta.type === "text_delta") {
|
|
399
|
+
parts.push({ type: "text-delta", id, delta: delta.text })
|
|
400
|
+
} else if (delta.type === "thinking_delta" && delta.thinking) {
|
|
401
|
+
parts.push({ type: "reasoning-delta", id, delta: delta.thinking })
|
|
402
|
+
}
|
|
403
|
+
break
|
|
404
|
+
}
|
|
405
|
+
case "content_block_stop": {
|
|
406
|
+
const kind = blocks.get(event.index)
|
|
407
|
+
if (kind !== undefined) {
|
|
408
|
+
parts.push({
|
|
409
|
+
type: `${kind}-end`,
|
|
410
|
+
id: `${messageId}:${event.index}`,
|
|
411
|
+
})
|
|
412
|
+
blocks.delete(event.index)
|
|
413
|
+
}
|
|
414
|
+
break
|
|
415
|
+
}
|
|
416
|
+
case "message_delta":
|
|
417
|
+
usage.update(messageId, event.usage)
|
|
418
|
+
break
|
|
419
|
+
case "message_stop":
|
|
420
|
+
// The step ends once Claude has called clanka's tool: its handler
|
|
421
|
+
// waits for the result of the next step.
|
|
422
|
+
if (calledTools) {
|
|
423
|
+
parts.push({
|
|
424
|
+
type: "finish",
|
|
425
|
+
reason: "tool-calls",
|
|
426
|
+
usage: usage.snapshot(),
|
|
427
|
+
})
|
|
428
|
+
}
|
|
429
|
+
break
|
|
430
|
+
}
|
|
431
|
+
} else if (
|
|
432
|
+
message.type === "assistant" &&
|
|
433
|
+
message.parent_tool_use_id === null
|
|
434
|
+
) {
|
|
435
|
+
// Synthetic API error messages are diagnostics; the result reports
|
|
436
|
+
// the failure.
|
|
437
|
+
if (message.error !== undefined) {
|
|
438
|
+
errorCode = message.error
|
|
439
|
+
return Effect.succeed(parts)
|
|
440
|
+
}
|
|
441
|
+
usage.update(message.message.id, message.message.usage)
|
|
442
|
+
// Assistant messages repeat streamed content, so only use their text
|
|
443
|
+
// when nothing was streamed.
|
|
444
|
+
const replay = !streamed.has(message.message.id)
|
|
445
|
+
message.message.content.forEach((block, index) => {
|
|
446
|
+
const id = `${message.uuid}:${index}`
|
|
447
|
+
if (block.type === "tool_use") {
|
|
448
|
+
// Claude Code answers calls to tools clanka did not offer itself.
|
|
449
|
+
if (!block.name.startsWith(toolPrefix)) return
|
|
450
|
+
calledTools = true
|
|
451
|
+
parts.push({
|
|
452
|
+
type: "tool-call",
|
|
453
|
+
id: block.id,
|
|
454
|
+
name: block.name.slice(toolPrefix.length),
|
|
455
|
+
params: block.input,
|
|
456
|
+
providerExecuted: false,
|
|
457
|
+
})
|
|
458
|
+
} else if (replay && block.type === "text") {
|
|
459
|
+
parts.push(
|
|
460
|
+
{ type: "text-start", id },
|
|
461
|
+
{ type: "text-delta", id, delta: block.text },
|
|
462
|
+
{ type: "text-end", id },
|
|
463
|
+
)
|
|
464
|
+
} else if (replay && block.type === "thinking") {
|
|
465
|
+
parts.push(
|
|
466
|
+
{ type: "reasoning-start", id },
|
|
467
|
+
{ type: "reasoning-delta", id, delta: block.thinking },
|
|
468
|
+
{ type: "reasoning-end", id },
|
|
469
|
+
)
|
|
470
|
+
}
|
|
471
|
+
})
|
|
472
|
+
} else if (message.type === "result") {
|
|
473
|
+
const error = resultError(message, errorCode)
|
|
474
|
+
if (error !== undefined) return Effect.fail(error)
|
|
475
|
+
usage.result(message.usage)
|
|
476
|
+
parts.push({
|
|
477
|
+
type: "finish",
|
|
478
|
+
reason: message.stop_reason === "max_tokens" ? "length" : "stop",
|
|
479
|
+
usage: usage.snapshot(),
|
|
480
|
+
})
|
|
481
|
+
}
|
|
482
|
+
return Effect.succeed(parts)
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/**
|
|
487
|
+
* Converts the Claude Agent SDK messages of one model step to response
|
|
488
|
+
* parts, ending at the step's `finish` part. A step ends when Claude Code
|
|
489
|
+
* finishes its turn, or after an API message that called clanka's tools.
|
|
490
|
+
*
|
|
491
|
+
* @since 1.0.0
|
|
492
|
+
* @category Messages
|
|
493
|
+
*/
|
|
494
|
+
export const toStreamParts = <E, R>(
|
|
495
|
+
self: Stream.Stream<Sdk.SDKMessage, E, R>,
|
|
496
|
+
): Stream.Stream<Response.StreamPartEncoded, E | AiError.AiError, R> =>
|
|
497
|
+
Stream.suspend(() => {
|
|
498
|
+
const convert = makeConverter()
|
|
499
|
+
return self.pipe(
|
|
500
|
+
Stream.mapEffect(convert),
|
|
501
|
+
Stream.flattenIterable,
|
|
502
|
+
Stream.takeUntil((part) => part.type === "finish"),
|
|
503
|
+
)
|
|
504
|
+
})
|
|
505
|
+
|
|
506
|
+
// =============================================================================
|
|
507
|
+
// Sessions
|
|
508
|
+
// =============================================================================
|
|
509
|
+
|
|
510
|
+
const userMessage = (
|
|
511
|
+
content: ReadonlyArray<ContentBlock>,
|
|
512
|
+
priority?: "next",
|
|
513
|
+
): Sdk.SDKUserMessage => ({
|
|
514
|
+
type: "user",
|
|
515
|
+
message: { role: "user", content: content as Array<ContentBlock> },
|
|
516
|
+
parent_tool_use_id: null,
|
|
517
|
+
...(priority === undefined ? {} : { priority }),
|
|
518
|
+
})
|
|
519
|
+
|
|
520
|
+
const errorResult = (text: string): CallToolResult => ({
|
|
521
|
+
isError: true,
|
|
522
|
+
content: [{ type: "text", text }],
|
|
523
|
+
})
|
|
524
|
+
|
|
525
|
+
// The parked tool calls, keyed by the tool use id Claude Code tags each MCP
|
|
526
|
+
// call with. `onCall` reports each request as it arrives, `undefined` for an
|
|
527
|
+
// untagged one. A handler waits until the next step resolves its call with
|
|
528
|
+
// clanka's result.
|
|
529
|
+
const makeToolBridge = (onCall: (id: string | undefined) => void) => {
|
|
530
|
+
const calls = new Map<string, PromiseWithResolvers<CallToolResult>>()
|
|
531
|
+
const entry = (id: string) => {
|
|
532
|
+
let call = calls.get(id)
|
|
533
|
+
if (call === undefined) {
|
|
534
|
+
call = Promise.withResolvers<CallToolResult>()
|
|
535
|
+
calls.set(id, call)
|
|
536
|
+
}
|
|
537
|
+
return call
|
|
538
|
+
}
|
|
539
|
+
return {
|
|
540
|
+
async call(id: string | undefined): Promise<CallToolResult> {
|
|
541
|
+
onCall(id)
|
|
542
|
+
// Never guess which call an untagged request is.
|
|
543
|
+
if (id === undefined) return errorResult("Missing tool use id")
|
|
544
|
+
const result = await entry(id).promise
|
|
545
|
+
calls.delete(id)
|
|
546
|
+
return result
|
|
547
|
+
},
|
|
548
|
+
resolve(id: string, result: CallToolResult) {
|
|
549
|
+
entry(id).resolve(result)
|
|
550
|
+
},
|
|
551
|
+
cancel() {
|
|
552
|
+
for (const call of calls.values()) call.resolve(errorResult("Cancelled"))
|
|
553
|
+
calls.clear()
|
|
554
|
+
},
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
type ToolBridge = ReturnType<typeof makeToolBridge>
|
|
559
|
+
|
|
560
|
+
const makeToolServer = (
|
|
561
|
+
tools: ReadonlyArray<Tool.Any>,
|
|
562
|
+
bridge: ToolBridge,
|
|
563
|
+
): Effect.Effect<Sdk.McpSdkServerConfigWithInstance, AiError.AiError> =>
|
|
564
|
+
Effect.tryPromise({
|
|
565
|
+
try: async () => {
|
|
566
|
+
// Loaded on first use, like the SDK.
|
|
567
|
+
const [{ Server }, { CallToolRequestSchema, ListToolsRequestSchema }] =
|
|
568
|
+
await Promise.all([
|
|
569
|
+
import("@modelcontextprotocol/sdk/server/index.js"),
|
|
570
|
+
import("@modelcontextprotocol/sdk/types.js"),
|
|
571
|
+
])
|
|
572
|
+
const server = new Server(
|
|
573
|
+
{ name: serverName, version: packageJson.version },
|
|
574
|
+
{ capabilities: { tools: {} } },
|
|
575
|
+
)
|
|
576
|
+
const definitions = tools.map((tool) => ({
|
|
577
|
+
name: tool.name,
|
|
578
|
+
description: Tool.getDescription(tool) ?? "",
|
|
579
|
+
inputSchema: Tool.getJsonSchema(tool) as {
|
|
580
|
+
readonly type: "object"
|
|
581
|
+
},
|
|
582
|
+
annotations: { readOnlyHint: false },
|
|
583
|
+
_meta: { "anthropic/alwaysLoad": true },
|
|
584
|
+
}))
|
|
585
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
586
|
+
tools: definitions,
|
|
587
|
+
}))
|
|
588
|
+
server.setRequestHandler(CallToolRequestSchema, (request) => {
|
|
589
|
+
const toolUseId = request.params._meta?.["claudecode/toolUseId"]
|
|
590
|
+
return bridge.call(
|
|
591
|
+
typeof toolUseId === "string" ? toolUseId : undefined,
|
|
592
|
+
)
|
|
593
|
+
})
|
|
594
|
+
return {
|
|
595
|
+
type: "sdk" as const,
|
|
596
|
+
name: serverName,
|
|
597
|
+
// The SDK names the high-level McpServer, but connects any server.
|
|
598
|
+
instance:
|
|
599
|
+
server as unknown as Sdk.McpSdkServerConfigWithInstance["instance"],
|
|
600
|
+
}
|
|
601
|
+
},
|
|
602
|
+
catch: (cause) =>
|
|
603
|
+
unknownError(`Failed to start the clanka MCP server: ${String(cause)}`),
|
|
604
|
+
})
|
|
605
|
+
|
|
606
|
+
const loadSdk = Effect.tryPromise({
|
|
607
|
+
try: () => import("@anthropic-ai/claude-agent-sdk"),
|
|
608
|
+
catch: () =>
|
|
609
|
+
unknownError(
|
|
610
|
+
"The claude provider needs @anthropic-ai/claude-agent-sdk. Install it next to clanka.",
|
|
611
|
+
),
|
|
612
|
+
})
|
|
613
|
+
|
|
614
|
+
const executableNames =
|
|
615
|
+
process.platform === "win32" ? ["claude.exe", "claude.cmd"] : ["claude"]
|
|
616
|
+
|
|
617
|
+
const isExecutable = (path: string) => {
|
|
618
|
+
try {
|
|
619
|
+
Fs.accessSync(path, Fs.constants.X_OK)
|
|
620
|
+
return true
|
|
621
|
+
} catch {
|
|
622
|
+
return false
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
const findExecutable = Effect.suspend(() => {
|
|
627
|
+
const found =
|
|
628
|
+
process.env.CLANKA_CLAUDE_PATH ||
|
|
629
|
+
(process.env.PATH ?? "")
|
|
630
|
+
.split(Path.delimiter)
|
|
631
|
+
.flatMap((dir) => executableNames.map((name) => Path.join(dir, name)))
|
|
632
|
+
.find(isExecutable)
|
|
633
|
+
return found === undefined
|
|
634
|
+
? Effect.fail(
|
|
635
|
+
unknownError(
|
|
636
|
+
"Claude Code was not found. Install Claude Code and run `claude auth login`, or set CLANKA_CLAUDE_PATH.",
|
|
637
|
+
),
|
|
638
|
+
)
|
|
639
|
+
: Effect.succeed(found)
|
|
640
|
+
})
|
|
641
|
+
|
|
642
|
+
const compareVersions = (a: string, b: string) => {
|
|
643
|
+
const left = a.split(/[.-]/).map(Number)
|
|
644
|
+
const right = b.split(/[.-]/).map(Number)
|
|
645
|
+
for (let i = 0; i < 3; i++) {
|
|
646
|
+
const diff = (left[i] ?? 0) - (right[i] ?? 0)
|
|
647
|
+
if (diff !== 0) return diff
|
|
648
|
+
}
|
|
649
|
+
return 0
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
// What a session reads: the SDK's messages, and the MCP requests for
|
|
653
|
+
// clanka's tool as they park.
|
|
654
|
+
type SessionEvent =
|
|
655
|
+
| Sdk.SDKMessage
|
|
656
|
+
| { readonly type: "clanka_parked"; readonly id: string | undefined }
|
|
657
|
+
|
|
658
|
+
// How a step ended: with the text it emitted and the tool calls it holds
|
|
659
|
+
// parked, or by ending Claude's turn.
|
|
660
|
+
interface Outcome {
|
|
661
|
+
readonly _tag: "Tools" | "Stop"
|
|
662
|
+
readonly calls: ReadonlyArray<Response.ToolCallPartEncoded>
|
|
663
|
+
readonly text: string
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
interface Session {
|
|
667
|
+
readonly query: Sdk.Query
|
|
668
|
+
// The streaming input of the `query()`.
|
|
669
|
+
readonly input: Queue.Queue<Sdk.SDKUserMessage, Cause.Done>
|
|
670
|
+
readonly bridge: ToolBridge
|
|
671
|
+
readonly messages: Queue.Queue<SessionEvent, AiError.AiError | Cause.Done>
|
|
672
|
+
readonly scope: Scope.Closeable
|
|
673
|
+
readonly toolNames: string
|
|
674
|
+
// The prompt of the last step, and how that step ended. `undefined`
|
|
675
|
+
// while a step runs.
|
|
676
|
+
seen: ReadonlyArray<Prompt.Message>
|
|
677
|
+
outcome: Outcome | undefined
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
const closeSession = (session: Session) =>
|
|
681
|
+
Effect.suspend(() => {
|
|
682
|
+
session.bridge.cancel()
|
|
683
|
+
session.query.close()
|
|
684
|
+
return Queue.end(session.input).pipe(
|
|
685
|
+
Effect.andThen(Scope.close(session.scope, Exit.void)),
|
|
686
|
+
)
|
|
687
|
+
})
|
|
688
|
+
|
|
689
|
+
const startSession = Effect.fnUntraced(function* (
|
|
690
|
+
model: string,
|
|
691
|
+
options: ModelOptions | undefined,
|
|
692
|
+
provider: LanguageModel.ProviderOptions,
|
|
693
|
+
withTools: boolean,
|
|
694
|
+
) {
|
|
695
|
+
const query = options?.query ?? (yield* loadSdk).query
|
|
696
|
+
const executable = options?.executable ?? (yield* findExecutable)
|
|
697
|
+
const messages = yield* Queue.make<
|
|
698
|
+
SessionEvent,
|
|
699
|
+
AiError.AiError | Cause.Done
|
|
700
|
+
>()
|
|
701
|
+
const bridge = makeToolBridge((id) => {
|
|
702
|
+
Queue.offerUnsafe(messages, { type: "clanka_parked", id })
|
|
703
|
+
})
|
|
704
|
+
const mcpServers = withTools
|
|
705
|
+
? { [serverName]: yield* makeToolServer(provider.tools, bridge) }
|
|
706
|
+
: {}
|
|
707
|
+
const input = yield* Queue.make<Sdk.SDKUserMessage, Cause.Done>()
|
|
708
|
+
Queue.offerUnsafe(input, userMessage(toUserContent(provider.prompt)))
|
|
709
|
+
if (!withTools) yield* Queue.end(input)
|
|
710
|
+
const session = query({
|
|
711
|
+
prompt: Stream.toAsyncIterable(Stream.fromQueue(input)),
|
|
712
|
+
options: {
|
|
713
|
+
...queryOptions({
|
|
714
|
+
model,
|
|
715
|
+
prompt: provider.prompt,
|
|
716
|
+
cwd: options?.cwd ?? process.cwd(),
|
|
717
|
+
pathToClaudeCodeExecutable: executable,
|
|
718
|
+
effort: options?.effort,
|
|
719
|
+
}),
|
|
720
|
+
mcpServers,
|
|
721
|
+
},
|
|
722
|
+
})
|
|
723
|
+
const scope = yield* Scope.make()
|
|
724
|
+
yield* Stream.fromAsyncIterable(session, (cause) =>
|
|
725
|
+
unknownError(`Claude Code failed: ${String(cause)}`),
|
|
726
|
+
).pipe(
|
|
727
|
+
Stream.runForEach((message) => Queue.offer(messages, message)),
|
|
728
|
+
Effect.matchCauseEffect({
|
|
729
|
+
onSuccess: () => Queue.end(messages),
|
|
730
|
+
onFailure: (cause) => Queue.failCause(messages, cause),
|
|
731
|
+
}),
|
|
732
|
+
Effect.forkIn(scope),
|
|
733
|
+
)
|
|
734
|
+
const live: Session = {
|
|
735
|
+
query: session,
|
|
736
|
+
input,
|
|
737
|
+
bridge,
|
|
738
|
+
messages,
|
|
739
|
+
scope,
|
|
740
|
+
toolNames: provider.tools.map((tool) => tool.name).join(","),
|
|
741
|
+
seen: provider.prompt.content,
|
|
742
|
+
outcome: undefined,
|
|
743
|
+
}
|
|
744
|
+
yield* Effect.tryPromise({
|
|
745
|
+
try: () => session.initializationResult(),
|
|
746
|
+
catch: (cause) =>
|
|
747
|
+
unknownError(`Claude Code failed to start: ${String(cause)}`),
|
|
748
|
+
}).pipe(
|
|
749
|
+
Effect.flatMap((init) =>
|
|
750
|
+
init.claude_code_version !== undefined &&
|
|
751
|
+
compareVersions(init.claude_code_version, minimumClaudeCodeVersion) < 0
|
|
752
|
+
? Effect.fail(
|
|
753
|
+
unknownError(
|
|
754
|
+
`Claude Code ${init.claude_code_version} is too old, clanka needs ${minimumClaudeCodeVersion} or later. Run \`claude update\`.`,
|
|
755
|
+
),
|
|
756
|
+
)
|
|
757
|
+
: Effect.void,
|
|
758
|
+
),
|
|
759
|
+
Effect.onError(() => closeSession(live)),
|
|
760
|
+
)
|
|
761
|
+
return live
|
|
762
|
+
})
|
|
763
|
+
|
|
764
|
+
const toolResult = (part: Prompt.ToolResultPart): CallToolResult => ({
|
|
765
|
+
content: [{ type: "text", text: render(part.result) }],
|
|
766
|
+
isError: part.isFailure,
|
|
767
|
+
})
|
|
768
|
+
|
|
769
|
+
const isImageOnly = (message: Prompt.Message) =>
|
|
770
|
+
message.role === "user" &&
|
|
771
|
+
message.content.length > 0 &&
|
|
772
|
+
message.content.every((part) => part.type === "file")
|
|
773
|
+
|
|
774
|
+
// What a step emitted, as its assistant message in the history must hold.
|
|
775
|
+
const emitted = (outcome: Outcome) => ({
|
|
776
|
+
text: outcome.text,
|
|
777
|
+
calls: outcome.calls.map(({ id, name, params }) => ({ id, name, params })),
|
|
778
|
+
})
|
|
779
|
+
|
|
780
|
+
const appended = (message: Prompt.AssistantMessage) => ({
|
|
781
|
+
text: message.content
|
|
782
|
+
.flatMap((part) => (part.type === "text" ? [part.text] : []))
|
|
783
|
+
.join(""),
|
|
784
|
+
calls: message.content.flatMap((part) =>
|
|
785
|
+
part.type === "tool-call" && !part.providerExecuted
|
|
786
|
+
? [{ id: part.id, name: part.name, params: part.params }]
|
|
787
|
+
: [],
|
|
788
|
+
),
|
|
789
|
+
})
|
|
790
|
+
|
|
791
|
+
// How `prompt` continues the live session: the messages of the last step,
|
|
792
|
+
// then its response as emitted, then a result for each of its tool calls,
|
|
793
|
+
// then user messages (at least one after a `Stop`). `undefined` when it does
|
|
794
|
+
// not, and the session has to start over with the full history.
|
|
795
|
+
const continuation = (
|
|
796
|
+
session: Session,
|
|
797
|
+
provider: LanguageModel.ProviderOptions,
|
|
798
|
+
) => {
|
|
799
|
+
const outcome = session.outcome
|
|
800
|
+
const messages = provider.prompt.content
|
|
801
|
+
const seen = session.seen
|
|
802
|
+
const response = messages[seen.length]
|
|
803
|
+
if (
|
|
804
|
+
outcome === undefined ||
|
|
805
|
+
session.toolNames !== provider.tools.map((tool) => tool.name).join(",") ||
|
|
806
|
+
response?.role !== "assistant" ||
|
|
807
|
+
!seen.every((message, i) => messages[i] === message) ||
|
|
808
|
+
!isDeepStrictEqual(appended(response), emitted(outcome))
|
|
809
|
+
) {
|
|
810
|
+
return undefined
|
|
811
|
+
}
|
|
812
|
+
const [toolMessages, users] = Array.span(
|
|
813
|
+
messages.slice(seen.length + 1),
|
|
814
|
+
(message): message is Prompt.ToolMessage => message.role === "tool",
|
|
815
|
+
)
|
|
816
|
+
const results = new Map(
|
|
817
|
+
toolMessages.flatMap((message) =>
|
|
818
|
+
message.content.flatMap((part) =>
|
|
819
|
+
part.type === "tool-result" ? [[part.id, part] as const] : [],
|
|
820
|
+
),
|
|
821
|
+
),
|
|
822
|
+
)
|
|
823
|
+
const ids = outcome.calls.map((call) => call.id)
|
|
824
|
+
if (
|
|
825
|
+
results.size !== ids.length ||
|
|
826
|
+
!ids.every((id) => results.has(id)) ||
|
|
827
|
+
!users.every((message) => message.role === "user") ||
|
|
828
|
+
(outcome._tag === "Stop" && users.length === 0)
|
|
829
|
+
) {
|
|
830
|
+
return undefined
|
|
831
|
+
}
|
|
832
|
+
return { ids, results, users }
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
const continueSession = (
|
|
836
|
+
session: Session,
|
|
837
|
+
plan: NonNullable<ReturnType<typeof continuation>>,
|
|
838
|
+
) => {
|
|
839
|
+
const results = plan.ids.map((id) => toolResult(plan.results.get(id)!))
|
|
840
|
+
// Images attached by the tool calls follow their results; they go back
|
|
841
|
+
// with the last result.
|
|
842
|
+
const last = results.at(-1)
|
|
843
|
+
let users = plan.users
|
|
844
|
+
if (last !== undefined) {
|
|
845
|
+
while (users[0] !== undefined && isImageOnly(users[0])) {
|
|
846
|
+
for (const block of toUserContent(Prompt.fromMessages([users[0]]))) {
|
|
847
|
+
if (block.type === "image") {
|
|
848
|
+
last.content.push({
|
|
849
|
+
type: "image",
|
|
850
|
+
data: block.source.data,
|
|
851
|
+
mimeType: block.source.media_type,
|
|
852
|
+
})
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
users = users.slice(1)
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
if (users.length > 0) {
|
|
859
|
+
Queue.offerUnsafe(
|
|
860
|
+
session.input,
|
|
861
|
+
userMessage(
|
|
862
|
+
toUserContent(Prompt.fromMessages(users)),
|
|
863
|
+
last === undefined ? undefined : "next",
|
|
864
|
+
),
|
|
865
|
+
)
|
|
866
|
+
}
|
|
867
|
+
plan.ids.forEach((id, i) => session.bridge.resolve(id, results[i]!))
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
// The ids of the tool results in an SDK user message.
|
|
871
|
+
const toolResultIds = (message: Sdk.SDKUserMessage): Array<string> =>
|
|
872
|
+
typeof message.message.content === "string"
|
|
873
|
+
? []
|
|
874
|
+
: message.message.content.flatMap((block) =>
|
|
875
|
+
block.type === "tool_result" ? [block.tool_use_id] : [],
|
|
876
|
+
)
|
|
877
|
+
|
|
878
|
+
// Reads one step from the session, recording how it ended. A step that does
|
|
879
|
+
// not finish leaves the session in an unknown state, so it is closed.
|
|
880
|
+
//
|
|
881
|
+
// A tool step holds back its tool calls and its finish until Claude Code has
|
|
882
|
+
// parked an MCP request for every call. Effect runs a call's handler as soon
|
|
883
|
+
// as more parts follow it, so emitting a call earlier could run a script
|
|
884
|
+
// that Claude Code never waits for. An untagged request, or Claude Code
|
|
885
|
+
// answering a call itself, fails the step before any script runs.
|
|
886
|
+
const readStep = (
|
|
887
|
+
session: Session,
|
|
888
|
+
onAbandon: Effect.Effect<void>,
|
|
889
|
+
): Stream.Stream<Response.StreamPartEncoded, AiError.AiError> =>
|
|
890
|
+
Stream.suspend(() => {
|
|
891
|
+
const convert = makeConverter()
|
|
892
|
+
const calls: Array<Response.ToolCallPartEncoded> = []
|
|
893
|
+
const parked = new Set<string>()
|
|
894
|
+
let finish: Response.FinishPartEncoded | undefined
|
|
895
|
+
let text = ""
|
|
896
|
+
|
|
897
|
+
// Once the tool message's `message_stop` is read, every call it made is
|
|
898
|
+
// known, so a park for any other id can never be released.
|
|
899
|
+
const release = (): Effect.Effect<
|
|
900
|
+
Array<Response.StreamPartEncoded>,
|
|
901
|
+
AiError.AiError
|
|
902
|
+
> => {
|
|
903
|
+
if (finish === undefined) return Effect.succeed([])
|
|
904
|
+
const unknown = [...parked].find(
|
|
905
|
+
(id) => !calls.some((call) => call.id === id),
|
|
906
|
+
)
|
|
907
|
+
if (unknown !== undefined) {
|
|
908
|
+
return Effect.fail(
|
|
909
|
+
unknownError(
|
|
910
|
+
`Claude Code called clanka for tool call ${unknown}, which it never made.`,
|
|
911
|
+
),
|
|
912
|
+
)
|
|
913
|
+
}
|
|
914
|
+
if (!calls.every((call) => parked.has(call.id))) return Effect.succeed([])
|
|
915
|
+
session.outcome = { _tag: "Tools", calls, text }
|
|
916
|
+
return Effect.succeed([...calls, finish])
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
const handle = (
|
|
920
|
+
event: SessionEvent,
|
|
921
|
+
): Effect.Effect<Array<Response.StreamPartEncoded>, AiError.AiError> => {
|
|
922
|
+
if (event.type === "clanka_parked") {
|
|
923
|
+
if (event.id === undefined) {
|
|
924
|
+
return Effect.fail(
|
|
925
|
+
unknownError(
|
|
926
|
+
"Claude Code sent a tool call without its tool use id. This Claude Code version is not supported.",
|
|
927
|
+
),
|
|
928
|
+
)
|
|
929
|
+
}
|
|
930
|
+
parked.add(event.id)
|
|
931
|
+
return release()
|
|
932
|
+
}
|
|
933
|
+
if (event.type === "user" && event.parent_tool_use_id === null) {
|
|
934
|
+
const answered = toolResultIds(event).find(
|
|
935
|
+
(id) => !parked.has(id) && calls.some((call) => call.id === id),
|
|
936
|
+
)
|
|
937
|
+
if (answered !== undefined) {
|
|
938
|
+
return Effect.fail(
|
|
939
|
+
unknownError(
|
|
940
|
+
`Claude Code answered the tool call ${answered} itself instead of calling clanka.`,
|
|
941
|
+
),
|
|
942
|
+
)
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
return Effect.flatMap(convert(event), (parts) => {
|
|
946
|
+
const out: Array<Response.StreamPartEncoded> = []
|
|
947
|
+
for (const part of parts) {
|
|
948
|
+
switch (part.type) {
|
|
949
|
+
case "tool-call":
|
|
950
|
+
calls.push(part)
|
|
951
|
+
break
|
|
952
|
+
case "text-delta":
|
|
953
|
+
text += part.delta
|
|
954
|
+
out.push(part)
|
|
955
|
+
break
|
|
956
|
+
case "finish":
|
|
957
|
+
if (part.reason === "tool-calls") {
|
|
958
|
+
finish = part
|
|
959
|
+
break
|
|
960
|
+
}
|
|
961
|
+
session.outcome = { _tag: "Stop", calls: [], text }
|
|
962
|
+
out.push(part)
|
|
963
|
+
break
|
|
964
|
+
default:
|
|
965
|
+
out.push(part)
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
return Effect.map(release(), (released) => [...out, ...released])
|
|
969
|
+
})
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
return Stream.fromQueue(session.messages).pipe(
|
|
973
|
+
Stream.mapEffect(handle),
|
|
974
|
+
Stream.flattenIterable,
|
|
975
|
+
// The queue ends when Claude Code exits, so reaching this means it
|
|
976
|
+
// stopped mid-step.
|
|
977
|
+
Stream.concat(
|
|
978
|
+
Stream.fail(
|
|
979
|
+
unknownError("Claude Code stopped before finishing its reply"),
|
|
980
|
+
),
|
|
981
|
+
),
|
|
982
|
+
Stream.takeUntil((part) => part.type === "finish"),
|
|
983
|
+
Stream.onExit(() =>
|
|
984
|
+
session.outcome === undefined ? onAbandon : Effect.void,
|
|
985
|
+
),
|
|
986
|
+
)
|
|
987
|
+
})
|
|
988
|
+
|
|
989
|
+
// A call without tools, such as a compaction summary, runs on its own
|
|
990
|
+
// short-lived Claude Code.
|
|
991
|
+
const oneShot = (
|
|
992
|
+
model: string,
|
|
993
|
+
options: ModelOptions | undefined,
|
|
994
|
+
provider: LanguageModel.ProviderOptions,
|
|
995
|
+
) =>
|
|
996
|
+
Stream.unwrap(
|
|
997
|
+
Effect.map(
|
|
998
|
+
Effect.acquireRelease(
|
|
999
|
+
startSession(model, options, provider, false),
|
|
1000
|
+
closeSession,
|
|
1001
|
+
),
|
|
1002
|
+
(session) => readStep(session, Effect.void),
|
|
1003
|
+
),
|
|
1004
|
+
).pipe(Stream.scoped)
|
|
1005
|
+
|
|
1006
|
+
const layerLanguageModel = (
|
|
1007
|
+
model: string,
|
|
1008
|
+
options: ModelOptions | undefined,
|
|
1009
|
+
): Layer.Layer<LanguageModel.LanguageModel> =>
|
|
1010
|
+
Layer.effect(
|
|
1011
|
+
LanguageModel.LanguageModel,
|
|
1012
|
+
Effect.gen(function* () {
|
|
1013
|
+
// The live session of the conversation, one per model layer.
|
|
1014
|
+
let current: Session | undefined
|
|
1015
|
+
const closeCurrent = Effect.suspend(() => {
|
|
1016
|
+
const session = current
|
|
1017
|
+
current = undefined
|
|
1018
|
+
return session === undefined ? Effect.void : closeSession(session)
|
|
1019
|
+
})
|
|
1020
|
+
yield* Effect.addFinalizer(() => closeCurrent)
|
|
1021
|
+
|
|
1022
|
+
const step = (provider: LanguageModel.ProviderOptions) =>
|
|
1023
|
+
Stream.unwrap(
|
|
1024
|
+
Effect.gen(function* () {
|
|
1025
|
+
const plan =
|
|
1026
|
+
current === undefined
|
|
1027
|
+
? undefined
|
|
1028
|
+
: continuation(current, provider)
|
|
1029
|
+
if (current !== undefined && plan !== undefined) {
|
|
1030
|
+
continueSession(current, plan)
|
|
1031
|
+
current.seen = provider.prompt.content
|
|
1032
|
+
current.outcome = undefined
|
|
1033
|
+
return readStep(current, closeCurrent)
|
|
1034
|
+
}
|
|
1035
|
+
yield* closeCurrent
|
|
1036
|
+
current = yield* startSession(model, options, provider, true)
|
|
1037
|
+
return readStep(current, closeCurrent)
|
|
1038
|
+
}),
|
|
1039
|
+
)
|
|
1040
|
+
|
|
1041
|
+
const streamText = (provider: LanguageModel.ProviderOptions) =>
|
|
1042
|
+
provider.tools.length === 0
|
|
1043
|
+
? oneShot(model, options, provider)
|
|
1044
|
+
: step(provider)
|
|
1045
|
+
|
|
1046
|
+
return yield* LanguageModel.make({
|
|
1047
|
+
streamText,
|
|
1048
|
+
generateText: (provider) =>
|
|
1049
|
+
streamText(provider).pipe(Stream.runCollect, Effect.map(toParts)),
|
|
1050
|
+
})
|
|
1051
|
+
}),
|
|
1052
|
+
)
|
|
1053
|
+
|
|
1054
|
+
// Stream parts as the parts of a whole response.
|
|
1055
|
+
const toParts = (
|
|
1056
|
+
parts: ReadonlyArray<Response.StreamPartEncoded>,
|
|
1057
|
+
): Array<Response.PartEncoded> => {
|
|
1058
|
+
const result: Array<Response.PartEncoded> = []
|
|
1059
|
+
const texts = new Map<string, { type: "text" | "reasoning"; text: string }>()
|
|
1060
|
+
for (const part of parts) {
|
|
1061
|
+
switch (part.type) {
|
|
1062
|
+
case "text-start":
|
|
1063
|
+
case "reasoning-start":
|
|
1064
|
+
texts.set(part.id, {
|
|
1065
|
+
type: part.type === "text-start" ? "text" : "reasoning",
|
|
1066
|
+
text: "",
|
|
1067
|
+
})
|
|
1068
|
+
break
|
|
1069
|
+
case "text-delta":
|
|
1070
|
+
case "reasoning-delta": {
|
|
1071
|
+
const text = texts.get(part.id)
|
|
1072
|
+
if (text !== undefined) text.text += part.delta
|
|
1073
|
+
break
|
|
1074
|
+
}
|
|
1075
|
+
case "text-end":
|
|
1076
|
+
case "reasoning-end": {
|
|
1077
|
+
const text = texts.get(part.id)
|
|
1078
|
+
if (text !== undefined)
|
|
1079
|
+
result.push({ type: text.type, text: text.text })
|
|
1080
|
+
break
|
|
1081
|
+
}
|
|
1082
|
+
case "tool-call":
|
|
1083
|
+
case "finish":
|
|
1084
|
+
result.push(part)
|
|
1085
|
+
break
|
|
1086
|
+
}
|
|
1087
|
+
}
|
|
1088
|
+
return result
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
/**
|
|
1092
|
+
* A Claude model run by the user's installed Claude Code, with whatever
|
|
1093
|
+
* login it has: a Claude subscription, an API key, or Bedrock, Vertex or
|
|
1094
|
+
* Foundry credentials.
|
|
1095
|
+
*
|
|
1096
|
+
* @since 1.0.0
|
|
1097
|
+
* @category Layers
|
|
1098
|
+
*/
|
|
1099
|
+
export const model = (
|
|
1100
|
+
model: string,
|
|
1101
|
+
options?: ModelOptions | undefined,
|
|
1102
|
+
): Model.Model<"claude", LanguageModel.LanguageModel, never> =>
|
|
1103
|
+
Model.make(
|
|
1104
|
+
"claude",
|
|
1105
|
+
model,
|
|
1106
|
+
Layer.merge(
|
|
1107
|
+
layerLanguageModel(model, options),
|
|
1108
|
+
// The system prompt stays in the Prompt, where `queryOptions` reads
|
|
1109
|
+
// it. No Compaction.SummarizerTransform: Claude Code takes no
|
|
1110
|
+
// per-request output cap.
|
|
1111
|
+
AgentModelConfig.layer({ supportsImages: options?.supportsImages }),
|
|
1112
|
+
),
|
|
1113
|
+
)
|