@kitman-sh/cli 0.11.7 → 0.12.0-rc.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.
@@ -1,8 +1,4 @@
1
1
  // @bun
2
- import {
3
- FileSystem,
4
- Path
5
- } from "./chunk-0b93nv6j.js";
6
2
  import {
7
3
  isObject2,
8
4
  isUint8Array,
@@ -21,21 +17,25 @@ import"./chunk-0qz10ek8.js";
21
17
  import {
22
18
  isJsonObject
23
19
  } from "./chunk-c6rbt85q.js";
20
+ import {
21
+ FileSystem,
22
+ Path
23
+ } from "./chunk-3d4d52e5.js";
24
24
  import {
25
25
  tomlTableHeader2,
26
26
  tomlKeyPath2,
27
27
  kitmanSkillEntry,
28
28
  isPathWithin2
29
- } from "./chunk-y1rfbqaf.js";
29
+ } from "./chunk-bxqfgc6z.js";
30
30
  import {
31
31
  instructionsStart,
32
32
  instructionsEnd,
33
33
  renderMcpServer,
34
34
  materializeKitSetup,
35
35
  tomlInline
36
- } from "./chunk-5wvqtbfp.js";
37
- import"./chunk-z2dnw6ey.js";
38
- import"./chunk-2qarscbj.js";
36
+ } from "./chunk-fhyn2b38.js";
37
+ import"./chunk-n6hxwdm6.js";
38
+ import"./chunk-sk6ceghr.js";
39
39
 
40
40
  // packages/agent-runtime/src/kit-setup-sync.ts
41
41
  class KitSyncError extends TaggedError("KitSyncError") {
@@ -76,10 +76,6 @@ import {
76
76
  toCodecJson,
77
77
  Json
78
78
  } from "./chunk-vtfwjhzh.js";
79
- import {
80
- runForEach,
81
- FileSystem
82
- } from "./chunk-0b93nv6j.js";
83
79
  import {
84
80
  guard
85
81
  } from "./chunk-0qz10ek8.js";
@@ -109,7 +105,11 @@ import {
109
105
  KitDigest,
110
106
  KitSetup,
111
107
  RunnerRpcError
112
- } from "./chunk-5wvqtbfp.js";
108
+ } from "./chunk-fhyn2b38.js";
109
+ import {
110
+ runForEach,
111
+ FileSystem
112
+ } from "./chunk-3d4d52e5.js";
113
113
 
114
114
  // node_modules/.bun/effect@4.1.2/node_modules/effect/dist/crypto/internal/webCrypto.js
115
115
  var subtleUnavailable = () => new Error("crypto.subtle is unavailable; browsers expose it only in secure contexts");
@@ -248,15 +248,6 @@ var makeEquivalence = (equivalence) => {
248
248
  return (self, that) => is(self, that) && is(that, self);
249
249
  };
250
250
 
251
- // node_modules/.bun/effect@4.1.2/node_modules/effect/dist/BigInt.js
252
- var BigInt2 = globalThis.BigInt;
253
- var toNumber = (b) => {
254
- if (b > BigInt2(Number.MAX_SAFE_INTEGER) || b < BigInt2(Number.MIN_SAFE_INTEGER)) {
255
- return none();
256
- }
257
- return some(Number(b));
258
- };
259
-
260
251
  // node_modules/.bun/effect@4.1.2/node_modules/effect/dist/ByteSize.js
261
252
  var bigint0 = /* @__PURE__ */ BigInt(0);
262
253
  var bigint1 = /* @__PURE__ */ BigInt(1);
@@ -3561,4 +3552,4 @@ var srtArgv2 = (srtCommand, settingsFile, argv) => [
3561
3552
  ...argv
3562
3553
  ];
3563
3554
 
3564
- export { map, makeEquivalence, toNumber, bytes, join, interrupt, getCurrent, BadArgument, systemError, badArgument, makeUnsafe2, make8, unbounded, publishUnsafe, make9, bounded, sliding, unbounded2, offer, offerUnsafe, offerAll, fail, failCause, failCauseUnsafe, end, endUnsafe, shutdownUnsafe, take, poll, makeUnsafe3, fromTransform, mapDone, isSink, fromChannel, drain, make10, get3, isStream, fromChannel2, callback, empty2, make11, suspend, fail2, fromQueue, fromPubSub, fromReadableStream, unwrap, map2, tap, drainFork, concat, merge2, filter, catchCause, tapError, mapError, transduce, decodeText, encodeText, splitLines, interruptWhen, ensuring, provideContext, run, runCollect, runFold, runHead, runForEach, runDrain, mkString, mkArrayBuffer, toReadableStreamEffect, FileSystem, make12, FileTypeId, WatchBackend, Path, make13, embeddedFile, extractEmbeddedFile, map3, all, withDefault, option, String2, optionalEnv, operatorConfigHome, harnessesUnsupportedInSrt2, compiled2, pinnedSrtCommand2, pinnedSrtStepCommand2, runSrtCli2, kitmanCacheDirectory2, srtSettings2, srtCacheEnvironment2, srtInheritedEnv2, inheritedEnvironment2, withOnlyEnvironment2, writeSrtSettings2, srtStepArgv2, srtArgv2 };
3555
+ export { map, makeEquivalence, bytes, join, interrupt, getCurrent, BadArgument, systemError, badArgument, makeUnsafe2, make8, unbounded, publishUnsafe, make9, bounded, sliding, unbounded2, offer, offerUnsafe, offerAll, fail, failCause, failCauseUnsafe, end, endUnsafe, shutdownUnsafe, take, poll, makeUnsafe3, fromTransform, mapDone, isSink, fromChannel, drain, make10, get3, isStream, fromChannel2, callback, empty2, make11, suspend, fail2, fromQueue, fromPubSub, fromReadableStream, unwrap, map2, tap, drainFork, concat, merge2, filter, catchCause, tapError, mapError, transduce, decodeText, encodeText, splitLines, interruptWhen, ensuring, provideContext, run, runCollect, runFold, runHead, runForEach, runDrain, mkString, mkArrayBuffer, toReadableStreamEffect, FileSystem, make12, FileTypeId, WatchBackend, Path, make13, embeddedFile, extractEmbeddedFile, map3, all, withDefault, option, String2, optionalEnv, operatorConfigHome, harnessesUnsupportedInSrt2, compiled2, pinnedSrtCommand2, pinnedSrtStepCommand2, runSrtCli2, kitmanCacheDirectory2, srtSettings2, srtCacheEnvironment2, srtInheritedEnv2, inheritedEnvironment2, withOnlyEnvironment2, writeSrtSettings2, srtStepArgv2, srtArgv2 };
@@ -1,12 +1,4 @@
1
1
  // @bun
2
- import {
3
- decodeText,
4
- mkString,
5
- FileSystem,
6
- Path,
7
- withDefault,
8
- String2
9
- } from "./chunk-0b93nv6j.js";
10
2
  import {
11
3
  isString2,
12
4
  hasProperty,
@@ -43,6 +35,14 @@ import {
43
35
  } from "./chunk-vtfwjhzh.js";
44
36
  import"./chunk-0qz10ek8.js";
45
37
  import"./chunk-c6rbt85q.js";
38
+ import {
39
+ decodeText,
40
+ mkString,
41
+ FileSystem,
42
+ Path,
43
+ withDefault,
44
+ String2
45
+ } from "./chunk-3d4d52e5.js";
46
46
  import {
47
47
  SecureRandom,
48
48
  layerWebCrypto,
@@ -54,23 +54,23 @@ import {
54
54
  layer4,
55
55
  kitmanMcpServer,
56
56
  RunnerRpcProtocolVersion
57
- } from "./chunk-5wvqtbfp.js";
57
+ } from "./chunk-fhyn2b38.js";
58
58
  import {
59
59
  Packument,
60
60
  tarballMatches
61
- } from "./chunk-z2dnw6ey.js";
62
- import"./chunk-akzke77d.js";
61
+ } from "./chunk-n6hxwdm6.js";
62
+ import"./chunk-myqf27w2.js";
63
63
  import {
64
64
  AgentDeclaration,
65
65
  KitDeclarations,
66
66
  describeFlag,
67
67
  Described
68
- } from "./chunk-z9zqctv2.js";
68
+ } from "./chunk-2ptxq9cq.js";
69
69
  import {
70
70
  ChildProcessSpawner,
71
71
  make3
72
- } from "./chunk-2qarscbj.js";
73
- import"./chunk-f3cbjk00.js";
72
+ } from "./chunk-sk6ceghr.js";
73
+ import"./chunk-db9q9y8h.js";
74
74
 
75
75
  // packages/sdk/src/build/index.ts
76
76
  class DependencyInstallFailed extends TaggedError2()("DependencyInstallFailed", {
@@ -7,46 +7,6 @@ import {
7
7
  isJsonObject,
8
8
  isString
9
9
  } from "./chunk-c6rbt85q.js";
10
- import {
11
- join,
12
- interrupt,
13
- unbounded,
14
- publishUnsafe,
15
- unbounded2,
16
- offer,
17
- makeUnsafe3,
18
- make11,
19
- fromQueue,
20
- fromPubSub,
21
- map2,
22
- filter,
23
- decodeText,
24
- encodeText,
25
- splitLines,
26
- run,
27
- runHead,
28
- runForEach,
29
- FileSystem,
30
- Path,
31
- embeddedFile,
32
- extractEmbeddedFile,
33
- optionalEnv,
34
- operatorConfigHome,
35
- harnessesUnsupportedInSrt2,
36
- compiled2,
37
- pinnedSrtCommand2,
38
- pinnedSrtStepCommand2,
39
- runSrtCli2,
40
- kitmanCacheDirectory2,
41
- srtSettings2,
42
- srtCacheEnvironment2,
43
- srtInheritedEnv2,
44
- inheritedEnvironment2,
45
- withOnlyEnvironment2,
46
- writeSrtSettings2,
47
- srtStepArgv2,
48
- srtArgv2
49
- } from "./chunk-0b93nv6j.js";
50
10
  import {
51
11
  pipeArguments,
52
12
  dual,
@@ -236,6 +196,7 @@ import {
236
196
  verificationNetworkAllowlist,
237
197
  programNetworkHosts,
238
198
  canonicalSha256,
199
+ tokensSpent,
239
200
  isTestReportName,
240
201
  checkTests,
241
202
  MeasureSample,
@@ -287,7 +248,47 @@ import {
287
248
  installCommand,
288
249
  checkServicesFile,
289
250
  checkServices
290
- } from "./chunk-5wvqtbfp.js";
251
+ } from "./chunk-fhyn2b38.js";
252
+ import {
253
+ join,
254
+ interrupt,
255
+ unbounded,
256
+ publishUnsafe,
257
+ unbounded2,
258
+ offer,
259
+ makeUnsafe3,
260
+ make11,
261
+ fromQueue,
262
+ fromPubSub,
263
+ map2,
264
+ filter,
265
+ decodeText,
266
+ encodeText,
267
+ splitLines,
268
+ run,
269
+ runHead,
270
+ runForEach,
271
+ FileSystem,
272
+ Path,
273
+ embeddedFile,
274
+ extractEmbeddedFile,
275
+ optionalEnv,
276
+ operatorConfigHome,
277
+ harnessesUnsupportedInSrt2,
278
+ compiled2,
279
+ pinnedSrtCommand2,
280
+ pinnedSrtStepCommand2,
281
+ runSrtCli2,
282
+ kitmanCacheDirectory2,
283
+ srtSettings2,
284
+ srtCacheEnvironment2,
285
+ srtInheritedEnv2,
286
+ inheritedEnvironment2,
287
+ withOnlyEnvironment2,
288
+ writeSrtSettings2,
289
+ srtStepArgv2,
290
+ srtArgv2
291
+ } from "./chunk-3d4d52e5.js";
291
292
  import {
292
293
  writeAgentEnvironmentConfigFile2,
293
294
  readManifestSkillPaths2,
@@ -303,8 +304,8 @@ import {
303
304
  applyAgentEnvironmentMaterialization2,
304
305
  isPathWithin2,
305
306
  skillIdentity2
306
- } from "./chunk-y1rfbqaf.js";
307
- import"./chunk-z2dnw6ey.js";
307
+ } from "./chunk-bxqfgc6z.js";
308
+ import"./chunk-n6hxwdm6.js";
308
309
  import {
309
310
  egressAllowed,
310
311
  writeSecretRegistry,
@@ -322,23 +323,23 @@ import {
322
323
  decodedOption2,
323
324
  decoded2,
324
325
  readOpencode2
325
- } from "./chunk-kpfrhex3.js";
326
+ } from "./chunk-vmv7gwwr.js";
326
327
  import {
327
328
  uploadRunFile,
328
329
  programLease,
329
330
  rpcRunFiles,
330
331
  programHostsEnv,
331
332
  undeclaredHostsEnv
332
- } from "./chunk-z9zqctv2.js";
333
- import"./chunk-akzke77d.js";
333
+ } from "./chunk-2ptxq9cq.js";
334
+ import"./chunk-myqf27w2.js";
334
335
  import {
335
336
  nextInt
336
337
  } from "./chunk-nzjb36ad.js";
337
338
  import {
338
339
  ChildProcessSpawner,
339
340
  make3
340
- } from "./chunk-2qarscbj.js";
341
- import"./chunk-f3cbjk00.js";
341
+ } from "./chunk-sk6ceghr.js";
342
+ import"./chunk-db9q9y8h.js";
342
343
 
343
344
  // packages/core/src/sync-kit.ts
344
345
  import { createHash } from "crypto";
@@ -3614,14 +3615,20 @@ var readSessionRange = (file, position, length) => gen(function* () {
3614
3615
  }).pipe(scoped);
3615
3616
  var sessionFileSize = (file) => map8(openSession(file), ({ size }) => size).pipe(scoped);
3616
3617
  var maxSubagentFiles = 1024;
3617
- var sessionExtent = (file) => gen(function* () {
3618
+ var subagentFiles = (file) => gen(function* () {
3618
3619
  const fs = yield* FileSystem;
3619
- const own = yield* sessionFileSize(file);
3620
3620
  if (file.subagents === undefined)
3621
- return own;
3621
+ return [];
3622
3622
  const found = yield* sessionFiles(file.subagents, 0, file.confinedTo);
3623
- const sizes = yield* forEach(found.slice(0, maxSubagentFiles), (path) => fs.stat(path).pipe(map8((info) => Number(info.size)), orElseSucceed(() => 0)));
3624
- return sizes.reduce((total, size) => total + size, own);
3623
+ return yield* forEach(found.slice(0, maxSubagentFiles), (path) => fs.stat(path).pipe(map8((info) => {
3624
+ const modifiedAt = getOrUndefined(info.mtime)?.getTime();
3625
+ return { path, size: Number(info.size), ...modifiedAt === undefined ? undefined : { modifiedAt } };
3626
+ }), orElseSucceed(() => ({ path, size: 0 }))));
3627
+ });
3628
+ var sessionExtent = (file) => gen(function* () {
3629
+ const own = yield* sessionFileSize(file);
3630
+ const subagents = yield* subagentFiles(file);
3631
+ return subagents.reduce((total, { size }) => total + size, own);
3625
3632
  });
3626
3633
  var packConfined = (file, root) => gen(function* () {
3627
3634
  const { handle, size } = yield* openSession(file);
@@ -4572,6 +4579,7 @@ var boundChange = (change) => {
4572
4579
  truncated: omittedPaths > 0 || changedPaths.length > files.length || files.some((file) => file.truncated)
4573
4580
  };
4574
4581
  };
4582
+ var outputLength = outputLines * EvidenceLimits.lineLength;
4575
4583
  var DriftStatus = Literals(["open", "correction_sent", "escalated", "verified", "dismissed"]);
4576
4584
  var DriftActor = Struct({ actorType: String4, actorId: String4 });
4577
4585
  var DriftResolution = Struct({
@@ -4949,15 +4957,21 @@ function runReplica(control, executor, signals) {
4949
4957
  let completed = false;
4950
4958
  let leaseLost = false;
4951
4959
  let crashed;
4960
+ let tokens;
4961
+ const takeSpent = executor.spent?.(work.id) ?? undefined_;
4952
4962
  return yield* gen(function* () {
4953
4963
  const execution = executor.execute(work).pipe(mapError2((cause) => new RunnerReplicaError({ operation: "execute", kind: "rejected", cause })));
4954
- const outcome = yield* raceFirst(execution, raceFirst(workHeartbeat, pushedStop)).pipe(catchIf((error) => error instanceof RunnerReplicaCancellation, () => succeed6({ status: "canceled", failureSummary: "Cancellation requested" })));
4964
+ const raced = yield* raceFirst(execution, raceFirst(workHeartbeat, pushedStop)).pipe(catchIf((error) => error instanceof RunnerReplicaCancellation, () => succeed6({ status: "canceled", failureSummary: "Cancellation requested" })));
4965
+ const cutOff = yield* takeSpent;
4966
+ const outcome = "tokens" in raced || cutOff === undefined ? raced : { ...raced, tokens: cutOff };
4955
4967
  if (outcome.status === "deferred") {
4956
4968
  crashed = outcome.crashed;
4969
+ tokens = outcome.tokens;
4957
4970
  return { status: "deferred" };
4958
4971
  }
4959
4972
  if (outcome.status === "settled") {
4960
- completed = true;
4973
+ tokens = "tokens" in outcome ? outcome.tokens : undefined;
4974
+ completed = tokens === undefined;
4961
4975
  return { status: "completed", workUnitId: work.id };
4962
4976
  }
4963
4977
  yield* call("complete", () => control.complete({
@@ -4970,7 +4984,7 @@ function runReplica(control, executor, signals) {
4970
4984
  return { status: "completed", workUnitId: work.id };
4971
4985
  }).pipe(tapError2((error) => sync2(() => {
4972
4986
  leaseLost = error instanceof RunnerReplicaError && error.operation !== "execute" && error.kind !== "transient";
4973
- })), ensuring2(suspend3(() => completed || leaseLost ? void_3 : call("release", () => control.release(work.id, lease, crashed)).pipe(timeout(releaseTimeout), catch_((error) => logWarning("runner_release_failed", error.message))))), ensuring2(control.finished?.() ?? void_3));
4987
+ })), ensuring2(suspend3(() => completed || leaseLost ? void_3 : call("release", () => control.release(work.id, lease, crashed, tokens)).pipe(timeout(releaseTimeout), catch_((error) => logWarning("runner_release_failed", error.message))))), ensuring2(asVoid(takeSpent)), ensuring2(control.finished?.() ?? void_3));
4974
4988
  }));
4975
4989
  }
4976
4990
  var ConcurrencyRecheck = seconds(1);
@@ -5242,6 +5256,114 @@ var sessionRefusals = new Map([
5242
5256
  ["codex", codexProviderRefusal],
5243
5257
  ["pi", piProviderRefusal]
5244
5258
  ]);
5259
+ var count = (value) => isNumber(value) && value > 0 ? Math.floor(value) : 0;
5260
+ var tokenCounter = (harness) => {
5261
+ const counted = { input: 0, output: 0, cached: 0 };
5262
+ let reported = false;
5263
+ let message;
5264
+ let codexTotal;
5265
+ const add = (usage) => {
5266
+ reported = true;
5267
+ counted.input += usage.input;
5268
+ counted.output += usage.output;
5269
+ counted.cached += usage.cached;
5270
+ };
5271
+ const claude = (line) => {
5272
+ const { message: said } = line;
5273
+ if (!isJsonObject(said) || !isJsonObject(said.usage))
5274
+ return;
5275
+ const { usage } = said;
5276
+ const id = isString(said.id) ? said.id : undefined;
5277
+ const spent = {
5278
+ input: count(usage.input_tokens) + count(usage.cache_creation_input_tokens),
5279
+ output: count(usage.output_tokens),
5280
+ cached: count(usage.cache_read_input_tokens)
5281
+ };
5282
+ reported = true;
5283
+ if (id !== undefined && message?.id === id) {
5284
+ message.usage = spent;
5285
+ return;
5286
+ }
5287
+ if (message !== undefined)
5288
+ add(message.usage);
5289
+ message = id === undefined ? undefined : { id, usage: spent };
5290
+ if (id === undefined)
5291
+ add(spent);
5292
+ };
5293
+ const codex = (line) => {
5294
+ const event = line.type === "event_msg" ? line.payload : undefined;
5295
+ const info = isJsonObject(event) && event.type === "token_count" ? event.info : undefined;
5296
+ if (!isJsonObject(info) || !isJsonObject(info.last_token_usage))
5297
+ return;
5298
+ const total = encodeUnknownJsonStringSync(info.total_token_usage ?? null);
5299
+ if (total === codexTotal)
5300
+ return;
5301
+ codexTotal = total;
5302
+ const last = info.last_token_usage;
5303
+ const cached = count(last.cached_input_tokens);
5304
+ add({ input: Math.max(0, count(last.input_tokens) - cached), output: count(last.output_tokens), cached });
5305
+ };
5306
+ const pi = (line) => {
5307
+ const said = line.type === "message" ? line.message : undefined;
5308
+ if (!isJsonObject(said) || said.role !== "assistant" || !isJsonObject(said.usage))
5309
+ return;
5310
+ const { usage } = said;
5311
+ add({
5312
+ input: count(usage.input) + count(usage.cacheWrite),
5313
+ output: count(usage.output),
5314
+ cached: count(usage.cacheRead)
5315
+ });
5316
+ };
5317
+ const readers = new Map([
5318
+ ["claude", claude],
5319
+ ["codex", codex],
5320
+ ["pi", pi]
5321
+ ]);
5322
+ const read = readers.get(harness);
5323
+ return {
5324
+ saw: (line) => {
5325
+ if (read !== undefined && isJsonObject(line))
5326
+ read(line);
5327
+ },
5328
+ tokens: () => {
5329
+ if (!reported)
5330
+ return "none";
5331
+ return message === undefined ? { ...counted } : {
5332
+ input: counted.input + message.usage.input,
5333
+ output: counted.output + message.usage.output,
5334
+ cached: counted.cached + message.usage.cached
5335
+ };
5336
+ }
5337
+ };
5338
+ };
5339
+ var subagentTokens = (harness, file, from) => gen(function* () {
5340
+ const counter = tokenCounter(harness);
5341
+ let pending = new Uint8Array(0);
5342
+ let overlong = false;
5343
+ for (let position = from;; ) {
5344
+ const bytes = yield* readSessionRange(file, position, sliceBytes2);
5345
+ if (bytes.length === 0)
5346
+ return counter.tokens();
5347
+ position += bytes.length;
5348
+ const joined = new Uint8Array(pending.length + bytes.length);
5349
+ joined.set(pending);
5350
+ joined.set(bytes, pending.length);
5351
+ let start = 0;
5352
+ for (let end = joined.indexOf(newline);end >= 0; end = joined.indexOf(newline, start)) {
5353
+ const line = overlong ? "" : new TextDecoder().decode(joined.subarray(start, end));
5354
+ overlong = false;
5355
+ start = end + 1;
5356
+ if (line.includes('"usage"'))
5357
+ counter.saw(decoded2(line));
5358
+ }
5359
+ pending = joined.subarray(start);
5360
+ if (pending.length > maxLineBytes2) {
5361
+ overlong = true;
5362
+ pending = new Uint8Array(0);
5363
+ }
5364
+ yield* yieldNow;
5365
+ }
5366
+ });
5245
5367
  var sessionNormalizer = (harness) => {
5246
5368
  const asks = new Set;
5247
5369
  const called = (fullCallId, name, args) => {
@@ -5405,6 +5527,8 @@ var opencodeV2Part = (part) => {
5405
5527
  };
5406
5528
  var transcriptRelay = (input) => {
5407
5529
  const normalize = sessionNormalizer(input.harness);
5530
+ const tokens = tokenCounter(input.harness);
5531
+ let subagentsFrom;
5408
5532
  let sequence = input.sequence ?? 0;
5409
5533
  let skip = input.skipLines ?? 0;
5410
5534
  let position = 0;
@@ -5514,6 +5638,7 @@ var transcriptRelay = (input) => {
5514
5638
  while (queued.length > 0) {
5515
5639
  yield* suspend3(() => record(queued.splice(0, linesPerTurn2).flatMap((line) => {
5516
5640
  const value = decoded2(line);
5641
+ tokens.saw(value);
5517
5642
  if (input.harness === "claude")
5518
5643
  loginLost = claudeLoginLost(value) ?? loginLost;
5519
5644
  if (input.harness === "codex")
@@ -5642,6 +5767,15 @@ var transcriptRelay = (input) => {
5642
5767
  asking: sync2(() => asking.size > 0),
5643
5768
  loginLost: sync2(() => loginLost),
5644
5769
  refusal: sync2(() => refusal),
5770
+ tokens: (source) => gen(function* () {
5771
+ const own = tokens.tokens();
5772
+ if (source?.kind !== "file" || source.subagents === undefined)
5773
+ return own;
5774
+ const from = subagentsFrom ?? new Map;
5775
+ const files = (yield* subagentFiles(source)).filter((file) => file.path.endsWith(".jsonl"));
5776
+ const spent = yield* forEach(files, (file) => subagentTokens(input.harness, { path: file.path, ...source.confinedTo === undefined ? undefined : { confinedTo: source.confinedTo } }, from.get(file.path) ?? 0).pipe(catch_((error) => as(logWarning("runner_subagent_tokens_unread", error.message), "none"))));
5777
+ return tokensSpent([own, ...spent]) ?? "none";
5778
+ }),
5645
5779
  read: (source) => gen(function* () {
5646
5780
  if (source.kind === "opencode_v2") {
5647
5781
  const extent = yield* readOpencode2(source, "extent", {});
@@ -5667,6 +5801,10 @@ var transcriptRelay = (input) => {
5667
5801
  return;
5668
5802
  }
5669
5803
  yield* drain;
5804
+ if (source.subagents !== undefined && subagentsFrom === undefined) {
5805
+ const earlier = (yield* subagentFiles(source)).filter((file) => input.startedAt !== undefined && file.modifiedAt !== undefined && file.modifiedAt < input.startedAt);
5806
+ subagentsFrom = new Map(earlier.map((file) => [file.path, file.size]));
5807
+ }
5670
5808
  if (backedUp() || source.subagents !== undefined)
5671
5809
  yield* sawSession(yield* sessionExtent(source));
5672
5810
  while (!backedUp() && (yield* take(source))) {
@@ -6068,7 +6206,7 @@ var stepAttempt = (input, resending) => (work) => gen(function* () {
6068
6206
  const restored = repoBinding === undefined || saved === undefined ? undefined : yield* checkouts.checkout(work, repoBinding, saved).pipe(catch_((error) => as(logWarning("runner_checkpoint_not_restored", error.message), undefined)));
6069
6207
  const worktree = restored ?? (repoBinding === undefined ? yield* checkouts.scratch(work) : yield* checkouts.checkout(work, repoBinding));
6070
6208
  const merge = merging === undefined ? undefined : yield* mergeTarget(worktree, merging);
6071
- const deliver = (branch) => gen(function* () {
6209
+ const deliver = (branch, spent) => gen(function* () {
6072
6210
  const mergeCommit = merge === undefined ? undefined : (yield* runCommand2("git", ["-C", worktree, "rev-parse", "HEAD"])).trim();
6073
6211
  const revision = yield* pushWork(worktree, branch, work.stepKey, sharedBranch(work), yield* checkouts.transferEnv(repoBinding));
6074
6212
  const boundary = yield* runChange(worktree, work.runBaseRevision ?? work.baseRevision ?? `origin/${repoBinding?.defaultTargetBranch ?? "HEAD"}`).pipe(catch_((error) => as(logWarning("runner_boundary_unread", error.message), undefined)));
@@ -6086,7 +6224,8 @@ var stepAttempt = (input, resending) => (work) => gen(function* () {
6086
6224
  ...boundary === undefined ? undefined : { boundary },
6087
6225
  ...catchUp === undefined ? undefined : { catchUp },
6088
6226
  ...merge === undefined ? undefined : { syncedTarget: merge.target },
6089
- ...merge?.clean === undefined ? undefined : { cleanSync: merge.clean }
6227
+ ...merge?.clean === undefined ? undefined : { cleanSync: merge.clean },
6228
+ ...spent
6090
6229
  };
6091
6230
  return completed;
6092
6231
  });
@@ -6139,14 +6278,16 @@ var stepAttempt = (input, resending) => (work) => gen(function* () {
6139
6278
  const earlierSend = resending.get(work.id);
6140
6279
  resending.delete(work.id);
6141
6280
  const sentTo = earlierSend === undefined ? 0 : yield* join(earlierSend);
6281
+ const startedAt = yield* currentTimeMillis;
6142
6282
  const relay = transcripts === undefined || adapter === undefined ? undefined : transcriptRelay({
6143
6283
  harness: adapter.id,
6144
6284
  send: (entries) => transcripts(work, entries),
6145
6285
  skipLines: transcript === undefined ? 0 : yield* sessionLines(transcript).pipe(orElseSucceed(() => 0)),
6146
- sequence: Math.max(work.transcriptSequence ?? 0, sentTo)
6286
+ sequence: Math.max(work.transcriptSequence ?? 0, sentTo),
6287
+ startedAt
6147
6288
  });
6148
6289
  let source;
6149
- const startedAt = yield* currentTimeMillis;
6290
+ let tokens;
6150
6291
  const relayed = relay === undefined || adapter === undefined ? void_3 : gen(function* () {
6151
6292
  source ??= yield* transcriptSource(adapter, {
6152
6293
  ...sessions,
@@ -6248,6 +6389,9 @@ var stepAttempt = (input, resending) => (work) => gen(function* () {
6248
6389
  yield* interrupt(relaying);
6249
6390
  const state = isSuccess2(exit) ? exit.value.status : hasInterrupts(exit) ? "canceled" : "failed";
6250
6391
  yield* relayed.pipe(timeout("5 seconds"), ignore);
6392
+ const spentNow = yield* relay.tokens(source).pipe(timeoutOrElse({ duration: "5 seconds", orElse: () => relay.tokens(undefined) }));
6393
+ tokens = spentNow;
6394
+ input.spending?.set(work.id, spentNow);
6251
6395
  yield* andThen2(relay.record([{ kind: "lifecycle", state }]), relay.lastFlush).pipe(timeout("5 seconds"), ignore);
6252
6396
  const sending = yield* forkIn(relay.sendRest, input.runnerScope ?? makeUnsafe6());
6253
6397
  resending.set(work.id, sending);
@@ -6256,8 +6400,9 @@ var stepAttempt = (input, resending) => (work) => gen(function* () {
6256
6400
  })));
6257
6401
  if (checkpointing !== undefined)
6258
6402
  yield* interrupt(checkpointing);
6403
+ const spent = tokens === undefined ? undefined : { tokens };
6259
6404
  if (ran.status === "parked")
6260
- return { status: "deferred" };
6405
+ return { status: "deferred", ...spent };
6261
6406
  const refused = ran.status === "failed" && !("harnessHold" in ran) && relay !== undefined ? yield* relay.refusal : undefined;
6262
6407
  const deliversOutput = refused !== undefined && (yield* outputSubmitted);
6263
6408
  if (ran.status !== "finished" && !deliversOutput) {
@@ -6266,35 +6411,39 @@ var stepAttempt = (input, resending) => (work) => gen(function* () {
6266
6411
  return {
6267
6412
  status: "failed",
6268
6413
  failureSummary: refused.summary,
6269
- harnessHold: refusalHold(refused)
6414
+ harnessHold: refusalHold(refused),
6415
+ ...spent
6270
6416
  };
6271
6417
  if (backend === "docker" && "restart" in ran && ran.restart !== undefined)
6272
6418
  return {
6273
6419
  status: "failed",
6274
6420
  failureSummary: ran.summary,
6275
- harnessHold: refusalHold({ summary: ran.summary, kind: "login_refused" })
6421
+ harnessHold: refusalHold({ summary: ran.summary, kind: "login_refused" }),
6422
+ ...spent
6276
6423
  };
6277
6424
  return {
6278
6425
  status: ran.status,
6279
6426
  failureSummary: ran.summary,
6280
6427
  ..."harnessHold" in ran && ran.harnessHold !== undefined ? { harnessHold: ran.harnessHold } : undefined,
6281
- ..."restart" in ran && ran.restart !== undefined ? { restart: ran.restart } : undefined
6428
+ ..."restart" in ran && ran.restart !== undefined ? { restart: ran.restart } : undefined,
6429
+ ...spent
6282
6430
  };
6283
6431
  }
6284
6432
  const state = yield* input.heartbeat(work);
6285
6433
  if (state.settled)
6286
- return { status: "settled" };
6434
+ return { status: "settled", ...spent };
6287
6435
  if (state.outputSubmitted !== true)
6288
6436
  return {
6289
6437
  status: "failed",
6290
- failureSummary: "The agent finished without submitting its Output"
6438
+ failureSummary: "The agent finished without submitting its Output",
6439
+ ...spent
6291
6440
  };
6292
6441
  if (work.checkout !== "write" || work.branch === undefined)
6293
- return { status: "completed" };
6442
+ return { status: "completed", ...spent };
6294
6443
  const unmerged = merge === undefined ? undefined : yield* concludeMerge(worktree, merge.conflicted, state.outputMerged === true);
6295
6444
  if (unmerged !== undefined)
6296
- return { status: "failed", failureSummary: unmerged };
6297
- return yield* deliver(work.branch);
6445
+ return { status: "failed", failureSummary: unmerged, ...spent };
6446
+ return yield* deliver(work.branch, spent);
6298
6447
  }).pipe(scoped);
6299
6448
  var agentStepExecutor = (input) => stepAttempt(input, new Map);
6300
6449
  var checkpointRef = (work) => `refs/kitman/checkpoints/${work.runId}/${work.id}`;