@kitman-sh/cli 0.11.7 → 0.12.0-rc.1

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.
@@ -236,6 +236,7 @@ import {
236
236
  verificationNetworkAllowlist,
237
237
  programNetworkHosts,
238
238
  canonicalSha256,
239
+ tokensSpent,
239
240
  isTestReportName,
240
241
  checkTests,
241
242
  MeasureSample,
@@ -287,7 +288,7 @@ import {
287
288
  installCommand,
288
289
  checkServicesFile,
289
290
  checkServices
290
- } from "./chunk-5wvqtbfp.js";
291
+ } from "./chunk-dc57c8s5.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-1sy32p83.js";
308
+ import"./chunk-ejhfa1t6.js";
308
309
  import {
309
310
  egressAllowed,
310
311
  writeSecretRegistry,
@@ -329,8 +330,8 @@ import {
329
330
  rpcRunFiles,
330
331
  programHostsEnv,
331
332
  undeclaredHostsEnv
332
- } from "./chunk-z9zqctv2.js";
333
- import"./chunk-akzke77d.js";
333
+ } from "./chunk-rr0yw34p.js";
334
+ import"./chunk-kfwp70pn.js";
334
335
  import {
335
336
  nextInt
336
337
  } from "./chunk-nzjb36ad.js";
@@ -338,7 +339,7 @@ import {
338
339
  ChildProcessSpawner,
339
340
  make3
340
341
  } from "./chunk-2qarscbj.js";
341
- import"./chunk-f3cbjk00.js";
342
+ import"./chunk-rm3vqk5d.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);
@@ -4949,15 +4956,21 @@ function runReplica(control, executor, signals) {
4949
4956
  let completed = false;
4950
4957
  let leaseLost = false;
4951
4958
  let crashed;
4959
+ let tokens;
4960
+ const takeSpent = executor.spent?.(work.id) ?? undefined_;
4952
4961
  return yield* gen(function* () {
4953
4962
  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" })));
4963
+ const raced = yield* raceFirst(execution, raceFirst(workHeartbeat, pushedStop)).pipe(catchIf((error) => error instanceof RunnerReplicaCancellation, () => succeed6({ status: "canceled", failureSummary: "Cancellation requested" })));
4964
+ const cutOff = yield* takeSpent;
4965
+ const outcome = "tokens" in raced || cutOff === undefined ? raced : { ...raced, tokens: cutOff };
4955
4966
  if (outcome.status === "deferred") {
4956
4967
  crashed = outcome.crashed;
4968
+ tokens = outcome.tokens;
4957
4969
  return { status: "deferred" };
4958
4970
  }
4959
4971
  if (outcome.status === "settled") {
4960
- completed = true;
4972
+ tokens = "tokens" in outcome ? outcome.tokens : undefined;
4973
+ completed = tokens === undefined;
4961
4974
  return { status: "completed", workUnitId: work.id };
4962
4975
  }
4963
4976
  yield* call("complete", () => control.complete({
@@ -4970,7 +4983,7 @@ function runReplica(control, executor, signals) {
4970
4983
  return { status: "completed", workUnitId: work.id };
4971
4984
  }).pipe(tapError2((error) => sync2(() => {
4972
4985
  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));
4986
+ })), 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
4987
  }));
4975
4988
  }
4976
4989
  var ConcurrencyRecheck = seconds(1);
@@ -5242,6 +5255,114 @@ var sessionRefusals = new Map([
5242
5255
  ["codex", codexProviderRefusal],
5243
5256
  ["pi", piProviderRefusal]
5244
5257
  ]);
5258
+ var count = (value) => isNumber(value) && value > 0 ? Math.floor(value) : 0;
5259
+ var tokenCounter = (harness) => {
5260
+ const counted = { input: 0, output: 0, cached: 0 };
5261
+ let reported = false;
5262
+ let message;
5263
+ let codexTotal;
5264
+ const add = (usage) => {
5265
+ reported = true;
5266
+ counted.input += usage.input;
5267
+ counted.output += usage.output;
5268
+ counted.cached += usage.cached;
5269
+ };
5270
+ const claude = (line) => {
5271
+ const { message: said } = line;
5272
+ if (!isJsonObject(said) || !isJsonObject(said.usage))
5273
+ return;
5274
+ const { usage } = said;
5275
+ const id = isString(said.id) ? said.id : undefined;
5276
+ const spent = {
5277
+ input: count(usage.input_tokens) + count(usage.cache_creation_input_tokens),
5278
+ output: count(usage.output_tokens),
5279
+ cached: count(usage.cache_read_input_tokens)
5280
+ };
5281
+ reported = true;
5282
+ if (id !== undefined && message?.id === id) {
5283
+ message.usage = spent;
5284
+ return;
5285
+ }
5286
+ if (message !== undefined)
5287
+ add(message.usage);
5288
+ message = id === undefined ? undefined : { id, usage: spent };
5289
+ if (id === undefined)
5290
+ add(spent);
5291
+ };
5292
+ const codex = (line) => {
5293
+ const event = line.type === "event_msg" ? line.payload : undefined;
5294
+ const info = isJsonObject(event) && event.type === "token_count" ? event.info : undefined;
5295
+ if (!isJsonObject(info) || !isJsonObject(info.last_token_usage))
5296
+ return;
5297
+ const total = encodeUnknownJsonStringSync(info.total_token_usage ?? null);
5298
+ if (total === codexTotal)
5299
+ return;
5300
+ codexTotal = total;
5301
+ const last = info.last_token_usage;
5302
+ const cached = count(last.cached_input_tokens);
5303
+ add({ input: Math.max(0, count(last.input_tokens) - cached), output: count(last.output_tokens), cached });
5304
+ };
5305
+ const pi = (line) => {
5306
+ const said = line.type === "message" ? line.message : undefined;
5307
+ if (!isJsonObject(said) || said.role !== "assistant" || !isJsonObject(said.usage))
5308
+ return;
5309
+ const { usage } = said;
5310
+ add({
5311
+ input: count(usage.input) + count(usage.cacheWrite),
5312
+ output: count(usage.output),
5313
+ cached: count(usage.cacheRead)
5314
+ });
5315
+ };
5316
+ const readers = new Map([
5317
+ ["claude", claude],
5318
+ ["codex", codex],
5319
+ ["pi", pi]
5320
+ ]);
5321
+ const read = readers.get(harness);
5322
+ return {
5323
+ saw: (line) => {
5324
+ if (read !== undefined && isJsonObject(line))
5325
+ read(line);
5326
+ },
5327
+ tokens: () => {
5328
+ if (!reported)
5329
+ return "none";
5330
+ return message === undefined ? { ...counted } : {
5331
+ input: counted.input + message.usage.input,
5332
+ output: counted.output + message.usage.output,
5333
+ cached: counted.cached + message.usage.cached
5334
+ };
5335
+ }
5336
+ };
5337
+ };
5338
+ var subagentTokens = (harness, file, from) => gen(function* () {
5339
+ const counter = tokenCounter(harness);
5340
+ let pending = new Uint8Array(0);
5341
+ let overlong = false;
5342
+ for (let position = from;; ) {
5343
+ const bytes = yield* readSessionRange(file, position, sliceBytes2);
5344
+ if (bytes.length === 0)
5345
+ return counter.tokens();
5346
+ position += bytes.length;
5347
+ const joined = new Uint8Array(pending.length + bytes.length);
5348
+ joined.set(pending);
5349
+ joined.set(bytes, pending.length);
5350
+ let start = 0;
5351
+ for (let end = joined.indexOf(newline);end >= 0; end = joined.indexOf(newline, start)) {
5352
+ const line = overlong ? "" : new TextDecoder().decode(joined.subarray(start, end));
5353
+ overlong = false;
5354
+ start = end + 1;
5355
+ if (line.includes('"usage"'))
5356
+ counter.saw(decoded2(line));
5357
+ }
5358
+ pending = joined.subarray(start);
5359
+ if (pending.length > maxLineBytes2) {
5360
+ overlong = true;
5361
+ pending = new Uint8Array(0);
5362
+ }
5363
+ yield* yieldNow;
5364
+ }
5365
+ });
5245
5366
  var sessionNormalizer = (harness) => {
5246
5367
  const asks = new Set;
5247
5368
  const called = (fullCallId, name, args) => {
@@ -5405,6 +5526,8 @@ var opencodeV2Part = (part) => {
5405
5526
  };
5406
5527
  var transcriptRelay = (input) => {
5407
5528
  const normalize = sessionNormalizer(input.harness);
5529
+ const tokens = tokenCounter(input.harness);
5530
+ let subagentsFrom;
5408
5531
  let sequence = input.sequence ?? 0;
5409
5532
  let skip = input.skipLines ?? 0;
5410
5533
  let position = 0;
@@ -5514,6 +5637,7 @@ var transcriptRelay = (input) => {
5514
5637
  while (queued.length > 0) {
5515
5638
  yield* suspend3(() => record(queued.splice(0, linesPerTurn2).flatMap((line) => {
5516
5639
  const value = decoded2(line);
5640
+ tokens.saw(value);
5517
5641
  if (input.harness === "claude")
5518
5642
  loginLost = claudeLoginLost(value) ?? loginLost;
5519
5643
  if (input.harness === "codex")
@@ -5642,6 +5766,15 @@ var transcriptRelay = (input) => {
5642
5766
  asking: sync2(() => asking.size > 0),
5643
5767
  loginLost: sync2(() => loginLost),
5644
5768
  refusal: sync2(() => refusal),
5769
+ tokens: (source) => gen(function* () {
5770
+ const own = tokens.tokens();
5771
+ if (source?.kind !== "file" || source.subagents === undefined)
5772
+ return own;
5773
+ const from = subagentsFrom ?? new Map;
5774
+ const files = (yield* subagentFiles(source)).filter((file) => file.path.endsWith(".jsonl"));
5775
+ 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"))));
5776
+ return tokensSpent([own, ...spent]) ?? "none";
5777
+ }),
5645
5778
  read: (source) => gen(function* () {
5646
5779
  if (source.kind === "opencode_v2") {
5647
5780
  const extent = yield* readOpencode2(source, "extent", {});
@@ -5667,6 +5800,10 @@ var transcriptRelay = (input) => {
5667
5800
  return;
5668
5801
  }
5669
5802
  yield* drain;
5803
+ if (source.subagents !== undefined && subagentsFrom === undefined) {
5804
+ const earlier = (yield* subagentFiles(source)).filter((file) => input.startedAt !== undefined && file.modifiedAt !== undefined && file.modifiedAt < input.startedAt);
5805
+ subagentsFrom = new Map(earlier.map((file) => [file.path, file.size]));
5806
+ }
5670
5807
  if (backedUp() || source.subagents !== undefined)
5671
5808
  yield* sawSession(yield* sessionExtent(source));
5672
5809
  while (!backedUp() && (yield* take(source))) {
@@ -6068,7 +6205,7 @@ var stepAttempt = (input, resending) => (work) => gen(function* () {
6068
6205
  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
6206
  const worktree = restored ?? (repoBinding === undefined ? yield* checkouts.scratch(work) : yield* checkouts.checkout(work, repoBinding));
6070
6207
  const merge = merging === undefined ? undefined : yield* mergeTarget(worktree, merging);
6071
- const deliver = (branch) => gen(function* () {
6208
+ const deliver = (branch, spent) => gen(function* () {
6072
6209
  const mergeCommit = merge === undefined ? undefined : (yield* runCommand2("git", ["-C", worktree, "rev-parse", "HEAD"])).trim();
6073
6210
  const revision = yield* pushWork(worktree, branch, work.stepKey, sharedBranch(work), yield* checkouts.transferEnv(repoBinding));
6074
6211
  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 +6223,8 @@ var stepAttempt = (input, resending) => (work) => gen(function* () {
6086
6223
  ...boundary === undefined ? undefined : { boundary },
6087
6224
  ...catchUp === undefined ? undefined : { catchUp },
6088
6225
  ...merge === undefined ? undefined : { syncedTarget: merge.target },
6089
- ...merge?.clean === undefined ? undefined : { cleanSync: merge.clean }
6226
+ ...merge?.clean === undefined ? undefined : { cleanSync: merge.clean },
6227
+ ...spent
6090
6228
  };
6091
6229
  return completed;
6092
6230
  });
@@ -6139,14 +6277,16 @@ var stepAttempt = (input, resending) => (work) => gen(function* () {
6139
6277
  const earlierSend = resending.get(work.id);
6140
6278
  resending.delete(work.id);
6141
6279
  const sentTo = earlierSend === undefined ? 0 : yield* join(earlierSend);
6280
+ const startedAt = yield* currentTimeMillis;
6142
6281
  const relay = transcripts === undefined || adapter === undefined ? undefined : transcriptRelay({
6143
6282
  harness: adapter.id,
6144
6283
  send: (entries) => transcripts(work, entries),
6145
6284
  skipLines: transcript === undefined ? 0 : yield* sessionLines(transcript).pipe(orElseSucceed(() => 0)),
6146
- sequence: Math.max(work.transcriptSequence ?? 0, sentTo)
6285
+ sequence: Math.max(work.transcriptSequence ?? 0, sentTo),
6286
+ startedAt
6147
6287
  });
6148
6288
  let source;
6149
- const startedAt = yield* currentTimeMillis;
6289
+ let tokens;
6150
6290
  const relayed = relay === undefined || adapter === undefined ? void_3 : gen(function* () {
6151
6291
  source ??= yield* transcriptSource(adapter, {
6152
6292
  ...sessions,
@@ -6248,6 +6388,9 @@ var stepAttempt = (input, resending) => (work) => gen(function* () {
6248
6388
  yield* interrupt(relaying);
6249
6389
  const state = isSuccess2(exit) ? exit.value.status : hasInterrupts(exit) ? "canceled" : "failed";
6250
6390
  yield* relayed.pipe(timeout("5 seconds"), ignore);
6391
+ const spentNow = yield* relay.tokens(source).pipe(timeoutOrElse({ duration: "5 seconds", orElse: () => relay.tokens(undefined) }));
6392
+ tokens = spentNow;
6393
+ input.spending?.set(work.id, spentNow);
6251
6394
  yield* andThen2(relay.record([{ kind: "lifecycle", state }]), relay.lastFlush).pipe(timeout("5 seconds"), ignore);
6252
6395
  const sending = yield* forkIn(relay.sendRest, input.runnerScope ?? makeUnsafe6());
6253
6396
  resending.set(work.id, sending);
@@ -6256,8 +6399,9 @@ var stepAttempt = (input, resending) => (work) => gen(function* () {
6256
6399
  })));
6257
6400
  if (checkpointing !== undefined)
6258
6401
  yield* interrupt(checkpointing);
6402
+ const spent = tokens === undefined ? undefined : { tokens };
6259
6403
  if (ran.status === "parked")
6260
- return { status: "deferred" };
6404
+ return { status: "deferred", ...spent };
6261
6405
  const refused = ran.status === "failed" && !("harnessHold" in ran) && relay !== undefined ? yield* relay.refusal : undefined;
6262
6406
  const deliversOutput = refused !== undefined && (yield* outputSubmitted);
6263
6407
  if (ran.status !== "finished" && !deliversOutput) {
@@ -6266,35 +6410,39 @@ var stepAttempt = (input, resending) => (work) => gen(function* () {
6266
6410
  return {
6267
6411
  status: "failed",
6268
6412
  failureSummary: refused.summary,
6269
- harnessHold: refusalHold(refused)
6413
+ harnessHold: refusalHold(refused),
6414
+ ...spent
6270
6415
  };
6271
6416
  if (backend === "docker" && "restart" in ran && ran.restart !== undefined)
6272
6417
  return {
6273
6418
  status: "failed",
6274
6419
  failureSummary: ran.summary,
6275
- harnessHold: refusalHold({ summary: ran.summary, kind: "login_refused" })
6420
+ harnessHold: refusalHold({ summary: ran.summary, kind: "login_refused" }),
6421
+ ...spent
6276
6422
  };
6277
6423
  return {
6278
6424
  status: ran.status,
6279
6425
  failureSummary: ran.summary,
6280
6426
  ..."harnessHold" in ran && ran.harnessHold !== undefined ? { harnessHold: ran.harnessHold } : undefined,
6281
- ..."restart" in ran && ran.restart !== undefined ? { restart: ran.restart } : undefined
6427
+ ..."restart" in ran && ran.restart !== undefined ? { restart: ran.restart } : undefined,
6428
+ ...spent
6282
6429
  };
6283
6430
  }
6284
6431
  const state = yield* input.heartbeat(work);
6285
6432
  if (state.settled)
6286
- return { status: "settled" };
6433
+ return { status: "settled", ...spent };
6287
6434
  if (state.outputSubmitted !== true)
6288
6435
  return {
6289
6436
  status: "failed",
6290
- failureSummary: "The agent finished without submitting its Output"
6437
+ failureSummary: "The agent finished without submitting its Output",
6438
+ ...spent
6291
6439
  };
6292
6440
  if (work.checkout !== "write" || work.branch === undefined)
6293
- return { status: "completed" };
6441
+ return { status: "completed", ...spent };
6294
6442
  const unmerged = merge === undefined ? undefined : yield* concludeMerge(worktree, merge.conflicted, state.outputMerged === true);
6295
6443
  if (unmerged !== undefined)
6296
- return { status: "failed", failureSummary: unmerged };
6297
- return yield* deliver(work.branch);
6444
+ return { status: "failed", failureSummary: unmerged, ...spent };
6445
+ return yield* deliver(work.branch, spent);
6298
6446
  }).pipe(scoped);
6299
6447
  var agentStepExecutor = (input) => stepAttempt(input, new Map);
6300
6448
  var checkpointRef = (work) => `refs/kitman/checkpoints/${work.runId}/${work.id}`;
@@ -54,23 +54,23 @@ import {
54
54
  layer4,
55
55
  kitmanMcpServer,
56
56
  RunnerRpcProtocolVersion
57
- } from "./chunk-5wvqtbfp.js";
57
+ } from "./chunk-dc57c8s5.js";
58
58
  import {
59
59
  Packument,
60
60
  tarballMatches
61
- } from "./chunk-z2dnw6ey.js";
62
- import"./chunk-akzke77d.js";
61
+ } from "./chunk-ejhfa1t6.js";
62
+ import"./chunk-kfwp70pn.js";
63
63
  import {
64
64
  AgentDeclaration,
65
65
  KitDeclarations,
66
66
  describeFlag,
67
67
  Described
68
- } from "./chunk-z9zqctv2.js";
68
+ } from "./chunk-rr0yw34p.js";
69
69
  import {
70
70
  ChildProcessSpawner,
71
71
  make3
72
72
  } from "./chunk-2qarscbj.js";
73
- import"./chunk-f3cbjk00.js";
73
+ import"./chunk-rm3vqk5d.js";
74
74
 
75
75
  // packages/sdk/src/build/index.ts
76
76
  class DependencyInstallFailed extends TaggedError2()("DependencyInstallFailed", {