@kitman-sh/cli 0.11.6 → 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.
@@ -7,6 +7,46 @@ 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";
10
50
  import {
11
51
  pipeArguments,
12
52
  dual,
@@ -17,6 +57,7 @@ import {
17
57
  isUint8Array,
18
58
  PipeInspectableProto,
19
59
  none,
60
+ some,
20
61
  isNone,
21
62
  isSome,
22
63
  match,
@@ -195,6 +236,7 @@ import {
195
236
  verificationNetworkAllowlist,
196
237
  programNetworkHosts,
197
238
  canonicalSha256,
239
+ tokensSpent,
198
240
  isTestReportName,
199
241
  checkTests,
200
242
  MeasureSample,
@@ -246,47 +288,7 @@ import {
246
288
  installCommand,
247
289
  checkServicesFile,
248
290
  checkServices
249
- } from "./chunk-vxftwsbn.js";
250
- import {
251
- join,
252
- interrupt,
253
- unbounded,
254
- publishUnsafe,
255
- unbounded2,
256
- offer,
257
- makeUnsafe3,
258
- make11,
259
- fromQueue,
260
- fromPubSub,
261
- map2,
262
- filter,
263
- decodeText,
264
- encodeText,
265
- splitLines,
266
- run,
267
- runHead,
268
- runForEach,
269
- FileSystem,
270
- Path,
271
- embeddedFile,
272
- extractEmbeddedFile,
273
- optionalEnv,
274
- operatorConfigHome,
275
- harnessesUnsupportedInSrt2,
276
- compiled2,
277
- pinnedSrtCommand2,
278
- pinnedSrtStepCommand2,
279
- runSrtCli2,
280
- kitmanCacheDirectory2,
281
- srtSettings2,
282
- srtCacheEnvironment2,
283
- srtInheritedEnv2,
284
- inheritedEnvironment2,
285
- withOnlyEnvironment2,
286
- writeSrtSettings2,
287
- srtStepArgv2,
288
- srtArgv2
289
- } from "./chunk-3d4d52e5.js";
291
+ } from "./chunk-dc57c8s5.js";
290
292
  import {
291
293
  writeAgentEnvironmentConfigFile2,
292
294
  readManifestSkillPaths2,
@@ -302,8 +304,8 @@ import {
302
304
  applyAgentEnvironmentMaterialization2,
303
305
  isPathWithin2,
304
306
  skillIdentity2
305
- } from "./chunk-7ww1ztjr.js";
306
- import"./chunk-yz9mt7sj.js";
307
+ } from "./chunk-1sy32p83.js";
308
+ import"./chunk-ejhfa1t6.js";
307
309
  import {
308
310
  egressAllowed,
309
311
  writeSecretRegistry,
@@ -321,23 +323,23 @@ import {
321
323
  decodedOption2,
322
324
  decoded2,
323
325
  readOpencode2
324
- } from "./chunk-vmv7gwwr.js";
326
+ } from "./chunk-kpfrhex3.js";
325
327
  import {
326
328
  uploadRunFile,
327
329
  programLease,
328
330
  rpcRunFiles,
329
331
  programHostsEnv,
330
332
  undeclaredHostsEnv
331
- } from "./chunk-pft5558d.js";
332
- import"./chunk-3nwq8a1k.js";
333
+ } from "./chunk-rr0yw34p.js";
334
+ import"./chunk-kfwp70pn.js";
333
335
  import {
334
336
  nextInt
335
337
  } from "./chunk-nzjb36ad.js";
336
338
  import {
337
339
  ChildProcessSpawner,
338
340
  make3
339
- } from "./chunk-sk6ceghr.js";
340
- import"./chunk-wf6hts0g.js";
341
+ } from "./chunk-2qarscbj.js";
342
+ import"./chunk-rm3vqk5d.js";
341
343
 
342
344
  // packages/core/src/sync-kit.ts
343
345
  import { createHash } from "crypto";
@@ -3083,7 +3085,19 @@ var setUnsafe = (self, value) => {
3083
3085
  var update = /* @__PURE__ */ dual(2, (self, update) => self.semaphore.withPermit(sync2(() => setUnsafe(self, update(self.value)))));
3084
3086
 
3085
3087
  // packages/agent-runtime/src/claude-workspace-trust.ts
3088
+ class ClaudeTrustNotRecorded extends TaggedError("ClaudeTrustNotRecorded") {
3089
+ get message() {
3090
+ return `${this.file}: ${this.reason}`;
3091
+ }
3092
+ }
3093
+
3094
+ class ConfigLockHeld extends TaggedError("ConfigLockHeld") {
3095
+ }
3086
3096
  var withEntry = (object, key, value) => Object.fromEntries([...Object.entries(object), [key, value]]);
3097
+ var configLockStaleMs = 1e4;
3098
+ var configLockPollMs = 25;
3099
+ var configLockPolls = 2 * configLockStaleMs / configLockPollMs;
3100
+ var recordAttempts = 3;
3087
3101
  var writePermits = new Map;
3088
3102
  var trustClaudeWorkspace = (home, workspace) => {
3089
3103
  const permit = writePermits.get(home) ?? makeUnsafe3(1);
@@ -3093,21 +3107,62 @@ var trustClaudeWorkspace = (home, workspace) => {
3093
3107
  var trust = (home, workspace) => gen(function* () {
3094
3108
  const fs = yield* FileSystem;
3095
3109
  const file = `${home}/.claude.json`;
3110
+ yield* fs.makeDirectory(home, { recursive: true });
3111
+ for (let attempt = 0;attempt < recordAttempts; attempt++) {
3112
+ if (yield* isTrusted(file, workspace))
3113
+ return;
3114
+ if (attempt > 0)
3115
+ yield* logWarning("claude_trust_lost", { file, workspace });
3116
+ yield* scoped(andThen2(holdConfigLock(file), record(home, workspace)));
3117
+ }
3118
+ if (yield* isTrusted(file, workspace))
3119
+ return;
3120
+ return yield* new ClaudeTrustNotRecorded({
3121
+ file,
3122
+ reason: `the trust of ${workspace} was overwritten after each of ${recordAttempts} writes`
3123
+ });
3124
+ });
3125
+ var readConfig = (file) => gen(function* () {
3126
+ const fs = yield* FileSystem;
3096
3127
  const text = yield* fs.readFileString(file).pipe(catchReason("PlatformError", "NotFound", () => succeed6("{}")));
3097
3128
  const config = yield* decodeJsonString(text).pipe(orElseSucceed(() => {
3098
3129
  return;
3099
3130
  }));
3100
- if (!isJsonObject(config))
3101
- return yield* logWarning("claude_trust_skipped", `${file} is not a JSON object`);
3131
+ return isJsonObject(config) ? some(config) : none();
3132
+ });
3133
+ var projectOf = (config, workspace) => {
3102
3134
  const projects = isJsonObject(config.projects) ? config.projects : {};
3103
3135
  const project = isJsonObject(projects[workspace]) ? projects[workspace] : {};
3136
+ return { projects, project };
3137
+ };
3138
+ var isTrusted = (file, workspace) => map8(readConfig(file), (config) => isSome(config) ? projectOf(config.value, workspace).project.hasTrustDialogAccepted === true : false);
3139
+ var holdConfigLock = (file) => gen(function* () {
3140
+ const fs = yield* FileSystem;
3141
+ const lock = `${file}.lock`;
3142
+ const take = fs.makeDirectory(lock).pipe(catchReason("PlatformError", "AlreadyExists", () => gen(function* () {
3143
+ const modified = flatMap(yield* option2(fs.stat(lock)), (info) => info.mtime);
3144
+ const now = yield* currentTimeMillis;
3145
+ if (isSome(modified) && now - modified.value.getTime() > configLockStaleMs)
3146
+ yield* fs.remove(lock, { recursive: true }).pipe(ignore);
3147
+ return yield* new ConfigLockHeld;
3148
+ })), retry({
3149
+ while: isTagged("ConfigLockHeld"),
3150
+ schedule: spaced(configLockPollMs),
3151
+ times: configLockPolls
3152
+ }), catchTag("ConfigLockHeld", () => fail7(new ClaudeTrustNotRecorded({ file, reason: `${lock} stayed held` }))));
3153
+ yield* acquireRelease(take, () => fs.remove(lock, { recursive: true }).pipe(ignore));
3154
+ });
3155
+ var record = (home, workspace) => gen(function* () {
3156
+ const fs = yield* FileSystem;
3157
+ const file = `${home}/.claude.json`;
3158
+ const config = yield* readConfig(file);
3159
+ if (isNone(config))
3160
+ return yield* new ClaudeTrustNotRecorded({ file, reason: "it is not a JSON object" });
3161
+ const { projects, project } = projectOf(config.value, workspace);
3104
3162
  if (project.hasTrustDialogAccepted === true)
3105
3163
  return;
3106
- const json = yield* encodePrettyJsonString(withEntry(config, "projects", withEntry(projects, workspace, withEntry(project, "hasTrustDialogAccepted", true))));
3107
- const temporary = yield* fs.makeTempFile({
3108
- directory: home,
3109
- prefix: ".claude.json.kitman-"
3110
- });
3164
+ const json = yield* encodePrettyJsonString(withEntry(config.value, "projects", withEntry(projects, workspace, withEntry(project, "hasTrustDialogAccepted", true))));
3165
+ const temporary = yield* fs.makeTempFile({ directory: home, prefix: ".claude.json.kitman-" });
3111
3166
  yield* fs.chmod(temporary, 384);
3112
3167
  yield* fs.writeFileString(temporary, `${json}
3113
3168
  `);
@@ -3560,14 +3615,20 @@ var readSessionRange = (file, position, length) => gen(function* () {
3560
3615
  }).pipe(scoped);
3561
3616
  var sessionFileSize = (file) => map8(openSession(file), ({ size }) => size).pipe(scoped);
3562
3617
  var maxSubagentFiles = 1024;
3563
- var sessionExtent = (file) => gen(function* () {
3618
+ var subagentFiles = (file) => gen(function* () {
3564
3619
  const fs = yield* FileSystem;
3565
- const own = yield* sessionFileSize(file);
3566
3620
  if (file.subagents === undefined)
3567
- return own;
3621
+ return [];
3568
3622
  const found = yield* sessionFiles(file.subagents, 0, file.confinedTo);
3569
- const sizes = yield* forEach(found.slice(0, maxSubagentFiles), (path) => fs.stat(path).pipe(map8((info) => Number(info.size)), orElseSucceed(() => 0)));
3570
- 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);
3571
3632
  });
3572
3633
  var packConfined = (file, root) => gen(function* () {
3573
3634
  const { handle, size } = yield* openSession(file);
@@ -4225,10 +4286,15 @@ var runAttempt = (request, options) => gen(function* () {
4225
4286
  }
4226
4287
  }
4227
4288
  }), registry === undefined ? void_3 : watchSecretRegistry(registry, request, options.secretRevocationMs))));
4228
- if (adapter.id === "claude" && request.sandbox.backend !== "docker")
4229
- yield* trustClaudeWorkspace(launch.globalConfig === undefined ? options.home : (yield* Path).dirname(launch.globalConfig.path), workspace).pipe(catch_((error) => logWarning("claude_trust_failed", error)));
4230
4289
  if (isFailure(command))
4231
4290
  return failed(command.failure.reason, command.failure.summary);
4291
+ if (adapter.id === "claude" && request.sandbox.backend !== "docker") {
4292
+ const trusted = yield* result(trustClaudeWorkspace(launch.globalConfig === undefined ? options.home : (yield* Path).dirname(launch.globalConfig.path), workspace));
4293
+ if (isFailure(trusted)) {
4294
+ yield* logWarning("claude_trust_failed", trusted.failure);
4295
+ return failed("harness_launch_failed", `Kitman could not record the workspace's trust, so Claude Code would wait on its folder trust prompt: ${trusted.failure.message}`);
4296
+ }
4297
+ }
4232
4298
  const call = requester(options.core, yield* scope2);
4233
4299
  const argv = yield* options.stepProcesses.contain(request.runnerId, attempt.id, command.success.argv);
4234
4300
  const run = (connection) => connection.run({
@@ -4890,15 +4956,21 @@ function runReplica(control, executor, signals) {
4890
4956
  let completed = false;
4891
4957
  let leaseLost = false;
4892
4958
  let crashed;
4959
+ let tokens;
4960
+ const takeSpent = executor.spent?.(work.id) ?? undefined_;
4893
4961
  return yield* gen(function* () {
4894
4962
  const execution = executor.execute(work).pipe(mapError2((cause) => new RunnerReplicaError({ operation: "execute", kind: "rejected", cause })));
4895
- 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 };
4896
4966
  if (outcome.status === "deferred") {
4897
4967
  crashed = outcome.crashed;
4968
+ tokens = outcome.tokens;
4898
4969
  return { status: "deferred" };
4899
4970
  }
4900
4971
  if (outcome.status === "settled") {
4901
- completed = true;
4972
+ tokens = "tokens" in outcome ? outcome.tokens : undefined;
4973
+ completed = tokens === undefined;
4902
4974
  return { status: "completed", workUnitId: work.id };
4903
4975
  }
4904
4976
  yield* call("complete", () => control.complete({
@@ -4911,7 +4983,7 @@ function runReplica(control, executor, signals) {
4911
4983
  return { status: "completed", workUnitId: work.id };
4912
4984
  }).pipe(tapError2((error) => sync2(() => {
4913
4985
  leaseLost = error instanceof RunnerReplicaError && error.operation !== "execute" && error.kind !== "transient";
4914
- })), 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));
4915
4987
  }));
4916
4988
  }
4917
4989
  var ConcurrencyRecheck = seconds(1);
@@ -5183,6 +5255,114 @@ var sessionRefusals = new Map([
5183
5255
  ["codex", codexProviderRefusal],
5184
5256
  ["pi", piProviderRefusal]
5185
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
+ });
5186
5366
  var sessionNormalizer = (harness) => {
5187
5367
  const asks = new Set;
5188
5368
  const called = (fullCallId, name, args) => {
@@ -5346,6 +5526,8 @@ var opencodeV2Part = (part) => {
5346
5526
  };
5347
5527
  var transcriptRelay = (input) => {
5348
5528
  const normalize = sessionNormalizer(input.harness);
5529
+ const tokens = tokenCounter(input.harness);
5530
+ let subagentsFrom;
5349
5531
  let sequence = input.sequence ?? 0;
5350
5532
  let skip = input.skipLines ?? 0;
5351
5533
  let position = 0;
@@ -5455,6 +5637,7 @@ var transcriptRelay = (input) => {
5455
5637
  while (queued.length > 0) {
5456
5638
  yield* suspend3(() => record(queued.splice(0, linesPerTurn2).flatMap((line) => {
5457
5639
  const value = decoded2(line);
5640
+ tokens.saw(value);
5458
5641
  if (input.harness === "claude")
5459
5642
  loginLost = claudeLoginLost(value) ?? loginLost;
5460
5643
  if (input.harness === "codex")
@@ -5583,6 +5766,15 @@ var transcriptRelay = (input) => {
5583
5766
  asking: sync2(() => asking.size > 0),
5584
5767
  loginLost: sync2(() => loginLost),
5585
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
+ }),
5586
5778
  read: (source) => gen(function* () {
5587
5779
  if (source.kind === "opencode_v2") {
5588
5780
  const extent = yield* readOpencode2(source, "extent", {});
@@ -5608,6 +5800,10 @@ var transcriptRelay = (input) => {
5608
5800
  return;
5609
5801
  }
5610
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
+ }
5611
5807
  if (backedUp() || source.subagents !== undefined)
5612
5808
  yield* sawSession(yield* sessionExtent(source));
5613
5809
  while (!backedUp() && (yield* take(source))) {
@@ -6009,6 +6205,31 @@ var stepAttempt = (input, resending) => (work) => gen(function* () {
6009
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)));
6010
6206
  const worktree = restored ?? (repoBinding === undefined ? yield* checkouts.scratch(work) : yield* checkouts.checkout(work, repoBinding));
6011
6207
  const merge = merging === undefined ? undefined : yield* mergeTarget(worktree, merging);
6208
+ const deliver = (branch, spent) => gen(function* () {
6209
+ const mergeCommit = merge === undefined ? undefined : (yield* runCommand2("git", ["-C", worktree, "rev-parse", "HEAD"])).trim();
6210
+ const revision = yield* pushWork(worktree, branch, work.stepKey, sharedBranch(work), yield* checkouts.transferEnv(repoBinding));
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)));
6212
+ const catchUp = merge === undefined || merging === undefined || mergeCommit === undefined || mergeCommit === merge.from ? undefined : yield* catchUpReport(worktree, {
6213
+ from: merge.from,
6214
+ merged: mergeCommit,
6215
+ head: revision,
6216
+ target: merging,
6217
+ conflicted: merge.conflicted,
6218
+ ...merge.automerged === undefined ? undefined : { automerged: merge.automerged }
6219
+ }).pipe(catch_((error) => as(logWarning("runner_catch_up_unread", error.message), undefined)));
6220
+ const completed = {
6221
+ status: "completed",
6222
+ revision,
6223
+ ...boundary === undefined ? undefined : { boundary },
6224
+ ...catchUp === undefined ? undefined : { catchUp },
6225
+ ...merge === undefined ? undefined : { syncedTarget: merge.target },
6226
+ ...merge?.clean === undefined ? undefined : { cleanSync: merge.clean },
6227
+ ...spent
6228
+ };
6229
+ return completed;
6230
+ });
6231
+ if (merge?.clean === "up_to_date" && work.branch !== undefined)
6232
+ return yield* deliver(work.branch);
6012
6233
  const notes = [...work.resumeNotes ?? [], ...merge === undefined ? [] : [merge.note]];
6013
6234
  const configDir = yield* (yield* FileSystem).makeTempDirectoryScoped({ prefix: "kitman-harness-" }).pipe(orDie);
6014
6235
  const backend = work.sandbox ?? (isFunction2(input.sandbox) ? input.sandbox(work) : input.sandbox);
@@ -6056,14 +6277,16 @@ var stepAttempt = (input, resending) => (work) => gen(function* () {
6056
6277
  const earlierSend = resending.get(work.id);
6057
6278
  resending.delete(work.id);
6058
6279
  const sentTo = earlierSend === undefined ? 0 : yield* join(earlierSend);
6280
+ const startedAt = yield* currentTimeMillis;
6059
6281
  const relay = transcripts === undefined || adapter === undefined ? undefined : transcriptRelay({
6060
6282
  harness: adapter.id,
6061
6283
  send: (entries) => transcripts(work, entries),
6062
6284
  skipLines: transcript === undefined ? 0 : yield* sessionLines(transcript).pipe(orElseSucceed(() => 0)),
6063
- sequence: Math.max(work.transcriptSequence ?? 0, sentTo)
6285
+ sequence: Math.max(work.transcriptSequence ?? 0, sentTo),
6286
+ startedAt
6064
6287
  });
6065
6288
  let source;
6066
- const startedAt = yield* currentTimeMillis;
6289
+ let tokens;
6067
6290
  const relayed = relay === undefined || adapter === undefined ? void_3 : gen(function* () {
6068
6291
  source ??= yield* transcriptSource(adapter, {
6069
6292
  ...sessions,
@@ -6165,6 +6388,9 @@ var stepAttempt = (input, resending) => (work) => gen(function* () {
6165
6388
  yield* interrupt(relaying);
6166
6389
  const state = isSuccess2(exit) ? exit.value.status : hasInterrupts(exit) ? "canceled" : "failed";
6167
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);
6168
6394
  yield* andThen2(relay.record([{ kind: "lifecycle", state }]), relay.lastFlush).pipe(timeout("5 seconds"), ignore);
6169
6395
  const sending = yield* forkIn(relay.sendRest, input.runnerScope ?? makeUnsafe6());
6170
6396
  resending.set(work.id, sending);
@@ -6173,8 +6399,9 @@ var stepAttempt = (input, resending) => (work) => gen(function* () {
6173
6399
  })));
6174
6400
  if (checkpointing !== undefined)
6175
6401
  yield* interrupt(checkpointing);
6402
+ const spent = tokens === undefined ? undefined : { tokens };
6176
6403
  if (ran.status === "parked")
6177
- return { status: "deferred" };
6404
+ return { status: "deferred", ...spent };
6178
6405
  const refused = ran.status === "failed" && !("harnessHold" in ran) && relay !== undefined ? yield* relay.refusal : undefined;
6179
6406
  const deliversOutput = refused !== undefined && (yield* outputSubmitted);
6180
6407
  if (ran.status !== "finished" && !deliversOutput) {
@@ -6183,54 +6410,39 @@ var stepAttempt = (input, resending) => (work) => gen(function* () {
6183
6410
  return {
6184
6411
  status: "failed",
6185
6412
  failureSummary: refused.summary,
6186
- harnessHold: refusalHold(refused)
6413
+ harnessHold: refusalHold(refused),
6414
+ ...spent
6187
6415
  };
6188
6416
  if (backend === "docker" && "restart" in ran && ran.restart !== undefined)
6189
6417
  return {
6190
6418
  status: "failed",
6191
6419
  failureSummary: ran.summary,
6192
- harnessHold: refusalHold({ summary: ran.summary, kind: "login_refused" })
6420
+ harnessHold: refusalHold({ summary: ran.summary, kind: "login_refused" }),
6421
+ ...spent
6193
6422
  };
6194
6423
  return {
6195
6424
  status: ran.status,
6196
6425
  failureSummary: ran.summary,
6197
6426
  ..."harnessHold" in ran && ran.harnessHold !== undefined ? { harnessHold: ran.harnessHold } : undefined,
6198
- ..."restart" in ran && ran.restart !== undefined ? { restart: ran.restart } : undefined
6427
+ ..."restart" in ran && ran.restart !== undefined ? { restart: ran.restart } : undefined,
6428
+ ...spent
6199
6429
  };
6200
6430
  }
6201
6431
  const state = yield* input.heartbeat(work);
6202
6432
  if (state.settled)
6203
- return { status: "settled" };
6433
+ return { status: "settled", ...spent };
6204
6434
  if (state.outputSubmitted !== true)
6205
6435
  return {
6206
6436
  status: "failed",
6207
- failureSummary: "The agent finished without submitting its Output"
6437
+ failureSummary: "The agent finished without submitting its Output",
6438
+ ...spent
6208
6439
  };
6209
6440
  if (work.checkout !== "write" || work.branch === undefined)
6210
- return { status: "completed" };
6441
+ return { status: "completed", ...spent };
6211
6442
  const unmerged = merge === undefined ? undefined : yield* concludeMerge(worktree, merge.conflicted, state.outputMerged === true);
6212
6443
  if (unmerged !== undefined)
6213
- return { status: "failed", failureSummary: unmerged };
6214
- const mergeCommit = merge === undefined ? undefined : (yield* runCommand2("git", ["-C", worktree, "rev-parse", "HEAD"])).trim();
6215
- const revision = yield* pushWork(worktree, work.branch, work.stepKey, sharedBranch(work), yield* checkouts.transferEnv(repoBinding));
6216
- const boundary = yield* runChange(worktree, work.runBaseRevision ?? work.baseRevision ?? `origin/${repoBinding?.defaultTargetBranch ?? "HEAD"}`).pipe(catch_((error) => as(logWarning("runner_boundary_unread", error.message), undefined)));
6217
- const catchUp = merge === undefined || merging === undefined || mergeCommit === undefined || mergeCommit === merge.from ? undefined : yield* catchUpReport(worktree, {
6218
- from: merge.from,
6219
- merged: mergeCommit,
6220
- head: revision,
6221
- target: merging,
6222
- conflicted: merge.conflicted,
6223
- ...merge.automerged === undefined ? undefined : { automerged: merge.automerged }
6224
- }).pipe(catch_((error) => as(logWarning("runner_catch_up_unread", error.message), undefined)));
6225
- const completed = {
6226
- status: "completed",
6227
- revision,
6228
- ...boundary === undefined ? undefined : { boundary },
6229
- ...catchUp === undefined ? undefined : { catchUp },
6230
- ...merge === undefined ? undefined : { syncedTarget: merge.target },
6231
- ...merge?.clean === undefined ? undefined : { cleanSync: merge.clean }
6232
- };
6233
- return completed;
6444
+ return { status: "failed", failureSummary: unmerged, ...spent };
6445
+ return yield* deliver(work.branch, spent);
6234
6446
  }).pipe(scoped);
6235
6447
  var agentStepExecutor = (input) => stepAttempt(input, new Map);
6236
6448
  var checkpointRef = (work) => `refs/kitman/checkpoints/${work.runId}/${work.id}`;
@@ -1,4 +1,12 @@
1
1
  // @bun
2
+ import {
3
+ decodeText,
4
+ mkString,
5
+ FileSystem,
6
+ Path,
7
+ withDefault,
8
+ String2
9
+ } from "./chunk-0b93nv6j.js";
2
10
  import {
3
11
  isString2,
4
12
  hasProperty,
@@ -46,31 +54,23 @@ import {
46
54
  layer4,
47
55
  kitmanMcpServer,
48
56
  RunnerRpcProtocolVersion
49
- } from "./chunk-vxftwsbn.js";
50
- import {
51
- decodeText,
52
- mkString,
53
- FileSystem,
54
- Path,
55
- withDefault,
56
- String2
57
- } from "./chunk-3d4d52e5.js";
57
+ } from "./chunk-dc57c8s5.js";
58
58
  import {
59
59
  Packument,
60
60
  tarballMatches
61
- } from "./chunk-yz9mt7sj.js";
62
- import"./chunk-3nwq8a1k.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-pft5558d.js";
68
+ } from "./chunk-rr0yw34p.js";
69
69
  import {
70
70
  ChildProcessSpawner,
71
71
  make3
72
- } from "./chunk-sk6ceghr.js";
73
- import"./chunk-wf6hts0g.js";
72
+ } from "./chunk-2qarscbj.js";
73
+ import"./chunk-rm3vqk5d.js";
74
74
 
75
75
  // packages/sdk/src/build/index.ts
76
76
  class DependencyInstallFailed extends TaggedError2()("DependencyInstallFailed", {