@kitman-sh/cli 0.31.0 → 0.33.0

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 (29) hide show
  1. package/dist/{chunk-fjdp3rd6.js → chunk-1zb8h7gv.js} +45 -32
  2. package/dist/{chunk-r2kzvdrg.js → chunk-4qjfn1sa.js} +1 -1
  3. package/dist/{chunk-m1qp6swh.js → chunk-5kqt4bqp.js} +1 -1
  4. package/dist/{chunk-z59pvcbk.js → chunk-8fyfsajs.js} +179 -31
  5. package/dist/{chunk-vh2a72d1.js → chunk-9nbqzdqp.js} +60 -14
  6. package/dist/{chunk-emw9ragp.js → chunk-9tyv6211.js} +21 -21
  7. package/dist/{chunk-vwynec02.js → chunk-a9ncx2a8.js} +1 -1
  8. package/dist/{chunk-yjc2w86k.js → chunk-ak1qrm4q.js} +7 -7
  9. package/dist/{chunk-9vqkjkya.js → chunk-bnhb3cth.js} +2 -2
  10. package/dist/{chunk-2sazk478.js → chunk-gnq1ryhx.js} +8 -4
  11. package/dist/{chunk-y64ssczv.js → chunk-h2f26xbd.js} +40 -226
  12. package/dist/{chunk-s4r49vbj.js → chunk-hgxhpj6m.js} +4 -4
  13. package/dist/{chunk-qb11yda6.js → chunk-jrwpte6y.js} +41 -41
  14. package/dist/{chunk-qbrkeg49.js → chunk-mhx0tgm3.js} +7 -7
  15. package/dist/{chunk-5qrjf4xq.js → chunk-np5n54ky.js} +6 -6
  16. package/dist/{chunk-xxcxramy.js → chunk-nwbry6c8.js} +130 -124
  17. package/dist/{chunk-nndgeync.js → chunk-py3133q0.js} +6 -6
  18. package/dist/{chunk-nk0ew12p.js → chunk-racse7zf.js} +449 -37
  19. package/dist/chunk-s34am3kw.js +399 -0
  20. package/dist/{chunk-9a6wbk11.js → chunk-samxkpbz.js} +3 -3
  21. package/dist/{chunk-njgay1ed.js → chunk-sgkgwzvb.js} +6 -6
  22. package/dist/{chunk-pd3azxev.js → chunk-tsx0347c.js} +1 -1
  23. package/dist/{chunk-zy21drtv.js → chunk-vz38kngm.js} +2 -2
  24. package/dist/{chunk-qjxgew0k.js → chunk-x29m7k25.js} +2 -2
  25. package/dist/{chunk-9yvknsnj.js → chunk-xkkyx7bn.js} +3 -3
  26. package/dist/{chunk-38drrdzp.js → chunk-yveqd8ye.js} +4 -4
  27. package/dist/index.js +4 -4
  28. package/package.json +1 -1
  29. package/dist/chunk-kx8rpa62.js +0 -230
@@ -14,6 +14,7 @@ import {
14
14
  isSome,
15
15
  match,
16
16
  getOrElse,
17
+ fromUndefinedOr,
17
18
  getOrUndefined,
18
19
  liftThrowable,
19
20
  map4,
@@ -43,7 +44,7 @@ import {
43
44
  isFailure2,
44
45
  hasInterrupts,
45
46
  makeUnsafe5,
46
- make15,
47
+ make16,
47
48
  _await,
48
49
  fail5,
49
50
  isDoneUnsafe,
@@ -125,6 +126,7 @@ import {
125
126
  repeat,
126
127
  forkIn,
127
128
  forkScoped,
129
+ forkDetach,
128
130
  fnUntraced,
129
131
  logWarning,
130
132
  logError,
@@ -172,9 +174,8 @@ import {
172
174
  decodeJsonStringSync,
173
175
  encodeUnknownJsonStringSync,
174
176
  storable
175
- } from "./chunk-y64ssczv.js";
177
+ } from "./chunk-h2f26xbd.js";
176
178
  import {
177
- currentTimeMillis,
178
179
  SecureRandom,
179
180
  layerWebCrypto,
180
181
  layer,
@@ -261,8 +262,9 @@ import {
261
262
  checkServicesFile,
262
263
  checkServices,
263
264
  serviceChecks
264
- } from "./chunk-xxcxramy.js";
265
+ } from "./chunk-nwbry6c8.js";
265
266
  import {
267
+ currentTimeMillis,
266
268
  join,
267
269
  interrupt,
268
270
  unbounded,
@@ -270,7 +272,7 @@ import {
270
272
  unbounded2,
271
273
  offer,
272
274
  makeUnsafe3,
273
- make10,
275
+ make11,
274
276
  fromQueue,
275
277
  fromPubSub,
276
278
  map2,
@@ -289,6 +291,8 @@ import {
289
291
  Path,
290
292
  embeddedFile,
291
293
  extractEmbeddedFile,
294
+ withDefault,
295
+ String2,
292
296
  optionalEnv,
293
297
  operatorConfigHome,
294
298
  tempDirectoryScoped,
@@ -307,7 +311,7 @@ import {
307
311
  writeSrtSettings2,
308
312
  srtStepArgv2,
309
313
  srtArgv2
310
- } from "./chunk-z59pvcbk.js";
314
+ } from "./chunk-8fyfsajs.js";
311
315
  import {
312
316
  writeAgentEnvironmentConfigFile2,
313
317
  readManifestSkillPaths2,
@@ -323,12 +327,8 @@ import {
323
327
  applyAgentEnvironmentMaterialization2,
324
328
  isPathWithin2,
325
329
  skillIdentity2
326
- } from "./chunk-s4r49vbj.js";
327
- import"./chunk-9yvknsnj.js";
328
- import {
329
- ChildProcessSpawner,
330
- make2
331
- } from "./chunk-vh2a72d1.js";
330
+ } from "./chunk-hgxhpj6m.js";
331
+ import"./chunk-xkkyx7bn.js";
332
332
  import {
333
333
  egressAllowed,
334
334
  writeSecretRegistry,
@@ -338,33 +338,39 @@ import {
338
338
  secretFilter2,
339
339
  opaqueTunnelRefusal2,
340
340
  isOpaqueConnectReason2
341
- } from "./chunk-zy21drtv.js";
341
+ } from "./chunk-vz38kngm.js";
342
342
  import {
343
343
  sliceBytes2,
344
344
  maxLineBytes2,
345
345
  linesPerTurn2,
346
346
  decodedOption2,
347
347
  decoded2,
348
- readOpencode2
349
- } from "./chunk-kx8rpa62.js";
348
+ lookAtOpencode2,
349
+ readOpencode2,
350
+ databaseStamp2
351
+ } from "./chunk-s34am3kw.js";
350
352
  import {
351
353
  uploadRunFile,
352
354
  programLease,
353
355
  rpcRunFiles,
354
356
  programHostsEnv,
355
357
  undeclaredHostsEnv
356
- } from "./chunk-njgay1ed.js";
357
- import"./chunk-qbrkeg49.js";
358
+ } from "./chunk-sgkgwzvb.js";
359
+ import"./chunk-mhx0tgm3.js";
358
360
  import {
359
361
  nextInt
360
- } from "./chunk-m1qp6swh.js";
361
- import"./chunk-pd3azxev.js";
362
- import"./chunk-5qrjf4xq.js";
362
+ } from "./chunk-5kqt4bqp.js";
363
+ import"./chunk-tsx0347c.js";
364
+ import {
365
+ ChildProcessSpawner,
366
+ make3
367
+ } from "./chunk-9nbqzdqp.js";
368
+ import"./chunk-np5n54ky.js";
363
369
  import {
364
370
  Id,
365
371
  secretReference,
366
372
  secretPlaceholder
367
- } from "./chunk-r2kzvdrg.js";
373
+ } from "./chunk-4qjfn1sa.js";
368
374
 
369
375
  // packages/core/src/sync-kit.ts
370
376
  import { createHash } from "crypto";
@@ -3901,6 +3907,13 @@ var transcriptSource = (adapter, place) => gen(function* () {
3901
3907
  const store = place.configDir !== undefined && sandboxed !== undefined && (yield* fs.exists(`${place.configDir}/${sandboxed}`)) ? { database: `${place.configDir}/${sandboxed}`, confinedTo: place.configDir } : place.confinedTo === undefined ? { database: `${place.home}/${adapter.sessionDatabase}` } : undefined;
3902
3908
  if (store === undefined || !(yield* fs.exists(store.database)))
3903
3909
  return;
3910
+ if (store.confinedTo !== undefined)
3911
+ return {
3912
+ kind: "opencode_database",
3913
+ ...store,
3914
+ worktree: place.worktree,
3915
+ startedAt: place.startedAt ?? 0
3916
+ };
3904
3917
  const session = yield* readOpencode2(store, "newestSession", {
3905
3918
  worktree: place.worktree,
3906
3919
  startedAt: place.startedAt ?? 0
@@ -3966,6 +3979,294 @@ var stepSecretRegistry = (directory, initial, references) => gen(function* () {
3966
3979
  };
3967
3980
  });
3968
3981
 
3982
+ // packages/agent-runtime/src/step-containers.ts
3983
+ import * as net from "net";
3984
+ var stepAttemptDockerLabel = (attemptId) => `kitman.step-attempt.${attemptId}`;
3985
+ var stepRunnerDockerLabel = (runnerId) => `kitman.step-runner.${runnerId}`;
3986
+ var handedOnDockerLabel = "kitman.handed-on";
3987
+ var createPath = /^\/(?:v[\d.]+\/)?(?:containers|networks|volumes)\/create(?:\?|$)/;
3988
+ var attachPath = /^\/(?:v[\d.]+\/)?containers\/[^/]+\/attach(?:\?|$)/;
3989
+ var execStartPath = /^\/(?:v[\d.]+\/)?exec\/[^/]+\/start(?:\?|$)/;
3990
+ var crlf = Buffer.from(`\r
3991
+ `);
3992
+ var headEnd = Buffer.from(`\r
3993
+ \r
3994
+ `);
3995
+ var maxHead = 1024 * 1024;
3996
+ var parseHead = (head) => {
3997
+ const [requestLine = "", ...lines] = head.split(`\r
3998
+ `);
3999
+ const [method = "", path = ""] = requestLine.split(" ");
4000
+ return { method, path, lines: [requestLine, ...lines] };
4001
+ };
4002
+ var header = (head, name) => head.lines.slice(1).flatMap((line) => {
4003
+ const at = line.indexOf(":");
4004
+ return at > 0 && line.slice(0, at).trim().toLowerCase() === name ? [line.slice(at + 1).trim()] : [];
4005
+ }).at(0);
4006
+ var decodeChunked = (data) => {
4007
+ const parts = [];
4008
+ let at = 0;
4009
+ for (;; ) {
4010
+ const lineEnd = data.indexOf(crlf, at);
4011
+ if (lineEnd < 0)
4012
+ return;
4013
+ const size = Number.parseInt(data.subarray(at, lineEnd).toString().split(";")[0] ?? "", 16);
4014
+ at = lineEnd + 2;
4015
+ if (size === 0 || Number.isNaN(size))
4016
+ break;
4017
+ if (data.length < at + size + 2)
4018
+ return;
4019
+ parts.push(data.subarray(at, at + size));
4020
+ at += size + 2;
4021
+ }
4022
+ for (;; ) {
4023
+ const lineEnd = data.indexOf(crlf, at);
4024
+ if (lineEnd < 0)
4025
+ return;
4026
+ const empty = lineEnd === at;
4027
+ at = lineEnd + 2;
4028
+ if (empty)
4029
+ break;
4030
+ }
4031
+ return { body: Buffer.concat(parts), consumed: at };
4032
+ };
4033
+ var CreateBody = fromJsonString(Record(String4, Unknown));
4034
+ var detached = (body) => match(decodeOption(CreateBody)(body.toString()), {
4035
+ onNone: () => false,
4036
+ onSome: (parsed) => parsed["Detach"] === true
4037
+ });
4038
+ var Labels = Record(String4, Unknown);
4039
+ var labelled = (body, labels) => {
4040
+ const parsed = decodeOption(CreateBody)(body.toString());
4041
+ if (isNone(parsed))
4042
+ return body;
4043
+ const current = getOrElse(decodeUnknownOption(Labels)(parsed.value["Labels"]), () => ({}));
4044
+ if (handedOnDockerLabel in current)
4045
+ return body;
4046
+ return Buffer.from(JSON.stringify({ ...parsed.value, Labels: { ...current, ...labels } }));
4047
+ };
4048
+ var labelDockerRequests = (labels, answer = () => {
4049
+ return;
4050
+ }) => {
4051
+ let pending = Buffer.alloc(0);
4052
+ let state = { kind: "head" };
4053
+ const take = (count) => {
4054
+ const taken = pending.subarray(0, count);
4055
+ pending = pending.subarray(count);
4056
+ return taken;
4057
+ };
4058
+ const step = (out) => {
4059
+ switch (state.kind) {
4060
+ case "raw": {
4061
+ if (pending.length === 0)
4062
+ return false;
4063
+ out.push(take(pending.length));
4064
+ return true;
4065
+ }
4066
+ case "head": {
4067
+ const end = pending.indexOf(headEnd);
4068
+ if (end < 0) {
4069
+ if (pending.length > maxHead)
4070
+ state = { kind: "raw" };
4071
+ return pending.length > maxHead;
4072
+ }
4073
+ const raw = take(end + 4);
4074
+ const head = parseHead(raw.subarray(0, end).toString("latin1"));
4075
+ const chunked = /chunked/i.test(header(head, "transfer-encoding") ?? "");
4076
+ const length = Number(header(head, "content-length") ?? 0);
4077
+ const held = head.method === "POST" && createPath.test(head.path) ? "create" : head.method === "POST" && execStartPath.test(head.path) ? "exec" : undefined;
4078
+ if (header(head, "upgrade") !== undefined || attachPath.test(head.path)) {
4079
+ out.push(raw);
4080
+ state = { kind: "raw" };
4081
+ } else if (held !== undefined) {
4082
+ const continues = /100-continue/i.test(header(head, "expect") ?? "");
4083
+ if (continues)
4084
+ answer(Buffer.from(`HTTP/1.1 100 Continue\r
4085
+ \r
4086
+ `, "latin1"));
4087
+ state = {
4088
+ kind: held,
4089
+ head: continues ? { ...head, lines: head.lines.filter((line) => !/^expect\s*:/i.test(line)) } : head,
4090
+ length: chunked ? "chunked" : length
4091
+ };
4092
+ } else {
4093
+ out.push(raw);
4094
+ state = chunked ? { kind: "chunk-size" } : length > 0 ? { kind: "fixed", remaining: length } : { kind: "head" };
4095
+ }
4096
+ return true;
4097
+ }
4098
+ case "fixed":
4099
+ case "chunk-data": {
4100
+ if (pending.length === 0)
4101
+ return false;
4102
+ const taken = take(Math.min(state.remaining, pending.length));
4103
+ out.push(taken);
4104
+ state.remaining -= taken.length;
4105
+ if (state.remaining === 0)
4106
+ state = state.kind === "fixed" ? { kind: "head" } : { kind: "chunk-size" };
4107
+ return true;
4108
+ }
4109
+ case "chunk-size":
4110
+ case "trailer": {
4111
+ const end = pending.indexOf(crlf);
4112
+ if (end < 0)
4113
+ return false;
4114
+ const line = take(end + 2);
4115
+ out.push(line);
4116
+ if (state.kind === "trailer") {
4117
+ if (end === 0)
4118
+ state = { kind: "head" };
4119
+ } else {
4120
+ const size = Number.parseInt(line.toString("latin1").split(";")[0] ?? "", 16);
4121
+ state = size > 0 ? { kind: "chunk-data", remaining: size + 2 } : { kind: "trailer" };
4122
+ }
4123
+ return true;
4124
+ }
4125
+ case "create":
4126
+ case "exec": {
4127
+ const { kind, head, length } = state;
4128
+ const decoded = length === "chunked" ? decodeChunked(pending) : pending.length >= length ? { body: pending.subarray(0, length), consumed: length } : undefined;
4129
+ if (decoded === undefined)
4130
+ return false;
4131
+ take(decoded.consumed);
4132
+ const body = kind === "create" ? labelled(decoded.body, labels) : decoded.body;
4133
+ const lines = head.lines.filter((line, index) => index === 0 || !/^(content-length|transfer-encoding)\s*:/i.test(line));
4134
+ out.push(Buffer.from([...lines, `Content-Length: ${body.length}`, "", ""].join(`\r
4135
+ `), "latin1"), body);
4136
+ state = kind === "exec" && !detached(body) ? { kind: "raw" } : { kind: "head" };
4137
+ return true;
4138
+ }
4139
+ }
4140
+ };
4141
+ return {
4142
+ push: (chunk) => {
4143
+ pending = Buffer.concat([pending, chunk]);
4144
+ const out = [];
4145
+ while (step(out))
4146
+ ;
4147
+ return out;
4148
+ }
4149
+ };
4150
+ };
4151
+ var serveStepDocker = (input) => acquireRelease(callback3((resume) => {
4152
+ const open = new Set;
4153
+ const server = net.createServer({ allowHalfOpen: true }, (client) => {
4154
+ const upstream = net.connect({ path: input.upstream, allowHalfOpen: true });
4155
+ const labeller = labelDockerRequests(input.labels, (reply) => client.write(reply));
4156
+ for (const connection of [client, upstream]) {
4157
+ open.add(connection);
4158
+ connection.on("close", () => open.delete(connection));
4159
+ }
4160
+ client.on("data", (data) => {
4161
+ const writes = labeller.push(Buffer.from(data)).map((chunk) => upstream.write(chunk));
4162
+ if (writes.includes(false))
4163
+ client.pause();
4164
+ });
4165
+ upstream.on("drain", () => client.resume());
4166
+ client.on("end", () => upstream.end());
4167
+ upstream.pipe(client);
4168
+ client.on("error", () => upstream.destroy());
4169
+ upstream.on("error", () => client.destroy());
4170
+ });
4171
+ server.once("error", (error) => resume(fail7(error)));
4172
+ server.listen(input.socket, () => resume(succeed6({ server, open })));
4173
+ }), ({ server, open }) => callback3((resume) => {
4174
+ server.close(() => resume(void_3));
4175
+ open.forEach((connection) => connection.destroy());
4176
+ })).pipe(as(input.socket));
4177
+ var unixPath = (host) => host.startsWith("unix://") ? host.slice("unix://".length) : undefined;
4178
+ var dockerSocket = (spawner) => gen(function* () {
4179
+ const configured = yield* String2("DOCKER_HOST").pipe(withDefault(""), orElseSucceed(() => ""));
4180
+ if (configured !== "")
4181
+ return unixPath(configured);
4182
+ const host = yield* runCommand2("docker", ["context", "inspect", "--format", "{{.Endpoints.docker.Host}}"], {
4183
+ timeout: "10 seconds"
4184
+ }).pipe(provideService(ChildProcessSpawner, spawner), option2);
4185
+ return getOrUndefined(flatMap(host, (value) => fromUndefinedOr(unixPath(value.trim()))));
4186
+ });
4187
+ var dockerStepContainers = gen(function* () {
4188
+ const fs = yield* FileSystem;
4189
+ const spawner = yield* ChildProcessSpawner;
4190
+ const upstream = yield* dockerSocket(spawner);
4191
+ if (upstream === undefined)
4192
+ return;
4193
+ const docker = (args) => runCommand2("docker", args, { timeout: "2 minutes" }).pipe(provideService(ChildProcessSpawner, spawner));
4194
+ const ids = (listing) => listing.split(`
4195
+ `).map((line) => line.trim()).filter((line) => line !== "");
4196
+ const removeAll = (kind, label) => gen(function* () {
4197
+ const found = ids(yield* docker([kind, "ls", "--all", "--quiet", "--filter", `label=${label}`].filter((arg) => kind === "container" || arg !== "--all")));
4198
+ if (found.length === 0)
4199
+ return true;
4200
+ yield* docker(kind === "container" ? ["container", "rm", "--force", "--volumes", ...found] : [kind, "rm", ...found]);
4201
+ yield* logInfo("step_docker_removed", { of: label, kind, count: found.length });
4202
+ return true;
4203
+ }).pipe(catch_((error) => as(logWarning("step_docker_unremoved", { of: label, kind, error: error.message }), false)));
4204
+ return {
4205
+ environment: (runnerId, attemptId) => gen(function* () {
4206
+ const dir = yield* tempDirectoryScoped(fs, { prefix: "kitman-docker-" });
4207
+ const socket = yield* serveStepDocker({
4208
+ upstream,
4209
+ socket: `${dir}/docker.sock`,
4210
+ labels: { [stepAttemptDockerLabel(attemptId)]: "", [stepRunnerDockerLabel(runnerId)]: "" }
4211
+ });
4212
+ return { DOCKER_HOST: `unix://${socket}` };
4213
+ }).pipe(catch_((error) => as(logWarning("step_docker_unlabelled", { attempt: attemptId, error: String(error) }), {}))),
4214
+ remove: (label) => map9(all3([removeAll("container", label), removeAll("network", label), removeAll("volume", label)], {
4215
+ concurrency: 1
4216
+ }), (removed) => removed.every(Boolean))
4217
+ };
4218
+ });
4219
+ var dockerRootDirectory = runCommand2("docker", ["info", "--format", "{{.DockerRootDir}}"], {
4220
+ timeout: "10 seconds"
4221
+ }).pipe(map9((directory) => directory.trim() || undefined), orElseSucceed(() => {
4222
+ return;
4223
+ }));
4224
+ var gib = 1024 ** 3;
4225
+ var shown = (bytes) => `${(bytes / gib).toFixed(1)} GiB`;
4226
+ var diskSpaceProblem = (disks) => {
4227
+ const full = disks.filter((disk) => disk.available < Math.min(10 * gib, disk.size / 10));
4228
+ if (full.length === 0)
4229
+ return;
4230
+ const message = `The disk is nearly full, so checks and Steps may fail on it: ${full.map((disk) => `${shown(disk.available)} free of ${shown(disk.size)} where ${disk.paths.join(", ")} ${disk.paths.length === 1 ? "is" : "are"}`).join("; ")}.`;
4231
+ return {
4232
+ code: "disk_nearly_full",
4233
+ message: message.length <= 500 ? message : `${message.slice(0, 499)}\u2026`,
4234
+ fix: "Free space on the Runner's host, such as with `docker container prune`, `docker volume prune` and `docker image prune` for what nothing uses, or give it a larger disk."
4235
+ };
4236
+ };
4237
+ var diskSpaceFromDf = (listing, paths) => {
4238
+ const disks = new Map;
4239
+ listing.split(`
4240
+ `).slice(1).filter((line) => line.trim() !== "").forEach((line, index) => {
4241
+ const [, size, available, mountPoint] = /^.*?\s+(\d+)\s+\d+\s+(\d+)\s+\d+%\s+(.*)$/.exec(line.trim()) ?? [];
4242
+ const path = paths[index];
4243
+ if (path === undefined || size === undefined || available === undefined || mountPoint === undefined)
4244
+ return;
4245
+ const disk = disks.get(mountPoint);
4246
+ if (disk === undefined)
4247
+ disks.set(mountPoint, { paths: [path], available: Number(available) * 1024, size: Number(size) * 1024 });
4248
+ else
4249
+ disk.paths.push(path);
4250
+ });
4251
+ return [...disks.values()];
4252
+ };
4253
+ var diskSpaceMeter = gen(function* () {
4254
+ const fs = yield* FileSystem;
4255
+ const spawner = yield* ChildProcessSpawner;
4256
+ const measure = (path) => gen(function* () {
4257
+ if (!(yield* fs.exists(path)))
4258
+ return [];
4259
+ const listing = yield* runCommand2("df", ["-P", "-k", "--", path], { timeout: "10 seconds" }).pipe(provideService(ChildProcessSpawner, spawner));
4260
+ return listing.split(`
4261
+ `).filter((line) => line.trim() !== "").slice(1, 2).map((line) => ({ path, line }));
4262
+ }).pipe(orElseSucceed(() => []));
4263
+ return (paths) => map9(forEach(paths, measure, { concurrency: "unbounded" }), (measured) => {
4264
+ const found = measured.flat();
4265
+ return diskSpaceFromDf(["", ...found.map(({ line }) => line)].join(`
4266
+ `), found.map(({ path }) => path));
4267
+ });
4268
+ });
4269
+
3969
4270
  // packages/agent-runtime/src/step-processes.ts
3970
4271
  var stepAttemptVariable = "KITMAN_STEP_ATTEMPT";
3971
4272
  var stepRunnerVariable = "KITMAN_STEP_RUNNER";
@@ -4082,7 +4383,10 @@ var systemdScopes = gen(function* () {
4082
4383
  var reapRounds = 3;
4083
4384
  var problemText = (text) => text.length <= 500 ? text : `${text.slice(0, 499)}\u2026`;
4084
4385
  var makeStepProcesses = (table, options = {}) => {
4085
- const { scopes } = options;
4386
+ const { scopes, containers } = options;
4387
+ const unremoved = new Set;
4388
+ let removingAgain = false;
4389
+ const labelling = new Set;
4086
4390
  const unreaped = new Map;
4087
4391
  const pollMs = options.pollMs ?? 50;
4088
4392
  const finding = (marker, scoped) => map9(all3([table.marked(marker), scoped]), ([marked, inScopes]) => {
@@ -4130,7 +4434,20 @@ var makeStepProcesses = (table, options = {}) => {
4130
4434
  }
4131
4435
  return left;
4132
4436
  });
4437
+ const removeLabelled = (label) => containers === undefined ? void_3 : map9(containers.remove(label), (removed) => {
4438
+ if (removed)
4439
+ unremoved.delete(label);
4440
+ else
4441
+ unremoved.add(label);
4442
+ });
4443
+ const removeAgain = suspend3(() => {
4444
+ if (removingAgain || unremoved.size === 0)
4445
+ return void_3;
4446
+ removingAgain = true;
4447
+ return forEach([...unremoved], removeLabelled, { discard: true }).pipe(ensuring2(sync2(() => removingAgain = false)), forkDetach, asVoid);
4448
+ });
4133
4449
  const problems = gen(function* () {
4450
+ yield* removeAgain;
4134
4451
  for (const [key, entry] of unreaped) {
4135
4452
  entry.left = yield* running(yield* entry.find);
4136
4453
  if (entry.left.length === 0)
@@ -4155,8 +4472,12 @@ var makeStepProcesses = (table, options = {}) => {
4155
4472
  return {
4156
4473
  scoped: scopes !== undefined,
4157
4474
  contain: (runnerId, attemptId, argv) => scopes === undefined ? succeed6(argv) : scopes.contain(runnerId, attemptId, argv),
4158
- reapAttempt: (runnerId, attemptId) => reap(`attempt ${attemptId}`, finding({ name: stepAttemptVariable, value: attemptId }, scopes === undefined ? none : scopes.processes(runnerId, attemptId))),
4159
- reapRunner: (runnerId) => reap(`runner ${runnerId}`, finding({ name: stepRunnerVariable, value: runnerId }, scopes === undefined ? none : scopes.processes(runnerId))),
4475
+ dockerEnvironment: (runnerId, attemptId) => containers === undefined ? succeed6({}) : tap2(containers.environment(runnerId, attemptId), (environment) => sync2(() => {
4476
+ if (Object.keys(environment).length > 0)
4477
+ labelling.add(attemptId);
4478
+ })),
4479
+ reapAttempt: (runnerId, attemptId) => reap(`attempt ${attemptId}`, finding({ name: stepAttemptVariable, value: attemptId }, scopes === undefined ? none : scopes.processes(runnerId, attemptId))).pipe(tap2(() => labelling.delete(attemptId) ? removeLabelled(stepAttemptDockerLabel(attemptId)) : void_3)),
4480
+ reapRunner: (runnerId) => reap(`runner ${runnerId}`, finding({ name: stepRunnerVariable, value: runnerId }, scopes === undefined ? none : scopes.processes(runnerId))).pipe(tap2(() => removeLabelled(stepRunnerDockerLabel(runnerId)))),
4160
4481
  problems
4161
4482
  };
4162
4483
  };
@@ -4176,7 +4497,7 @@ class StepProcesses extends Service2()("StepProcesses") {
4176
4497
  var stepProcessesLayer = effect(StepProcesses, map9(systemProcessTable, (table) => makeStepProcesses(table)));
4177
4498
  var systemStepProcessesLayer = effect(StepProcesses, gen(function* () {
4178
4499
  const table = yield* systemProcessTable;
4179
- return makeStepProcesses(table, { scopes: yield* systemdScopes });
4500
+ return makeStepProcesses(table, { scopes: yield* systemdScopes, containers: yield* dockerStepContainers });
4180
4501
  }));
4181
4502
 
4182
4503
  // packages/agent-runtime/src/thread-budget.ts
@@ -4527,6 +4848,7 @@ var runAttempt = (request, options) => gen(function* () {
4527
4848
  const env = {
4528
4849
  ...yield* inheritedEnvironment2(["SSH_AUTH_SOCK"]),
4529
4850
  ...policy.environment,
4851
+ ...yield* options.stepProcesses.dockerEnvironment(request.runnerId, attempt.id),
4530
4852
  ...attemptEnvironment
4531
4853
  };
4532
4854
  return { argv: harnessArgv, env, registry: undefined };
@@ -5772,6 +6094,7 @@ var batchSize = 100;
5772
6094
  var maxEventsPerLine = 1024;
5773
6095
  var maxBatchChars = 2 * 1024 * 1024;
5774
6096
  var maxUnsentChars = 16 * 1024 * 1024;
6097
+ var maxFailedLooks = 3;
5775
6098
  var maxFailingMillis = 30000;
5776
6099
  var firstResendMillis = 1000;
5777
6100
  var longestResendMillis = 30000;
@@ -6318,6 +6641,7 @@ var opencodeV2Part = (part) => {
6318
6641
  }
6319
6642
  };
6320
6643
  };
6644
+ var sandboxed = (source) => source.kind !== "file" && source.confinedTo !== undefined;
6321
6645
  var transcriptRelay = (input) => {
6322
6646
  const normalize = sessionNormalizer(input.harness);
6323
6647
  const tokens = tokenCounter(input.harness);
@@ -6345,6 +6669,12 @@ var transcriptRelay = (input) => {
6345
6669
  let refusal;
6346
6670
  let harnessError;
6347
6671
  let codexLimits;
6672
+ let lookedAt;
6673
+ let stampSeen;
6674
+ let failedAt;
6675
+ let failedLooks = 0;
6676
+ let lookedAtExtent;
6677
+ let found;
6348
6678
  let errorReadAt;
6349
6679
  let opencodeModel;
6350
6680
  const namedModel = (named) => {
@@ -6561,6 +6891,76 @@ var transcriptRelay = (input) => {
6561
6891
  openMessage.clear();
6562
6892
  closedTo = seq;
6563
6893
  }).pipe(uninterruptible);
6894
+ const sawFrame = (frame) => gen(function* () {
6895
+ switch (frame.kind) {
6896
+ case "found":
6897
+ found = frame.session ?? undefined;
6898
+ return true;
6899
+ case "extent":
6900
+ lookedAtExtent = frame.extent;
6901
+ yield* sawSession(frame.extent);
6902
+ return true;
6903
+ case "error":
6904
+ heard(opencodeProviderRefusal(frame.error));
6905
+ return true;
6906
+ case "model":
6907
+ namedModel(frame.model);
6908
+ errorReadAt = lookedAtExtent;
6909
+ return true;
6910
+ case "unsaid":
6911
+ yield* logWarning("runner_transcript_unread", frame.reason);
6912
+ return true;
6913
+ case "messages":
6914
+ for (const message of frame.messages)
6915
+ yield* sawMessage(message);
6916
+ break;
6917
+ case "open":
6918
+ for (const part of frame.parts)
6919
+ yield* uninterruptible(sawPart(part));
6920
+ break;
6921
+ case "past":
6922
+ for (const part of frame.parts)
6923
+ yield* sawPart(part).pipe(andThen2(sync2(() => {
6924
+ recordedTo = part.position;
6925
+ })), uninterruptible);
6926
+ }
6927
+ yield* flush;
6928
+ yield* yieldNow;
6929
+ return !backedUp();
6930
+ });
6931
+ const lookAt = (source) => gen(function* () {
6932
+ const { stamp, settled } = yield* databaseStamp2(source.database);
6933
+ const changed = stamp !== stampSeen;
6934
+ stampSeen = stamp;
6935
+ if (backedUp())
6936
+ yield* flush;
6937
+ if (backedUp()) {
6938
+ if (changed)
6939
+ progressAt = yield* currentTimeMillis;
6940
+ return;
6941
+ }
6942
+ if (settled && stamp === lookedAt)
6943
+ return;
6944
+ const sessionId = source.kind === "opencode_database" ? found?.id : source.sessionId;
6945
+ const whole = yield* lookAtOpencode2({
6946
+ database: source.database,
6947
+ confinedTo: source.confinedTo,
6948
+ ...sessionId === undefined ? undefined : { sessionId }
6949
+ }, {
6950
+ ...source.kind !== "opencode_database" ? { kind: source.kind } : found === undefined ? { find: { worktree: source.worktree, startedAt: source.startedAt } } : { kind: found.kind },
6951
+ closedTo,
6952
+ saidAt: errorReadAt ?? null,
6953
+ open: [...stages.keys()],
6954
+ recordedTo
6955
+ }, sawFrame).pipe(tapError2(() => sync2(() => {
6956
+ failedLooks = failedAt === stamp ? failedLooks + 1 : 1;
6957
+ failedAt = stamp;
6958
+ if (failedLooks >= maxFailedLooks)
6959
+ lookedAt = stamp;
6960
+ })));
6961
+ if (whole && settled)
6962
+ lookedAt = stamp;
6963
+ });
6564
6964
  const takeMessages = (source) => gen(function* () {
6565
6965
  const start = closedTo;
6566
6966
  for (const message of yield* readOpencode2(source, "messagesPast", { seq: closedTo }))
@@ -6585,6 +6985,8 @@ var transcriptRelay = (input) => {
6585
6985
  return tokensSpent([own, ...spent]) ?? "none";
6586
6986
  }),
6587
6987
  read: (source) => gen(function* () {
6988
+ if (sandboxed(source))
6989
+ return yield* lookAt(source);
6588
6990
  if (source.kind === "opencode_v2") {
6589
6991
  const extent = yield* readOpencode2(source, "extent", {});
6590
6992
  yield* sawSession(extent);
@@ -7679,7 +8081,7 @@ var harnessesInSrt = (input) => gen(function* () {
7679
8081
  };
7680
8082
  });
7681
8083
  // packages/agent-runtime/src/loopback-tunnel.ts
7682
- import * as net from "net";
8084
+ import * as net2 from "net";
7683
8085
  class LoopbackTunnelUnavailable extends TaggedError("LoopbackTunnelUnavailable") {
7684
8086
  }
7685
8087
  var srtLoopbackTunnel = (tunnel) => [
@@ -7718,8 +8120,8 @@ var loopbackSocketForwarder = (hostPort, socket) => gen(function* () {
7718
8120
  const dir = yield* flatMap3(tempDirectoryScoped(fs, { prefix: "kitman-lo-" }), fs.realPath).pipe(mapError2((error) => new LoopbackTunnelUnavailable({ reason: error.message })));
7719
8121
  yield* acquireRelease(callback3((resume) => {
7720
8122
  const open = new Set;
7721
- const server = net.createServer({ allowHalfOpen: true }, (client) => {
7722
- const upstream = net.connect({ port: hostPort, host: "127.0.0.1", allowHalfOpen: true });
8123
+ const server = net2.createServer({ allowHalfOpen: true }, (client) => {
8124
+ const upstream = net2.connect({ port: hostPort, host: "127.0.0.1", allowHalfOpen: true });
7723
8125
  for (const connection of [client, upstream]) {
7724
8126
  open.add(connection);
7725
8127
  connection.on("close", () => open.delete(connection));
@@ -8075,7 +8477,7 @@ var codexAppServer = (binary = "codex") => (env) => gen(function* () {
8075
8477
  const input = yield* unbounded2();
8076
8478
  const pending = new Map;
8077
8479
  let lastId = 0;
8078
- const handle = yield* spawner.spawn(make2(binary, ["app-server"], {
8480
+ const handle = yield* spawner.spawn(make3(binary, ["app-server"], {
8079
8481
  cwd: env.home,
8080
8482
  extendEnv: true,
8081
8483
  env: { HOME: env.home, CODEX_HOME: env.codexHome },
@@ -8098,7 +8500,7 @@ var codexAppServer = (binary = "codex") => (env) => gen(function* () {
8098
8500
  return {
8099
8501
  request: (method, params) => gen(function* () {
8100
8502
  const id = ++lastId;
8101
- const deferred = yield* make15();
8503
+ const deferred = yield* make16();
8102
8504
  pending.set(id, deferred);
8103
8505
  yield* send({ id, method, params });
8104
8506
  return yield* _await(deferred).pipe(mapError2((error) => new CodexAppServerFailed({ reason: `${method}: ${error.message}` })));
@@ -8238,10 +8640,10 @@ var handshake = [
8238
8640
  `).join("");
8239
8641
  var kitmanMcpPreflight = (mcp) => gen(function* () {
8240
8642
  const spawner = yield* ChildProcessSpawner;
8241
- const server = yield* spawner.spawn(make2(mcp.command, [...mcp.args], {
8643
+ const server = yield* spawner.spawn(make3(mcp.command, [...mcp.args], {
8242
8644
  extendEnv: true,
8243
8645
  env: mcp.env,
8244
- stdin: { stream: make10(new TextEncoder().encode(handshake)), endOnDone: false },
8646
+ stdin: { stream: make11(new TextEncoder().encode(handshake)), endOnDone: false },
8245
8647
  stderr: "ignore"
8246
8648
  }));
8247
8649
  const reply = yield* server.stdout.pipe(decodeText, splitLines, map2((line) => getOrUndefined(decodeJsonStringOption(line))), filter((message) => isJsonObject(message) && message.id === 2), runHead);
@@ -8314,8 +8716,8 @@ var programProcessExecutor = (input) => (work) => gen(function* () {
8314
8716
  };
8315
8717
  const exitCode = sandbox === undefined ? yield* gen(function* () {
8316
8718
  const spawner = yield* ChildProcessSpawner;
8317
- const handle = yield* spawner.spawn(make2(input.bun ?? process.execPath, [file], {
8318
- stdin: make10(new TextEncoder().encode(stdin)),
8719
+ const handle = yield* spawner.spawn(make3(input.bun ?? process.execPath, [file], {
8720
+ stdin: make11(new TextEncoder().encode(stdin)),
8319
8721
  stdout: "inherit",
8320
8722
  stderr: "inherit",
8321
8723
  extendEnv: false,
@@ -8597,7 +8999,7 @@ var readCommitHistory = (checkout, spec, commitMax = compareCommitMax) => gen(fu
8597
8999
 
8598
9000
  // packages/agent-runtime/src/half-close-relay.ts
8599
9001
  import { once } from "events";
8600
- import { connect as connect2, createServer as createServer2 } from "net";
9002
+ import { connect as connect3, createServer as createServer3 } from "net";
8601
9003
  var frameHeader = 4;
8602
9004
  var endOfInput = Buffer.alloc(frameHeader);
8603
9005
  var maxFrame = 1024 * 1024;
@@ -8612,8 +9014,8 @@ var closeTogether = (...sockets) => sockets.forEach((socket) => {
8612
9014
  socket.on("close", () => sockets.forEach((other) => other.end()));
8613
9015
  });
8614
9016
  var listening = (server, port) => once(server.listen(port, "127.0.0.1"), "listening").then(() => server);
8615
- var startHalfCloseDecoder = (input) => listening(createServer2({ allowHalfOpen: true }, (client) => {
8616
- const upstream = connect2({ port: input.targetPort, host: "127.0.0.1", allowHalfOpen: true });
9017
+ var startHalfCloseDecoder = (input) => listening(createServer3({ allowHalfOpen: true }, (client) => {
9018
+ const upstream = connect3({ port: input.targetPort, host: "127.0.0.1", allowHalfOpen: true });
8617
9019
  let pending = Buffer.alloc(0);
8618
9020
  client.on("data", (chunk) => {
8619
9021
  pending = Buffer.concat([pending, chunk]);
@@ -9830,18 +10232,24 @@ export {
9830
10232
  controlFailureKind,
9831
10233
  defaultAgentRuntimeUserConfigPath,
9832
10234
  detectHarnesses2 as detectHarnesses,
10235
+ diskSpaceFromDf,
10236
+ diskSpaceMeter,
10237
+ diskSpaceProblem,
9833
10238
  dockerCheckDaemon,
9834
10239
  dockerCheckPostgres,
9835
10240
  dockerContainerRunner,
9836
10241
  dockerExecArgv,
9837
10242
  dockerHome,
9838
10243
  dockerMissing,
10244
+ dockerRootDirectory,
10245
+ dockerStepContainers,
9839
10246
  failed,
9840
10247
  failedWhenUnrun,
9841
10248
  firstMessage,
9842
10249
  gitCheckouts2 as gitCheckouts,
9843
10250
  gitRemote,
9844
10251
  halfCloseListener,
10252
+ handedOnDockerLabel,
9845
10253
  harnessAdapter,
9846
10254
  harnessConfigUnwritable,
9847
10255
  harnessNetworkHosts,
@@ -9867,6 +10275,7 @@ export {
9867
10275
  kitmanMcpPreflight,
9868
10276
  kitmanMcpToolTimeout,
9869
10277
  kitmanMcpToolTimeoutSeconds,
10278
+ labelDockerRequests,
9870
10279
  lacksLoginSecret,
9871
10280
  listBuiltInLaunchProfiles,
9872
10281
  listenForSignals,
@@ -9920,6 +10329,7 @@ export {
9920
10329
  runsOnHost,
9921
10330
  sampleMetrics,
9922
10331
  sandboxedLaunch,
10332
+ serveStepDocker,
9923
10333
  setDefaultAgentRuntimeProfile,
9924
10334
  sha256,
9925
10335
  shellOutputTailChars2 as shellOutputTailChars,
@@ -9932,11 +10342,13 @@ export {
9932
10342
  srtSettings2 as srtSettings,
9933
10343
  srtStepArgv2 as srtStepArgv,
9934
10344
  startDockerSandbox,
10345
+ stepAttemptDockerLabel,
9935
10346
  stepAttemptVariable,
9936
10347
  stepKitSetup,
9937
10348
  stepProcessEnvironment,
9938
10349
  stepProcessesLayer,
9939
10350
  stepProcessesUncontained,
10351
+ stepRunnerDockerLabel,
9940
10352
  stepRunnerVariable,
9941
10353
  stepSandboxPolicy,
9942
10354
  superviseReplica,