clanka 0.17.1 → 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.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "clanka",
3
3
  "type": "module",
4
- "version": "0.17.1",
4
+ "version": "0.17.2",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
package/src/Agent.test.ts CHANGED
@@ -144,6 +144,75 @@ describe("Agent", () => {
144
144
  }),
145
145
  ),
146
146
  )
147
+
148
+ it.effect("gives a sub-agent its own model instance", () =>
149
+ Effect.gen(function* () {
150
+ // Which model instance served each call, by the agent that made it.
151
+ const calls: Array<{
152
+ readonly child: boolean
153
+ readonly instance: number
154
+ }> = []
155
+ let instances = 0
156
+ const modelLayer = Layer.mergeAll(
157
+ Layer.effect(
158
+ LanguageModel.LanguageModel,
159
+ Effect.suspend(() => {
160
+ const instance = ++instances
161
+ return LanguageModel.make({
162
+ generateText: () => Effect.succeed([]),
163
+ streamText: ({ prompt }) => {
164
+ const child = JSON.stringify(prompt).includes("TASK-CHILD")
165
+ const index = calls.push({ child, instance }) - 1
166
+ return Stream.make(
167
+ toolCall(`call-${index}`, child || index > 0 ? "done" : ""),
168
+ )
169
+ },
170
+ })
171
+ }),
172
+ ),
173
+ Layer.succeed(Model.ProviderName, "test-provider"),
174
+ Layer.succeed(Model.ModelName, "test-model"),
175
+ )
176
+ // The root delegates once in the foreground, then every agent finishes.
177
+ const executor = makeExecutor(
178
+ ({ script, environment, subagents, onTaskComplete }) =>
179
+ Stream.fromEffect(
180
+ (script === "done"
181
+ ? onTaskComplete("done")
182
+ : subagents.delegate({
183
+ prompt: "TASK-CHILD",
184
+ background: false,
185
+ environment: new AgentExecutor.EnvironmentUpdate({
186
+ environment,
187
+ update: Option.none(),
188
+ }),
189
+ })
190
+ ).pipe(Effect.as(""), Effect.orDie),
191
+ ),
192
+ )
193
+ const agent = yield* Agent.make.pipe(
194
+ Effect.provideService(AgentExecutor.AgentExecutor, executor),
195
+ )
196
+ const exit = yield* agent.send({ prompt: "hello" }).pipe(
197
+ Effect.flatMap(Stream.runDrain),
198
+ Effect.catchTag("AgentFinished", () => Effect.void),
199
+ Effect.provide(
200
+ Layer.mergeAll(
201
+ modelLayer,
202
+ Agent.ConversationMode.layer(false),
203
+ Agent.layerSubagentModel(modelLayer),
204
+ ),
205
+ ),
206
+ Effect.exit,
207
+ )
208
+ assert.deepStrictEqual(exit, Exit.void)
209
+ const root = calls.filter((call) => !call.child)
210
+ const child = calls.filter((call) => call.child)
211
+ assert.lengthOf(root, 2)
212
+ assert.lengthOf(child, 1)
213
+ assert.notStrictEqual(child[0]!.instance, root[0]!.instance)
214
+ }).pipe(Effect.scoped),
215
+ )
147
216
  })
148
217
 
149
218
  // =============================================================================
package/src/Agent.ts CHANGED
@@ -1680,6 +1680,10 @@ export class SubagentModel extends Context.Service<
1680
1680
  >()("clanka/Agent/SubagentModel") {}
1681
1681
 
1682
1682
  /**
1683
+ * The model every sub-agent runs on. Each sub-agent builds its own instance,
1684
+ * even when `layer` is also this agent's model layer, so a stateful model
1685
+ * such as Claude Agent never shares its session with another agent.
1686
+ *
1683
1687
  * @since 1.0.0
1684
1688
  * @category Subagent model
1685
1689
  */
@@ -1694,7 +1698,7 @@ export const layerSubagentModel = <E, R>(
1694
1698
  SubagentModel,
1695
1699
  Effect.gen(function* () {
1696
1700
  const services = yield* Effect.context<R>()
1697
- return Layer.orDie(layer).pipe(
1701
+ return Layer.fresh(Layer.orDie(layer)).pipe(
1698
1702
  Layer.provide(Layer.succeedContext(services)),
1699
1703
  )
1700
1704
  }),
@@ -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