clanka 0.17.0 → 0.17.2

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 (62) hide show
  1. package/dist/Agent.d.ts +4 -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/Agent.test.js +35 -0
  6. package/dist/Agent.test.js.map +1 -1
  7. package/dist/AgentCallerConfig.test.js +5 -3
  8. package/dist/AgentCallerConfig.test.js.map +1 -1
  9. package/dist/ChunkRepo.d.ts +1 -1
  10. package/dist/ClaudeAgent.d.ts.map +1 -1
  11. package/dist/ClaudeAgent.js +46 -17
  12. package/dist/ClaudeAgent.js.map +1 -1
  13. package/dist/ClaudeAgent.test.js +87 -16
  14. package/dist/ClaudeAgent.test.js.map +1 -1
  15. package/dist/Compaction.test.js +2 -1
  16. package/dist/Compaction.test.js.map +1 -1
  17. package/dist/CompactionTokens.test.js +15 -8
  18. package/dist/CompactionTokens.test.js.map +1 -1
  19. package/dist/bin/{Effect-On-1ks2z.mjs → Effect-DNYYQ84C.mjs} +421 -367
  20. package/dist/bin/Effect-DNYYQ84C.mjs.map +1 -0
  21. package/dist/bin/Latch-BSlIwuxI.mjs +7 -0
  22. package/dist/bin/Latch-BSlIwuxI.mjs.map +1 -0
  23. package/dist/bin/{McpClient-iwrW83Si.mjs → McpClient-C7ctqJWo.mjs} +4 -5
  24. package/dist/bin/{McpClient-iwrW83Si.mjs.map → McpClient-C7ctqJWo.mjs.map} +1 -1
  25. package/dist/bin/{OutputFormatter-DeNaqhQM.mjs → OutputFormatter-DXej05JW.mjs} +8 -13
  26. package/dist/bin/{OutputFormatter-DeNaqhQM.mjs.map → OutputFormatter-DXej05JW.mjs.map} +1 -1
  27. package/dist/bin/{Schema-B3pFcw4E.mjs → Schema-CSQN_Zso.mjs} +754 -800
  28. package/dist/bin/Schema-CSQN_Zso.mjs.map +1 -0
  29. package/dist/bin/{SemanticSearch-BZIXkWYz.mjs → SemanticSearch-BiwCnpKX.mjs} +241 -148
  30. package/dist/bin/SemanticSearch-BiwCnpKX.mjs.map +1 -0
  31. package/dist/bin/{Stream-DCB3_nIX.mjs → Stream-Dwvj9X5X.mjs} +161 -116
  32. package/dist/bin/Stream-Dwvj9X5X.mjs.map +1 -0
  33. package/dist/bin/cli.mjs +4022 -3231
  34. package/dist/bin/cli.mjs.map +1 -1
  35. package/dist/bin/{helpers-BPLUsjsL.mjs → helpers-CljL9OKa.mjs} +143 -177
  36. package/dist/bin/helpers-CljL9OKa.mjs.map +1 -0
  37. package/dist/bin/index.min-ClUfQ5ji.mjs +3782 -0
  38. package/dist/bin/index.min-ClUfQ5ji.mjs.map +1 -0
  39. package/dist/bin/{rolldown-runtime-Cjv6nE1W.mjs → rolldown-runtime-5zChB7MF.mjs} +1 -2
  40. package/dist/bin/{server-CBmuybpI.mjs → server-HlLriZxF.mjs} +5 -7
  41. package/dist/bin/{server-CBmuybpI.mjs.map → server-HlLriZxF.mjs.map} +1 -1
  42. package/dist/bin/{turndown.cjs-cie0BXQQ.mjs → turndown.cjs-C2WBxeA-.mjs} +56 -110
  43. package/dist/bin/{turndown.cjs-cie0BXQQ.mjs.map → turndown.cjs-C2WBxeA-.mjs.map} +1 -1
  44. package/dist/bin/{types-RT_9fFNm.mjs → types-LcwjLVkt.mjs} +20 -38
  45. package/dist/bin/{types-RT_9fFNm.mjs.map → types-LcwjLVkt.mjs.map} +1 -1
  46. package/dist/bin/upgrade-BSNjCnra.mjs +342 -0
  47. package/dist/bin/upgrade-BSNjCnra.mjs.map +1 -0
  48. package/package.json +14 -20
  49. package/src/Agent.test.ts +69 -0
  50. package/src/Agent.ts +5 -1
  51. package/src/AgentCallerConfig.test.ts +5 -3
  52. package/src/ClaudeAgent.test.ts +120 -21
  53. package/src/ClaudeAgent.ts +59 -19
  54. package/src/Compaction.test.ts +2 -1
  55. package/src/CompactionTokens.test.ts +15 -11
  56. package/dist/bin/Effect-On-1ks2z.mjs.map +0 -1
  57. package/dist/bin/Schema-B3pFcw4E.mjs.map +0 -1
  58. package/dist/bin/SemanticSearch-BZIXkWYz.mjs.map +0 -1
  59. package/dist/bin/Stream-DCB3_nIX.mjs.map +0 -1
  60. package/dist/bin/helpers-BPLUsjsL.mjs.map +0 -1
  61. package/dist/bin/index.min-Bkz7vIWv.mjs +0 -3300
  62. package/dist/bin/index.min-Bkz7vIWv.mjs.map +0 -1
@@ -3,13 +3,18 @@ import type {
3
3
  query as SdkQuery,
4
4
  SDKUserMessage,
5
5
  } from "@anthropic-ai/claude-agent-sdk"
6
- import { assert, describe, it } from "@effect/vitest"
6
+ import { assert, beforeEach, describe, it } from "@effect/vitest"
7
7
  import { Client } from "@modelcontextprotocol/sdk/client/index.js"
8
8
  import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"
9
+ import * as Context from "effect/Context"
10
+ import * as Deferred from "effect/Deferred"
9
11
  import * as Effect from "effect/Effect"
12
+ import * as Exit from "effect/Exit"
13
+ import * as Fiber from "effect/Fiber"
10
14
  import * as Layer from "effect/Layer"
11
15
  import * as Base64 from "effect/encoding/Base64"
12
16
  import * as Schema from "effect/Schema"
17
+ import * as Scope from "effect/Scope"
13
18
  import * as Stream from "effect/Stream"
14
19
  import * as LanguageModel from "effect/ai/LanguageModel"
15
20
  import * as Prompt from "effect/ai/Prompt"
@@ -302,7 +307,9 @@ const fakeClaude = (run: (session: FakeSession) => AsyncGenerator<object>) => {
302
307
  }
303
308
 
304
309
  // Claude Code calling clanka's `execute` tool over MCP, each call tagged with
305
- // its tool use id unless `tagged` is false.
310
+ // its tool use id unless `tagged` is false. Like Claude Code, it runs the calls
311
+ // together only when `tools/list` marks the tool read-only, and otherwise
312
+ // requests each call after the previous one returns.
306
313
  const callExecute = async (
307
314
  session: FakeSession,
308
315
  calls: ReadonlyArray<readonly [id: string, script: string]>,
@@ -318,13 +325,22 @@ const callExecute = async (
318
325
  await server.instance.connect(serverTransport)
319
326
  const client = new Client({ name: "claude-code", version: "0.0.0" })
320
327
  await client.connect(clientTransport)
321
- return Promise.all(
322
- calls.map(([id, script]) =>
323
- client.callTool({
324
- name: "execute",
325
- arguments: { script },
326
- ...(tagged ? { _meta: { "claudecode/toolUseId": id } } : {}),
327
- }),
328
+ const { tools } = await client.listTools()
329
+ const readOnly =
330
+ tools.find((tool) => tool.name === "execute")?.annotations?.readOnlyHint ===
331
+ true
332
+ return Effect.runPromise(
333
+ Effect.forEach(
334
+ calls,
335
+ ([id, script]) =>
336
+ Effect.promise(() =>
337
+ client.callTool({
338
+ name: "execute",
339
+ arguments: { script },
340
+ ...(tagged ? { _meta: { "claudecode/toolUseId": id } } : {}),
341
+ }),
342
+ ),
343
+ { concurrency: readOnly ? "unbounded" : 1 },
328
344
  ),
329
345
  )
330
346
  }
@@ -373,6 +389,21 @@ const finalStep = [
373
389
  },
374
390
  ]
375
391
 
392
+ // The start of a step that is still writing its reply.
393
+ const replying = [
394
+ ...executeStep([]).slice(0, 1),
395
+ event({
396
+ type: "content_block_start",
397
+ index: 0,
398
+ content_block: { type: "text", text: "" },
399
+ }),
400
+ event({
401
+ type: "content_block_delta",
402
+ index: 0,
403
+ delta: { type: "text_delta", text: "Working" },
404
+ }),
405
+ ]
406
+
376
407
  const Execute = Toolkit.make(
377
408
  Tool.make("execute", {
378
409
  parameters: Schema.Struct({ script: Schema.String }),
@@ -383,6 +414,10 @@ const Execute = Toolkit.make(
383
414
  // The scripts clanka's `execute` handler ran.
384
415
  const executed: Array<string> = []
385
416
 
417
+ beforeEach(() => {
418
+ executed.length = 0
419
+ })
420
+
386
421
  const ExecuteHandlers = Execute.toLayer({
387
422
  execute: ({ script }) =>
388
423
  Effect.sync(() => {
@@ -438,6 +473,7 @@ describe("ClaudeAgent.model", () => {
438
473
  results.map((result: any) => result.content),
439
474
  [[{ type: "text", text: "ran a" }], [{ type: "text", text: "ran b" }]],
440
475
  )
476
+ assert.deepStrictEqual(executed.toSorted(), ["a", "b"])
441
477
  assert.lengthOf(fake.sessions, 1)
442
478
  }),
443
479
  )
@@ -451,7 +487,6 @@ describe("ClaudeAgent.model", () => {
451
487
  ["toolu_b", "b"],
452
488
  ] as const
453
489
  let results: ReadonlyArray<unknown> = []
454
- executed.length = 0
455
490
  const fake = fakeClaude(async function* (session) {
456
491
  await session.input.next()
457
492
  yield* executeStep(calls)
@@ -498,17 +533,7 @@ describe("ClaudeAgent.model", () => {
498
533
  Effect.gen(function* () {
499
534
  const fake = fakeClaude(async function* (session) {
500
535
  await session.input.next()
501
- yield* executeStep([]).slice(0, 1)
502
- yield event({
503
- type: "content_block_start",
504
- index: 0,
505
- content_block: { type: "text", text: "" },
506
- })
507
- yield event({
508
- type: "content_block_delta",
509
- index: 0,
510
- delta: { type: "text_delta", text: "Working" },
511
- })
536
+ yield* replying
512
537
  await new Promise(() => {})
513
538
  })
514
539
  const prompt = Prompt.fromMessages([system, user("go")])
@@ -523,4 +548,78 @@ describe("ClaudeAgent.model", () => {
523
548
  }).pipe(Effect.provide(modelWith(fake)))
524
549
  }),
525
550
  )
551
+
552
+ it.effect(
553
+ "refuses a second step while one is read, keeping the first session",
554
+ () =>
555
+ Effect.gen(function* () {
556
+ const released = Promise.withResolvers<void>()
557
+ const fake = fakeClaude(async function* (session) {
558
+ await session.input.next()
559
+ if (session === fake.sessions[0]) {
560
+ yield* replying
561
+ await released.promise
562
+ }
563
+ yield* finalStep
564
+ })
565
+ yield* Effect.gen(function* () {
566
+ const ai = yield* LanguageModel.LanguageModel
567
+ const reading = yield* Deferred.make<void>()
568
+ const first = yield* ai
569
+ .streamText({
570
+ prompt: Prompt.fromMessages([system, user("go")]),
571
+ toolkit: Execute,
572
+ })
573
+ .pipe(
574
+ Stream.tap(() => Deferred.succeed(reading, undefined)),
575
+ Stream.runDrain,
576
+ Effect.forkChild,
577
+ )
578
+ yield* Deferred.await(reading)
579
+ const second = yield* ai
580
+ .streamText({
581
+ prompt: Prompt.fromMessages([system, user("something else")]),
582
+ toolkit: Execute,
583
+ })
584
+ .pipe(Stream.runDrain, Effect.exit)
585
+ assert.isTrue(Exit.isFailure(second))
586
+ assert.lengthOf(fake.sessions, 1)
587
+ assert.isFalse(fake.sessions[0]!.closed)
588
+ released.resolve()
589
+ yield* Fiber.join(first)
590
+ }).pipe(Effect.provide(modelWith(fake)))
591
+ }),
592
+ )
593
+
594
+ it.live("fails a reader whose session was closed instead of hanging", () =>
595
+ Effect.gen(function* () {
596
+ const fake = fakeClaude(async function* (session) {
597
+ await session.input.next()
598
+ yield* replying
599
+ await new Promise(() => {})
600
+ })
601
+ const scope = yield* Scope.make()
602
+ const context = yield* Layer.buildWithScope(modelWith(fake), scope)
603
+ const reading = yield* Deferred.make<void>()
604
+ const reader = yield* Context.get(context, LanguageModel.LanguageModel)
605
+ .streamText({
606
+ prompt: Prompt.fromMessages([system, user("go")]),
607
+ toolkit: Execute,
608
+ })
609
+ .pipe(
610
+ Stream.tap(() => Deferred.succeed(reading, undefined)),
611
+ Stream.runDrain,
612
+ Effect.provideContext(context),
613
+ Effect.forkChild,
614
+ )
615
+ yield* Deferred.await(reading)
616
+ // Closing the model closes Claude Code under the step being read.
617
+ yield* Scope.close(scope, Exit.void)
618
+ const error = yield* Fiber.join(reader).pipe(
619
+ Effect.flip,
620
+ Effect.timeout("1 second"),
621
+ )
622
+ assert.strictEqual(error._tag, "AiError")
623
+ }),
624
+ )
526
625
  })
@@ -478,6 +478,24 @@ const makeConverter = () => {
478
478
  reason: message.stop_reason === "max_tokens" ? "length" : "stop",
479
479
  usage: usage.snapshot(),
480
480
  })
481
+ } else if (message.type === "system" && message.subtype === "api_retry") {
482
+ // Logged so a long retry by Claude Code is not mistaken for a stall.
483
+ return Effect.logDebug("Claude Code is retrying an API request").pipe(
484
+ Effect.annotateLogs({
485
+ attempt: message.attempt,
486
+ maxRetries: message.max_retries,
487
+ retryDelayMs: message.retry_delay_ms,
488
+ errorStatus: message.error_status,
489
+ error: message.error,
490
+ ...(message.no_response === undefined
491
+ ? {}
492
+ : {
493
+ noResponseWaitedMs: message.no_response.waited_ms,
494
+ noResponseRetryWaitMs: message.no_response.retry_wait_ms,
495
+ }),
496
+ }),
497
+ Effect.as(parts),
498
+ )
481
499
  }
482
500
  return Effect.succeed(parts)
483
501
  }
@@ -579,7 +597,7 @@ const makeToolServer = (
579
597
  inputSchema: Tool.getJsonSchema(tool) as {
580
598
  readonly type: "object"
581
599
  },
582
- annotations: { readOnlyHint: false },
600
+ annotations: { readOnlyHint: true },
583
601
  _meta: { "anthropic/alwaysLoad": true },
584
602
  }))
585
603
  server.setRequestHandler(ListToolsRequestSchema, async () => ({
@@ -677,11 +695,14 @@ interface Session {
677
695
  outcome: Outcome | undefined
678
696
  }
679
697
 
698
+ // Ends `messages` before closing the scope, which interrupts the fiber that
699
+ // would end it, so a step still reading the session fails instead of waiting.
680
700
  const closeSession = (session: Session) =>
681
701
  Effect.suspend(() => {
682
702
  session.bridge.cancel()
683
703
  session.query.close()
684
704
  return Queue.end(session.input).pipe(
705
+ Effect.andThen(Queue.end(session.messages)),
685
706
  Effect.andThen(Scope.close(session.scope, Exit.void)),
686
707
  )
687
708
  })
@@ -972,8 +993,8 @@ const readStep = (
972
993
  return Stream.fromQueue(session.messages).pipe(
973
994
  Stream.mapEffect(handle),
974
995
  Stream.flattenIterable,
975
- // The queue ends when Claude Code exits, so reaching this means it
976
- // stopped mid-step.
996
+ // The queue ends when Claude Code exits or the session is closed, so
997
+ // reaching this means it stopped mid-step.
977
998
  Stream.concat(
978
999
  Stream.fail(
979
1000
  unknownError("Claude Code stopped before finishing its reply"),
@@ -1018,25 +1039,44 @@ const layerLanguageModel = (
1018
1039
  return session === undefined ? Effect.void : closeSession(session)
1019
1040
  })
1020
1041
  yield* Effect.addFinalizer(() => closeCurrent)
1042
+ // Set while a step is read. Another step would close the session under
1043
+ // it, so it fails instead.
1044
+ let reading = false
1021
1045
 
1022
1046
  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
1047
+ Stream.suspend(() => {
1048
+ if (reading) {
1049
+ return Stream.fail(
1050
+ unknownError(
1051
+ "This Claude Agent model is already reading a step. Every agent needs its own model instance.",
1052
+ ),
1053
+ )
1054
+ }
1055
+ reading = true
1056
+ return Stream.unwrap(
1057
+ Effect.gen(function* () {
1058
+ const plan =
1059
+ current === undefined
1060
+ ? undefined
1061
+ : continuation(current, provider)
1062
+ if (current !== undefined && plan !== undefined) {
1063
+ continueSession(current, plan)
1064
+ current.seen = provider.prompt.content
1065
+ current.outcome = undefined
1066
+ return readStep(current, closeCurrent)
1067
+ }
1068
+ yield* closeCurrent
1069
+ current = yield* startSession(model, options, provider, true)
1033
1070
  return readStep(current, closeCurrent)
1034
- }
1035
- yield* closeCurrent
1036
- current = yield* startSession(model, options, provider, true)
1037
- return readStep(current, closeCurrent)
1038
- }),
1039
- )
1071
+ }),
1072
+ ).pipe(
1073
+ Stream.ensuring(
1074
+ Effect.sync(() => {
1075
+ reading = false
1076
+ }),
1077
+ ),
1078
+ )
1079
+ })
1040
1080
 
1041
1081
  const streamText = (provider: LanguageModel.ProviderOptions) =>
1042
1082
  provider.tools.length === 0
@@ -439,7 +439,8 @@ describe("Compaction.isContextLengthError", () => {
439
439
  openAiError(
440
440
  new AiError.NetworkError({
441
441
  reason: "TransportError",
442
- request,
442
+ method: request.method,
443
+ url: request.url,
443
444
  description: "socket timeout",
444
445
  }),
445
446
  ),
@@ -10,14 +10,15 @@ const user = (value: string) =>
10
10
  Prompt.makeMessage("user", { content: [text(value)] })
11
11
 
12
12
  // Estimation treats image payloads as opaque; no image decoder is involved.
13
- const imageMessage = (size: number) =>
13
+ const imageBytes = (size: number) => new Uint8Array(size).fill(137)
14
+ const imageMessage = (data: string | Uint8Array) =>
14
15
  Prompt.makeMessage("user", {
15
16
  content: [
16
17
  text("Describe this screenshot"),
17
18
  Prompt.makePart("file", {
18
19
  mediaType: "image/png",
19
20
  fileName: "screenshot.png",
20
- data: new Uint8Array(size).fill(137),
21
+ data,
21
22
  }),
22
23
  ],
23
24
  })
@@ -52,9 +53,15 @@ const toolResult = (result: string) =>
52
53
  })
53
54
 
54
55
  describe("Compaction image token estimates", () => {
55
- for (const representation of ["binary", "reloaded base64"] as const) {
56
+ // Older releases persisted image bytes as plain base64 strings, so those
57
+ // histories still reload with string data.
58
+ for (const representation of ["binary", "base64", "reloaded"] as const) {
56
59
  const history = (size: number) => {
57
- const prompt = Prompt.fromMessages([imageMessage(size)])
60
+ const bytes = imageBytes(size)
61
+ if (representation === "base64") {
62
+ return reload(Prompt.fromMessages([imageMessage(Base64.encode(bytes))]))
63
+ }
64
+ const prompt = Prompt.fromMessages([imageMessage(bytes)])
58
65
  return representation === "binary" ? prompt : reload(prompt)
59
66
  }
60
67
 
@@ -130,8 +137,8 @@ describe("Compaction image token estimates", () => {
130
137
  })
131
138
  }
132
139
 
133
- it("preserves estimates across the binary-to-base64 persistence round trip", () => {
134
- const prompt = Prompt.fromMessages([imageMessage(1024)])
140
+ it("preserves binary data and estimates across the persistence round trip", () => {
141
+ const prompt = Prompt.fromMessages([imageMessage(imageBytes(1024))])
135
142
  const restored = reload(prompt)
136
143
  const message = restored.content[0]!
137
144
  assert.strictEqual(message.role, "user")
@@ -139,10 +146,7 @@ describe("Compaction image token estimates", () => {
139
146
  const image = message.content[1]!
140
147
  assert.strictEqual(image.type, "file")
141
148
  if (image.type !== "file") return
142
- assert.strictEqual(
143
- image.data,
144
- Base64.encode(new Uint8Array(1024).fill(137)),
145
- )
149
+ assert.deepStrictEqual(image.data, imageBytes(1024))
146
150
  assert.strictEqual(
147
151
  Compaction.estimateTokens(restored),
148
152
  Compaction.estimateTokens(prompt),
@@ -154,7 +158,7 @@ describe("Compaction image token estimates", () => {
154
158
  })
155
159
 
156
160
  it("charges for each image rather than ignoring all file parts", () => {
157
- const one = imageMessage(32)
161
+ const one = imageMessage(imageBytes(32))
158
162
  const two = Prompt.makeMessage("user", {
159
163
  content: [...one.content, one.content[1]!],
160
164
  })