clanka 0.17.2 → 0.17.3

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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "clanka",
3
3
  "type": "module",
4
- "version": "0.17.2",
4
+ "version": "0.17.3",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -309,17 +309,36 @@ const fakeClaude = (run: (session: FakeSession) => AsyncGenerator<object>) => {
309
309
  // Claude Code calling clanka's `execute` tool over MCP, each call tagged with
310
310
  // its tool use id unless `tagged` is false. Like Claude Code, it runs the calls
311
311
  // together only when `tools/list` marks the tool read-only, and otherwise
312
- // requests each call after the previous one returns.
312
+ // requests each call after the previous one returns. `onRequest` runs once
313
+ // clanka's handler has taken each request.
313
314
  const callExecute = async (
314
315
  session: FakeSession,
315
316
  calls: ReadonlyArray<readonly [id: string, script: string]>,
316
317
  tagged = true,
318
+ onRequest?: () => void,
317
319
  ) => {
318
- const server = session.options.mcpServers?.clanka as {
320
+ const server = session.options.mcpServers?.clanka as unknown as {
319
321
  readonly instance: {
320
322
  connect: (transport: InMemoryTransport) => Promise<void>
323
+ // The MCP SDK's handlers by method. Not public, but the SDK has no
324
+ // other way to see a request reach a handler that never returns.
325
+ readonly _requestHandlers: Map<
326
+ string,
327
+ (request: unknown, extra: unknown) => Promise<unknown>
328
+ >
321
329
  }
322
330
  }
331
+ if (onRequest !== undefined) {
332
+ const handlers = server.instance._requestHandlers
333
+ const handler = handlers.get("tools/call")
334
+ assert.isDefined(handler)
335
+ // The SDK's wrapper calls clanka's handler before its first await.
336
+ handlers.set("tools/call", (request, extra) => {
337
+ const result = handler(request, extra)
338
+ onRequest()
339
+ return result
340
+ })
341
+ }
323
342
  const [clientTransport, serverTransport] =
324
343
  InMemoryTransport.createLinkedPair()
325
344
  await server.instance.connect(serverTransport)
@@ -346,11 +365,14 @@ const callExecute = async (
346
365
  }
347
366
 
348
367
  // One API message calling `execute` once per call.
349
- const executeStep = (calls: ReadonlyArray<readonly [string, string]>) => [
368
+ const executeStep = (
369
+ calls: ReadonlyArray<readonly [string, string]>,
370
+ id = "msg_tools",
371
+ ) => [
350
372
  event({
351
373
  type: "message_start",
352
374
  message: {
353
- id: "msg_tools",
375
+ id,
354
376
  type: "message",
355
377
  role: "assistant",
356
378
  model: "claude-opus-5-5",
@@ -376,6 +398,22 @@ const executeStep = (calls: ReadonlyArray<readonly [string, string]>) => [
376
398
  event({ type: "message_stop" }),
377
399
  ]
378
400
 
401
+ // Claude Code answering a call itself instead of calling clanka, as it does
402
+ // for input it cannot validate or a call it aborts.
403
+ const answeredByClaude = (id: string, content: string) => ({
404
+ ...frame,
405
+ type: "user",
406
+ message: {
407
+ role: "user",
408
+ content: [
409
+ { type: "tool_result", tool_use_id: id, content, is_error: true },
410
+ ],
411
+ },
412
+ })
413
+
414
+ const invalidInput =
415
+ "<tool_use_error>InputValidationError: JSON parse failed</tool_use_error>"
416
+
379
417
  const finalStep = [
380
418
  assistant({ type: "text", text: "Done." }),
381
419
  {
@@ -505,6 +543,122 @@ describe("ClaudeAgent.model", () => {
505
543
  }),
506
544
  )
507
545
 
546
+ it.effect(
547
+ "drops a call Claude Code answered itself and runs the parked one",
548
+ () =>
549
+ Effect.gen(function* () {
550
+ let results: ReadonlyArray<unknown> = []
551
+ const fake = fakeClaude(async function* (session) {
552
+ await session.input.next()
553
+ yield* executeStep([
554
+ ["toolu_a", "a"],
555
+ ["toolu_b", "b"],
556
+ ])
557
+ yield answeredByClaude("toolu_a", invalidInput)
558
+ results = await callExecute(session, [["toolu_b", "b"]])
559
+ yield* finalStep
560
+ })
561
+ yield* runSteps(fake, (first, response) =>
562
+ Prompt.concat(first, response),
563
+ )
564
+ assert.deepStrictEqual(
565
+ results.map((result: any) => result.content),
566
+ [[{ type: "text", text: "ran b" }]],
567
+ )
568
+ assert.deepStrictEqual(executed, ["b"])
569
+ assert.lengthOf(fake.sessions, 1)
570
+ }),
571
+ )
572
+
573
+ it.effect(
574
+ "keeps reading when Claude Code answers the only call and Claude retries",
575
+ () =>
576
+ Effect.gen(function* () {
577
+ let results: ReadonlyArray<unknown> = []
578
+ const fake = fakeClaude(async function* (session) {
579
+ await session.input.next()
580
+ yield* executeStep([["toolu_a", "a"]])
581
+ yield answeredByClaude("toolu_a", invalidInput)
582
+ yield* executeStep([["toolu_b", "b"]], "msg_retry")
583
+ results = await callExecute(session, [["toolu_b", "b"]])
584
+ yield* finalStep
585
+ })
586
+ yield* runSteps(fake, (first, response) =>
587
+ Prompt.concat(first, response),
588
+ )
589
+ assert.deepStrictEqual(
590
+ results.map((result: any) => result.content),
591
+ [[{ type: "text", text: "ran b" }]],
592
+ )
593
+ assert.deepStrictEqual(executed, ["b"])
594
+ assert.lengthOf(fake.sessions, 1)
595
+ }),
596
+ )
597
+
598
+ it.effect(
599
+ "holds a retry's calls until its message stops, even when they park first",
600
+ () =>
601
+ Effect.gen(function* () {
602
+ const retry = [
603
+ ["toolu_b", "b"],
604
+ ["toolu_c", "c"],
605
+ ] as const
606
+ let results: ReadonlyArray<unknown> = []
607
+ const fake = fakeClaude(async function* (session) {
608
+ await session.input.next()
609
+ yield* executeStep([["toolu_a", "a"]])
610
+ yield answeredByClaude("toolu_a", invalidInput)
611
+ const retryStep = executeStep(retry, "msg_retry")
612
+ yield* retryStep.slice(0, 1)
613
+ // Claude Code runs a call as soon as its block streams, so the
614
+ // retry's requests park before its assistant events and its
615
+ // message_stop.
616
+ const parked = Promise.withResolvers<void>()
617
+ let requests = 0
618
+ const parking = callExecute(session, retry, true, () => {
619
+ if (++requests === retry.length) parked.resolve()
620
+ })
621
+ await parked.promise
622
+ yield* retryStep.slice(1)
623
+ results = await parking
624
+ yield* finalStep
625
+ })
626
+ yield* runSteps(fake, (first, response) =>
627
+ Prompt.concat(first, response),
628
+ )
629
+ assert.deepStrictEqual(
630
+ results.map((result: any) => result.content),
631
+ [
632
+ [{ type: "text", text: "ran b" }],
633
+ [{ type: "text", text: "ran c" }],
634
+ ],
635
+ )
636
+ assert.deepStrictEqual(executed.toSorted(), ["b", "c"])
637
+ assert.lengthOf(fake.sessions, 1)
638
+ }),
639
+ )
640
+
641
+ it.effect("fails an aborted call with the result Claude Code gave it", () =>
642
+ Effect.gen(function* () {
643
+ const fake = fakeClaude(async function* (session) {
644
+ await session.input.next()
645
+ yield* executeStep([["toolu_a", "a"]])
646
+ yield answeredByClaude(
647
+ "toolu_a",
648
+ "[Request interrupted by user for tool use]",
649
+ )
650
+ })
651
+ const error = yield* Effect.flip(
652
+ runSteps(fake, (first, response) => Prompt.concat(first, response)),
653
+ )
654
+ assert.include(
655
+ error.message,
656
+ "[Request interrupted by user for tool use]",
657
+ )
658
+ assert.deepStrictEqual(executed, [])
659
+ }),
660
+ )
661
+
508
662
  it.effect(
509
663
  "starts over when the prompt's answer is not the one Claude gave",
510
664
  () =>
@@ -372,6 +372,7 @@ const makeConverter = () => {
372
372
  switch (event.type) {
373
373
  case "message_start":
374
374
  messageId = event.message.id
375
+ calledTools = false
375
376
  streamed.add(messageId)
376
377
  usage.update(messageId, event.message.usage)
377
378
  break
@@ -888,22 +889,51 @@ const continueSession = (
888
889
  plan.ids.forEach((id, i) => session.bridge.resolve(id, results[i]!))
889
890
  }
890
891
 
891
- // The ids of the tool results in an SDK user message.
892
- const toolResultIds = (message: Sdk.SDKUserMessage): Array<string> =>
892
+ // The tool results in an SDK user message, with their text.
893
+ const toolResults = (
894
+ message: Sdk.SDKUserMessage,
895
+ ): Array<{
896
+ readonly id: string
897
+ readonly isError: boolean
898
+ readonly text: string
899
+ }> =>
893
900
  typeof message.message.content === "string"
894
901
  ? []
895
902
  : message.message.content.flatMap((block) =>
896
- block.type === "tool_result" ? [block.tool_use_id] : [],
903
+ block.type === "tool_result"
904
+ ? [
905
+ {
906
+ id: block.tool_use_id,
907
+ isError: block.is_error === true,
908
+ text:
909
+ typeof block.content === "string"
910
+ ? block.content
911
+ : (block.content ?? [])
912
+ .flatMap((part) =>
913
+ part.type === "text" ? [part.text] : [],
914
+ )
915
+ .join("\n"),
916
+ },
917
+ ]
918
+ : [],
897
919
  )
898
920
 
921
+ // Claude Code wraps the errors it hands back to the model, such as invalid
922
+ // input, a streaming fallback or an unknown tool, in this tag, and marks
923
+ // their results `is_error`. Aborts are not wrapped.
924
+ const isToolUseError = (text: string) =>
925
+ text.trimStart().startsWith("<tool_use_error>")
926
+
899
927
  // Reads one step from the session, recording how it ended. A step that does
900
928
  // not finish leaves the session in an unknown state, so it is closed.
901
929
  //
902
930
  // A tool step holds back its tool calls and its finish until Claude Code has
903
931
  // parked an MCP request for every call. Effect runs a call's handler as soon
904
932
  // as more parts follow it, so emitting a call earlier could run a script
905
- // that Claude Code never waits for. An untagged request, or Claude Code
906
- // answering a call itself, fails the step before any script runs.
933
+ // that Claude Code never waits for. When Claude Code answers a held call
934
+ // itself with an error for the model, the call is dropped and the step keeps
935
+ // reading while the model retries. An untagged request, or any other answer
936
+ // from Claude Code, fails the step before any script runs.
907
937
  const readStep = (
908
938
  session: Session,
909
939
  onAbandon: Effect.Effect<void>,
@@ -932,7 +962,11 @@ const readStep = (
932
962
  ),
933
963
  )
934
964
  }
935
- if (!calls.every((call) => parked.has(call.id))) return Effect.succeed([])
965
+ // With every call dropped, the step waits for the model's retry or
966
+ // the end of its turn.
967
+ if (calls.length === 0 || !calls.every((call) => parked.has(call.id))) {
968
+ return Effect.succeed([])
969
+ }
936
970
  session.outcome = { _tag: "Tools", calls, text }
937
971
  return Effect.succeed([...calls, finish])
938
972
  }
@@ -952,16 +986,30 @@ const readStep = (
952
986
  return release()
953
987
  }
954
988
  if (event.type === "user" && event.parent_tool_use_id === null) {
955
- const answered = toolResultIds(event).find(
956
- (id) => !parked.has(id) && calls.some((call) => call.id === id),
957
- )
958
- if (answered !== undefined) {
959
- return Effect.fail(
960
- unknownError(
961
- `Claude Code answered the tool call ${answered} itself instead of calling clanka.`,
962
- ),
963
- )
989
+ let dropped = false
990
+ for (const result of toolResults(event)) {
991
+ const index = calls.findIndex((call) => call.id === result.id)
992
+ if (index === -1 || parked.has(result.id)) continue
993
+ if (!result.isError || !isToolUseError(result.text)) {
994
+ return Effect.fail(
995
+ unknownError(
996
+ `Claude Code answered the tool call ${result.id} itself instead of calling clanka: ${result.text}`,
997
+ ),
998
+ )
999
+ }
1000
+ calls.splice(index, 1)
1001
+ dropped = true
964
1002
  }
1003
+ if (dropped) return release()
1004
+ }
1005
+ // A retry after dropped calls is a new API message; the last one's
1006
+ // finish must not release its calls before its own `message_stop`.
1007
+ if (
1008
+ event.type === "stream_event" &&
1009
+ event.parent_tool_use_id === null &&
1010
+ event.event.type === "message_start"
1011
+ ) {
1012
+ finish = undefined
965
1013
  }
966
1014
  return Effect.flatMap(convert(event), (parts) => {
967
1015
  const out: Array<Response.StreamPartEncoded> = []