clanka 0.24.3 → 0.24.5

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 (36) hide show
  1. package/dist/Agent.d.ts.map +1 -1
  2. package/dist/Agent.js +24 -11
  3. package/dist/Agent.js.map +1 -1
  4. package/dist/Agent.test.js +137 -0
  5. package/dist/Agent.test.js.map +1 -1
  6. package/dist/AgentTools.d.ts +88 -88
  7. package/dist/AgentTools.d.ts.map +1 -1
  8. package/dist/OutputFormatter.d.ts +1 -1
  9. package/dist/OutputFormatter.d.ts.map +1 -1
  10. package/dist/OutputFormatter.js +42 -2
  11. package/dist/OutputFormatter.js.map +1 -1
  12. package/dist/OutputFormatter.test.d.ts +2 -0
  13. package/dist/OutputFormatter.test.d.ts.map +1 -0
  14. package/dist/OutputFormatter.test.js +93 -0
  15. package/dist/OutputFormatter.test.js.map +1 -0
  16. package/dist/bin/{Stream-C51usiew.mjs → AiError-CsvdOsKR.mjs} +533 -74
  17. package/dist/bin/Latch-B3e9629m.mjs +5 -0
  18. package/dist/bin/{McpClient-DoPNaNzW.mjs → McpClient-BCxZZgnA.mjs} +2 -3
  19. package/dist/bin/{OutputFormatter-U02YKTfy.mjs → OutputFormatter-ByMjyBhe.mjs} +40 -4
  20. package/dist/bin/{Schema-Box_9VZG.mjs → Schema-BfUmMefy.mjs} +5602 -360
  21. package/dist/bin/{SemanticSearch-CH125AHH.mjs → SemanticSearch-DMzIsoZb.mjs} +80 -68
  22. package/dist/bin/cli.mjs +849 -1163
  23. package/dist/bin/{helpers-CljL9OKa.mjs → helpers-Bb68A2Sv.mjs} +2 -2
  24. package/dist/bin/{index.min-ClUfQ5ji.mjs → index.min-CuA3AuA-.mjs} +1448 -1348
  25. package/dist/bin/{rolldown-runtime-5zChB7MF.mjs → rolldown-runtime-CXhmmSW5.mjs} +4 -4
  26. package/dist/bin/{server-HlLriZxF.mjs → server-D4nrvZHH.mjs} +2 -2
  27. package/dist/bin/{turndown.cjs-C2WBxeA-.mjs → turndown.cjs-CwE2EFNQ.mjs} +15 -10
  28. package/dist/bin/{types-LcwjLVkt.mjs → types-N9Z-HYP0.mjs} +1 -1
  29. package/dist/bin/{upgrade-HMRGSqq8.mjs → upgrade-t590zYhO.mjs} +5 -6
  30. package/package.json +15 -15
  31. package/src/Agent.test.ts +198 -0
  32. package/src/Agent.ts +28 -11
  33. package/src/OutputFormatter.test.ts +158 -0
  34. package/src/OutputFormatter.ts +56 -1
  35. package/dist/bin/Effect-5XYMLOiB.mjs +0 -5183
  36. package/dist/bin/Latch-BnrpWMd1.mjs +0 -5
@@ -7,18 +7,18 @@ var __getOwnPropNames = Object.getOwnPropertyNames;
7
7
  var __getProtoOf = Object.getPrototypeOf;
8
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
9
  var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod, mod.exports), cb = null), mod.exports);
10
- var __exportAll = (all, no_symbols) => {
11
- let target = {};
10
+ var __exportAll = (all, flags) => {
11
+ let target = Object.setPrototypeOf({}, null);
12
12
  for (var name in all) {
13
13
  __defProp(target, name, {
14
14
  get: all[name],
15
15
  enumerable: true
16
16
  });
17
17
  }
18
- if (!no_symbols) {
18
+ if (!(flags & 1)) {
19
19
  __defProp(target, Symbol.toStringTag, { value: "Module" });
20
20
  }
21
- return target;
21
+ return flags & 2 ? target : Object.preventExtensions(target);
22
22
  };
23
23
  var __copyProps = (to, from, except, desc) => {
24
24
  if (from && typeof from === "object" || typeof from === "function") {
@@ -1,5 +1,5 @@
1
- import { a as mergeCapabilities, c as safeParse, i as Protocol, n as assertToolsCallTaskCapability, o as getLiteralValue, r as AjvJsonSchemaValidator, s as getObjectShape, t as assertClientRequestTaskCapability } from "./helpers-CljL9OKa.mjs";
2
- import { B as SUPPORTED_PROTOCOL_VERSIONS, C as LATEST_PROTOCOL_VERSION, M as LoggingLevelSchema, N as McpError, O as ListRootsResultSchema, V as SetLevelRequestSchema, c as CreateMessageResultSchema, f as ElicitResultSchema, l as CreateMessageResultWithToolsSchema, m as ErrorCode, n as CallToolResultSchema, p as EmptyResultSchema, t as CallToolRequestSchema, u as CreateTaskResultSchema, x as InitializedNotificationSchema, y as InitializeRequestSchema } from "./types-LcwjLVkt.mjs";
1
+ import { a as mergeCapabilities, c as safeParse, i as Protocol, n as assertToolsCallTaskCapability, o as getLiteralValue, r as AjvJsonSchemaValidator, s as getObjectShape, t as assertClientRequestTaskCapability } from "./helpers-Bb68A2Sv.mjs";
2
+ import { B as SUPPORTED_PROTOCOL_VERSIONS, C as LATEST_PROTOCOL_VERSION, M as LoggingLevelSchema, N as McpError, O as ListRootsResultSchema, V as SetLevelRequestSchema, c as CreateMessageResultSchema, f as ElicitResultSchema, l as CreateMessageResultWithToolsSchema, m as ErrorCode, n as CallToolResultSchema, p as EmptyResultSchema, t as CallToolRequestSchema, u as CreateTaskResultSchema, x as InitializedNotificationSchema, y as InitializeRequestSchema } from "./types-N9Z-HYP0.mjs";
3
3
  // node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_zod@4.4.2/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.js
4
4
  var ExperimentalServerTasks = class {
5
5
  constructor(_server) {
@@ -1,4 +1,4 @@
1
- import { t as __commonJSMin } from "./rolldown-runtime-5zChB7MF.mjs";
1
+ import { t as __commonJSMin } from "./rolldown-runtime-CXhmmSW5.mjs";
2
2
  // node_modules/.pnpm/@mixmark-io+domino@2.2.0/node_modules/@mixmark-io/domino/lib/Event.js
3
3
  var require_Event = __commonJSMin(((exports, module) => {
4
4
  module.exports = Event;
@@ -14506,7 +14506,7 @@ var require_lib = __commonJSMin(((exports) => {
14506
14506
  };
14507
14507
  exports.impl = impl;
14508
14508
  }));
14509
- // node_modules/.pnpm/turndown@7.2.4/node_modules/turndown/lib/turndown.cjs.js
14509
+ // node_modules/.pnpm/turndown@7.2.5/node_modules/turndown/lib/turndown.cjs.js
14510
14510
  var require_turndown_cjs = __commonJSMin(((exports, module) => {
14511
14511
  function extend(destination) {
14512
14512
  for (var i = 1; i < arguments.length; i++) {
@@ -15107,28 +15107,33 @@ var require_turndown_cjs = __commonJSMin(((exports, module) => {
15107
15107
  var replacement = "";
15108
15108
  if (node.nodeType === 3) replacement = node.isCode ? node.nodeValue : self.escape(node.nodeValue);
15109
15109
  else if (node.nodeType === 1) replacement = replacementForNode.call(self, node);
15110
- return join(output, replacement);
15111
- }, "");
15110
+ join(output, replacement);
15111
+ return output;
15112
+ }, []);
15112
15113
  }
15113
15114
  function postProcess(output) {
15114
15115
  var self = this;
15115
15116
  this.rules.forEach(function(rule) {
15116
- if (typeof rule.append === "function") output = join(output, rule.append(self.options));
15117
+ if (typeof rule.append === "function") join(output, rule.append(self.options));
15117
15118
  });
15118
- return output.replace(/^[\t\r\n]+/, "").replace(/[\t\r\n\s]+$/, "");
15119
+ return output.join("").replace(/^[\t\r\n]+/, "").replace(/[\t\r\n\s]+$/, "");
15119
15120
  }
15120
15121
  function replacementForNode(node) {
15121
15122
  var rule = this.rules.forNode(node);
15122
- var content = process.call(this, node);
15123
+ var content = process.call(this, node).join("");
15123
15124
  var whitespace = node.flankingWhitespace;
15124
15125
  if (whitespace.leading || whitespace.trailing) content = content.trim();
15125
15126
  return whitespace.leading + rule.replacement(content, node, this.options) + whitespace.trailing;
15126
15127
  }
15127
15128
  function join(output, replacement) {
15128
- var s1 = trimTrailingNewlines(output);
15129
+ var tail = output.pop() || "";
15130
+ var s1 = trimTrailingNewlines(tail);
15129
15131
  var s2 = trimLeadingNewlines(replacement);
15130
- var nls = Math.max(output.length - s1.length, replacement.length - s2.length);
15131
- return s1 + "\n\n".substring(0, nls) + s2;
15132
+ var nls = Math.max(tail.length - s1.length, replacement.length - s2.length);
15133
+ var separator = "\n\n".substring(0, nls);
15134
+ if (s1) output.push(s1);
15135
+ if (separator) output.push(separator);
15136
+ if (s2) output.push(s2);
15132
15137
  }
15133
15138
  function canConvert(input) {
15134
15139
  return input != null && (typeof input === "string" || input.nodeType && (input.nodeType === 1 || input.nodeType === 9 || input.nodeType === 11));
@@ -1,4 +1,4 @@
1
- import { n as __exportAll } from "./rolldown-runtime-5zChB7MF.mjs";
1
+ import { n as __exportAll } from "./rolldown-runtime-CXhmmSW5.mjs";
2
2
  // node_modules/.pnpm/zod@4.4.2/node_modules/zod/v4/core/core.js
3
3
  var _a$1;
4
4
  const NEVER = Object.freeze({ status: "aborted" });
@@ -1,11 +1,10 @@
1
- import { Ao as merge, Bt as scope, Ia as map, Kt as succeed, M as fail, Pc as identity, Ur as addFinalizer, Xr as provide, Xt as sync, Yt as suspend, Z as gen, c as as, cn as updateContext, dn as void_, mn as withFiber, nn as timeoutOrElse, p as callback, t as acquireRelease, xa as ensure } from "./Effect-5XYMLOiB.mjs";
2
- import { _ as SocketReadError, b as isCloseEvent, g as SocketOpenError, h as SocketError, m as SocketCloseError, v as SocketUpgradeError, x as make, y as SocketWriteError } from "./cli.mjs";
3
- import { n as makeUnsafe } from "./Latch-BnrpWMd1.mjs";
4
- import { ei as value } from "./Schema-Box_9VZG.mjs";
1
+ import { Ba as scope, Bd as identity, Fi as fail, Ka as succeed, Qi as gen, Us as addFinalizer, Xa as sync, Xs as provide, Ya as suspend, _l as ensure, co as updateContext, di as as, do as void_, gi as callback, ii as acquireRelease, jl as map, mo as withFiber, ni as value, no as timeoutOrElse, xu as merge } from "./Schema-BfUmMefy.mjs";
2
+ import { C as make, S as isCloseEvent, _ as SocketError, b as SocketUpgradeError, g as SocketCloseError, v as SocketOpenError, x as SocketWriteError, y as SocketReadError } from "./cli.mjs";
3
+ import { n as makeUnsafe } from "./Latch-B3e9629m.mjs";
5
4
  import { Readable, finished } from "node:stream";
6
5
  import { Buffer as Buffer$1 } from "node:buffer";
7
6
  import * as Tls from "node:tls";
8
- // node_modules/.pnpm/@effect+platform-node-shared@4.1.1_effect@4.1.1/node_modules/@effect/platform-node-shared/dist/NodeSocket.js
7
+ // node_modules/.pnpm/@effect+platform-node-shared@4.1.3_effect@4.1.3/node_modules/@effect/platform-node-shared/dist/NodeSocket.js
9
8
  const isDeno = "Deno" in globalThis;
10
9
  const readAvailable = (conn, chunkSize) => {
11
10
  const first = conn.read();
@@ -253,7 +252,7 @@ const fromDuplex = (open, options) => withFiber((fiber) => {
253
252
  writer
254
253
  }));
255
254
  });
256
- // node_modules/.pnpm/@effect+platform-node@4.1.1_effect@4.1.1_redis@6.2.1_@opentelemetry+api@1.10.0_/node_modules/@effect/platform-node/dist/internal/upgrade.js
255
+ // node_modules/.pnpm/@effect+platform-node@4.1.3_effect@4.1.3_redis@6.2.1_@opentelemetry+api@1.10.0_/node_modules/@effect/platform-node/dist/internal/upgrade.js
257
256
  const toSocket = (conn, open = void_) => fromDuplex(acquireRelease(suspend(() => conn.destroyed ? fail(openError("The upgraded connection closed before it was read")) : as(open, conn)), (conn) => sync(() => {
258
257
  if (conn.destroyed) return;
259
258
  if ("destroySoon" in conn) conn.destroySoon();
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "clanka",
3
3
  "type": "module",
4
- "version": "0.24.3",
4
+ "version": "0.24.5",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -25,17 +25,17 @@
25
25
  "url": "https://github.com/Effectful-Tech/clanka.git"
26
26
  },
27
27
  "dependencies": {
28
- "@anthropic-ai/claude-agent-sdk": "^0.3.314",
28
+ "@anthropic-ai/claude-agent-sdk": "^0.3.322",
29
29
  "@modelcontextprotocol/sdk": "^1.32.2",
30
30
  "@silvia-odwyer/photon-node": "^0.3.4",
31
31
  "@vscode/ripgrep": "^1.18.0",
32
32
  "chalk": "^6.0.1",
33
- "glob": "^14.0.3",
33
+ "glob": "^14.0.4",
34
34
  "sqlite-vec": "0.1.9",
35
35
  "tree-sitter": "^0.21.1",
36
36
  "tree-sitter-javascript": "^0.23.1",
37
37
  "tree-sitter-typescript": "^0.23.2",
38
- "turndown": "^7.2.4"
38
+ "turndown": "^7.2.5"
39
39
  },
40
40
  "peerDependencies": {
41
41
  "@effect/ai-openai": "^4.0.0",
@@ -45,25 +45,25 @@
45
45
  "effect": "^4.0.0"
46
46
  },
47
47
  "devDependencies": {
48
- "@anthropic-ai/sdk": "^1.3.0",
48
+ "@anthropic-ai/sdk": "^1.7.0",
49
49
  "@changesets/changelog-github": "^1.0.1",
50
50
  "@changesets/cli": "^3.0.3",
51
- "@effect/ai-openai": "4.1.1",
52
- "@effect/ai-openai-compat": "4.1.1",
53
- "@effect/platform-node": "4.1.1",
54
- "@effect/sql-sqlite-node": "4.1.1",
55
- "@effect/tsgo": "0.63.0",
56
- "@effect/vitest": "4.1.1",
51
+ "@effect/ai-openai": "4.1.3",
52
+ "@effect/ai-openai-compat": "4.1.3",
53
+ "@effect/platform-node": "4.1.3",
54
+ "@effect/sql-sqlite-node": "4.1.3",
55
+ "@effect/tsgo": "0.67.5",
56
+ "@effect/vitest": "4.1.3",
57
57
  "@types/node": "^26.6.6",
58
58
  "@types/turndown": "^5.0.6",
59
- "effect": "4.1.1",
59
+ "effect": "4.1.3",
60
60
  "husky": "^9.1.7",
61
61
  "lint-staged": "^17.6.0",
62
- "oxlint": "^1.90.0",
62
+ "oxlint": "^1.93.0",
63
63
  "prettier": "^3.9.10",
64
- "tsdown": "^0.23.4",
64
+ "tsdown": "^0.23.7",
65
65
  "typescript": "^7.0.2",
66
- "vitest": "^5.0.5"
66
+ "vitest": "^5.1.0"
67
67
  },
68
68
  "lint-staged": {
69
69
  "*.{ts,tsx}": [
package/src/Agent.test.ts CHANGED
@@ -21,6 +21,8 @@ import * as Agent from "./Agent.ts"
21
21
  import * as AgentExecutor from "./AgentExecutor.ts"
22
22
  import { agentTasksUnavailable } from "./AgentTools.ts"
23
23
  import * as AgentOutput from "./AgentOutput.ts"
24
+ import * as OutputFormatter from "./OutputFormatter.ts"
25
+ import { stripVTControlCharacters } from "node:util"
24
26
  import * as Compaction from "./Compaction.ts"
25
27
 
26
28
  const capabilities = new AgentExecutor.Capabilities({
@@ -621,6 +623,202 @@ it.layer(localExecutorLayer, { excludeTestServices: true })(
621
623
  // --- tests -------------------------------------------------------------------
622
624
 
623
625
  describe("Agent usage", () => {
626
+ for (const background of [false, true]) {
627
+ it.effect(
628
+ `aggregates nested subagent usage once (background: ${background})`,
629
+ () =>
630
+ Effect.gen(function* () {
631
+ const { exit, outputs } = yield* runAgentCollect({
632
+ executor: makeExecutor(({ script, environment, agentTasks }) =>
633
+ Stream.fromEffect(
634
+ Effect.gen(function* () {
635
+ const task = yield* agentTasks.subagent({
636
+ id: script,
637
+ prompt: "nested task",
638
+ background,
639
+ environment: new AgentExecutor.EnvironmentUpdate({
640
+ environment,
641
+ update: Option.none(),
642
+ }),
643
+ })
644
+ yield* agentTasks.waitTasks([task.id], { timeoutMs: 60_000 })
645
+ // Reading completion again must not add the child's usage again.
646
+ yield* agentTasks.taskOutput(task.id)
647
+ if (script === "1") {
648
+ yield* agentTasks.messageAgent({
649
+ id: task.id,
650
+ message: "follow up",
651
+ })
652
+ yield* agentTasks.waitTasks([task.id], {
653
+ timeoutMs: 60_000,
654
+ })
655
+ }
656
+ return "done"
657
+ }).pipe(Effect.orDie),
658
+ ),
659
+ ),
660
+ respond: (_call, index) => {
661
+ switch (index) {
662
+ case 0:
663
+ return Stream.make(
664
+ toolCall("root", "1"),
665
+ finish(100, "tool-calls", { read: 10, write: 1 }),
666
+ )
667
+ case 1:
668
+ return Stream.make(
669
+ toolCall("child", "2"),
670
+ finish(200, "tool-calls", { read: 20, write: 2 }),
671
+ )
672
+ case 2:
673
+ return Stream.fromIterable([
674
+ ...text("grandchild"),
675
+ finish(300, "stop", { read: 30, write: 3 }),
676
+ ])
677
+ case 3:
678
+ return Stream.fromIterable([
679
+ ...text("child"),
680
+ finish(400, "stop", { read: 40, write: 4 }),
681
+ ])
682
+ case 4:
683
+ return Stream.fromIterable([
684
+ ...text("resumed child"),
685
+ finish(50, "stop", { read: 5, write: 1 }),
686
+ ])
687
+ case 5:
688
+ return Stream.fromIterable([
689
+ ...text("complete"),
690
+ finish(500, "stop", { read: 50, write: 5 }),
691
+ ])
692
+ default:
693
+ return Stream.die(`unexpected call ${index}`)
694
+ }
695
+ },
696
+ })
697
+ assert.deepStrictEqual(exit, Exit.succeed("complete"))
698
+ const usage = outputsOfTag(outputs, "Usage")
699
+ // Child context windows must never replace the parent's window.
700
+ assert.deepStrictEqual(
701
+ usage.map((part) => [part.inputTokens, part.contextTokens]),
702
+ [
703
+ [300, 0],
704
+ [500, 0],
705
+ [900, 0],
706
+ [950, 0],
707
+ [1050, 100],
708
+ [1550, 500],
709
+ ],
710
+ )
711
+ assert.deepStrictEqual(
712
+ usage.at(-1),
713
+ new AgentOutput.Usage({
714
+ contextTokens: 500,
715
+ inputTokens: 1550,
716
+ outputTokens: 60,
717
+ cacheRead: 155,
718
+ cacheWrite: 16,
719
+ }),
720
+ )
721
+ }),
722
+ )
723
+ }
724
+
725
+ it.effect(
726
+ "keeps background sibling usage out of the foreground output buffer",
727
+ () =>
728
+ Effect.gen(function* () {
729
+ const reasoningStarted = yield* Deferred.make<void>()
730
+ const backgroundDone = yield* Deferred.make<void>()
731
+ // B completes while A holds the display lock, before A ends its reasoning.
732
+ const { exit, outputs } = yield* runAgentCollect({
733
+ executor: makeExecutor(({ environment, agentTasks }) =>
734
+ Stream.fromEffect(
735
+ Effect.gen(function* () {
736
+ const update = new AgentExecutor.EnvironmentUpdate({
737
+ environment,
738
+ update: Option.none(),
739
+ })
740
+ const background = yield* agentTasks.subagent({
741
+ id: "1",
742
+ prompt: "sibling-b",
743
+ background: true,
744
+ environment: update,
745
+ })
746
+ yield* agentTasks
747
+ .waitTasks([background.id], { timeoutMs: 60_000 })
748
+ .pipe(
749
+ Effect.andThen(Deferred.done(backgroundDone, Exit.void)),
750
+ Effect.forkScoped,
751
+ )
752
+ yield* agentTasks.subagent({
753
+ id: "2",
754
+ prompt: "sibling-a",
755
+ background: false,
756
+ environment: update,
757
+ })
758
+ return "done"
759
+ }).pipe(Effect.scoped, Effect.orDie),
760
+ ),
761
+ ),
762
+ respond: (_call, index) => {
763
+ if (index === 0) {
764
+ return Stream.make(toolCall("root", "siblings"), finish(100))
765
+ }
766
+ if (index === 1) {
767
+ return Stream.fromEffect(Deferred.await(reasoningStarted)).pipe(
768
+ Stream.flatMap(() =>
769
+ Stream.fromIterable([...text("b done"), finish(300, "stop")]),
770
+ ),
771
+ )
772
+ }
773
+ if (index === 2) {
774
+ const [start, delta, end] = reasoning("thinking")
775
+ return Stream.make(start!, delta!).pipe(
776
+ Stream.concat(
777
+ Stream.fromEffect(
778
+ Deferred.done(reasoningStarted, Exit.void).pipe(
779
+ Effect.andThen(Deferred.await(backgroundDone)),
780
+ Effect.as(end!),
781
+ ),
782
+ ),
783
+ ),
784
+ Stream.concat(
785
+ Stream.fromIterable([...text("a done"), finish(200, "stop")]),
786
+ ),
787
+ )
788
+ }
789
+ return Stream.fromIterable([
790
+ ...text("complete"),
791
+ finish(400, "stop"),
792
+ ])
793
+ },
794
+ })
795
+ assert.deepStrictEqual(exit, Exit.succeed("complete"))
796
+ const usage = outputsOfTag(outputs, "Usage")
797
+ assert.deepStrictEqual(
798
+ usage.map((part) => [part.inputTokens, part.contextTokens]),
799
+ [
800
+ [300, 0],
801
+ [500, 0],
802
+ [600, 100],
803
+ [1000, 400],
804
+ ],
805
+ )
806
+ assert.strictEqual(usage.at(-1)?.outputTokens, 40)
807
+ const formatted = yield* Stream.fromIterable(outputs).pipe(
808
+ OutputFormatter.pretty(),
809
+ Stream.runCollect,
810
+ )
811
+ assert.include(
812
+ stripVTControlCharacters(formatted.join("")),
813
+ "Thinking: thinking\n\n",
814
+ )
815
+ assert.include(
816
+ stripVTControlCharacters(formatted.join("")),
817
+ "Usage: 0 context / 300 input / 10 output",
818
+ )
819
+ }),
820
+ )
821
+
624
822
  it.effect("accumulates provider cache reads and writes", () =>
625
823
  Effect.gen(function* () {
626
824
  const { exit, outputs } = yield* runAgentCollect({
package/src/Agent.ts CHANGED
@@ -338,6 +338,19 @@ export const makeWith = Effect.fnUntraced(function* <
338
338
  let outputTokens = 0
339
339
  let cacheRead = 0
340
340
  let cacheWrite = 0
341
+ // Never through the display buffer: it is flushed into the stream of
342
+ // whichever agent releases it, where these totals would count as its own.
343
+ const sendUsage = () =>
344
+ Queue.offerUnsafe(
345
+ output,
346
+ new Usage({
347
+ contextTokens: lastContextTokens ?? 0,
348
+ inputTokens,
349
+ outputTokens,
350
+ cacheRead,
351
+ cacheWrite,
352
+ }),
353
+ )
341
354
  const prompt = opts.history
342
355
  const mailbox = opts.mailbox
343
356
 
@@ -533,6 +546,8 @@ export const makeWith = Effect.fnUntraced(function* <
533
546
  }) {
534
547
  const { child } = options
535
548
  const turn = child.turn
549
+ // Each spawn starts fresh counters, including when a child is resumed.
550
+ let childUsage: Usage | undefined
536
551
  const display = opts.display && !options.background
537
552
  const stream = spawn({
538
553
  agentId: child.id,
@@ -561,6 +576,17 @@ export const makeWith = Effect.fnUntraced(function* <
561
576
  return yield* stream.pipe(
562
577
  Stream.runForEachArray((parts) => {
563
578
  for (const part of parts) {
579
+ // Only direct Usage snapshots contribute: nested SubagentParts
580
+ // are display events already included in the child's totals.
581
+ if (part._tag === "Usage") {
582
+ inputTokens += part.inputTokens - (childUsage?.inputTokens ?? 0)
583
+ outputTokens +=
584
+ part.outputTokens - (childUsage?.outputTokens ?? 0)
585
+ cacheRead += part.cacheRead - (childUsage?.cacheRead ?? 0)
586
+ cacheWrite += part.cacheWrite - (childUsage?.cacheWrite ?? 0)
587
+ childUsage = part
588
+ sendUsage()
589
+ }
564
590
  switch (part._tag) {
565
591
  case "AgentStart":
566
592
  case "HistoryAppended":
@@ -1304,16 +1330,7 @@ ${prompt}`,
1304
1330
  if (usage.inputTokens.total !== undefined) {
1305
1331
  lastContextTokens = usage.inputTokens.total
1306
1332
  inputTokens += usage.inputTokens.total
1307
- maybeSend({
1308
- agentId,
1309
- part: new Usage({
1310
- contextTokens: usage.inputTokens.total,
1311
- inputTokens,
1312
- outputTokens,
1313
- cacheRead,
1314
- cacheWrite,
1315
- }),
1316
- })
1333
+ sendUsage()
1317
1334
  }
1318
1335
  break
1319
1336
  case "tool-call":
@@ -1674,7 +1691,7 @@ const incompleteResponseError = (description: string) =>
1674
1691
 
1675
1692
  const retryPolicy = Schedule.min([
1676
1693
  Schedule.exponential(100, 1.5),
1677
- Schedule.spaced(5000),
1694
+ Schedule.spaced({ minutes: 5 }),
1678
1695
  ]).pipe(Schedule.jittered)
1679
1696
 
1680
1697
  const environmentUpdateOpen = "<environment-update>"
@@ -0,0 +1,158 @@
1
+ import { assert, describe, it } from "@effect/vitest"
2
+ import * as Cause from "effect/Cause"
3
+ import * as Effect from "effect/Effect"
4
+ import * as Fiber from "effect/Fiber"
5
+ import * as Latch from "effect/Latch"
6
+ import * as Stream from "effect/Stream"
7
+ import * as AgentOutput from "./AgentOutput.ts"
8
+ import { layerMuxer, Muxer, pretty } from "./OutputFormatter.ts"
9
+
10
+ describe("layerMuxer", () => {
11
+ for (const block of ["Reasoning", "Script"] as const) {
12
+ it.effect(
13
+ "keeps concurrent output outside a " + block + " block containing Usage",
14
+ () =>
15
+ Effect.gen(function* () {
16
+ const muxer = yield* Muxer
17
+ const paused = yield* Latch.make()
18
+ const resume = yield* Latch.make()
19
+ const competing = yield* Latch.make()
20
+ const collected = yield* muxer.output.pipe(
21
+ Stream.take(6),
22
+ Stream.runCollect,
23
+ Effect.forkChild({ startImmediately: true }),
24
+ )
25
+ const start =
26
+ block === "Reasoning"
27
+ ? new AgentOutput.ReasoningStart()
28
+ : new AgentOutput.ScriptStart()
29
+ const delta =
30
+ block === "Reasoning"
31
+ ? new AgentOutput.ReasoningDelta({ delta: "text" })
32
+ : new AgentOutput.ScriptDelta({ delta: "text" })
33
+ const end =
34
+ block === "Reasoning"
35
+ ? new AgentOutput.ReasoningEnd()
36
+ : new AgentOutput.ScriptEnd()
37
+ yield* muxer.add(
38
+ Stream.make(
39
+ start,
40
+ delta,
41
+ new AgentOutput.Usage({
42
+ contextTokens: 10,
43
+ inputTokens: 10,
44
+ outputTokens: 2,
45
+ cacheRead: 0,
46
+ cacheWrite: 0,
47
+ }),
48
+ ).pipe(
49
+ Stream.concat(
50
+ Stream.fromEffect(
51
+ paused.open.pipe(
52
+ Effect.andThen(resume.await),
53
+ Effect.as(delta),
54
+ ),
55
+ ),
56
+ ),
57
+ Stream.concat(Stream.succeed(end)),
58
+ ),
59
+ )
60
+ yield* paused.await
61
+ yield* muxer.add(
62
+ Stream.fromEffect(
63
+ competing.open.pipe(
64
+ Effect.as(
65
+ new AgentOutput.ScriptOutput({ output: "other agent" }),
66
+ ),
67
+ ),
68
+ ),
69
+ )
70
+ yield* competing.await
71
+ yield* Effect.yieldNow
72
+ yield* resume.open
73
+ const output = yield* Fiber.join(collected)
74
+ assert.deepStrictEqual(output.slice(0, 4), [
75
+ block + "Start",
76
+ block + "Delta",
77
+ block + "Delta",
78
+ block + "End",
79
+ ])
80
+ assert.deepStrictEqual(output.slice(4).toSorted(), [
81
+ "ScriptOutput",
82
+ "Usage",
83
+ ])
84
+ }).pipe(
85
+ Effect.provide(
86
+ layerMuxer((stream) =>
87
+ stream.pipe(
88
+ Stream.map((part) => part._tag),
89
+ Stream.orDie,
90
+ ),
91
+ ),
92
+ ),
93
+ ),
94
+ )
95
+ }
96
+ })
97
+
98
+ describe("pretty", () => {
99
+ for (const block of ["Reasoning", "Script"] as const) {
100
+ for (const termination of ["end", "eof", "finished", "error"] as const) {
101
+ it.effect(block + " defers Usage until " + termination, () =>
102
+ Effect.gen(function* () {
103
+ const start =
104
+ block === "Reasoning"
105
+ ? new AgentOutput.ReasoningStart()
106
+ : new AgentOutput.ScriptStart()
107
+ const delta =
108
+ block === "Reasoning"
109
+ ? new AgentOutput.ReasoningDelta({ delta: "before" })
110
+ : new AgentOutput.ScriptDelta({ delta: "before" })
111
+ const end =
112
+ block === "Reasoning"
113
+ ? new AgentOutput.ReasoningEnd()
114
+ : new AgentOutput.ScriptEnd()
115
+ const tail: Stream.Stream<
116
+ AgentOutput.Output,
117
+ AgentOutput.AgentFinished | string
118
+ > =
119
+ termination === "end"
120
+ ? Stream.succeed(end)
121
+ : termination === "eof"
122
+ ? Stream.empty
123
+ : termination === "finished"
124
+ ? Stream.fail(
125
+ new AgentOutput.AgentFinished({ summary: "done" }),
126
+ )
127
+ : Stream.fail("failure")
128
+ const output = yield* Stream.make(
129
+ start,
130
+ delta,
131
+ new AgentOutput.Usage({
132
+ contextTokens: 10,
133
+ inputTokens: 10,
134
+ outputTokens: 2,
135
+ cacheRead: 0,
136
+ cacheWrite: 0,
137
+ }),
138
+ block === "Reasoning"
139
+ ? new AgentOutput.ReasoningDelta({ delta: "after" })
140
+ : new AgentOutput.ScriptDelta({ delta: "after" }),
141
+ ).pipe(
142
+ Stream.concat(tail),
143
+ pretty(),
144
+ Stream.catchCause((cause) => Stream.succeed(Cause.pretty(cause))),
145
+ Stream.runCollect,
146
+ )
147
+ assert.include(output[2], "after")
148
+ assert.strictEqual(output[3], "\n\n")
149
+ assert.include(output[4], "Usage:")
150
+ assert.include(output[4], "10 context / 10 input / 2 output")
151
+ if (termination === "finished")
152
+ assert.include(output[5], "Task complete:")
153
+ if (termination === "error") assert.include(output[5], "failure")
154
+ }),
155
+ )
156
+ }
157
+ }
158
+ })