@aspectlylabs/mikka 0.0.648 → 0.0.651

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.
package/mikka.js CHANGED
@@ -879,10 +879,10 @@ var require_truncate = __commonJS({
879
879
  "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/truncate.js"(exports, module) {
880
880
  "use strict";
881
881
  var parse2 = require_parse();
882
- var constants9 = require_constants();
882
+ var constants10 = require_constants();
883
883
  var SemVer = require_semver();
884
884
  var truncate = (version, truncation, options) => {
885
- if (!constants9.RELEASE_TYPES.includes(truncation)) {
885
+ if (!constants10.RELEASE_TYPES.includes(truncation)) {
886
886
  return null;
887
887
  }
888
888
  const clonedVersion = cloneInputVersion(version, options);
@@ -1931,7 +1931,7 @@ var require_semver2 = __commonJS({
1931
1931
  "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/index.js"(exports, module) {
1932
1932
  "use strict";
1933
1933
  var internalRe = require_re();
1934
- var constants9 = require_constants();
1934
+ var constants10 = require_constants();
1935
1935
  var SemVer = require_semver();
1936
1936
  var identifiers = require_identifiers();
1937
1937
  var parse2 = require_parse();
@@ -2015,8 +2015,8 @@ var require_semver2 = __commonJS({
2015
2015
  re: internalRe.re,
2016
2016
  src: internalRe.src,
2017
2017
  tokens: internalRe.t,
2018
- SEMVER_SPEC_VERSION: constants9.SEMVER_SPEC_VERSION,
2019
- RELEASE_TYPES: constants9.RELEASE_TYPES,
2018
+ SEMVER_SPEC_VERSION: constants10.SEMVER_SPEC_VERSION,
2019
+ RELEASE_TYPES: constants10.RELEASE_TYPES,
2020
2020
  compareIdentifiers: identifiers.compareIdentifiers,
2021
2021
  rcompareIdentifiers: identifiers.rcompareIdentifiers
2022
2022
  };
@@ -2103,11 +2103,11 @@ function daemonProcessAlive(dataDir) {
2103
2103
  return pid !== null && processAlive(pid);
2104
2104
  }
2105
2105
  function socketAnswers(socketPath) {
2106
- return new Promise((resolve19) => {
2106
+ return new Promise((resolve20) => {
2107
2107
  const socket = createConnection(socketPath);
2108
2108
  const done = (alive) => {
2109
2109
  socket.destroy();
2110
- resolve19(alive);
2110
+ resolve20(alive);
2111
2111
  };
2112
2112
  socket.once("connect", () => done(true));
2113
2113
  socket.once("error", () => done(false));
@@ -2216,7 +2216,7 @@ function closeLogger(logger) {
2216
2216
  const file = files.get(logger);
2217
2217
  if (!file) return Promise.resolve();
2218
2218
  files.delete(logger);
2219
- return new Promise((resolve19) => file.end(resolve19));
2219
+ return new Promise((resolve20) => file.end(resolve20));
2220
2220
  }
2221
2221
 
2222
2222
  // src/auto-update.ts
@@ -2938,6 +2938,7 @@ var harnessInfoSchema = z7.object({
2938
2938
  computerBroker: z7.literal(true).optional(),
2939
2939
  /** Run-scoped CLI approvals and policy-version checks are supported. */
2940
2940
  toolApproval: z7.literal(true).optional(),
2941
+ activeTurnSteer: z7.literal(true).optional(),
2941
2942
  /**
2942
2943
  * The CLI exists but `installed` stays false because the daemon cannot run it
2943
2944
  * in a sandbox. `missing` names the absent packages; empty means the machine
@@ -3352,6 +3353,24 @@ function logCodedError(error, fields = {}, log = consoleCodedErrorLog) {
3352
3353
 
3353
3354
  // ../protocol/src/user-error-codes.ts
3354
3355
  var USER_ERROR_CODES = {
3356
+ review_auth_required: [],
3357
+ review_not_found: [],
3358
+ not_owner_terminal: [],
3359
+ review_machine_gone: [],
3360
+ review_binding_changed: [],
3361
+ review_checkout_unavailable: [],
3362
+ review_preview_unavailable: ["configuration", "runtime", "protocol", "scope_changed", "limit"],
3363
+ terminal_unsupported: ["local_device", "runtime_version"],
3364
+ terminal_already_controlled: [],
3365
+ terminal_binding_changed: [],
3366
+ terminal_ended: [],
3367
+ terminal_input_too_large: [],
3368
+ terminal_invalid_request: [],
3369
+ terminal_request_conflict: [],
3370
+ terminal_input_uncertain: [],
3371
+ terminal_limit: [],
3372
+ terminal_unavailable: ["configuration", "runtime", "protocol", "installation", "lease"],
3373
+ terminal_control_unavailable: ["fence_unavailable", "fence_lost"],
3355
3374
  review_scope_denied: ["sponsored_placement"],
3356
3375
  workspace_not_found: [],
3357
3376
  workspace_snapshot_unavailable: [],
@@ -3435,6 +3454,8 @@ var USER_ERROR_CODES = {
3435
3454
  web_auth_exchange_rejected: [],
3436
3455
  web_auth_session_expired: [],
3437
3456
  factory_spec_approval_required: [],
3457
+ factory_visual_evidence_required: [],
3458
+ factory_public_evidence_required: [],
3438
3459
  map_invalid_request: ["invalid_query", "invalid_token"],
3439
3460
  map_not_found: [],
3440
3461
  map_snapshot_changed: ["source_changed"],
@@ -4110,6 +4131,7 @@ var runSafePoint = z14.object({
4110
4131
  checkpoint: z14.enum(["ready", "unavailable"]),
4111
4132
  checkpointTakenAt: z14.iso.datetime({ offset: true }).optional()
4112
4133
  }).strict().refine((value) => value.checkpoint === "ready" ? value.checkpointTakenAt !== void 0 && Date.parse(value.observedAt) >= Date.parse(value.checkpointTakenAt) : value.checkpointTakenAt === void 0, { message: "A ready final checkpoint requires its acknowledged snapshot time" });
4134
+ var runVisualEvidence = z14.array(z14.object({ captureId: z14.uuid(), publicSafe: z14.literal(true) }).strict()).max(40);
4113
4135
  var runReport = z14.object({
4114
4136
  repositorySelection: runRepositorySelection.optional(),
4115
4137
  /** Worktree base journaled before the adapter started; never agent-supplied. */
@@ -4178,6 +4200,10 @@ var runReport = z14.object({
4178
4200
  previewDatabaseBranch: z14.string().trim().min(1).max(500).optional(),
4179
4201
  /** Acceptance criteria the agent checked, with evidence. */
4180
4202
  criteria: z14.array(runCriterion).max(200).optional(),
4203
+ /** Captures from this run whose full visible content was checked for public sharing.
4204
+ * This is an explicit content review, not an automatic pixel-redaction claim.
4205
+ * The server resolves capture ownership and creates the existing share URL. */
4206
+ visualEvidence: runVisualEvidence.optional(),
4181
4207
  /** A review completes once; this verdict never changes daemon-owned verification. */
4182
4208
  reviewVerdict: reviewVerdict.optional(),
4183
4209
  /**
@@ -5840,6 +5866,7 @@ var COMMANDS_MAX_SKIP = 100;
5840
5866
  var COMMANDS_DAEMON_LATEST_PARAM = "daemonLatest";
5841
5867
  var COMMANDS_SKIP_DEVICE_COMMANDS_PARAM = "skipDeviceCommands";
5842
5868
  var COMMANDS_MAX_SKIP_DEVICE_COMMANDS = 10;
5869
+ var ACTIVE_TURN_STEER_HEADER = "x-mikka-active-turn-steer";
5843
5870
  var MAILBOX_NOTICE_HEADER = "x-mikka-mailbox-notices";
5844
5871
  var runCommandSchema = z24.discriminatedUnion("kind", [
5845
5872
  z24.object({
@@ -5848,6 +5875,7 @@ var runCommandSchema = z24.discriminatedUnion("kind", [
5848
5875
  messageId: z24.uuid(),
5849
5876
  text: z24.string().min(1).max(1e5)
5850
5877
  }),
5878
+ z24.object({ kind: z24.literal("steer"), runId: id3, messageId: z24.uuid(), text: z24.string().min(1).max(1e5) }),
5851
5879
  z24.object({ kind: z24.literal("stop"), runId: id3 }),
5852
5880
  // A host notification carries addresses only; peer content remains behind
5853
5881
  // the authenticated mailbox read and retains its original provenance.
@@ -5869,7 +5897,8 @@ var runCommandsResponse = z24.object({
5869
5897
  deviceCommands: z24.array(deviceManagementCommand).max(1).optional().catch(void 0)
5870
5898
  });
5871
5899
  var runCommandsAck = z24.object({
5872
- delivered: z24.array(z24.uuid()).max(500)
5900
+ delivered: z24.array(z24.uuid()).max(500),
5901
+ refusedSteers: z24.array(z24.uuid()).max(500).optional()
5873
5902
  });
5874
5903
  var FS_REQUESTS_MAX_WAIT_SECONDS = 25;
5875
5904
  var FS_MAX_ENTRIES = 500;
@@ -6543,7 +6572,7 @@ import { join as join4 } from "node:path";
6543
6572
  // package.json
6544
6573
  var package_default = {
6545
6574
  name: "@mikka/daemon",
6546
- version: "0.0.648",
6575
+ version: "0.0.651",
6547
6576
  description: "Local Mikka daemon: runs agents through the user's own CLIs",
6548
6577
  type: "module",
6549
6578
  private: true,
@@ -6611,7 +6640,7 @@ var package_default = {
6611
6640
  engines: {
6612
6641
  node: ">=22"
6613
6642
  },
6614
- gitHead: "2e9c04daba44caec091c927f23b3cb825d9c4e23"
6643
+ gitHead: "1a57df9c1a1d8e475820afad14e3fa0e6429c60b"
6615
6644
  };
6616
6645
 
6617
6646
  // src/paths.ts
@@ -6787,7 +6816,7 @@ var ToolApprovalGate = class {
6787
6816
  /** Resolves on the next push or mode switch, or after the mode's cadence.
6788
6817
  * A paused run waits here instead of asking the server every second. */
6789
6818
  changed(signal) {
6790
- return new Promise((resolve19, reject) => {
6819
+ return new Promise((resolve20, reject) => {
6791
6820
  if (signal.aborted || this.revoked) {
6792
6821
  reject(new Error("cancelled"));
6793
6822
  return;
@@ -6798,7 +6827,7 @@ var ToolApprovalGate = class {
6798
6827
  this.changes.delete(wake);
6799
6828
  signal.removeEventListener("abort", abort);
6800
6829
  if (error) reject(error);
6801
- else resolve19();
6830
+ else resolve20();
6802
6831
  };
6803
6832
  const wake = () => done(this.revoked ? new Error("cancelled") : void 0);
6804
6833
  const abort = () => done(new Error("cancelled"));
@@ -6918,12 +6947,12 @@ import { createHash as createHash2, createPublicKey, verify } from "node:crypto"
6918
6947
  var policySnapshotHash = (policy) => createHash2("sha256").update(runPolicyDigestInput(policy)).digest("hex");
6919
6948
  function verifyPolicySnapshot(value, trusted, expected2, options = {}) {
6920
6949
  const context = policyDistributionContextSchema.parse(trusted);
6921
- const snapshot3 = signedPolicySnapshotSchema.parse(value), p = snapshot3.payload, now = options.now ?? Date.now();
6922
- if (policyIssuer(context.issuer) !== context.issuer || policyIssuer(p.issuer) !== context.issuer || p.ownerId !== context.ownerId || p.deviceId !== context.deviceId || p.runId !== context.runId || p.revision !== context.revision || p.policyHash !== policySnapshotHash(p.policy) || p.runId !== expected2.runId || p.deviceId !== expected2.deviceId || p.revision !== expected2.revision || snapshot3.keyId !== context.keyId || JSON.stringify(p.scope) !== JSON.stringify(context.scope) || expected2.policy && JSON.stringify(p.policy) !== JSON.stringify(runPolicySchema.parse(expected2.policy))) throw Error("policySnapshotBindingInvalid");
6950
+ const snapshot4 = signedPolicySnapshotSchema.parse(value), p = snapshot4.payload, now = options.now ?? Date.now();
6951
+ if (policyIssuer(context.issuer) !== context.issuer || policyIssuer(p.issuer) !== context.issuer || p.ownerId !== context.ownerId || p.deviceId !== context.deviceId || p.runId !== context.runId || p.revision !== context.revision || p.policyHash !== policySnapshotHash(p.policy) || p.runId !== expected2.runId || p.deviceId !== expected2.deviceId || p.revision !== expected2.revision || snapshot4.keyId !== context.keyId || JSON.stringify(p.scope) !== JSON.stringify(context.scope) || expected2.policy && JSON.stringify(p.policy) !== JSON.stringify(runPolicySchema.parse(expected2.policy))) throw Error("policySnapshotBindingInvalid");
6923
6952
  if (p.issuedAt > now + 3e4 || p.expiresAt <= p.issuedAt || p.expiresAt - p.issuedAt > POLICY_SNAPSHOT_TTL_MS || !options.allowExpired && p.expiresAt <= now) throw Error("policySnapshotExpired");
6924
6953
  const der = Buffer2.from(context.publicKey, "base64url");
6925
- if (createHash2("sha256").update(der).digest("hex") !== context.keyId || !verify(null, policySnapshotMessage(p), createPublicKey({ key: der, type: "spki", format: "der" }), Buffer2.from(snapshot3.signature, "base64url"))) throw Error("policySnapshotSignatureInvalid");
6926
- return snapshot3;
6954
+ if (createHash2("sha256").update(der).digest("hex") !== context.keyId || !verify(null, policySnapshotMessage(p), createPublicKey({ key: der, type: "spki", format: "der" }), Buffer2.from(snapshot4.signature, "base64url"))) throw Error("policySnapshotSignatureInvalid");
6955
+ return snapshot4;
6927
6956
  }
6928
6957
 
6929
6958
  // ../protocol/src/capture.ts
@@ -6942,6 +6971,7 @@ var CAPTURE_MAX_BYTES = {
6942
6971
  video: 1e8
6943
6972
  };
6944
6973
  var RECORDING_MAX_SECONDS = 300;
6974
+ var CAPTURE_MAX_DURATION_MS = 36e5;
6945
6975
  var CAPTURE_TITLE_MAX = 200;
6946
6976
  function captureKind(contentType) {
6947
6977
  return contentType.startsWith("video/") ? "video" : "image";
@@ -6972,14 +7002,31 @@ function cleanCaptureTitle(title2) {
6972
7002
  }
6973
7003
  var sha256 = z33.string().regex(/^[a-f0-9]{64}$/);
6974
7004
  var title = z33.string().trim().min(1).max(CAPTURE_TITLE_MAX);
7005
+ var recordingStep = z33.object({
7006
+ atMs: z33.number().int().min(0).max(CAPTURE_MAX_DURATION_MS),
7007
+ label: title,
7008
+ source: z33.enum(["action", "mark"]),
7009
+ durationMs: z33.number().int().min(0).max(CAPTURE_MAX_DURATION_MS).nullable().optional()
7010
+ }).strict().refine((step) => step.durationMs == null || step.source === "action" && step.durationMs <= step.atMs, {
7011
+ message: "An action duration must fit its recorded end offset."
7012
+ });
6975
7013
  var captureUploadRequest = z33.object({
6976
7014
  /** Stable client id, persisted before the first network attempt. */
6977
7015
  captureId: z33.uuid().optional(),
6978
7016
  title,
6979
7017
  contentType: z33.enum(CAPTURE_CONTENT_TYPES),
6980
7018
  size: z33.number().int().min(1).max(CAPTURE_MAX_BYTES.video),
6981
- sha256
6982
- }).strict();
7019
+ sha256,
7020
+ /** Final, processed video duration and its remapped timeline. */
7021
+ durationMs: z33.number().int().min(1).max(CAPTURE_MAX_DURATION_MS).optional(),
7022
+ steps: z33.array(recordingStep).max(200).optional()
7023
+ }).strict().superRefine((value, ctx) => {
7024
+ if (value.durationMs !== void 0 || value.steps !== void 0) {
7025
+ if (!value.contentType.startsWith("video/")) ctx.addIssue({ code: "custom", message: "Only videos carry a recording timeline." });
7026
+ if (value.steps?.some((step) => value.durationMs === void 0 || step.atMs > value.durationMs))
7027
+ ctx.addIssue({ code: "custom", message: "Recording steps must fit the final video duration." });
7028
+ }
7029
+ });
6983
7030
  var captureUploadTarget = z33.discriminatedUnion("target", [
6984
7031
  z33.object({ target: z33.literal("storage"), url: z33.url({ protocol: /^https$/ }), headers: z33.record(z33.string(), z33.string()) }),
6985
7032
  z33.object({ target: z33.literal("server") })
@@ -7004,7 +7051,12 @@ var screenCaptureRequest = z33.discriminatedUnion("action", [
7004
7051
  z33.object({ action: z33.literal("start_recording"), title, maxSeconds: z33.number().int().min(5).max(RECORDING_MAX_SECONDS).optional() }).strict(),
7005
7052
  z33.object({ action: z33.literal("stop_recording") }).strict(),
7006
7053
  // A step on the recording's timeline: an action's own description, or a moment the agent marks.
7007
- z33.object({ action: z33.literal("step"), label: title, source: z33.enum(["action", "mark"]) }).strict()
7054
+ z33.object({
7055
+ action: z33.literal("step"),
7056
+ label: title,
7057
+ source: z33.enum(["action", "mark"]),
7058
+ durationMs: z33.number().int().min(0).max(RECORDING_MAX_SECONDS * 1e3).optional()
7059
+ }).strict().refine((step) => step.durationMs === void 0 || step.source === "action", { message: "Only actions have a duration." })
7008
7060
  ]);
7009
7061
  var screenCaptureResponse = z33.discriminatedUnion("action", [
7010
7062
  z33.object({ action: z33.literal("screenshot"), capture: captureView }),
@@ -8092,8 +8144,8 @@ var DaemonTracer = class {
8092
8144
  let timer;
8093
8145
  await Promise.race([
8094
8146
  work,
8095
- new Promise((resolve19) => {
8096
- timer = setTimeout(resolve19, timeoutMs);
8147
+ new Promise((resolve20) => {
8148
+ timer = setTimeout(resolve20, timeoutMs);
8097
8149
  timer.unref();
8098
8150
  })
8099
8151
  ]).finally(() => {
@@ -8493,13 +8545,13 @@ var HttpServerLink = class {
8493
8545
  }
8494
8546
  if (!assignment.policy || !assignment.policyRevision) throw Error("Run policy unavailable");
8495
8547
  const expected2 = { runId: assignment.runId, deviceId: assignment.deviceId, revision: assignment.policyRevision, policy: assignment.policy };
8496
- let snapshot3 = verifyPolicySnapshot(assignment.policySnapshot, context, expected2, { allowExpired: true });
8497
- if (snapshot3.payload.expiresAt - Date.now() <= POLICY_SNAPSHOT_REFRESH_MS) {
8498
- const renewed = await this.call("POST", path3, { body: { deviceId: assignment.deviceId, snapshot: snapshot3 }, schema: signedPolicySnapshotSchema, signal, timeoutMs: 5e3 });
8499
- snapshot3 = verifyPolicySnapshot(renewed, context, expected2);
8500
- } else snapshot3 = verifyPolicySnapshot(snapshot3, context, expected2);
8501
- assignment.policySnapshot = snapshot3;
8502
- assignment.policy = snapshot3.payload.policy;
8548
+ let snapshot4 = verifyPolicySnapshot(assignment.policySnapshot, context, expected2, { allowExpired: true });
8549
+ if (snapshot4.payload.expiresAt - Date.now() <= POLICY_SNAPSHOT_REFRESH_MS) {
8550
+ const renewed = await this.call("POST", path3, { body: { deviceId: assignment.deviceId, snapshot: snapshot4 }, schema: signedPolicySnapshotSchema, signal, timeoutMs: 5e3 });
8551
+ snapshot4 = verifyPolicySnapshot(renewed, context, expected2);
8552
+ } else snapshot4 = verifyPolicySnapshot(snapshot4, context, expected2);
8553
+ assignment.policySnapshot = snapshot4;
8554
+ assignment.policy = snapshot4.payload.policy;
8503
8555
  Object.freeze(assignment.policy.permissions);
8504
8556
  Object.freeze(assignment.policy.networkAllow);
8505
8557
  if (assignment.policy.networkCeiling) Object.freeze(assignment.policy.networkCeiling);
@@ -8616,6 +8668,7 @@ var HttpServerLink = class {
8616
8668
  ...initialRepository ? { [INITIAL_REPOSITORY_HEADER]: "1" } : {},
8617
8669
  [SUBSCRIPTION_MODEL_CATALOGUE_HEADER]: "1",
8618
8670
  [MAILBOX_NOTICE_HEADER]: "1",
8671
+ [ACTIVE_TURN_STEER_HEADER]: "1",
8619
8672
  [WORKSPACE_REQUEST_HEADER]: "1",
8620
8673
  [WORKSPACE_DIFF_REQUEST_HEADER]: "1",
8621
8674
  [WORKSPACE_GIT_REQUEST_HEADER]: "1",
@@ -8749,14 +8802,14 @@ var HttpServerLink = class {
8749
8802
  }
8750
8803
  return { contentType, body: response.body };
8751
8804
  }
8752
- async beginCapture(runId, request2) {
8753
- return this.call("POST", capturePaths.begin(checkId(runId)), { body: request2, schema: captureUploadResponse });
8805
+ async beginCapture(runId, request2, signal) {
8806
+ return this.call("POST", capturePaths.begin(checkId(runId)), { body: request2, schema: captureUploadResponse, signal });
8754
8807
  }
8755
- async resumeCapture(runId, captureId) {
8756
- return this.call("POST", capturePaths.upload(checkId(runId), checkId(captureId)), { schema: captureUploadResponse });
8808
+ async resumeCapture(runId, captureId, signal) {
8809
+ return this.call("POST", capturePaths.upload(checkId(runId), checkId(captureId)), { schema: captureUploadResponse, signal });
8757
8810
  }
8758
8811
  /** Straight to object storage with the signed headers, or to the server when it has no bucket. */
8759
- async sendCapture(runId, captureId, upload, bytes, contentType) {
8812
+ async sendCapture(runId, captureId, upload, bytes, contentType, signal) {
8760
8813
  const server = upload.target === "server";
8761
8814
  let response;
8762
8815
  try {
@@ -8765,7 +8818,7 @@ var HttpServerLink = class {
8765
8818
  headers: server ? { "content-type": contentType, [CLIENT_VERSION_HEADER]: this.clientVersion, ...this.credential ? { authorization: `Bearer ${this.credential}` } : {}, ...this.protectionBypass ? { "x-vercel-protection-bypass": this.protectionBypass } : {} } : upload.headers,
8766
8819
  body: bytes,
8767
8820
  redirect: "error",
8768
- signal: AbortSignal.timeout(3e5)
8821
+ signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(3e5)]) : AbortSignal.timeout(3e5)
8769
8822
  });
8770
8823
  } catch (error) {
8771
8824
  throw new ServerUnreachableError(error);
@@ -8774,8 +8827,8 @@ var HttpServerLink = class {
8774
8827
  if (response.status === 401 && server) throw new SessionRejectedError();
8775
8828
  if (!response.ok) throw new DaemonError(response.status, `PUT capture failed: ${response.status}`, { status: response.status });
8776
8829
  }
8777
- async completeCapture(runId, captureId) {
8778
- const { capture } = await this.call("POST", capturePaths.complete(checkId(runId), checkId(captureId)), { schema: captureCompleteResponse, timeoutMs: 12e4 });
8830
+ async completeCapture(runId, captureId, signal) {
8831
+ const { capture } = await this.call("POST", capturePaths.complete(checkId(runId), checkId(captureId)), { schema: captureCompleteResponse, timeoutMs: 12e4, signal });
8779
8832
  return capture;
8780
8833
  }
8781
8834
  async screenCapture(runId, request2, signal) {
@@ -8851,10 +8904,10 @@ var HttpServerLink = class {
8851
8904
  }
8852
8905
  }
8853
8906
  }
8854
- async ackCommands(deviceId, delivered) {
8855
- if (delivered.length === 0) return;
8907
+ async ackCommands(deviceId, delivered, refusedSteers = []) {
8908
+ if (!delivered.length && !refusedSteers.length) return;
8856
8909
  await this.call("POST", devicePaths.commandsAck(checkId(deviceId)), {
8857
- body: { delivered }
8910
+ body: { delivered, ...refusedSteers.length ? { refusedSteers } : {} }
8858
8911
  });
8859
8912
  }
8860
8913
  async fetchFsRequests(deviceId, waitSeconds, { signal } = {}) {
@@ -8926,7 +8979,7 @@ async function post(options, path3, body) {
8926
8979
  };
8927
8980
  }
8928
8981
  async function deviceLogin(options) {
8929
- const sleep3 = options.sleep ?? ((ms2) => new Promise((resolve19) => setTimeout(resolve19, ms2)));
8982
+ const sleep3 = options.sleep ?? ((ms2) => new Promise((resolve20) => setTimeout(resolve20, ms2)));
8930
8983
  const started = await post(options, DEVICE_CODE_PATH, {
8931
8984
  client_id: DAEMON_CLIENT_ID,
8932
8985
  device_name: options.deviceName ?? hostname(),
@@ -8998,7 +9051,7 @@ import {
8998
9051
  realpathSync as realpathSync15
8999
9052
  } from "node:fs";
9000
9053
  import { arch as arch2, hostname as hostname2, platform as platform4 } from "node:os";
9001
- import { join as join35 } from "node:path";
9054
+ import { join as join36 } from "node:path";
9002
9055
  import { fileURLToPath as fileURLToPath2 } from "node:url";
9003
9056
 
9004
9057
  // src/runs/quota-exhausted.ts
@@ -9082,7 +9135,7 @@ function quotaStopApplies(assignment) {
9082
9135
  import { spawn as spawn2 } from "node:child_process";
9083
9136
  import { randomUUID as randomUUID2 } from "node:crypto";
9084
9137
  import { realpathSync as realpathSync10 } from "node:fs";
9085
- import { join as join13 } from "node:path";
9138
+ import { join as join14 } from "node:path";
9086
9139
 
9087
9140
  // src/adapters/generation-metrics.ts
9088
9141
  var record2 = (value) => value && typeof value === "object" ? value : {};
@@ -9214,17 +9267,17 @@ var CodexGenerationMetrics = class {
9214
9267
  // src/adapters/claude-prewarm.ts
9215
9268
  import { randomUUID } from "node:crypto";
9216
9269
  import { realpathSync as realpathSync2 } from "node:fs";
9217
- function prepareAgentStart(signal, open4, diagnostics) {
9270
+ function prepareAgentStart(signal, open5, diagnostics) {
9218
9271
  const lifetime = new AbortController();
9219
9272
  let accept, refuse2;
9220
- const finalOptions = new Promise((resolve19, reject) => {
9221
- accept = resolve19;
9273
+ const finalOptions = new Promise((resolve20, reject) => {
9274
+ accept = resolve20;
9222
9275
  refuse2 = reject;
9223
9276
  });
9224
9277
  void finalOptions.catch(() => void 0);
9225
9278
  let parked, failed;
9226
- const ready = new Promise((resolve19, reject) => {
9227
- parked = resolve19;
9279
+ const ready = new Promise((resolve20, reject) => {
9280
+ parked = resolve20;
9228
9281
  failed = reject;
9229
9282
  });
9230
9283
  void ready.catch(() => void 0);
@@ -9233,7 +9286,7 @@ function prepareAgentStart(signal, open4, diagnostics) {
9233
9286
  const starting = Promise.resolve().then(() => {
9234
9287
  const work = () => {
9235
9288
  lifetime.signal.throwIfAborted();
9236
- return open4({ signal: lifetime.signal, finalOptions, parked });
9289
+ return open5({ signal: lifetime.signal, finalOptions, parked });
9237
9290
  };
9238
9291
  return diagnostics ? daemonTracer.preparation(
9239
9292
  { runIdHash: runIdHash(diagnostics.runId), harness: diagnostics.harness },
@@ -9307,8 +9360,8 @@ var ClaimedPromptQueue = class {
9307
9360
  while (!this.closed) {
9308
9361
  const item = this.items.shift();
9309
9362
  if (item) yield item;
9310
- else await new Promise((resolve19) => {
9311
- this.wake = resolve19;
9363
+ else await new Promise((resolve20) => {
9364
+ this.wake = resolve20;
9312
9365
  });
9313
9366
  }
9314
9367
  }
@@ -9490,6 +9543,14 @@ var SNAPSHOT_CREDENTIAL_GLOBS = [
9490
9543
  "/root/.git-credentials",
9491
9544
  // A Bot desktop's cached GitHub credential (lib/computer/desktop-github.ts).
9492
9545
  "/home/*/.mikka/github/token.json",
9546
+ // One-use bootstrap handoffs carry the same device credential. The worker
9547
+ // unlinks them after reading, but a pause may race an unconsumed handoff.
9548
+ // The daemon's own `device.json`/`daemon.secret` stay: they are the local
9549
+ // identity over a device token this machine revokes when it pauses, and
9550
+ // removing them would break a same-VM resume before that revocation.
9551
+ "/home/user/.mikka/bootstrap.json",
9552
+ "/home/user/.mikka/anonymous-claude.json",
9553
+ "/home/user/.mikka/anonymous-codex.json",
9493
9554
  ...runCredentialGlobs(CLOUD_WORKER_STATE_DIR)
9494
9555
  ];
9495
9556
 
@@ -9528,8 +9589,8 @@ function writeOwnFile(file, content) {
9528
9589
  writeFileSync(file, content, { flag: "wx", mode: 384 });
9529
9590
  }
9530
9591
  function ownDir(dir) {
9531
- const stat2 = lstatSync(dir, { throwIfNoEntry: false });
9532
- if (stat2 && !stat2.isDirectory()) rmSync2(dir, { force: true });
9592
+ const stat3 = lstatSync(dir, { throwIfNoEntry: false });
9593
+ if (stat3 && !stat3.isDirectory()) rmSync2(dir, { force: true });
9533
9594
  mkdirSync3(dir, { recursive: true, mode: 448 });
9534
9595
  }
9535
9596
  function carryHistory(from, to, entries) {
@@ -9585,8 +9646,8 @@ var EventQueue = class {
9585
9646
  if (next.type === "exit") return;
9586
9647
  continue;
9587
9648
  }
9588
- await new Promise((resolve19) => {
9589
- this.waiter = resolve19;
9649
+ await new Promise((resolve20) => {
9650
+ this.waiter = resolve20;
9590
9651
  });
9591
9652
  }
9592
9653
  }
@@ -9663,13 +9724,13 @@ async function spawnCli(sandbox, argv, options) {
9663
9724
  stderr = (stderr + data).slice(-STDERR_TAIL * 4);
9664
9725
  });
9665
9726
  const exited = new Promise(
9666
- (resolve19) => {
9727
+ (resolve20) => {
9667
9728
  child.once("error", (error) => {
9668
9729
  stderr += `
9669
9730
  ${error.message}`;
9670
- resolve19({ code: null, signal: null });
9731
+ resolve20({ code: null, signal: null });
9671
9732
  });
9672
- child.once("exit", (code, signal) => resolve19({ code, signal }));
9733
+ child.once("exit", (code, signal) => resolve20({ code, signal }));
9673
9734
  }
9674
9735
  ).finally(() => {
9675
9736
  signalGroup(pgid, "SIGKILL");
@@ -9686,8 +9747,8 @@ ${error.message}`;
9686
9747
  let timer;
9687
9748
  await Promise.race([
9688
9749
  exited,
9689
- new Promise((resolve19) => {
9690
- timer = setTimeout(resolve19, graceMs);
9750
+ new Promise((resolve20) => {
9751
+ timer = setTimeout(resolve20, graceMs);
9691
9752
  })
9692
9753
  ]);
9693
9754
  clearTimeout(timer);
@@ -10220,13 +10281,13 @@ async function excludeVerifyArtifacts(repoPath) {
10220
10281
  });
10221
10282
  }
10222
10283
  async function du(path3) {
10223
- let stat2;
10284
+ let stat3;
10224
10285
  try {
10225
- stat2 = await lstat(path3);
10286
+ stat3 = await lstat(path3);
10226
10287
  } catch {
10227
10288
  return 0;
10228
10289
  }
10229
- if (!stat2.isDirectory()) return stat2.size;
10290
+ if (!stat3.isDirectory()) return stat3.size;
10230
10291
  let entries;
10231
10292
  try {
10232
10293
  entries = await readdir(path3);
@@ -10745,7 +10806,7 @@ function nativeMcpProcess(server) {
10745
10806
 
10746
10807
  // src/agents/run-context.ts
10747
10808
  import { execFileSync } from "node:child_process";
10748
- import { createHash as createHash6 } from "node:crypto";
10809
+ import { createHash as createHash7 } from "node:crypto";
10749
10810
  import {
10750
10811
  lstatSync as lstatSync8,
10751
10812
  mkdirSync as mkdirSync8,
@@ -10756,7 +10817,7 @@ import {
10756
10817
  writeFileSync as writeFileSync4
10757
10818
  } from "node:fs";
10758
10819
  import { homedir as homedir4 } from "node:os";
10759
- import { dirname as dirname9, join as join12, resolve as resolve9 } from "node:path";
10820
+ import { dirname as dirname10, join as join13, resolve as resolve10 } from "node:path";
10760
10821
 
10761
10822
  // src/agents/skill-artifact.ts
10762
10823
  import { createHash as createHash4 } from "node:crypto";
@@ -10906,45 +10967,439 @@ function classifyWrite(worktree, target) {
10906
10967
  }
10907
10968
 
10908
10969
  // src/captures.ts
10970
+ import { createHash as createHash6 } from "node:crypto";
10971
+ import { closeSync as closeSync2, constants as constants3, createReadStream, fstatSync, lstatSync as lstatSync7, mkdirSync as mkdirSync7, mkdtempSync as mkdtempSync3, openSync as openSync2, readFileSync as readFileSync7, readSync, readdirSync as readdirSync4, rmSync as rmSync7 } from "node:fs";
10972
+ import { join as join12 } from "node:path";
10973
+ import { tmpdir as tmpdir3 } from "node:os";
10974
+
10975
+ // src/agents/capture-video.mjs
10976
+ import { execFile as execFile3 } from "node:child_process";
10909
10977
  import { createHash as createHash5 } from "node:crypto";
10910
- import { closeSync as closeSync2, constants as constants2, fstatSync, lstatSync as lstatSync7, mkdirSync as mkdirSync7, openSync as openSync2, readFileSync as readFileSync7, readdirSync as readdirSync4, rmSync as rmSync7 } from "node:fs";
10911
- import { join as join11 } from "node:path";
10978
+ import { constants as constants2, createWriteStream } from "node:fs";
10979
+ import { chmod, lstat as lstat2, mkdir as mkdir2, mkdtemp, open, readFile as readFile2, rename, rm as rm2, stat } from "node:fs/promises";
10980
+ import { dirname as dirname9, basename as basename4, join as join11, resolve as resolve9 } from "node:path";
10981
+ import { devNull } from "node:os";
10982
+ import { pipeline } from "node:stream/promises";
10983
+ import { pathToFileURL as pathToFileURL2 } from "node:url";
10984
+ import { promisify as promisify3 } from "node:util";
10985
+ var execute = promisify3(execFile3);
10986
+ var CAPTURE_RAW_MAX_BYTES = 1e9;
10987
+ var CAPTURE_VIDEO_MAX_BYTES = 1e8;
10988
+ var CAPTURE_TOOLCHAIN = {
10989
+ id: "ffmpeg-static-b6.1.1-linux-x64-e7e7fb30477f-4f231a1960d8",
10990
+ release: "https://github.com/eugeneware/ffmpeg-static/releases/tag/b6.1.1",
10991
+ version: "7.0.2-static",
10992
+ assets: {
10993
+ ffmpeg: {
10994
+ assetId: 316528626,
10995
+ gzip: true,
10996
+ downloadBytes: 29354986,
10997
+ downloadSha256: "bfe8a8fc511530457b528c48d77b5737527b504a3797a9bc4866aeca69c2dffa",
10998
+ bytes: 79826272,
10999
+ sha256: "e7e7fb30477f717e6f55f9180a70386c62677ef8a4d4d1a5d948f4098aa3eb99"
11000
+ },
11001
+ ffprobe: {
11002
+ assetId: 316529539,
11003
+ gzip: true,
11004
+ downloadBytes: 29276839,
11005
+ downloadSha256: "25d9b6ccb05e3d9de9e04e31e2506d8dd7f9f0418981965ac6df12e8d3afd067",
11006
+ bytes: 79665792,
11007
+ sha256: "4f231a1960d83e403d08f7971e271707bec278a9ae18e21b8b5b03186668450d"
11008
+ },
11009
+ LICENSE: {
11010
+ assetId: 316529924,
11011
+ gzip: false,
11012
+ downloadBytes: 35147,
11013
+ downloadSha256: "8ceb4b9ee5adedde47b31e975c1d90c73ad27b6b165a1dcd80c7c545eb65b903",
11014
+ bytes: 35147,
11015
+ sha256: "8ceb4b9ee5adedde47b31e975c1d90c73ad27b6b165a1dcd80c7c545eb65b903"
11016
+ },
11017
+ README: {
11018
+ assetId: 316529927,
11019
+ gzip: false,
11020
+ downloadBytes: 2235,
11021
+ downloadSha256: "72f4b1b06d419d22ace6e7cc75f06826f90737345aa0b1736158929f4aacc537",
11022
+ bytes: 2235,
11023
+ sha256: "72f4b1b06d419d22ace6e7cc75f06826f90737345aa0b1736158929f4aacc537"
11024
+ }
11025
+ }
11026
+ };
11027
+ var CAPTURE_TOOLS_ROOT = "/opt/mikka/runtime/capture-tools";
11028
+ var CAPTURE_TOOLS_DIRECTORY = `${CAPTURE_TOOLS_ROOT}/${CAPTURE_TOOLCHAIN.id}`;
11029
+ var MAX_STEPS = 200;
11030
+ var MAX_DURATION_MS = 36e5;
11031
+ var PADDING_BEFORE_MS = 1e3;
11032
+ var PADDING_AFTER_MS = 1500;
11033
+ var CaptureVideoError = class extends Error {
11034
+ constructor(code, options) {
11035
+ super(code, options);
11036
+ this.name = "CaptureVideoError";
11037
+ this.code = code;
11038
+ }
11039
+ };
11040
+ async function captureVideoBinaries({ directory = CAPTURE_TOOLS_DIRECTORY, ownerId = 0 } = {}) {
11041
+ const info = await lstat2(directory).catch((error) => {
11042
+ if (error.code === "ENOENT") return null;
11043
+ throw error;
11044
+ });
11045
+ if (!info) return { ffmpeg: "ffmpeg", ffprobe: "ffprobe" };
11046
+ try {
11047
+ if (!info.isDirectory() || info.uid !== ownerId || info.mode & 18) throw new Error("Private capture tools directory is unsafe");
11048
+ const binaries = { ffmpeg: join11(directory, "ffmpeg"), ffprobe: join11(directory, "ffprobe") };
11049
+ for (const path3 of Object.values(binaries)) {
11050
+ const binary = await lstat2(path3);
11051
+ if (!binary.isFile() || binary.uid !== ownerId || binary.mode & 18 || !(binary.mode & 73)) throw new Error("Private capture tool is unsafe");
11052
+ }
11053
+ return binaries;
11054
+ } catch (error) {
11055
+ throw new CaptureVideoError("captureVideoDependencyUnavailable", { cause: error });
11056
+ }
11057
+ }
11058
+ function normalizeRecordingSteps(input = []) {
11059
+ if (!Array.isArray(input) || input.length > MAX_STEPS) throw new CaptureVideoError("captureVideoStepsInvalid");
11060
+ return input.map((step) => {
11061
+ if (!step || typeof step !== "object" || Array.isArray(step) || !Number.isSafeInteger(step.atMs) || step.atMs < 0 || step.atMs > MAX_DURATION_MS || !["action", "mark"].includes(step.source) || typeof step.label !== "string" || !step.label.trim() || step.label.length > 200 || step.durationMs != null && (step.source !== "action" || !Number.isSafeInteger(step.durationMs) || step.durationMs < 0 || step.durationMs > MAX_DURATION_MS))
11062
+ throw new CaptureVideoError("captureVideoStepsInvalid");
11063
+ return {
11064
+ atMs: step.atMs,
11065
+ label: step.label.replace(/\s+/g, " ").trim(),
11066
+ source: step.source,
11067
+ ...step.durationMs == null ? {} : { durationMs: step.durationMs }
11068
+ };
11069
+ }).sort((left, right) => left.atMs - right.atMs);
11070
+ }
11071
+ function recordingWindows(durationMs, rawSteps = []) {
11072
+ if (!Number.isSafeInteger(durationMs) || durationMs <= 0 || durationMs > MAX_DURATION_MS)
11073
+ throw new CaptureVideoError("captureVideoDurationInvalid");
11074
+ const steps = normalizeRecordingSteps(rawSteps);
11075
+ const actions = steps.filter((step) => step.source === "action");
11076
+ if (!actions.length || actions.some((step) => step.durationMs == null) || steps.some((step) => step.atMs > durationMs + PADDING_AFTER_MS))
11077
+ return [{ startMs: 0, endMs: durationMs }];
11078
+ const windows = [
11079
+ { startMs: 0, endMs: Math.min(actions[0].atMs + PADDING_AFTER_MS, durationMs) },
11080
+ ...steps.map((step) => ({
11081
+ startMs: Math.max(0, step.atMs - (step.durationMs ?? 0) - PADDING_BEFORE_MS),
11082
+ endMs: Math.min(durationMs, step.atMs + PADDING_AFTER_MS)
11083
+ })),
11084
+ { startMs: Math.max(0, actions.at(-1).atMs - actions.at(-1).durationMs - PADDING_BEFORE_MS), endMs: durationMs }
11085
+ ].filter((window) => window.endMs > window.startMs).sort((a, b) => a.startMs - b.startMs);
11086
+ const merged = [];
11087
+ for (const window of windows) {
11088
+ const previous = merged.at(-1);
11089
+ if (previous && window.startMs <= previous.endMs + 500) previous.endMs = Math.max(previous.endMs, window.endMs);
11090
+ else merged.push({ ...window });
11091
+ }
11092
+ return merged;
11093
+ }
11094
+ function remapRecordingSteps(rawSteps, windows, durationMs) {
11095
+ const point = (atMs) => {
11096
+ let kept = 0;
11097
+ for (const window of windows) {
11098
+ if (atMs <= window.endMs) return Math.min(durationMs, Math.max(0, Math.round(kept + Math.max(0, atMs - window.startMs))));
11099
+ kept += window.endMs - window.startMs;
11100
+ }
11101
+ return Math.min(durationMs, Math.round(kept));
11102
+ };
11103
+ return normalizeRecordingSteps(rawSteps).map((step) => ({ ...step, atMs: point(step.atMs) }));
11104
+ }
11105
+ async function snapshot2(source, destination, signal) {
11106
+ signal?.throwIfAborted();
11107
+ const handle = await open(source, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
11108
+ try {
11109
+ const info = await handle.stat();
11110
+ if (!info.isFile() || info.size < 1 || info.size > CAPTURE_RAW_MAX_BYTES) throw new CaptureVideoError("captureVideoInputInvalid");
11111
+ const header = Buffer.alloc(64);
11112
+ const { bytesRead } = await handle.read(header, 0, header.length, 0);
11113
+ const mp4 = bytesRead >= 12 && header.subarray(4, 8).toString() === "ftyp";
11114
+ const webm = bytesRead >= 4 && header.subarray(0, 4).equals(Buffer.from([26, 69, 223, 163])) && header.toString("latin1").includes("webm");
11115
+ if (!mp4 && !webm) throw new CaptureVideoError("captureVideoInputInvalid");
11116
+ const hash2 = createHash5("sha256"), stream = handle.createReadStream({ autoClose: false, start: 0, end: info.size - 1 });
11117
+ stream.on("data", (bytes) => hash2.update(bytes));
11118
+ await pipeline(stream, createWriteStream(destination, { flags: "wx", mode: 384 }), { signal });
11119
+ if ((await stat(destination)).size !== info.size) throw new CaptureVideoError("captureVideoInputChanged");
11120
+ return { size: info.size, sha256: hash2.digest("hex") };
11121
+ } finally {
11122
+ await handle.close();
11123
+ }
11124
+ }
11125
+ function videoFilter(windows, width, fps) {
11126
+ const seconds = (milliseconds2) => (milliseconds2 / 1e3).toFixed(3);
11127
+ const parts = windows.map((window, i) => `[0:v:0]trim=start=${seconds(window.startMs)}:end=${seconds(window.endMs)},setpts=PTS-STARTPTS[v${i}]`);
11128
+ const combined = windows.length === 1 ? "[v0]" : windows.map((_, i) => `[v${i}]`).join("") + `concat=n=${windows.length}:v=1:a=0,`;
11129
+ return `${parts.join(";")};${combined}scale=w='min(${width},iw)':h=-2:force_divisible_by=2,fps=${fps},format=yuv420p[out]`;
11130
+ }
11131
+ async function processCaptureVideo(input, output, options = {}) {
11132
+ const maximum = options.maxBytes ?? CAPTURE_VIDEO_MAX_BYTES;
11133
+ if (!Number.isSafeInteger(maximum) || maximum < 1 || maximum > CAPTURE_VIDEO_MAX_BYTES || resolve9(input) === resolve9(output))
11134
+ throw new CaptureVideoError("captureVideoOptionsInvalid");
11135
+ const steps = normalizeRecordingSteps(options.steps);
11136
+ const deadline = Date.now() + Math.min(options.timeoutMs ?? 9e4, 18e4);
11137
+ const binaries = await captureVideoBinaries();
11138
+ await mkdir2(dirname9(output), { recursive: true, mode: 448 });
11139
+ const temporary = await mkdtemp(join11(dirname9(output), ".capture-process-"));
11140
+ await chmod(temporary, 448);
11141
+ const run3 = async (binary, args) => {
11142
+ options.signal?.throwIfAborted();
11143
+ const remaining = deadline - Date.now();
11144
+ if (remaining <= 0) throw new CaptureVideoError("captureVideoProcessingTimeout");
11145
+ try {
11146
+ return await execute(binary, args, { timeout: remaining, maxBuffer: 256 * 1024, signal: options.signal, windowsHide: true });
11147
+ } catch (error) {
11148
+ throw new CaptureVideoError(["ENOENT", "EACCES", "ENOEXEC"].includes(error.code) ? "captureVideoDependencyUnavailable" : "captureVideoProcessingFailed", { cause: error });
11149
+ }
11150
+ };
11151
+ const probe = async (path3) => {
11152
+ const { stdout } = await run3(binaries.ffprobe, [
11153
+ "-v",
11154
+ "error",
11155
+ "-protocol_whitelist",
11156
+ "file,pipe",
11157
+ "-format_whitelist",
11158
+ "mov,matroska,webm",
11159
+ "-select_streams",
11160
+ "v:0",
11161
+ "-show_entries",
11162
+ "format=duration:stream=width,height,duration,nb_frames",
11163
+ "-of",
11164
+ "json",
11165
+ path3
11166
+ ]);
11167
+ let value;
11168
+ try {
11169
+ value = JSON.parse(stdout);
11170
+ } catch (error) {
11171
+ throw new CaptureVideoError("captureVideoProbeInvalid", { cause: error });
11172
+ }
11173
+ const stream = value.streams?.[0], seconds = Number(value.format?.duration ?? stream?.duration);
11174
+ if (!stream || !Number.isFinite(seconds) || seconds <= 0 || seconds * 1e3 > MAX_DURATION_MS || !Number.isSafeInteger(stream.width) || stream.width < 1 || !Number.isSafeInteger(stream.height) || stream.height < 1)
11175
+ throw new CaptureVideoError("captureVideoProbeInvalid");
11176
+ return { durationMs: Math.round(seconds * 1e3), width: stream.width, height: stream.height };
11177
+ };
11178
+ try {
11179
+ const source = join11(temporary, "source.video");
11180
+ const originalFile = await snapshot2(input, source, options.signal);
11181
+ const original = await probe(source);
11182
+ const windows = recordingWindows(original.durationMs, steps);
11183
+ const retainedMs = windows.reduce((total, window) => total + window.endMs - window.startMs, 0);
11184
+ const result = join11(temporary, "final.mp4");
11185
+ const base = [
11186
+ "-y",
11187
+ "-nostdin",
11188
+ "-hide_banner",
11189
+ "-loglevel",
11190
+ "error",
11191
+ "-threads",
11192
+ "2",
11193
+ "-filter_complex_threads",
11194
+ "1",
11195
+ "-protocol_whitelist",
11196
+ "file,pipe",
11197
+ "-format_whitelist",
11198
+ "mov,matroska,webm",
11199
+ "-i",
11200
+ source
11201
+ ];
11202
+ const encode2 = async (width, fps, rate, pass) => {
11203
+ await run3(binaries.ffmpeg, [
11204
+ ...base,
11205
+ "-filter_complex",
11206
+ videoFilter(windows, width, fps),
11207
+ "-map",
11208
+ "[out]",
11209
+ "-map_metadata",
11210
+ "-1",
11211
+ "-map_chapters",
11212
+ "-1",
11213
+ "-an",
11214
+ "-sn",
11215
+ "-dn",
11216
+ "-c:v",
11217
+ "libx264",
11218
+ "-preset",
11219
+ "veryfast",
11220
+ "-threads",
11221
+ "2",
11222
+ "-pix_fmt",
11223
+ "yuv420p",
11224
+ ...rate ? ["-b:v", `${rate}k`, "-pass", String(pass), "-passlogfile", join11(temporary, "pass")] : ["-crf", "28"],
11225
+ ...pass === 1 ? ["-f", "null", devNull] : ["-movflags", "+faststart", result]
11226
+ ]);
11227
+ };
11228
+ await encode2(1280, 15);
11229
+ if ((await stat(result)).size > maximum) {
11230
+ const rate = Math.floor(maximum * 0.82 * 8 / (retainedMs / 1e3) / 1e3);
11231
+ if (rate < 8) throw new CaptureVideoError("captureVideoTooLarge");
11232
+ for (const [width, fps, fraction] of [[960, 12, 1], [640, 10, 0.8]]) {
11233
+ await encode2(width, fps, Math.max(8, Math.floor(rate * fraction)), 1);
11234
+ await encode2(width, fps, Math.max(8, Math.floor(rate * fraction)), 2);
11235
+ if ((await stat(result)).size <= maximum) break;
11236
+ }
11237
+ }
11238
+ const size = (await stat(result)).size;
11239
+ if (size > maximum || size === 0) throw new CaptureVideoError("captureVideoTooLarge");
11240
+ const measured = await probe(result);
11241
+ if (measured.durationMs > MAX_DURATION_MS) throw new CaptureVideoError("captureVideoDurationInvalid");
11242
+ if (Math.abs(measured.durationMs - retainedMs) > Math.max(250, windows.length * 100))
11243
+ throw new CaptureVideoError("captureVideoDurationMismatch");
11244
+ await chmod(result, 384);
11245
+ if (await lstat2(output).catch(() => null)) throw new CaptureVideoError("captureVideoOutputExists");
11246
+ options.signal?.throwIfAborted();
11247
+ await rename(result, output);
11248
+ return {
11249
+ durationMs: measured.durationMs,
11250
+ size,
11251
+ steps: remapRecordingSteps(steps, windows, measured.durationMs),
11252
+ processing: {
11253
+ version: 1,
11254
+ originalDurationMs: original.durationMs,
11255
+ originalSize: originalFile.size,
11256
+ originalSha256: originalFile.sha256,
11257
+ trimmedMs: original.durationMs - retainedMs,
11258
+ retainedMs,
11259
+ windows,
11260
+ width: measured.width,
11261
+ height: measured.height
11262
+ }
11263
+ };
11264
+ } finally {
11265
+ await rm2(temporary, { recursive: true, force: true });
11266
+ }
11267
+ }
11268
+ if (process.argv[1] && basename4(process.argv[1]) === "capture-video.mjs" && pathToFileURL2(resolve9(process.argv[1])).href === import.meta.url) {
11269
+ try {
11270
+ const [, , input, output, metadata2] = process.argv;
11271
+ if (!input || !output || !metadata2 || process.argv.length !== 5) throw new CaptureVideoError("captureVideoOptionsInvalid");
11272
+ const options = JSON.parse(await readFile2(metadata2, "utf8"));
11273
+ const result = await processCaptureVideo(input, output, options);
11274
+ process.stdout.write(JSON.stringify(result) + "\n");
11275
+ } catch (error) {
11276
+ process.stderr.write((error instanceof CaptureVideoError ? error.code : "captureVideoProcessingFailed") + "\n");
11277
+ process.exitCode = 1;
11278
+ }
11279
+ }
11280
+
11281
+ // src/captures.ts
10912
11282
  var CAPTURES_DIR = "captures";
10913
11283
  var ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
10914
11284
  var EXTENSIONS = ["png", "jpg", "webp", "mp4", "webm"];
10915
11285
  function readPlain(path3, max) {
10916
11286
  let fd;
10917
11287
  try {
10918
- fd = openSync2(path3, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
11288
+ fd = openSync2(path3, constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0));
10919
11289
  } catch {
10920
11290
  return null;
10921
11291
  }
10922
11292
  try {
10923
- const stat2 = fstatSync(fd);
10924
- if (!stat2.isFile() || stat2.size > max) return null;
11293
+ const stat3 = fstatSync(fd);
11294
+ if (!stat3.isFile() || stat3.size > max) return null;
10925
11295
  return new Uint8Array(readFileSync7(fd));
10926
11296
  } finally {
10927
11297
  closeSync2(fd);
10928
11298
  }
10929
11299
  }
10930
11300
  var drop = (dir, id5) => {
10931
- for (const name of [`${id5}.json`, ...EXTENSIONS.map((ext) => `${id5}.${ext}`)]) rmSync7(join11(dir, name), { force: true });
11301
+ for (const name of [`${id5}.json`, ...EXTENSIONS.map((ext) => `${id5}.${ext}`)]) rmSync7(join12(dir, name), { force: true });
10932
11302
  };
10933
- async function uploadCaptures(dir, runId, link, log, pendingDir, existingOnly = false) {
11303
+ async function hashPlain(path3, signal) {
11304
+ signal?.throwIfAborted();
11305
+ const fd = openSync2(path3, constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0));
11306
+ try {
11307
+ const info = fstatSync(fd);
11308
+ if (!info.isFile() || info.size < 1 || info.size > CAPTURE_RAW_MAX_BYTES) throw new Error("Invalid capture video input");
11309
+ const hash2 = createHash6("sha256");
11310
+ for await (const chunk of createReadStream(path3, { fd, autoClose: false, start: 0, end: info.size - 1, signal })) hash2.update(chunk);
11311
+ signal?.throwIfAborted();
11312
+ return hash2.digest("hex");
11313
+ } finally {
11314
+ closeSync2(fd);
11315
+ }
11316
+ }
11317
+ async function prepareVideo(file, id5, steps, pendingDir, signal) {
11318
+ signal?.throwIfAborted();
11319
+ const directory = pendingDir ?? mkdtempSync3(join12(tmpdir3(), "mikka-capture-pending-"));
11320
+ mkdirSync7(directory, { recursive: true, mode: 448 });
11321
+ const output = join12(directory, `${id5}.processed.mp4`), receipt = join12(directory, `${id5}.video.json`);
11322
+ try {
11323
+ const originalHash = await hashPlain(file, signal);
11324
+ const stepHash = createHash6("sha256").update(JSON.stringify(steps)).digest("hex");
11325
+ let result;
11326
+ const previous = readPlain(receipt, 128e3);
11327
+ if (previous) {
11328
+ try {
11329
+ const cached = JSON.parse(new TextDecoder().decode(previous));
11330
+ if (cached.originalHash === originalHash && cached.stepHash === stepHash && cached.result?.processing?.version === 1 && cached.result?.durationMs > 0 && cached.result.durationMs <= CAPTURE_MAX_DURATION_MS && await hashPlain(output, signal) === cached.sha256) result = cached.result;
11331
+ } catch {
11332
+ }
11333
+ }
11334
+ signal?.throwIfAborted();
11335
+ if (!result) {
11336
+ rmSync7(output, { force: true });
11337
+ rmSync7(receipt, { force: true });
11338
+ result = await processCaptureVideo(file, output, { steps, maxBytes: CAPTURE_MAX_BYTES.video, signal });
11339
+ if (result.processing.originalSha256 !== originalHash) throw new Error("Capture changed during video processing");
11340
+ writeJsonAtomic(receipt, { originalHash, stepHash, sha256: await hashPlain(output, signal), result });
11341
+ }
11342
+ signal?.throwIfAborted();
11343
+ const bytes = readPlain(output, CAPTURE_MAX_BYTES.video);
11344
+ if (!bytes || captureProblem(bytes, "video/mp4")) throw new Error("Processed capture video is invalid");
11345
+ return { bytes, durationMs: result.durationMs, steps: normalizeRecordingSteps(result.steps) };
11346
+ } finally {
11347
+ if (!pendingDir) rmSync7(directory, { recursive: true, force: true });
11348
+ }
11349
+ }
11350
+ function dropPrepared(pendingDir, id5) {
11351
+ if (!pendingDir) return;
11352
+ for (const name of [`${id5}.json`, `${id5}.processed.mp4`, `${id5}.video.json`]) rmSync7(join12(pendingDir, name), { force: true });
11353
+ }
11354
+ function fileType(path3) {
11355
+ let fd;
11356
+ try {
11357
+ fd = openSync2(path3, constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0));
11358
+ } catch {
11359
+ return null;
11360
+ }
11361
+ try {
11362
+ const info = fstatSync(fd);
11363
+ if (!info.isFile() || info.size < 1 || info.size > CAPTURE_RAW_MAX_BYTES) return null;
11364
+ const head = Buffer.alloc(64);
11365
+ return sniffCaptureType(head.subarray(0, readSync(fd, head, 0, head.length, 0)));
11366
+ } finally {
11367
+ closeSync2(fd);
11368
+ }
11369
+ }
11370
+ async function uploadCaptures(dir, runId, link, log, pendingDir, existingOnly = false, signal) {
11371
+ signal?.throwIfAborted();
10934
11372
  if (!link.beginCapture || !link.sendCapture || !link.completeCapture) return 0;
10935
11373
  if (!lstatSync7(dir, { throwIfNoEntry: false })?.isDirectory()) return 0;
10936
11374
  let sent = 0;
10937
11375
  for (const name of readdirSync4(dir).sort()) {
11376
+ signal?.throwIfAborted();
10938
11377
  const id5 = name.endsWith(".json") ? name.slice(0, -5) : "";
10939
11378
  if (!ID.test(id5)) continue;
10940
- const meta = readPlain(join11(dir, name), 4096);
11379
+ const meta = readPlain(join12(dir, name), 128e3);
10941
11380
  let title2 = "";
11381
+ let steps = [];
10942
11382
  try {
10943
- title2 = cleanCaptureTitle(String(JSON.parse(new TextDecoder().decode(meta ?? new Uint8Array())).title ?? ""));
11383
+ const data = JSON.parse(new TextDecoder().decode(meta ?? new Uint8Array()));
11384
+ title2 = cleanCaptureTitle(String(data.title ?? ""));
11385
+ steps = normalizeRecordingSteps(data.steps);
10944
11386
  } catch {
11387
+ title2 = "";
11388
+ }
11389
+ const file = EXTENSIONS.map((ext) => join12(dir, `${id5}.${ext}`)).find((path3) => lstatSync7(path3, { throwIfNoEntry: false }));
11390
+ const originalType = file ? fileType(file) : null;
11391
+ let video;
11392
+ if (file && title2 && originalType?.startsWith("video/")) {
11393
+ try {
11394
+ video = await prepareVideo(file, id5, steps, pendingDir, signal);
11395
+ } catch {
11396
+ signal?.throwIfAborted();
11397
+ log.warn({ run_id: runId, capture: id5 }, "capture video processing failed");
11398
+ continue;
11399
+ }
10945
11400
  }
10946
- const file = EXTENSIONS.map((ext) => join11(dir, `${id5}.${ext}`)).find((path3) => lstatSync7(path3, { throwIfNoEntry: false }));
10947
- const bytes = file ? readPlain(file, CAPTURE_MAX_BYTES.video) : null;
11401
+ signal?.throwIfAborted();
11402
+ const bytes = video?.bytes ?? (file && originalType?.startsWith("image/") ? readPlain(file, CAPTURE_MAX_BYTES.image) : null);
10948
11403
  const problem = !title2 ? "no title" : !bytes ? "no regular file" : captureProblem(bytes);
10949
11404
  const contentType = bytes && sniffCaptureType(bytes);
10950
11405
  if (problem || !bytes || !contentType) {
@@ -10953,8 +11408,8 @@ async function uploadCaptures(dir, runId, link, log, pendingDir, existingOnly =
10953
11408
  continue;
10954
11409
  }
10955
11410
  try {
10956
- const sha2562 = createHash5("sha256").update(bytes).digest("hex");
10957
- const pendingPath = pendingDir ? join11(pendingDir, `${id5}.json`) : null;
11411
+ const sha2562 = createHash6("sha256").update(bytes).digest("hex");
11412
+ const pendingPath = pendingDir ? join12(pendingDir, `${id5}.json`) : null;
10958
11413
  let pending;
10959
11414
  if (pendingPath) {
10960
11415
  try {
@@ -10967,36 +11422,43 @@ async function uploadCaptures(dir, runId, link, log, pendingDir, existingOnly =
10967
11422
  let target;
10968
11423
  if (pending) {
10969
11424
  try {
10970
- await link.completeCapture(runId, pending.captureId);
11425
+ await link.completeCapture(runId, pending.captureId, signal);
11426
+ signal?.throwIfAborted();
10971
11427
  drop(dir, id5);
10972
- if (pendingPath) rmSync7(pendingPath, { force: true });
11428
+ dropPrepared(pendingDir, id5);
10973
11429
  sent += 1;
10974
11430
  continue;
10975
11431
  } catch (error) {
11432
+ signal?.throwIfAborted();
10976
11433
  if (!(error instanceof DaemonError) || error instanceof ServerUnreachableError || error.code !== 404) throw error;
10977
11434
  }
10978
11435
  if (!link.resumeCapture) return sent;
10979
11436
  try {
10980
- target = await link.resumeCapture(runId, pending.captureId);
11437
+ target = await link.resumeCapture(runId, pending.captureId, signal);
10981
11438
  } catch (error) {
11439
+ signal?.throwIfAborted();
10982
11440
  if (existingOnly || !(error instanceof DaemonError) || error instanceof ServerUnreachableError || error.code !== 404) throw error;
10983
- target = await link.beginCapture(runId, { captureId: pending.captureId, title: title2, contentType, size: bytes.length, sha256: sha2562 });
11441
+ target = await link.beginCapture(runId, { captureId: pending.captureId, title: title2, contentType, size: bytes.length, sha256: sha2562, ...video ? { durationMs: video.durationMs, steps: video.steps } : {} }, signal);
10984
11442
  }
10985
11443
  } else {
10986
11444
  if (pendingPath) {
10987
11445
  mkdirSync7(pendingDir, { recursive: true, mode: 448 });
10988
11446
  writeJsonAtomic(pendingPath, { captureId: id5, sha256: sha2562 });
10989
11447
  }
10990
- target = await link.beginCapture(runId, { ...pendingPath ? { captureId: id5 } : {}, title: title2, contentType, size: bytes.length, sha256: sha2562 });
10991
- if (pendingPath && target.captureId !== id5) throw new Error("Capture reservation id changed");
11448
+ target = await link.beginCapture(runId, { captureId: id5, title: title2, contentType, size: bytes.length, sha256: sha2562, ...video ? { durationMs: video.durationMs, steps: video.steps } : {} }, signal);
11449
+ if (target.captureId !== id5) throw new Error("Capture reservation id changed");
10992
11450
  }
11451
+ signal?.throwIfAborted();
10993
11452
  const { captureId, upload } = target;
10994
- await link.sendCapture(runId, captureId, upload, bytes, contentType);
10995
- await link.completeCapture(runId, captureId);
11453
+ await link.sendCapture(runId, captureId, upload, bytes, contentType, signal);
11454
+ signal?.throwIfAborted();
11455
+ await link.completeCapture(runId, captureId, signal);
11456
+ signal?.throwIfAborted();
10996
11457
  drop(dir, id5);
10997
- if (pendingPath) rmSync7(pendingPath, { force: true });
11458
+ dropPrepared(pendingDir, id5);
10998
11459
  sent += 1;
10999
11460
  } catch (error) {
11461
+ signal?.throwIfAborted();
11000
11462
  if (error instanceof ServerUnreachableError) {
11001
11463
  log.warn({ run_id: runId, capture: id5 }, "capture upload deferred");
11002
11464
  return sent;
@@ -11005,13 +11467,13 @@ async function uploadCaptures(dir, runId, link, log, pendingDir, existingOnly =
11005
11467
  log.warn({ run_id: runId, capture: id5, status: error.code }, "capture reservation unavailable; retry stopped");
11006
11468
  if (pendingDir) {
11007
11469
  mkdirSync7(pendingDir, { recursive: true, mode: 448 });
11008
- writeJsonAtomic(join11(pendingDir, "blocked.json"), { status: error.code });
11470
+ writeJsonAtomic(join12(pendingDir, "blocked.json"), { status: error.code });
11009
11471
  }
11010
11472
  return sent;
11011
11473
  }
11012
11474
  log.warn({ run_id: runId, capture: id5, status: error instanceof DaemonError ? error.code : void 0 }, "capture refused");
11013
11475
  drop(dir, id5);
11014
- if (pendingDir) rmSync7(join11(pendingDir, `${id5}.json`), { force: true });
11476
+ dropPrepared(pendingDir, id5);
11015
11477
  }
11016
11478
  }
11017
11479
  return sent;
@@ -11028,15 +11490,31 @@ var CaptureUploader = class {
11028
11490
  log;
11029
11491
  pendingRoot;
11030
11492
  passes = /* @__PURE__ */ new Map();
11031
- flush(runId, existingOnly = false) {
11493
+ /** A final signal bounds both this pass and any earlier pass still in flight. */
11494
+ flush(runId, existingOnly = false, signal) {
11032
11495
  if (!/^[A-Za-z0-9_-]{1,64}$/.test(runId)) return Promise.resolve();
11033
- const pendingDir = this.pendingRoot ? join11(this.pendingRoot, runId) : void 0;
11034
- if (pendingDir && lstatSync7(join11(pendingDir, "blocked.json"), { throwIfNoEntry: false })) return Promise.resolve();
11035
- const previous = this.passes.get(runId) ?? Promise.resolve();
11036
- const next = previous.then(() => uploadCaptures(this.dirFor(runId), runId, this.link, this.log, pendingDir, existingOnly)).then(() => void 0, (error) => this.log.warn({ run_id: runId, err: error instanceof Error ? error.message : String(error) }, "capture upload failed")).finally(() => {
11037
- if (this.passes.get(runId) === next) this.passes.delete(runId);
11496
+ const pendingDir = this.pendingRoot ? join12(this.pendingRoot, runId) : void 0;
11497
+ if (pendingDir && lstatSync7(join12(pendingDir, "blocked.json"), { throwIfNoEntry: false }))
11498
+ return signal ? Promise.reject(new Error("Capture upload incomplete")) : Promise.resolve();
11499
+ const pass = this.passes.get(runId) ?? { tail: Promise.resolve(), abort: new AbortController() };
11500
+ const abort = () => pass.abort.abort(signal?.reason);
11501
+ signal?.addEventListener("abort", abort, { once: true });
11502
+ if (signal?.aborted) abort();
11503
+ const next = pass.tail.catch(() => void 0).then(async () => {
11504
+ const dir = this.dirFor(runId);
11505
+ await uploadCaptures(dir, runId, this.link, this.log, pendingDir, existingOnly, pass.abort.signal);
11506
+ pass.abort.signal.throwIfAborted();
11507
+ if (signal && lstatSync7(dir, { throwIfNoEntry: false })?.isDirectory() && readdirSync4(dir).some((name) => name.endsWith(".json") && ID.test(name.slice(0, -5))))
11508
+ throw new Error("Capture upload incomplete");
11509
+ }).catch((error) => {
11510
+ if (signal) throw error;
11511
+ this.log.warn({ run_id: runId, reason: pass.abort.signal.aborted ? "cancelled" : "failed" }, "capture upload failed");
11512
+ }).finally(() => {
11513
+ signal?.removeEventListener("abort", abort);
11514
+ if (this.passes.get(runId)?.tail === next) this.passes.delete(runId);
11038
11515
  });
11039
- this.passes.set(runId, next);
11516
+ pass.tail = next;
11517
+ this.passes.set(runId, pass);
11040
11518
  return next;
11041
11519
  }
11042
11520
  };
@@ -11061,7 +11539,7 @@ var HARNESS_DOMAINS = {
11061
11539
  "*.cursorapi.com"
11062
11540
  ]
11063
11541
  };
11064
- var MCP_SERVER_SCRIPT = resolve9(import.meta.dirname, "mikka-mcp.mjs");
11542
+ var MCP_SERVER_SCRIPT = resolve10(import.meta.dirname, "mikka-mcp.mjs");
11065
11543
  var MCP_SERVER_NAME = "mikka";
11066
11544
  var COMPUTER_MCP_SERVER_NAME = "mikka_computer";
11067
11545
  var RUN_GIT_CONFIG = [["maintenance.auto", "false"], ["gc.auto", "0"]];
@@ -11092,7 +11570,7 @@ function credentialDenyRead(harness, home = homedir4()) {
11092
11570
  // Other harnesses' logins; each harness still reads its own.
11093
11571
  ...harness === "codex" ? [] : [".codex/auth.json"],
11094
11572
  ...harness === "claude_code" ? [] : [".claude/.credentials.json"]
11095
- ].map((path3) => join12(home, path3));
11573
+ ].map((path3) => join13(home, path3));
11096
11574
  }
11097
11575
  function daemonSecrets(dataDir) {
11098
11576
  const paths = daemonPaths(realpathSync9(dataDir));
@@ -11103,18 +11581,18 @@ function daemonSecrets(dataDir) {
11103
11581
  paths.outbox,
11104
11582
  paths.logs,
11105
11583
  paths.devRepos,
11106
- join12(paths.adapterState, "pids")
11584
+ join13(paths.adapterState, "pids")
11107
11585
  ];
11108
11586
  }
11109
11587
  function runPaths(stateDir, runId) {
11110
11588
  const id5 = assertSafeId("run id", runId);
11111
11589
  return {
11112
11590
  /** The daemon's data dir (`stateDir` is `<dataDir>/adapters`). */
11113
- privateDir: resolve9(stateDir, ".."),
11591
+ privateDir: resolve10(stateDir, ".."),
11114
11592
  /** Writable from the sandbox. */
11115
- runDir: join12(stateDir, "runs", id5),
11593
+ runDir: join13(stateDir, "runs", id5),
11116
11594
  /** Daemon only. */
11117
- pidFile: join12(stateDir, "pids", `${id5}.pgid`)
11595
+ pidFile: join13(stateDir, "pids", `${id5}.pgid`)
11118
11596
  };
11119
11597
  }
11120
11598
  function repositorySkill(worktree, slug) {
@@ -11122,7 +11600,7 @@ function repositorySkill(worktree, slug) {
11122
11600
  const missing2 = (reason) => ({ id: id5, name: slug, description: "", source: "repository", digest: null, instructions: null, available: false, reason });
11123
11601
  if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(slug)) return missing2("invalid");
11124
11602
  for (const root of [".claude/skills", ".agents/skills"]) {
11125
- const file = join12(worktree, root, slug, SKILL_BODY_FILE);
11603
+ const file = join13(worktree, root, slug, SKILL_BODY_FILE);
11126
11604
  const meta = lstatSync8(file, { throwIfNoEntry: false });
11127
11605
  if (!meta) continue;
11128
11606
  if (!meta.isFile() || meta.isSymbolicLink() || meta.nlink !== 1 || meta.size < 1 || meta.size > MAX_PROFILE_SKILL_INSTRUCTIONS_LENGTH) return missing2("invalid");
@@ -11144,7 +11622,7 @@ function repositorySkill(worktree, slug) {
11144
11622
  name: (declaredName || slug).slice(0, 80),
11145
11623
  description: description.slice(0, 500),
11146
11624
  source: "repository",
11147
- digest: createHash6("sha256").update(body, "utf8").digest("hex"),
11625
+ digest: createHash7("sha256").update(body, "utf8").digest("hex"),
11148
11626
  instructions: body,
11149
11627
  available: true
11150
11628
  };
@@ -11158,16 +11636,16 @@ function writeProfileSkillManifest(options, runDir, worktree, includeRepository)
11158
11636
  if (assigned.length > MAX_PROFILE_SKILLS_PER_RUN || declared.length > MAX_PROFILE_SKILLS_PER_RUN) throw new Error("Profile Skill assignment limit");
11159
11637
  const entries = [];
11160
11638
  for (const skill of assigned) {
11161
- const digest9 = createHash6("sha256").update(skill.instructions, "utf8").digest("hex");
11639
+ const digest9 = createHash7("sha256").update(skill.instructions, "utf8").digest("hex");
11162
11640
  if (digest9 !== skill.digest) throw new Error("Profile Skill artifact digest mismatch");
11163
11641
  entries.push({ id: skill.id, name: skill.name, description: skill.description, source: skill.source, digest: digest9, instructions: skill.instructions, available: true });
11164
11642
  }
11165
11643
  for (const slug of declared) entries.push(includeRepository ? repositorySkill(worktree, slug) : { id: `repository:${slug}`, name: slug, description: "", source: "repository", digest: null, instructions: null, available: false, reason: "pending" });
11166
11644
  const unique = [...new Map(entries.map((entry) => [entry.id, entry])).values()];
11167
- const dir = join12(runDir, PROFILE_SKILLS_DIR);
11645
+ const dir = join13(runDir, PROFILE_SKILLS_DIR);
11168
11646
  ownDir(dir);
11169
11647
  const manifest = { version: 1, skills: unique };
11170
- const file = join12(dir, PROFILE_SKILL_MANIFEST_FILE);
11648
+ const file = join13(dir, PROFILE_SKILL_MANIFEST_FILE);
11171
11649
  const tmp = `${file}.${process.pid}.tmp`;
11172
11650
  writeFileSync4(tmp, `${JSON.stringify(manifest)}
11173
11651
  `, { encoding: "utf8", mode: 384 });
@@ -11178,11 +11656,11 @@ function prepareRunContextFiles(options) {
11178
11656
  ownDir(options.runDir);
11179
11657
  const runDir = realpathSync9(options.runDir);
11180
11658
  const files2 = {
11181
- worktree: resolve9(options.worktree),
11659
+ worktree: resolve10(options.worktree),
11182
11660
  runDir,
11183
- handoffFile: join12(runDir, "handoff.json"),
11184
- tmpDir: join12(runDir, "tmp"),
11185
- capturesDir: join12(runDir, CAPTURES_DIR)
11661
+ handoffFile: join13(runDir, "handoff.json"),
11662
+ tmpDir: join13(runDir, "tmp"),
11663
+ capturesDir: join13(runDir, CAPTURES_DIR)
11186
11664
  };
11187
11665
  ownDir(files2.tmpDir);
11188
11666
  ownDir(files2.capturesDir);
@@ -11216,7 +11694,7 @@ function runMcpServer(options, files2) {
11216
11694
  files2.worktree,
11217
11695
  "--capture-root",
11218
11696
  files2.tmpDir,
11219
- ...options.profileSkills?.length || options.repositorySkills?.length ? ["--profile-skills", join12(files2.runDir, PROFILE_SKILLS_DIR)] : [],
11697
+ ...options.profileSkills?.length || options.repositorySkills?.length ? ["--profile-skills", join13(files2.runDir, PROFILE_SKILLS_DIR)] : [],
11220
11698
  ...options.factoryCheck && (!options.factoryCheck.reportOnly || options.factoryCheck.inferCommand) ? ["--factory-verify", JSON.stringify({ cwd: files2.worktree, command: options.verifyCommand ?? null, infer: options.factoryCheck.inferCommand })] : [],
11221
11699
  ...options.factoryCheck?.reportOnly || readOnlyInspection ? ["--factory-artifacts", files2.worktree] : [],
11222
11700
  ...repositoryExecution ? ["--repository-selection", files2.worktree] : []
@@ -11264,13 +11742,13 @@ var RunContext = class {
11264
11742
  );
11265
11743
  ownDir(options.runDir);
11266
11744
  this.runDir = realpathSync9(options.runDir);
11267
- this.handoffFile = join12(this.runDir, "handoff.json");
11268
- this.skillsDir = join12(this.runDir, SKILLS_DIR);
11269
- this.tmpDir = join12(this.runDir, "tmp");
11745
+ this.handoffFile = join13(this.runDir, "handoff.json");
11746
+ this.skillsDir = join13(this.runDir, SKILLS_DIR);
11747
+ this.tmpDir = join13(this.runDir, "tmp");
11270
11748
  ownDir(this.tmpDir);
11271
- this.capturesDir = join12(this.runDir, CAPTURES_DIR);
11749
+ this.capturesDir = join13(this.runDir, CAPTURES_DIR);
11272
11750
  ownDir(this.capturesDir);
11273
- this.profileSkillsDir = join12(this.runDir, PROFILE_SKILLS_DIR);
11751
+ this.profileSkillsDir = join13(this.runDir, PROFILE_SKILLS_DIR);
11274
11752
  this.writeSkills();
11275
11753
  this.writeProfileSkills();
11276
11754
  if (options.github && !options.machineEnvironment) {
@@ -11313,23 +11791,23 @@ var RunContext = class {
11313
11791
  let slug = base;
11314
11792
  for (let n = 2; taken.has(slug); n += 1) slug = `${base}-${n}`;
11315
11793
  taken.add(slug);
11316
- const dir = join12(this.skillsDir, slug);
11794
+ const dir = join13(this.skillsDir, slug);
11317
11795
  if (this.options.skillReceipt) {
11318
11796
  const existing = lstatSync8(dir, { throwIfNoEntry: false });
11319
11797
  if (existing && (!existing.isDirectory() || existing.isSymbolicLink())) throw new Error("Unsafe Skill artifact directory");
11320
- const file = lstatSync8(join12(dir, SKILL_BODY_FILE), { throwIfNoEntry: false });
11798
+ const file = lstatSync8(join13(dir, SKILL_BODY_FILE), { throwIfNoEntry: false });
11321
11799
  if (file && (!file.isFile() || file.isSymbolicLink() || file.nlink !== 1)) throw new Error("Unsafe Skill artifact file");
11322
11800
  }
11323
11801
  mkdirSync8(dir, { recursive: true });
11324
- const bodyFile = join12(dir, SKILL_BODY_FILE);
11802
+ const bodyFile = join13(dir, SKILL_BODY_FILE);
11325
11803
  if (this.options.skillReceipt) {
11326
11804
  if (!lstatSync8(bodyFile, { throwIfNoEntry: false })) writeFileSync4(bodyFile, skillMarkdown(skill), { encoding: "utf8", flag: "wx", mode: 384 });
11327
11805
  } else writeFileSync4(bodyFile, skillMarkdown(skill), "utf8");
11328
- if (this.options.skillReceipt) verifyMountedSkill(join12(dir, SKILL_BODY_FILE), this.options.skillReceipt);
11806
+ if (this.options.skillReceipt) verifyMountedSkill(join13(dir, SKILL_BODY_FILE), this.options.skillReceipt);
11329
11807
  for (const file of skill.files) {
11330
- const target = resolve9(dir, file.path);
11808
+ const target = resolve10(dir, file.path);
11331
11809
  if (!target.startsWith(`${dir}/`)) continue;
11332
- mkdirSync8(dirname9(target), { recursive: true });
11810
+ mkdirSync8(dirname10(target), { recursive: true });
11333
11811
  writeFileSync4(target, file.content, "utf8");
11334
11812
  }
11335
11813
  }
@@ -11363,14 +11841,14 @@ var RunContext = class {
11363
11841
  denyWrite: [
11364
11842
  // The fixture's refs/objects are writable for push; its configuration
11365
11843
  // and hooks must remain host-owned because fixture verification runs Git.
11366
- ...fixtureOrigin ? [join12(fixtureOrigin, "config"), join12(fixtureOrigin, "hooks")] : [],
11367
- join12(this.worktree, ".git"),
11368
- join12(this.gitDir, "commondir"),
11369
- join12(this.gitDir, "gitdir"),
11370
- join12(this.gitDir, "config.worktree"),
11844
+ ...fixtureOrigin ? [join13(fixtureOrigin, "config"), join13(fixtureOrigin, "hooks")] : [],
11845
+ join13(this.worktree, ".git"),
11846
+ join13(this.gitDir, "commondir"),
11847
+ join13(this.gitDir, "gitdir"),
11848
+ join13(this.gitDir, "config.worktree"),
11371
11849
  // A repository's config and hooks in the shared clone, outside the
11372
11850
  // working directory, are declared read-only here too.
11373
- ...this.options.gitWritePaths?.length ? [join12(this.gitDir, "..", "..", "config"), join12(this.gitDir, "..", "..", "hooks")] : [],
11851
+ ...this.options.gitWritePaths?.length ? [join13(this.gitDir, "..", "..", "config"), join13(this.gitDir, "..", "..", "hooks")] : [],
11374
11852
  ...readOnly ? [this.worktree, ...this.options.gitWritePaths ?? []] : []
11375
11853
  ],
11376
11854
  denyRead: [
@@ -11424,7 +11902,7 @@ var RunContext = class {
11424
11902
  */
11425
11903
  tempEnv() {
11426
11904
  if (this.options.machineEnvironment) return this.options.policyHash ? { MIKKA_POLICY_HASH: this.options.policyHash } : {};
11427
- return { TMPDIR: this.tmpDir, TMPPREFIX: join12(this.tmpDir, "zsh"), ...withGitConfig(this.githubEnv, RUN_GIT_CONFIG), ...this.options.policyHash ? { MIKKA_POLICY_HASH: this.options.policyHash } : {} };
11905
+ return { TMPDIR: this.tmpDir, TMPPREFIX: join13(this.tmpDir, "zsh"), ...withGitConfig(this.githubEnv, RUN_GIT_CONFIG), ...this.options.policyHash ? { MIKKA_POLICY_HASH: this.options.policyHash } : {} };
11428
11906
  }
11429
11907
  /**
11430
11908
  * The agent delivers this run itself: it commits, pushes to the task
@@ -11440,17 +11918,18 @@ var RunContext = class {
11440
11918
  }
11441
11919
  /** The agent's hand-in as the session's exit, or null if it made none. */
11442
11920
  readHandoff(log) {
11443
- const stat2 = lstatSync8(this.handoffFile, { throwIfNoEntry: false });
11444
- if (!stat2) return null;
11921
+ const stat3 = lstatSync8(this.handoffFile, { throwIfNoEntry: false });
11922
+ if (!stat3) return null;
11445
11923
  let file;
11446
11924
  try {
11447
- if (!stat2.isFile()) throw new Error("not a regular file");
11925
+ if (!stat3.isFile()) throw new Error("not a regular file");
11448
11926
  file = JSON.parse(readFileSync8(this.handoffFile, "utf8"));
11449
11927
  } catch (error) {
11450
11928
  log?.warn({ err: error }, "unreadable handoff file; ignoring it");
11451
11929
  return null;
11452
11930
  }
11453
11931
  const plan = this.options.kind === "plan" ? planFromHandoff(file.plan, log) : null;
11932
+ const visualEvidence = runVisualEvidence.safeParse(file.visualEvidence);
11454
11933
  const question = runQuestion.safeParse(file.question);
11455
11934
  const repositorySelection = !this.options.factoryCheck && ["implement", "fix"].includes(this.options.kind ?? "") ? runRepositorySelection.safeParse(file.repositorySelection) : null;
11456
11935
  const report2 = {
@@ -11463,6 +11942,7 @@ var RunContext = class {
11463
11942
  ...plan ? { plan } : {},
11464
11943
  ...typeof file.previewDatabaseBranch === "string" ? { previewDatabaseBranch: file.previewDatabaseBranch } : {},
11465
11944
  ...Array.isArray(file.criteria) ? { criteria: file.criteria } : {},
11945
+ ...visualEvidence.success ? { visualEvidence: visualEvidence.data } : {},
11466
11946
  ...file.reviewVerdict ? { reviewVerdict: file.reviewVerdict } : {},
11467
11947
  ...file.verificationCommand ? { verificationCommand: file.verificationCommand } : {},
11468
11948
  ...runQuestion.safeParse(file.question).success ? { question: runQuestion.parse(file.question) } : {}
@@ -11908,8 +12388,8 @@ var PromptQueue = class {
11908
12388
  continue;
11909
12389
  }
11910
12390
  if (this.closed) return;
11911
- await new Promise((resolve19) => {
11912
- this.waiter = resolve19;
12391
+ await new Promise((resolve20) => {
12392
+ this.waiter = resolve20;
11913
12393
  });
11914
12394
  }
11915
12395
  }
@@ -11923,8 +12403,8 @@ async function untilSpoken(spoken) {
11923
12403
  try {
11924
12404
  return await Promise.race([
11925
12405
  spoken,
11926
- new Promise((resolve19) => {
11927
- timer = setTimeout(() => resolve19(true), CONTINUE_SILENCE_MS);
12406
+ new Promise((resolve20) => {
12407
+ timer = setTimeout(() => resolve20(true), CONTINUE_SILENCE_MS);
11928
12408
  })
11929
12409
  ]);
11930
12410
  } finally {
@@ -12067,15 +12547,15 @@ var ClaudeAdapter = class {
12067
12547
  throw new Error(SUBSCRIPTION_ERROR, { cause: error });
12068
12548
  }
12069
12549
  }
12070
- const nativeHome = options.machineEnvironment ? options.env.HOME : join13(runDir, "native-home");
12550
+ const nativeHome = options.machineEnvironment ? options.env.HOME : join14(runDir, "native-home");
12071
12551
  if (!nativeHome) throw new Error("Cloud machine HOME unavailable");
12072
- const configDir = options.machineEnvironment ? options.env.CLAUDE_CONFIG_DIR ?? join13(nativeHome, ".claude") : join13(nativeHome, ".claude");
12552
+ const configDir = options.machineEnvironment ? options.env.CLAUDE_CONFIG_DIR ?? join14(nativeHome, ".claude") : join14(nativeHome, ".claude");
12073
12553
  if (!options.machineEnvironment) {
12074
12554
  ownDir(nativeHome);
12075
12555
  ownDir(configDir);
12076
12556
  }
12077
12557
  if (!options.machineEnvironment && mode === "continue" && options.continueSession) {
12078
- carryHistory(join13(runPaths(this.options.stateDir, options.continueSession.runId).runDir, "native-home", ".claude"), configDir, ["projects"]);
12558
+ carryHistory(join14(runPaths(this.options.stateDir, options.continueSession.runId).runDir, "native-home", ".claude"), configDir, ["projects"]);
12079
12559
  }
12080
12560
  if (externalAuth && options.credential) throw new Error(SUBSCRIPTION_ERROR);
12081
12561
  const credentialEnv = claudeCredentialEnv(options.credential);
@@ -12110,8 +12590,8 @@ var ClaudeAdapter = class {
12110
12590
  privateDir: paths.privateDir,
12111
12591
  // Its session store, so `resume` works; keyed by the cwd it sees.
12112
12592
  extraWrite: preparing ? [] : [
12113
- join13(configDir, "projects", claudeProjectDirName(options.cwd)),
12114
- join13(
12593
+ join14(configDir, "projects", claudeProjectDirName(options.cwd)),
12594
+ join14(
12115
12595
  configDir,
12116
12596
  "projects",
12117
12597
  claudeProjectDirName(realpathSync10(options.cwd))
@@ -12145,15 +12625,15 @@ var ClaudeAdapter = class {
12145
12625
  let authTimer;
12146
12626
  let stderr = "";
12147
12627
  let stderrArrived = () => void 0;
12148
- const firstStderr = new Promise((resolve19) => {
12149
- stderrArrived = resolve19;
12628
+ const firstStderr = new Promise((resolve20) => {
12629
+ stderrArrived = resolve20;
12150
12630
  });
12151
12631
  const stderrTail = () => stderr.slice(-STDERR_TAIL2).trim() || "no output";
12152
12632
  let spoke = () => void 0;
12153
- const spoken = new Promise((resolve19) => spoke = resolve19);
12633
+ const spoken = new Promise((resolve20) => spoke = resolve20);
12154
12634
  let checkingContinuation = mode === "continue";
12155
12635
  let finished = () => void 0;
12156
- const gone = new Promise((resolve19) => finished = resolve19);
12636
+ const gone = new Promise((resolve20) => finished = resolve20);
12157
12637
  let nativeExit = Promise.resolve(false);
12158
12638
  if (externalAuth && this.options.onHostedSession) {
12159
12639
  try {
@@ -12192,10 +12672,10 @@ var ClaudeAdapter = class {
12192
12672
  stderr = previousStderr.slice(-STDERR_TAIL2 * 4);
12193
12673
  stderrArrived();
12194
12674
  }
12195
- nativeExit = new Promise((resolve19) => {
12196
- child.once("exit", () => resolve19(true));
12197
- child.once("error", () => resolve19(false));
12198
- if (child.exitCode !== null || child.signalCode) resolve19(true);
12675
+ nativeExit = new Promise((resolve20) => {
12676
+ child.once("exit", () => resolve20(true));
12677
+ child.once("error", () => resolve20(false));
12678
+ if (child.exitCode !== null || child.signalCode) resolve20(true);
12199
12679
  });
12200
12680
  child.stderr?.on("data", (data) => {
12201
12681
  stderr = (stderr + data.toString()).slice(-STDERR_TAIL2 * 4);
@@ -12254,7 +12734,7 @@ var ClaudeAdapter = class {
12254
12734
  if (preparation) {
12255
12735
  const { binding, control } = preparation;
12256
12736
  const fixed = claudePrewarmOptionsKey(options);
12257
- const parking = join13(runDir, "claude-parking");
12737
+ const parking = join14(runDir, "claude-parking");
12258
12738
  ownDir(parking);
12259
12739
  let anonymousAdopted = false;
12260
12740
  const prepared = prepareClaudeSession({
@@ -12421,8 +12901,8 @@ var ClaudeAdapter = class {
12421
12901
  if (!message.is_error) quota = void 0;
12422
12902
  if (message.is_error && externalAuth && !stderr) {
12423
12903
  let drainTimer;
12424
- await Promise.race([firstStderr, new Promise((resolve19) => {
12425
- drainTimer = setTimeout(resolve19, 100);
12904
+ await Promise.race([firstStderr, new Promise((resolve20) => {
12905
+ drainTimer = setTimeout(resolve20, 100);
12426
12906
  })]);
12427
12907
  clearTimeout(drainTimer);
12428
12908
  }
@@ -12610,7 +13090,7 @@ function codexFailureMessage(phase, info) {
12610
13090
  }
12611
13091
 
12612
13092
  // src/adapters/codex.ts
12613
- import { delimiter as delimiter3, dirname as dirname10, isAbsolute as isAbsolute5, join as join15, relative as relative4 } from "node:path";
13093
+ import { delimiter as delimiter3, dirname as dirname11, isAbsolute as isAbsolute5, join as join16, relative as relative4 } from "node:path";
12614
13094
  import { mkdirSync as mkdirSync10 } from "node:fs";
12615
13095
 
12616
13096
  // src/codex-generation-telemetry.ts
@@ -13030,11 +13510,11 @@ async function startCodexGenerationCollector(emit) {
13030
13510
  server.requestTimeout = 1e3;
13031
13511
  server.headersTimeout = 1e3;
13032
13512
  server.maxConnections = 4;
13033
- await new Promise((resolve19, reject) => {
13513
+ await new Promise((resolve20, reject) => {
13034
13514
  server.once("error", reject);
13035
13515
  server.listen(0, "127.0.0.1", () => {
13036
13516
  server.off("error", reject);
13037
- resolve19();
13517
+ resolve20();
13038
13518
  });
13039
13519
  });
13040
13520
  server.on("error", () => collector.reject());
@@ -13054,7 +13534,7 @@ async function startCodexGenerationCollector(emit) {
13054
13534
  "-c",
13055
13535
  "otel.log_guardian_assessments=false"
13056
13536
  ],
13057
- close: (cliExitObserved = false) => closed ??= new Promise((resolve19) => {
13537
+ close: (cliExitObserved = false) => closed ??= new Promise((resolve20) => {
13058
13538
  const timer = setTimeout(() => {
13059
13539
  collector.truncate();
13060
13540
  server.closeAllConnections();
@@ -13062,7 +13542,7 @@ async function startCodexGenerationCollector(emit) {
13062
13542
  timer.unref();
13063
13543
  server.close(() => {
13064
13544
  clearTimeout(timer);
13065
- resolve19(collector.finish(cliExitObserved));
13545
+ resolve20(collector.finish(cliExitObserved));
13066
13546
  });
13067
13547
  })
13068
13548
  };
@@ -13105,11 +13585,11 @@ var JsonlWriter = class extends AbstractMessageWriter {
13105
13585
  }
13106
13586
  stream;
13107
13587
  write(message) {
13108
- return new Promise((resolve19, reject) => {
13588
+ return new Promise((resolve20, reject) => {
13109
13589
  this.stream.write(
13110
13590
  `${JSON.stringify(message)}
13111
13591
  `,
13112
- (error) => error ? reject(error) : resolve19()
13592
+ (error) => error ? reject(error) : resolve20()
13113
13593
  );
13114
13594
  });
13115
13595
  }
@@ -13125,8 +13605,8 @@ function jsonlConnection(input, output) {
13125
13605
  }
13126
13606
 
13127
13607
  // src/adapters/codex-mailbox.ts
13128
- import { closeSync as closeSync3, constants as constants3, fstatSync as fstatSync2, lstatSync as lstatSync9, mkdirSync as mkdirSync9, openSync as openSync3, readSync } from "node:fs";
13129
- import { isAbsolute as isAbsolute4, join as join14, relative as relative3, sep as sep2 } from "node:path";
13608
+ import { closeSync as closeSync3, constants as constants4, fstatSync as fstatSync2, lstatSync as lstatSync9, mkdirSync as mkdirSync9, openSync as openSync3, readSync as readSync2 } from "node:fs";
13609
+ import { isAbsolute as isAbsolute4, join as join15, relative as relative3, sep as sep2 } from "node:path";
13130
13610
  import { isDeepStrictEqual } from "node:util";
13131
13611
  var unavailable2 = () => new Error("Run mailbox requires a verified original Codex thread");
13132
13612
  function codexMailboxResumeVersion(userAgent) {
@@ -13143,15 +13623,15 @@ function historyParts(value) {
13143
13623
  return parts;
13144
13624
  }
13145
13625
  function receiptFile(stateDir, runId) {
13146
- return join14(stateDir, "codex-mailbox", assertSafeId("run id", runId) + ".json");
13626
+ return join15(stateDir, "codex-mailbox", assertSafeId("run id", runId) + ".json");
13147
13627
  }
13148
13628
  function readJson2(file, limit, firstLine = false) {
13149
- const fd = openSync3(file, constants3.O_RDONLY | constants3.O_NOFOLLOW | constants3.O_NONBLOCK);
13629
+ const fd = openSync3(file, constants4.O_RDONLY | constants4.O_NOFOLLOW | constants4.O_NONBLOCK);
13150
13630
  try {
13151
- const stat2 = fstatSync2(fd);
13152
- if (!stat2.isFile() || stat2.nlink !== 1 || !firstLine && stat2.size > limit) throw unavailable2();
13153
- const buffer = Buffer.alloc(Math.min(stat2.size, limit + 1));
13154
- const length = readSync(fd, buffer, 0, buffer.length, 0);
13631
+ const stat3 = fstatSync2(fd);
13632
+ if (!stat3.isFile() || stat3.nlink !== 1 || !firstLine && stat3.size > limit) throw unavailable2();
13633
+ const buffer = Buffer.alloc(Math.min(stat3.size, limit + 1));
13634
+ const length = readSync2(fd, buffer, 0, buffer.length, 0);
13155
13635
  const end = firstLine ? buffer.subarray(0, length).indexOf(10) : length;
13156
13636
  if (end < 0 || end > limit) throw unavailable2();
13157
13637
  return JSON.parse(buffer.subarray(0, end).toString("utf8"));
@@ -13163,16 +13643,16 @@ function verifyHistory(home, path3, threadId, catalogue) {
13163
13643
  const parts = historyParts(path3);
13164
13644
  let parent = home;
13165
13645
  for (const part of ["", ...parts.slice(0, -1)]) {
13166
- if (part) parent = join14(parent, part);
13167
- const stat2 = lstatSync9(parent);
13168
- if (!stat2.isDirectory() || stat2.isSymbolicLink()) throw unavailable2();
13646
+ if (part) parent = join15(parent, part);
13647
+ const stat3 = lstatSync9(parent);
13648
+ if (!stat3.isDirectory() || stat3.isSymbolicLink()) throw unavailable2();
13169
13649
  }
13170
- const header = readJson2(join14(home, ...parts), 1024 * 1024, true);
13650
+ const header = readJson2(join15(home, ...parts), 1024 * 1024, true);
13171
13651
  if (header?.type !== "session_meta" || header.payload?.id !== threadId || !isDeepStrictEqual(header.payload.dynamic_tools, catalogue)) throw unavailable2();
13172
13652
  }
13173
13653
  function verifyCodexMailboxResume(stateDir, sourceRunId, home, threadId, catalogue) {
13174
13654
  try {
13175
- const dir = lstatSync9(join14(stateDir, "codex-mailbox"));
13655
+ const dir = lstatSync9(join15(stateDir, "codex-mailbox"));
13176
13656
  if (!dir.isDirectory() || dir.isSymbolicLink()) throw unavailable2();
13177
13657
  const receipt = readJson2(receiptFile(stateDir, sourceRunId), 256 * 1024);
13178
13658
  if (receipt?.version !== 1 || receipt.nativeVersion !== "0.163.0" && receipt.nativeVersion !== "0.166.0" && receipt.nativeVersion !== "0.167.0" || receipt.runId !== sourceRunId || receipt.threadId !== threadId || !isDeepStrictEqual(receipt.catalogue, catalogue) || typeof receipt.historyPath !== "string") throw unavailable2();
@@ -13188,10 +13668,10 @@ function recordCodexMailboxSession(stateDir, runId, home, thread, catalogue, res
13188
13668
  const historyPath = relative3(home, thread.path).split(sep2).join("/");
13189
13669
  historyParts(historyPath);
13190
13670
  if (resumed) verifyHistory(home, historyPath, thread.id, catalogue);
13191
- const dir = join14(stateDir, "codex-mailbox");
13671
+ const dir = join15(stateDir, "codex-mailbox");
13192
13672
  mkdirSync9(dir, { recursive: true, mode: 448 });
13193
- const stat2 = lstatSync9(dir);
13194
- if (!stat2.isDirectory() || stat2.isSymbolicLink()) throw unavailable2();
13673
+ const stat3 = lstatSync9(dir);
13674
+ if (!stat3.isDirectory() || stat3.isSymbolicLink()) throw unavailable2();
13195
13675
  writeJsonAtomic(receiptFile(stateDir, runId), { version: 1, nativeVersion, runId, threadId: thread.id, historyPath, catalogue });
13196
13676
  } catch {
13197
13677
  if (resumed) throw unavailable2();
@@ -13452,8 +13932,8 @@ var CodexAdapter = class {
13452
13932
  options.continueSession.runId
13453
13933
  ).runDir;
13454
13934
  carryHistory(
13455
- join15(earlier2, "codex-home"),
13456
- join15(runDir, "codex-home"),
13935
+ join16(earlier2, "codex-home"),
13936
+ join16(runDir, "codex-home"),
13457
13937
  CODEX_HISTORY
13458
13938
  );
13459
13939
  } catch (error) {
@@ -13464,7 +13944,7 @@ var CodexAdapter = class {
13464
13944
  log.info({ err: error }, "could not copy the earlier codex threads");
13465
13945
  }
13466
13946
  }
13467
- const codexHome = options.machineEnvironment ? { home: options.env.CODEX_HOME ?? join15(options.env.HOME, ".codex") } : prepareCodexHome(join15(runDir, "codex-home"), log);
13947
+ const codexHome = options.machineEnvironment ? { home: options.env.CODEX_HOME ?? join16(options.env.HOME, ".codex") } : prepareCodexHome(join16(runDir, "codex-home"), log);
13468
13948
  if (options.machineEnvironment) mkdirSync10(codexHome.home, { recursive: true, mode: 448 });
13469
13949
  const mailboxResumeVersion = mailboxCatalogue && threadId ? verifyCodexMailboxResume(
13470
13950
  this.options.stateDir,
@@ -13475,7 +13955,7 @@ var CodexAdapter = class {
13475
13955
  ) : null;
13476
13956
  const computerMcp = this.options.computerMcp ?? this.options.computerProvider?.(options.runId, options.policy);
13477
13957
  const binary = this.options.binary ?? await this.options.ensureBinary?.() ?? "codex";
13478
- const childPath = isAbsolute5(binary) ? dirname10(binary) + delimiter3 + (options.env.PATH ?? "") : options.env.PATH;
13958
+ const childPath = isAbsolute5(binary) ? dirname11(binary) + delimiter3 + (options.env.PATH ?? "") : options.env.PATH;
13479
13959
  if (externalAuth && options.credential) throw new Error(SUBSCRIPTION_AUTH_ERROR);
13480
13960
  const credential = codexCredential(brokerAuth ? { kind: "provider", protocol: "openai", baseUrl: "https://mikka.invalid", key: NATIVE_AUTH_PLACEHOLDER } : options.credential);
13481
13961
  const providerDomain = credentialDomain(options.credential);
@@ -13651,7 +14131,6 @@ var CodexAdapter = class {
13651
14131
  );
13652
14132
  const queue = new EventQueue();
13653
14133
  const streamed = /* @__PURE__ */ new Set();
13654
- const pending = [];
13655
14134
  let activeTurn = null;
13656
14135
  let pendingTurnStart = null;
13657
14136
  let ending = false;
@@ -13697,11 +14176,6 @@ var CodexAdapter = class {
13697
14176
  ending = true;
13698
14177
  pendingMcp.clear();
13699
14178
  options.toolApproval?.revoke();
13700
- if (pending.length > 0)
13701
- log.warn(
13702
- { dropped: pending.length },
13703
- "session ended with unsent messages"
13704
- );
13705
14179
  rpc.dispose();
13706
14180
  await child.kill();
13707
14181
  if (event) {
@@ -13884,17 +14358,6 @@ var CodexAdapter = class {
13884
14358
  });
13885
14359
  }
13886
14360
  }
13887
- const next = pending.shift();
13888
- if (next) {
13889
- await startTurn(next).catch(
13890
- (error) => finish({
13891
- outcome: "failed",
13892
- error: managedAuth ? turnStartFailure ?? subscriptionFailure("turn_start", codexFailureInfo(error)) : error instanceof ProviderFailureError ? error.message : `Codex: ${errorMessage(error)}`,
13893
- ...error instanceof ProviderFailureError ? { providerFailure: error.providerFailure } : {}
13894
- })
13895
- );
13896
- return;
13897
- }
13898
14361
  if (turn.status === "failed" || lastError) {
13899
14362
  quota = mergeQuota(quota, codexQuotaSignal(turn.error, rateLimits));
13900
14363
  const failure2 = codexFailureInfo(turn.error);
@@ -14081,7 +14544,7 @@ var CodexAdapter = class {
14081
14544
  sessionId,
14082
14545
  runtimeModel,
14083
14546
  events: () => queue.drain(),
14084
- async send(message) {
14547
+ async send(message, mode2) {
14085
14548
  sensitiveText.push(message);
14086
14549
  if (ending) throw new Error("The Codex session already ended");
14087
14550
  if (activeTurn) {
@@ -14092,11 +14555,16 @@ var CodexAdapter = class {
14092
14555
  expectedTurnId: activeTurn
14093
14556
  });
14094
14557
  return;
14095
- } catch {
14558
+ } catch (error) {
14559
+ const failure2 = codexFailureInfo(error);
14560
+ const { category, rpcCode } = failure2;
14561
+ const code = rpcCode === void 0 ? "" : `, RPC ${rpcCode}`;
14562
+ throw new Error(`Codex could not steer the active turn (${category}${code})`, { cause: failure2 });
14096
14563
  }
14097
14564
  }
14098
- if (activeTurn) pending.push(message);
14099
- else await startTurn(message);
14565
+ if (ending) throw new Error("The Codex session already ended");
14566
+ if (mode2 === "steer") throw new Error("The Codex turn is no longer active");
14567
+ await startTurn(message);
14100
14568
  },
14101
14569
  async cancel() {
14102
14570
  cancelling = true;
@@ -14120,7 +14588,7 @@ var CodexAdapter = class {
14120
14588
  // src/adapters/cursor.ts
14121
14589
  import { Readable, Writable } from "node:stream";
14122
14590
  import * as acp from "@agentclientprotocol/sdk";
14123
- import { join as join16 } from "node:path";
14591
+ import { join as join17 } from "node:path";
14124
14592
  function cursorAppServers(apps) {
14125
14593
  return [
14126
14594
  ...(apps?.apps ?? []).map((app) => ({ type: "http", name: app.name, url: app.url, headers: [{ name: "Authorization", value: `Bearer ${apps.token}` }] })),
@@ -14252,15 +14720,15 @@ var CursorAdapter = class {
14252
14720
  options.continueSession.runId
14253
14721
  ).runDir;
14254
14722
  carryHistory(
14255
- join16(earlier2, "cursor-home"),
14256
- join16(paths.runDir, "cursor-home"),
14723
+ join17(earlier2, "cursor-home"),
14724
+ join17(paths.runDir, "cursor-home"),
14257
14725
  CURSOR_HISTORY
14258
14726
  );
14259
14727
  } catch (error) {
14260
14728
  log.info({ err: error }, "could not copy the earlier cursor chats");
14261
14729
  }
14262
14730
  }
14263
- const configDir = prepareCursorHome(join16(paths.runDir, "cursor-home"));
14731
+ const configDir = prepareCursorHome(join17(paths.runDir, "cursor-home"));
14264
14732
  const ctx = new RunContext({
14265
14733
  github: options.github,
14266
14734
  githubEnvironment: options.githubEnvironment,
@@ -14495,7 +14963,7 @@ ${firstMessage}` : firstMessage
14495
14963
  // src/adapters/mock.ts
14496
14964
  import { randomUUID as randomUUID3 } from "node:crypto";
14497
14965
  import { mkdirSync as mkdirSync11, readFileSync as readFileSync9, writeFileSync as writeFileSync5 } from "node:fs";
14498
- import { dirname as dirname11, join as join17, resolve as resolve10 } from "node:path";
14966
+ import { dirname as dirname12, join as join18, resolve as resolve11 } from "node:path";
14499
14967
  import { setTimeout as sleep2 } from "node:timers/promises";
14500
14968
  import { execa as execa5 } from "execa";
14501
14969
 
@@ -14527,7 +14995,7 @@ function isRunChunk(value) {
14527
14995
  }
14528
14996
 
14529
14997
  // src/adapters/mock.ts
14530
- var DEFAULT_FIXTURES_DIR = resolve10(
14998
+ var DEFAULT_FIXTURES_DIR = resolve11(
14531
14999
  import.meta.dirname,
14532
15000
  true ? "./fixtures" : "../../fixtures"
14533
15001
  );
@@ -14561,7 +15029,7 @@ var MockAdapter = class {
14561
15029
  fixturesDir;
14562
15030
  speed;
14563
15031
  stateFile(sessionId) {
14564
- return join17(
15032
+ return join18(
14565
15033
  this.options.stateDir,
14566
15034
  `mock-${assertSafeId("session id", sessionId)}.json`
14567
15035
  );
@@ -14605,7 +15073,7 @@ var MockAdapter = class {
14605
15073
  open(sessionId, state2, options) {
14606
15074
  const name = assertSafeId("fixture", state2.fixture.replace(/\.jsonl$/, ""));
14607
15075
  const lines = parseFixture(
14608
- readFileSync9(join17(this.fixturesDir, `${name}.jsonl`), "utf8"),
15076
+ readFileSync9(join18(this.fixturesDir, `${name}.jsonl`), "utf8"),
14609
15077
  name
14610
15078
  );
14611
15079
  const abort = new AbortController();
@@ -14643,7 +15111,7 @@ var MockAdapter = class {
14643
15111
  if (line.hang) {
14644
15112
  if (!abort.signal.aborted) {
14645
15113
  await new Promise(
14646
- (resolve19) => abort.signal.addEventListener("abort", resolve19, { once: true })
15114
+ (resolve20) => abort.signal.addEventListener("abort", resolve20, { once: true })
14647
15115
  );
14648
15116
  }
14649
15117
  yield { type: "exit", outcome: "cancelled" };
@@ -14655,8 +15123,8 @@ var MockAdapter = class {
14655
15123
  `mock fixture writes outside the worktree: ${line.write.path}`
14656
15124
  );
14657
15125
  }
14658
- const target = resolve10(options.cwd, line.write.path);
14659
- mkdirSync11(dirname11(target), { recursive: true });
15126
+ const target = resolve11(options.cwd, line.write.path);
15127
+ mkdirSync11(dirname12(target), { recursive: true });
14660
15128
  writeFileSync5(target, line.write.content);
14661
15129
  }
14662
15130
  if (line.chunk) yield { type: "chunk", chunk: line.chunk };
@@ -14718,14 +15186,14 @@ var MockAdapter = class {
14718
15186
  };
14719
15187
 
14720
15188
  // src/agents/local-github.ts
14721
- import { mkdirSync as mkdirSync13, mkdtempSync as mkdtempSync3, rmSync as rmSync10, writeFileSync as writeFileSync7 } from "node:fs";
15189
+ import { mkdirSync as mkdirSync13, mkdtempSync as mkdtempSync4, rmSync as rmSync10, writeFileSync as writeFileSync7 } from "node:fs";
14722
15190
  import { homedir as homedir5 } from "node:os";
14723
- import { delimiter as delimiter4, join as join19 } from "node:path";
15191
+ import { delimiter as delimiter4, join as join20 } from "node:path";
14724
15192
 
14725
15193
  // src/agents/machine-github.ts
14726
15194
  import { existsSync as existsSync4, mkdirSync as mkdirSync12, readFileSync as readFileSync10, renameSync as renameSync3, rmSync as rmSync9, writeFileSync as writeFileSync6 } from "node:fs";
14727
15195
  import { randomUUID as randomUUID4 } from "node:crypto";
14728
- import { dirname as dirname12, join as join18 } from "node:path";
15196
+ import { dirname as dirname13, join as join19 } from "node:path";
14729
15197
  function githubHosts(contents, token) {
14730
15198
  if (!token || /[\r\n\0]/.test(token) || token.length > 32768) throw Error("github_credential_invalid");
14731
15199
  const lines = contents.split(/\r?\n/);
@@ -14750,8 +15218,8 @@ function prepareMachineGitHub(github, host) {
14750
15218
  if (!github.token) throw Error("github_credential_missing");
14751
15219
  const home = host.env.HOME;
14752
15220
  if (!home) throw Error("github_home_missing");
14753
- const directory = host.env.GH_CONFIG_DIR ?? join18(host.env.XDG_CONFIG_HOME ?? join18(home, ".config"), "gh");
14754
- const file = join18(directory, "hosts.yml");
15221
+ const directory = host.env.GH_CONFIG_DIR ?? join19(host.env.XDG_CONFIG_HOME ?? join19(home, ".config"), "gh");
15222
+ const file = join19(directory, "hosts.yml");
14755
15223
  const original = existsSync4(file) ? readFileSync10(file, "utf8") : void 0;
14756
15224
  let written;
14757
15225
  let closed = false;
@@ -14765,7 +15233,7 @@ function prepareMachineGitHub(github, host) {
14765
15233
  host.onCredential?.("GITHUB_TOKEN", credential.token);
14766
15234
  const latest = existsSync4(file) ? readFileSync10(file, "utf8") : "";
14767
15235
  const next = githubHosts(latest, credential.token);
14768
- mkdirSync12(dirname12(file), { recursive: true, mode: 448 });
15236
+ mkdirSync12(dirname13(file), { recursive: true, mode: 448 });
14769
15237
  const temporary = `${file}.${randomUUID4()}`;
14770
15238
  writeFileSync6(temporary, next, { mode: 384, flag: "wx" });
14771
15239
  renameSync3(temporary, file);
@@ -14851,14 +15319,14 @@ async function prepareLocalGitHub(assignment, host) {
14851
15319
  const credential = assignment.github.token ? { token: assignment.github.token, expiresAt: assignment.github.expiresAt ?? null } : await lease();
14852
15320
  if (host.signal.aborted) throw Error("github_run_closed");
14853
15321
  mkdirSync13(host.stateDir, { recursive: true, mode: 448 });
14854
- const directory = mkdtempSync3(join19(host.stateDir, "github-"));
15322
+ const directory = mkdtempSync4(join20(host.stateDir, "github-"));
14855
15323
  try {
14856
- const bin = join19(directory, "bin");
15324
+ const bin = join20(directory, "bin");
14857
15325
  const quote2 = (value) => `'${value.replaceAll("'", "'\\''")}'`;
14858
15326
  const helper2 = `${process.versions.electron ? "env ELECTRON_RUN_AS_NODE=1 " : ""}${quote2(process.execPath)} ${quote2(GITHUB_CREDENTIAL_SCRIPT)}`;
14859
15327
  if (binary) {
14860
15328
  mkdirSync13(bin, { mode: 448 });
14861
- writeFileSync7(join19(bin, "gh"), `#!/bin/sh
15329
+ writeFileSync7(join20(bin, "gh"), `#!/bin/sh
14862
15330
  exec ${helper2} native-gh ${quote2(binary)} ${quote2(directory)} "$@"
14863
15331
  `, { mode: 448, flag: "wx" });
14864
15332
  }
@@ -14898,18 +15366,18 @@ exec ${helper2} native-gh ${quote2(binary)} ${quote2(directory)} "$@"
14898
15366
  }
14899
15367
 
14900
15368
  // src/agents/verify.ts
14901
- import { existsSync as existsSync5, mkdirSync as mkdirSync14, mkdtempSync as mkdtempSync4, realpathSync as realpathSync11, rmSync as rmSync11 } from "node:fs";
14902
- import { join as join20 } from "node:path";
15369
+ import { existsSync as existsSync5, mkdirSync as mkdirSync14, mkdtempSync as mkdtempSync5, realpathSync as realpathSync11, rmSync as rmSync11 } from "node:fs";
15370
+ import { join as join21 } from "node:path";
14903
15371
  var OUTPUT_TAIL = 4e3;
14904
15372
  var SETUP_ATTEMPTS = 3;
14905
15373
  async function runVerify(sandbox, options) {
14906
15374
  options.signal?.throwIfAborted();
14907
15375
  mkdirSync14(options.tmpRoot, { recursive: true, mode: 448 });
14908
- const tmpDir = mkdtempSync4(join20(realpathSync11(options.tmpRoot), "verify-"));
15376
+ const tmpDir = mkdtempSync5(join21(realpathSync11(options.tmpRoot), "verify-"));
14909
15377
  const deadline = Date.now() + options.timeoutMs;
14910
15378
  try {
14911
15379
  for (let attempt = 1; ; attempt++) {
14912
- const started = join20(tmpDir, `.started-${attempt}`);
15380
+ const started = join21(tmpDir, `.started-${attempt}`);
14913
15381
  const result = await attemptVerify(sandbox, options, tmpDir, started, deadline - Date.now());
14914
15382
  if (result.exitCode === 0 || result.timedOut || options.signal?.aborted || existsSync5(started) || attempt >= SETUP_ATTEMPTS)
14915
15383
  return result;
@@ -14928,7 +15396,7 @@ async function attemptVerify(sandbox, options, tmpDir, started, timeoutMs) {
14928
15396
  policy: {
14929
15397
  allowWrite: options.readOnly ? [tmpDir] : [options.worktree, tmpDir],
14930
15398
  denyWrite: [
14931
- join20(options.worktree, ".git"),
15399
+ join21(options.worktree, ".git"),
14932
15400
  ...options.readOnly ? [options.worktree] : []
14933
15401
  ],
14934
15402
  denyRead: [
@@ -14998,12 +15466,12 @@ var NoSandbox = class {
14998
15466
  };
14999
15467
 
15000
15468
  // src/fs-browse.ts
15001
- import { execFile as execFile3 } from "node:child_process";
15002
- import { readdir as readdir2, realpath, stat } from "node:fs/promises";
15469
+ import { execFile as execFile4 } from "node:child_process";
15470
+ import { readdir as readdir2, realpath, stat as stat2 } from "node:fs/promises";
15003
15471
  import { homedir as homedir6, platform as platform2 } from "node:os";
15004
- import { basename as basename4, dirname as dirname13, isAbsolute as isAbsolute6, join as join21, resolve as resolve11 } from "node:path";
15005
- import { promisify as promisify3 } from "node:util";
15006
- var run = promisify3(execFile3);
15472
+ import { basename as basename5, dirname as dirname14, isAbsolute as isAbsolute6, join as join22, resolve as resolve12 } from "node:path";
15473
+ import { promisify as promisify4 } from "node:util";
15474
+ var run = promisify4(execFile4);
15007
15475
  async function git(cwd, args) {
15008
15476
  try {
15009
15477
  const { stdout } = await run("git", ["-C", cwd, ...args], {
@@ -15017,14 +15485,14 @@ async function git(cwd, args) {
15017
15485
  }
15018
15486
  async function isDir(path3) {
15019
15487
  try {
15020
- return (await stat(path3)).isDirectory();
15488
+ return (await stat2(path3)).isDirectory();
15021
15489
  } catch {
15022
15490
  return false;
15023
15491
  }
15024
15492
  }
15025
15493
  async function exists(path3) {
15026
15494
  try {
15027
- await stat(path3);
15495
+ await stat2(path3);
15028
15496
  return true;
15029
15497
  } catch {
15030
15498
  return false;
@@ -15047,7 +15515,7 @@ async function browseFolder(request2) {
15047
15515
  code: "not_found",
15048
15516
  message: "Expected an absolute path."
15049
15517
  };
15050
- const path3 = resolve11(wanted);
15518
+ const path3 = resolve12(wanted);
15051
15519
  if (!await exists(path3))
15052
15520
  return { ok: false, code: "not_found", message: `${path3} does not exist.` };
15053
15521
  if (!await isDir(path3))
@@ -15071,7 +15539,7 @@ async function browseFolder(request2) {
15071
15539
  let truncated = false;
15072
15540
  const dirs = names.filter((e) => e.isDirectory() || e.isSymbolicLink()).filter((e) => request2.showHidden || !e.name.startsWith(".")).sort((a, b) => a.name.localeCompare(b.name));
15073
15541
  for (const entry of dirs) {
15074
- const full = join21(path3, entry.name);
15542
+ const full = join22(path3, entry.name);
15075
15543
  if (entry.isSymbolicLink() && !await isDir(full)) continue;
15076
15544
  if (folders.length >= FS_MAX_ENTRIES) {
15077
15545
  truncated = true;
@@ -15080,14 +15548,14 @@ async function browseFolder(request2) {
15080
15548
  folders.push({
15081
15549
  name: entry.name,
15082
15550
  path: full,
15083
- isRepo: await exists(join21(full, ".git"))
15551
+ isRepo: await exists(join22(full, ".git"))
15084
15552
  });
15085
15553
  }
15086
- const parent = dirname13(path3);
15554
+ const parent = dirname14(path3);
15087
15555
  return {
15088
15556
  ok: true,
15089
15557
  path: path3,
15090
- parent: parent === path3 || basename4(path3) === "" ? null : parent,
15558
+ parent: parent === path3 || basename5(path3) === "" ? null : parent,
15091
15559
  home,
15092
15560
  platform: platform2(),
15093
15561
  entries: folders,
@@ -15108,7 +15576,7 @@ async function verifyExpectedOrigin(path3, expected2) {
15108
15576
  }
15109
15577
 
15110
15578
  // src/device-type.ts
15111
- import { readdir as readdir3, readFile as readFile2 } from "node:fs/promises";
15579
+ import { readdir as readdir3, readFile as readFile3 } from "node:fs/promises";
15112
15580
  import { execa as execa6 } from "execa";
15113
15581
  async function detectDeviceType() {
15114
15582
  try {
@@ -15124,7 +15592,7 @@ async function detectDeviceType() {
15124
15592
  const entries = await readdir3("/sys/class/power_supply");
15125
15593
  const types = await Promise.all(
15126
15594
  entries.map(
15127
- (entry) => readFile2(`/sys/class/power_supply/${entry}/type`, "utf8").catch(
15595
+ (entry) => readFile3(`/sys/class/power_supply/${entry}/type`, "utf8").catch(
15128
15596
  () => ""
15129
15597
  )
15130
15598
  )
@@ -15142,13 +15610,13 @@ import { arch, platform as platform3 } from "node:os";
15142
15610
  import { execa as execa7 } from "execa";
15143
15611
 
15144
15612
  // harness/install.mjs
15145
- import { createHash as createHash7, randomBytes as randomBytes2 } from "node:crypto";
15146
- import { execFile as execFile4 } from "node:child_process";
15147
- import { createWriteStream, existsSync as existsSync6, mkdirSync as mkdirSync15, readdirSync as readdirSync5, readFileSync as readFileSync11, renameSync as renameSync4, rmSync as rmSync12, statSync as statSync2, symlinkSync, writeFileSync as writeFileSync8 } from "node:fs";
15148
- import { dirname as dirname14, join as join22, relative as relative5 } from "node:path";
15613
+ import { createHash as createHash8, randomBytes as randomBytes2 } from "node:crypto";
15614
+ import { execFile as execFile5 } from "node:child_process";
15615
+ import { createWriteStream as createWriteStream2, existsSync as existsSync6, mkdirSync as mkdirSync15, readdirSync as readdirSync5, readFileSync as readFileSync11, renameSync as renameSync4, rmSync as rmSync12, statSync as statSync2, symlinkSync, writeFileSync as writeFileSync8 } from "node:fs";
15616
+ import { dirname as dirname15, join as join23, relative as relative5 } from "node:path";
15149
15617
  import { Readable as Readable2, Transform } from "node:stream";
15150
- import { pipeline } from "node:stream/promises";
15151
- import { promisify as promisify4 } from "node:util";
15618
+ import { pipeline as pipeline2 } from "node:stream/promises";
15619
+ import { promisify as promisify5 } from "node:util";
15152
15620
 
15153
15621
  // harness/pins.json
15154
15622
  var pins_default = {
@@ -15184,7 +15652,7 @@ var HARNESS_PINS = pins_default;
15184
15652
  var MARKER = ".mikka-installed";
15185
15653
  var INSTALL_FORMAT = "complete-package-v1\n";
15186
15654
  var installMarker = (pin, artifact) => INSTALL_FORMAT + artifact.integrity + (pin.companions?.length ? "\n" + pin.companions.join("\n") : "");
15187
- var run2 = promisify4(execFile4);
15655
+ var run2 = promisify5(execFile5);
15188
15656
  var inflight = /* @__PURE__ */ new Map();
15189
15657
  function platformKey(platform5 = process.platform, arch3 = process.arch) {
15190
15658
  return `${platform5}-${arch3}`;
@@ -15194,19 +15662,19 @@ function resolvePin(store, harness) {
15194
15662
  return { pin, artifact: pin.platforms[store.platform ?? platformKey()] };
15195
15663
  }
15196
15664
  function versionDir(store, harness) {
15197
- return join22(store.root, harness, resolvePin(store, harness).pin.version);
15665
+ return join23(store.root, harness, resolvePin(store, harness).pin.version);
15198
15666
  }
15199
15667
  function harnessBinaryPath(store, harness) {
15200
- return join22(versionDir(store, harness), "bin", resolvePin(store, harness).pin.command);
15668
+ return join23(versionDir(store, harness), "bin", resolvePin(store, harness).pin.command);
15201
15669
  }
15202
15670
  function harnessInstallState(store, harness) {
15203
15671
  const { pin, artifact } = resolvePin(store, harness);
15204
15672
  if (!artifact) return { state: "unsupported", version: pin.version };
15205
15673
  let installed = false;
15206
15674
  try {
15207
- installed = readFileSync11(join22(versionDir(store, harness), MARKER), "utf8") === installMarker(pin, artifact) && runtimeFiles(store, harness).every((path3) => {
15208
- const stat2 = statSync2(path3);
15209
- return stat2.isFile() && (stat2.mode & 73) !== 0;
15675
+ installed = readFileSync11(join23(versionDir(store, harness), MARKER), "utf8") === installMarker(pin, artifact) && runtimeFiles(store, harness).every((path3) => {
15676
+ const stat3 = statSync2(path3);
15677
+ return stat3.isFile() && (stat3.mode & 73) !== 0;
15210
15678
  });
15211
15679
  } catch {
15212
15680
  }
@@ -15214,7 +15682,7 @@ function harnessInstallState(store, harness) {
15214
15682
  }
15215
15683
  function runtimeFiles(store, harness) {
15216
15684
  const binary = harnessBinaryPath(store, harness);
15217
- return harness === "codex" ? [binary, join22(dirname14(binary), "codex-code-mode-host")] : [binary];
15685
+ return harness === "codex" ? [binary, join23(dirname15(binary), "codex-code-mode-host")] : [binary];
15218
15686
  }
15219
15687
  function ensureHarness(store, harness) {
15220
15688
  const key2 = `${store.root}\0${harness}`;
@@ -15231,27 +15699,27 @@ async function install(store, harness) {
15231
15699
  if (state2 === "unsupported") throw new Error(`${harness} has no build for ${store.platform ?? platformKey()}`);
15232
15700
  if (state2 === "installed") return binary;
15233
15701
  const { pin, artifact } = resolvePin(store, harness);
15234
- const parent = join22(store.root, harness);
15702
+ const parent = join23(store.root, harness);
15235
15703
  mkdirSync15(parent, { recursive: true, mode: 448 });
15236
- const staging = join22(parent, `.staging-${randomBytes2(6).toString("hex")}`);
15704
+ const staging = join23(parent, `.staging-${randomBytes2(6).toString("hex")}`);
15237
15705
  mkdirSync15(staging, { recursive: true, mode: 448 });
15238
15706
  try {
15239
- const tarball = join22(staging, "package.tgz");
15707
+ const tarball = join23(staging, "package.tgz");
15240
15708
  await download(`${(store.pins ?? HARNESS_PINS).registry.replace(/\/$/, "")}/${artifact.tarball}`, tarball, artifact.integrity);
15241
15709
  await run2("tar", ["-xzf", tarball, "-C", staging]);
15242
15710
  if (harness === "codex") {
15243
15711
  if (!artifact.entry.endsWith("/bin/codex")) throw new Error("Invalid Codex bundle entry");
15244
- const bundle = dirname14(dirname14(artifact.entry));
15245
- for (const name of readdirSync5(join22(staging, bundle))) symlinkSync(relative5(staging, join22(staging, bundle, name)), join22(staging, name));
15712
+ const bundle = dirname15(dirname15(artifact.entry));
15713
+ for (const name of readdirSync5(join23(staging, bundle))) symlinkSync(relative5(staging, join23(staging, bundle, name)), join23(staging, name));
15246
15714
  for (const name of ["codex", "codex-code-mode-host"]) {
15247
- const stat2 = statSync2(join22(staging, "bin", name));
15248
- if (!stat2.isFile() || (stat2.mode & 73) === 0) throw new Error("Incomplete Codex runtime bundle");
15715
+ const stat3 = statSync2(join23(staging, "bin", name));
15716
+ if (!stat3.isFile() || (stat3.mode & 73) === 0) throw new Error("Incomplete Codex runtime bundle");
15249
15717
  }
15250
15718
  } else {
15251
- mkdirSync15(join22(staging, "bin"), { mode: 448 });
15252
- symlinkSync(relative5(join22(staging, "bin"), join22(staging, artifact.entry)), join22(staging, "bin", pin.command));
15719
+ mkdirSync15(join23(staging, "bin"), { mode: 448 });
15720
+ symlinkSync(relative5(join23(staging, "bin"), join23(staging, artifact.entry)), join23(staging, "bin", pin.command));
15253
15721
  }
15254
- writeFileSync8(join22(staging, MARKER), installMarker(pin, artifact), { mode: 384 });
15722
+ writeFileSync8(join23(staging, MARKER), installMarker(pin, artifact), { mode: 384 });
15255
15723
  const target = versionDir(store, harness);
15256
15724
  const retained = existsSync6(target) ? `${target}.retained-${randomBytes2(6).toString("hex")}` : null;
15257
15725
  if (retained) renameSync4(target, retained);
@@ -15272,12 +15740,12 @@ async function download(url, file, integrity) {
15272
15740
  if (algorithm !== "sha512" || !expected2) throw new Error("Unsupported harness integrity");
15273
15741
  const response = await fetch(url, { redirect: "follow" });
15274
15742
  if (!response.ok || !response.body) throw new Error(`Harness download failed (${response.status})`);
15275
- const hash2 = createHash7("sha512");
15743
+ const hash2 = createHash8("sha512");
15276
15744
  const tap = new Transform({ transform(chunk, _encoding, done) {
15277
15745
  hash2.update(chunk);
15278
15746
  done(null, chunk);
15279
15747
  } });
15280
- await pipeline(Readable2.fromWeb(response.body), tap, createWriteStream(file, { mode: 384 }));
15748
+ await pipeline2(Readable2.fromWeb(response.body), tap, createWriteStream2(file, { mode: 384 }));
15281
15749
  if (hash2.digest("base64") !== expected2) throw new Error("Harness download failed its integrity check");
15282
15750
  }
15283
15751
  function managedHarnessReport(store) {
@@ -15332,8 +15800,8 @@ function harnessFingerprint(store) {
15332
15800
 
15333
15801
  // src/model-probe.ts
15334
15802
  import { spawn as spawn3 } from "node:child_process";
15335
- import { mkdtempSync as mkdtempSync5, readdirSync as readdirSync6, rmSync as rmSync13 } from "node:fs";
15336
- import { join as join23 } from "node:path";
15803
+ import { mkdtempSync as mkdtempSync6, readdirSync as readdirSync6, rmSync as rmSync13 } from "node:fs";
15804
+ import { join as join24 } from "node:path";
15337
15805
 
15338
15806
  // src/process-group.ts
15339
15807
  async function stopGroup(child, graceMs = 3e3) {
@@ -15353,12 +15821,12 @@ async function stopGroup(child, graceMs = 3e3) {
15353
15821
  };
15354
15822
  if (child.exitCode === null && child.signalCode === null) {
15355
15823
  signal("SIGTERM");
15356
- await new Promise((resolve19) => {
15357
- if (child.exitCode !== null || child.signalCode !== null) return resolve19();
15824
+ await new Promise((resolve20) => {
15825
+ if (child.exitCode !== null || child.signalCode !== null) return resolve20();
15358
15826
  const done = () => {
15359
15827
  clearTimeout(timer);
15360
15828
  child.off("exit", done);
15361
- resolve19();
15829
+ resolve20();
15362
15830
  };
15363
15831
  const timer = setTimeout(done, graceMs);
15364
15832
  child.once("exit", done);
@@ -15413,10 +15881,10 @@ function sweepModelProbeHomes(scratchDir) {
15413
15881
  } catch {
15414
15882
  return;
15415
15883
  }
15416
- for (const name of names) if (name.startsWith(HOME_PREFIX)) rmSync13(join23(scratchDir, name), { recursive: true, force: true });
15884
+ for (const name of names) if (name.startsWith(HOME_PREFIX)) rmSync13(join24(scratchDir, name), { recursive: true, force: true });
15417
15885
  }
15418
15886
  async function probeHarnessModels(harness, binary, options) {
15419
- const home = mkdtempSync5(join23(options.scratchDir, HOME_PREFIX));
15887
+ const home = mkdtempSync6(join24(options.scratchDir, HOME_PREFIX));
15420
15888
  try {
15421
15889
  return await exchange(harness, binary, home, options);
15422
15890
  } finally {
@@ -15425,15 +15893,15 @@ async function probeHarnessModels(harness, binary, options) {
15425
15893
  }
15426
15894
  function exchange(harness, binary, home, options) {
15427
15895
  const args = harness === "codex" ? ["app-server"] : ["-p", "--input-format", "stream-json", "--output-format", "stream-json", "--verbose"];
15428
- const env = { PATH: process.env.PATH ?? "", HOME: home, CODEX_HOME: home, CLAUDE_CONFIG_DIR: join23(home, ".claude"), LANG: process.env.LANG ?? "C.UTF-8" };
15429
- return new Promise((resolve19) => {
15896
+ const env = { PATH: process.env.PATH ?? "", HOME: home, CODEX_HOME: home, CLAUDE_CONFIG_DIR: join24(home, ".claude"), LANG: process.env.LANG ?? "C.UTF-8" };
15897
+ return new Promise((resolve20) => {
15430
15898
  const child = (options.spawnImpl ?? spawn3)(binary, args, { env, cwd: home, detached: process.platform !== "win32", stdio: ["pipe", "pipe", "ignore"] });
15431
15899
  let result;
15432
15900
  let stopping;
15433
15901
  const stop = () => stopping ??= Promise.resolve().then(() => stopGroup(child, 0));
15434
15902
  const done = () => {
15435
15903
  clearTimeout(timer);
15436
- resolve19(result ?? null);
15904
+ resolve20(result ?? null);
15437
15905
  };
15438
15906
  const finish = (value) => {
15439
15907
  if (result !== void 0) return;
@@ -15495,22 +15963,22 @@ function exchange(harness, binary, home, options) {
15495
15963
  }
15496
15964
 
15497
15965
  // src/cloud-registration.ts
15498
- import { createHash as createHash8 } from "node:crypto";
15499
- import { join as join24 } from "node:path";
15966
+ import { createHash as createHash9 } from "node:crypto";
15967
+ import { join as join25 } from "node:path";
15500
15968
  function writeCloudRegistration(dataDir, deviceId, workspaceId, credential) {
15501
- writeJsonAtomic(join24(dataDir, "registration.json"), {
15969
+ writeJsonAtomic(join25(dataDir, "registration.json"), {
15502
15970
  version: 1,
15503
15971
  deviceId,
15504
15972
  workspaceId,
15505
- tokenSha256: createHash8("sha256").update(credential).digest("hex")
15973
+ tokenSha256: createHash9("sha256").update(credential).digest("hex")
15506
15974
  });
15507
15975
  }
15508
15976
 
15509
15977
  // src/cloud-model-probe.ts
15510
- import { mkdtempSync as mkdtempSync6, rmSync as rmSync14, statSync as statSync3 } from "node:fs";
15978
+ import { mkdtempSync as mkdtempSync7, rmSync as rmSync14, statSync as statSync3 } from "node:fs";
15511
15979
 
15512
15980
  // src/hosted-binaries.ts
15513
- import { accessSync as accessSync2, constants as constants4, lstatSync as lstatSync10, readFileSync as readFileSync12, realpathSync as realpathSync12 } from "node:fs";
15981
+ import { accessSync as accessSync2, constants as constants5, lstatSync as lstatSync10, readFileSync as readFileSync12, realpathSync as realpathSync12 } from "node:fs";
15514
15982
  import { delimiter as delimiter5, isAbsolute as isAbsolute7 } from "node:path";
15515
15983
  import { z as z37 } from "zod";
15516
15984
  var HOSTED_CLI_MANIFEST = "/opt/mikka/worker/.mikka-original-cli.json";
@@ -15552,7 +16020,7 @@ function executable(path3) {
15552
16020
  if (!path3) return void 0;
15553
16021
  try {
15554
16022
  const resolved = realpathSync12(path3);
15555
- accessSync2(resolved, constants4.X_OK);
16023
+ accessSync2(resolved, constants5.X_OK);
15556
16024
  return lstatSync10(resolved).isFile() ? resolved : void 0;
15557
16025
  } catch {
15558
16026
  return void 0;
@@ -15705,10 +16173,10 @@ async function prepareSubscriptionCredentials(assignment, host) {
15705
16173
 
15706
16174
  // src/run-scratch.ts
15707
16175
  import { rmSync as rmSync15 } from "node:fs";
15708
- import { join as join25 } from "node:path";
16176
+ import { join as join26 } from "node:path";
15709
16177
  function removeRunCredentials(stateDir, runId) {
15710
16178
  const { runDir } = runPaths(stateDir, runId);
15711
- for (const path3 of RUN_CREDENTIAL_PATHS) rmSync15(join25(runDir, path3), { recursive: true, force: true });
16179
+ for (const path3 of RUN_CREDENTIAL_PATHS) rmSync15(join26(runDir, path3), { recursive: true, force: true });
15712
16180
  }
15713
16181
 
15714
16182
  // src/subscription-local-runner.ts
@@ -15784,7 +16252,7 @@ function createLocalSubscriptionRunner(host) {
15784
16252
  finish();
15785
16253
  }
15786
16254
  },
15787
- send: (text4) => session.send(text4),
16255
+ send: (text4, mode) => session.send(text4, mode),
15788
16256
  cancel: async () => {
15789
16257
  try {
15790
16258
  await session.cancel();
@@ -15806,8 +16274,8 @@ function createLocalSubscriptionRunner(host) {
15806
16274
  }
15807
16275
 
15808
16276
  // src/subscription-preflight.ts
15809
- import { mkdtempSync as mkdtempSync7, rmSync as rmSync16 } from "node:fs";
15810
- import { join as join26 } from "node:path";
16277
+ import { mkdtempSync as mkdtempSync8, rmSync as rmSync16 } from "node:fs";
16278
+ import { join as join27 } from "node:path";
15811
16279
  import { execa as execa8 } from "execa";
15812
16280
  var refused = (detail, cause) => ({
15813
16281
  ready: false,
@@ -15826,7 +16294,7 @@ async function preflightLocalSubscription(harness, options) {
15826
16294
  const expected2 = (options.store.pins ?? HARNESS_PINS).harnesses[harness].version;
15827
16295
  let home;
15828
16296
  try {
15829
- home = mkdtempSync7(join26(options.scratchDir, "subscription-preflight-"));
16297
+ home = mkdtempSync8(join27(options.scratchDir, "subscription-preflight-"));
15830
16298
  const result = await execa8(binary, ["--version"], {
15831
16299
  env: { ...env, HOME: home },
15832
16300
  extendEnv: false,
@@ -15890,8 +16358,8 @@ async function acquireCloudWorkspaceControl(input, root = CLOUD_WORKSPACE_CONTRO
15890
16358
  });
15891
16359
  let acquired = false, releasing = false, settled = false, output = "";
15892
16360
  let finished;
15893
- const done = new Promise((resolve19) => {
15894
- finished = resolve19;
16361
+ const done = new Promise((resolve20) => {
16362
+ finished = resolve20;
15895
16363
  });
15896
16364
  child.stdin.on("error", () => {
15897
16365
  if (!settled && !releasing) child.kill("SIGTERM");
@@ -15904,7 +16372,7 @@ async function acquireCloudWorkspaceControl(input, root = CLOUD_WORKSPACE_CONTRO
15904
16372
  if (!acquired || settled || releasing || !child.stdin.writable) throw new CodedError("terminal_control_unavailable", { detail: "fence_lost" });
15905
16373
  child.stdin.write(JSON.stringify(value) + "\n");
15906
16374
  };
15907
- await new Promise((resolve19, reject) => {
16375
+ await new Promise((resolve20, reject) => {
15908
16376
  const fail = (cause) => reject(new CodedError("terminal_control_unavailable", { detail: "fence_unavailable", cause }));
15909
16377
  child.once("error", fail);
15910
16378
  child.stdout.on("data", (data) => {
@@ -15919,7 +16387,7 @@ async function acquireCloudWorkspaceControl(input, root = CLOUD_WORKSPACE_CONTRO
15919
16387
  fail(input.signal.reason);
15920
16388
  return;
15921
16389
  }
15922
- resolve19();
16390
+ resolve20();
15923
16391
  } else if (output.length > 32) {
15924
16392
  child.kill("SIGTERM");
15925
16393
  fail();
@@ -15959,7 +16427,7 @@ import {
15959
16427
  rmSync as rmSync17,
15960
16428
  truncateSync
15961
16429
  } from "node:fs";
15962
- import { join as join27 } from "node:path";
16430
+ import { join as join28 } from "node:path";
15963
16431
  var Outbox = class {
15964
16432
  constructor(dir, link, log, retryMs = 1e3, onUndeliverable = () => void 0, retainResources = false, traceContext = () => void 0) {
15965
16433
  this.dir = dir;
@@ -15984,10 +16452,10 @@ var Outbox = class {
15984
16452
  /** Runs whose file was checked for a torn tail since this process started. */
15985
16453
  repaired = /* @__PURE__ */ new Set();
15986
16454
  file(runId) {
15987
- return join27(this.dir, `${assertSafeId("run id", runId)}.jsonl`);
16455
+ return join28(this.dir, `${assertSafeId("run id", runId)}.jsonl`);
15988
16456
  }
15989
16457
  ackFile(runId) {
15990
- return join27(this.dir, `${assertSafeId("run id", runId)}.ack.json`);
16458
+ return join28(this.dir, `${assertSafeId("run id", runId)}.ack.json`);
15991
16459
  }
15992
16460
  parse(runId) {
15993
16461
  let data;
@@ -16173,11 +16641,11 @@ var Outbox = class {
16173
16641
  };
16174
16642
 
16175
16643
  // src/quota/files.ts
16176
- import { execFile as execFile5 } from "node:child_process";
16177
- import { constants as constants5 } from "node:fs";
16178
- import { promisify as promisify5 } from "node:util";
16179
- var NOFOLLOW = constants5.O_NOFOLLOW ?? 0;
16180
- var execFileAsync = promisify5(execFile5);
16644
+ import { execFile as execFile6 } from "node:child_process";
16645
+ import { constants as constants6 } from "node:fs";
16646
+ import { promisify as promisify6 } from "node:util";
16647
+ var NOFOLLOW = constants6.O_NOFOLLOW ?? 0;
16648
+ var execFileAsync = promisify6(execFile6);
16181
16649
  var MAX_CREDENTIAL_BYTES = 64 * 1024;
16182
16650
  function sanitizeError(error) {
16183
16651
  const raw = error instanceof Error ? error.message : String(error);
@@ -16337,9 +16805,9 @@ var RpcServer = class {
16337
16805
  const { socketPath } = this.options;
16338
16806
  rmSync18(socketPath, { force: true });
16339
16807
  const server = createServer2((socket) => this.accept(socket));
16340
- await new Promise((resolve19, reject) => {
16808
+ await new Promise((resolve20, reject) => {
16341
16809
  server.once("error", reject);
16342
- server.listen(socketPath, () => resolve19());
16810
+ server.listen(socketPath, () => resolve20());
16343
16811
  });
16344
16812
  chmodSync(socketPath, 384);
16345
16813
  this.server = server;
@@ -16403,9 +16871,9 @@ var RpcServer = class {
16403
16871
  }
16404
16872
  async close() {
16405
16873
  for (const socket of this.sockets) socket.destroy();
16406
- await new Promise((resolve19) => {
16407
- if (!this.server) return resolve19();
16408
- this.server.close(() => resolve19());
16874
+ await new Promise((resolve20) => {
16875
+ if (!this.server) return resolve20();
16876
+ this.server.close(() => resolve20());
16409
16877
  });
16410
16878
  this.server = null;
16411
16879
  rmSync18(this.options.socketPath, { force: true });
@@ -16633,7 +17101,7 @@ async function startTaskSecretBridge(options) {
16633
17101
  };
16634
17102
  options.signal.addEventListener("abort", close, { once: true });
16635
17103
  try {
16636
- await new Promise((resolve19, reject) => {
17104
+ await new Promise((resolve20, reject) => {
16637
17105
  const cleanup = () => {
16638
17106
  server.off("error", failed);
16639
17107
  options.signal.removeEventListener("abort", cancelled);
@@ -16654,7 +17122,7 @@ async function startTaskSecretBridge(options) {
16654
17122
  }
16655
17123
  server.listen(0, "127.0.0.1", () => {
16656
17124
  cleanup();
16657
- resolve19();
17125
+ resolve20();
16658
17126
  });
16659
17127
  });
16660
17128
  options.signal.throwIfAborted();
@@ -16683,37 +17151,37 @@ async function startTaskSecretBridge(options) {
16683
17151
  }
16684
17152
 
16685
17153
  // src/agents/chat-files.ts
16686
- import { createHash as createHash9 } from "node:crypto";
16687
- import { lstat as lstat2, mkdir as mkdir2, readFile as readFile3, writeFile as writeFile2 } from "node:fs/promises";
16688
- import { join as join28 } from "node:path";
17154
+ import { createHash as createHash10 } from "node:crypto";
17155
+ import { lstat as lstat3, mkdir as mkdir3, readFile as readFile4, writeFile as writeFile2 } from "node:fs/promises";
17156
+ import { join as join29 } from "node:path";
16689
17157
  async function materializeChatFiles(text4, directory, download2) {
16690
17158
  const parsed = splitChatFiles(text4);
16691
17159
  if (!parsed.files.length) return text4;
16692
- await mkdir2(directory, { recursive: true, mode: 448 });
16693
- if (!(await lstat2(directory)).isDirectory() || (await lstat2(directory)).isSymbolicLink())
17160
+ await mkdir3(directory, { recursive: true, mode: 448 });
17161
+ if (!(await lstat3(directory)).isDirectory() || (await lstat3(directory)).isSymbolicLink())
16694
17162
  throw Error("Attachment directory unavailable");
16695
17163
  const entries = [];
16696
17164
  for (const ref of parsed.files) {
16697
17165
  const file = chatFileDownloadSchema.parse(await download2(ref.id));
16698
17166
  if (file.id !== ref.id) throw Error("Attachment identity mismatch");
16699
17167
  const bytes = Buffer.from(file.data, "base64");
16700
- if (bytes.length !== file.size || bytes.toString("base64") !== file.data || createHash9("sha256").update(bytes).digest("hex") !== file.sha256)
17168
+ if (bytes.length !== file.size || bytes.toString("base64") !== file.data || createHash10("sha256").update(bytes).digest("hex") !== file.sha256)
16701
17169
  throw Error("Attachment content mismatch");
16702
17170
  const ext = /\.([a-z0-9]{1,12})$/i.exec(file.name)?.[1]?.toLowerCase() ?? "bin";
16703
- const path3 = join28(directory, `${file.id}.${ext}`);
17171
+ const path3 = join29(directory, `${file.id}.${ext}`);
16704
17172
  try {
16705
17173
  await writeFile2(path3, bytes, { flag: "wx", mode: 256 });
16706
17174
  } catch (error) {
16707
- if (error.code !== "EEXIST" || (await lstat2(path3)).isSymbolicLink() || createHash9("sha256").update(await readFile3(path3)).digest("hex") !== file.sha256)
17175
+ if (error.code !== "EEXIST" || (await lstat3(path3)).isSymbolicLink() || createHash10("sha256").update(await readFile4(path3)).digest("hex") !== file.sha256)
16708
17176
  throw Error("Attachment file unavailable");
16709
17177
  }
16710
17178
  let textPath;
16711
17179
  if (file.text !== null) {
16712
- textPath = join28(directory, `${file.id}.extracted.txt`);
17180
+ textPath = join29(directory, `${file.id}.extracted.txt`);
16713
17181
  try {
16714
17182
  await writeFile2(textPath, file.text, { flag: "wx", mode: 256 });
16715
17183
  } catch (error) {
16716
- if (error.code !== "EEXIST" || (await lstat2(textPath)).isSymbolicLink() || await readFile3(textPath, "utf8") !== file.text)
17184
+ if (error.code !== "EEXIST" || (await lstat3(textPath)).isSymbolicLink() || await readFile4(textPath, "utf8") !== file.text)
16717
17185
  throw Error("Attachment text unavailable");
16718
17186
  }
16719
17187
  }
@@ -16903,23 +17371,23 @@ function createRunMasker(secrets) {
16903
17371
 
16904
17372
  // src/runs/supervisor.ts
16905
17373
  import { stdSerializers } from "pino";
16906
- import { createHash as createHash11, randomUUID as randomUUID6 } from "node:crypto";
16907
- import { join as join30, resolve as resolve13 } from "node:path";
16908
- import { tmpdir as tmpdir4 } from "node:os";
17374
+ import { createHash as createHash12, randomUUID as randomUUID6 } from "node:crypto";
17375
+ import { join as join31, resolve as resolve14 } from "node:path";
17376
+ import { tmpdir as tmpdir5 } from "node:os";
16909
17377
  import { execa as execa12 } from "execa";
16910
17378
 
16911
17379
  // src/agents/checkpoint.ts
16912
- import { mkdtempSync as mkdtempSync8, rmSync as rmSync19, writeFileSync as writeFileSync9 } from "node:fs";
16913
- import { tmpdir as tmpdir3 } from "node:os";
16914
- import { join as join29 } from "node:path";
17380
+ import { mkdtempSync as mkdtempSync9, rmSync as rmSync19, writeFileSync as writeFileSync9 } from "node:fs";
17381
+ import { tmpdir as tmpdir4 } from "node:os";
17382
+ import { join as join30 } from "node:path";
16915
17383
  import { gunzipSync as gunzipSync2, gzipSync as gzipSync2 } from "node:zlib";
16916
17384
  import { execa as execa11 } from "execa";
16917
17385
 
16918
17386
  // src/coding-workspace/checkpoint.ts
16919
- import { createHash as createHash10 } from "node:crypto";
16920
- import { resolve as resolve12 } from "node:path";
17387
+ import { createHash as createHash11 } from "node:crypto";
17388
+ import { resolve as resolve13 } from "node:path";
16921
17389
  import { execa as execa10 } from "execa";
16922
- var digest6 = (value) => createHash10("sha256").update(value).digest("hex");
17390
+ var digest6 = (value) => createHash11("sha256").update(value).digest("hex");
16923
17391
  var oid = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/;
16924
17392
  var MANIFEST_BYTES = 1536 * 1024;
16925
17393
  var regular = (mode) => mode === null || mode === "100644" || mode === "100755";
@@ -16951,7 +17419,7 @@ async function captureCheckpointReview(input) {
16951
17419
  const env = {
16952
17420
  ...buildChildEnv({}),
16953
17421
  GIT_DIR: gitDir,
16954
- GIT_COMMON_DIR: resolve12(gitDir, "..", ".."),
17422
+ GIT_COMMON_DIR: resolve13(gitDir, "..", ".."),
16955
17423
  GIT_WORK_TREE: input.worktree,
16956
17424
  GIT_CONFIG_NOSYSTEM: "1",
16957
17425
  GIT_CONFIG_GLOBAL: "/dev/null",
@@ -17138,8 +17606,8 @@ async function takeCheckpoint(options) {
17138
17606
  }
17139
17607
  async function applyCheckpoint(options) {
17140
17608
  const git3 = await pinnedGit(options.repoPath, options.worktree);
17141
- const dir = mkdtempSync8(join29(tmpdir3(), "mikka-checkpoint-"));
17142
- const file = join29(dir, "checkpoint.patch");
17609
+ const dir = mkdtempSync9(join30(tmpdir4(), "mikka-checkpoint-"));
17610
+ const file = join30(dir, "checkpoint.patch");
17143
17611
  try {
17144
17612
  const patch = gunzipSync2(Buffer.from(options.checkpoint.patch, "base64"));
17145
17613
  if (!patch.length && options.checkpoint.files === 0) return true;
@@ -17172,7 +17640,7 @@ async function hasCommit(repoPath, commit) {
17172
17640
 
17173
17641
  // src/server-link.ts
17174
17642
  import { randomUUID as randomUUID5 } from "node:crypto";
17175
- import { pathToFileURL as pathToFileURL2 } from "node:url";
17643
+ import { pathToFileURL as pathToFileURL3 } from "node:url";
17176
17644
  var MAX_CONTINUES = 3;
17177
17645
  var MAX_CRASH_RETRIES = 3;
17178
17646
  var MAX_FIX_ROUNDS = 3;
@@ -17256,7 +17724,7 @@ var MemoryServer = class {
17256
17724
  const runId = run3.runId ?? randomUUID5();
17257
17725
  const fixturePath = this.repos.get(deviceId)?.find((repo) => repo.repoId === run3.repoId)?.path;
17258
17726
  this.runs.set(runId, {
17259
- assignment: { ...run3, runId, remoteUrl: run3.remoteUrl ?? (fixturePath ? pathToFileURL2(fixturePath).href : void 0) },
17727
+ assignment: { ...run3, runId, remoteUrl: run3.remoteUrl ?? (fixturePath ? pathToFileURL3(fixturePath).href : void 0) },
17260
17728
  deviceId,
17261
17729
  state: "queued",
17262
17730
  patches: []
@@ -17394,12 +17862,12 @@ var MemoryServer = class {
17394
17862
  this.check();
17395
17863
  let pending = this.pendingCommands(deviceId, skip);
17396
17864
  if (pending.length === 0 && waitSeconds > 0 && !signal?.aborted) {
17397
- await new Promise((resolve19) => {
17398
- const timer = setTimeout(resolve19, waitSeconds * 1e3);
17399
- signal?.addEventListener("abort", () => resolve19(), { once: true });
17865
+ await new Promise((resolve20) => {
17866
+ const timer = setTimeout(resolve20, waitSeconds * 1e3);
17867
+ signal?.addEventListener("abort", () => resolve20(), { once: true });
17400
17868
  this.wakeCommands.push(() => {
17401
17869
  clearTimeout(timer);
17402
- resolve19();
17870
+ resolve20();
17403
17871
  });
17404
17872
  });
17405
17873
  this.check();
@@ -17867,10 +18335,11 @@ var RunSupervisor = class {
17867
18335
  check();
17868
18336
  await this.send(runId, mailboxNoticeText(runId, messageIds));
17869
18337
  }
17870
- async send(runId, text4) {
18338
+ async send(runId, text4, mode) {
17871
18339
  const run3 = this.active.get(runId);
17872
18340
  const adapter = this.adapterFor(runId);
17873
18341
  if (!run3?.session) throw new RunNotFoundError(runId);
18342
+ if (mode === "steer" && adapter.harness !== "codex") throw new Error("Active turn steering unavailable");
17874
18343
  if (!adapter.capabilities.supportsInterject) {
17875
18344
  throw new Error(
17876
18345
  `Harness "${adapter.harness}" cannot take messages mid-run`
@@ -17880,9 +18349,9 @@ var RunSupervisor = class {
17880
18349
  const entry = this.deps.journal.get(runId);
17881
18350
  if (splitChatFiles(text4).files.length) {
17882
18351
  if (!entry || !this.deps.downloadChatFile || !this.deps.adapterStateDir) throw Error("Run attachments unavailable");
17883
- text4 = await materializeChatFiles(text4, join30(this.deps.adapterStateDir, "inputs", runId), (id5) => this.deps.downloadChatFile(entry.assignment, id5, run3.abort.signal));
18352
+ text4 = await materializeChatFiles(text4, join31(this.deps.adapterStateDir, "inputs", runId), (id5) => this.deps.downloadChatFile(entry.assignment, id5, run3.abort.signal));
17884
18353
  }
17885
- await run3.session.send(text4);
18354
+ await run3.session.send(text4, mode);
17886
18355
  }
17887
18356
  async cancel(runId) {
17888
18357
  const entry = this.deps.journal.get(runId);
@@ -17910,9 +18379,9 @@ var RunSupervisor = class {
17910
18379
  run3.abort.abort();
17911
18380
  }
17912
18381
  let timer;
17913
- const grace = new Promise((resolve19) => {
18382
+ const grace = new Promise((resolve20) => {
17914
18383
  timer = setTimeout(
17915
- resolve19,
18384
+ resolve20,
17916
18385
  this.deps.stopGraceMs ?? DEFAULT_STOP_GRACE_MS
17917
18386
  );
17918
18387
  });
@@ -17938,10 +18407,10 @@ var RunSupervisor = class {
17938
18407
  this.active.get(runId)?.runtimeTiming?.chunk(chunk);
17939
18408
  if (chunk.type.startsWith("data-") && "transient" in chunk && chunk.transient)
17940
18409
  return this.append(runId, chunk);
17941
- const open4 = this.openParts.get(runId) ?? /* @__PURE__ */ new Set();
17942
- this.openParts.set(runId, open4);
17943
- if (this.cutMessages.has(runId) && open4.size === 0) this.endMessage(runId);
17944
- trackParts(open4, chunk);
18410
+ const open5 = this.openParts.get(runId) ?? /* @__PURE__ */ new Set();
18411
+ this.openParts.set(runId, open5);
18412
+ if (this.cutMessages.has(runId) && open5.size === 0) this.endMessage(runId);
18413
+ trackParts(open5, chunk);
17945
18414
  if (chunk.type === "start") {
17946
18415
  this.endMessage(runId);
17947
18416
  this.openMessages.add(runId);
@@ -17949,7 +18418,7 @@ var RunSupervisor = class {
17949
18418
  if (!this.openMessages.has(runId)) return;
17950
18419
  this.openMessages.delete(runId);
17951
18420
  this.cutMessages.delete(runId);
17952
- open4.clear();
18421
+ open5.clear();
17953
18422
  } else if (!this.openMessages.has(runId)) {
17954
18423
  this.append(runId, { type: "start", messageId: randomUUID6() });
17955
18424
  this.openMessages.add(runId);
@@ -18200,16 +18669,22 @@ var RunSupervisor = class {
18200
18669
  }
18201
18670
  });
18202
18671
  }
18203
- /** Waits for the run's capture uploads, but never longer than a minute. */
18204
- async flushCaptures(runId) {
18672
+ /** One minute for preparation and upload; cancellation drains before the terminal event. */
18673
+ async flushCaptures(runId, signal) {
18205
18674
  if (!this.deps.captures) return true;
18206
- let timer;
18207
- return Promise.race([
18208
- this.deps.captures.flush(runId).then(() => true),
18209
- new Promise((resolve19) => {
18210
- timer = setTimeout(() => resolve19(false), 6e4);
18211
- })
18212
- ]).finally(() => clearTimeout(timer));
18675
+ const deadline = new AbortController();
18676
+ const finishing = AbortSignal.any([signal, deadline.signal]);
18677
+ const timer = setTimeout(() => deadline.abort(new Error("Capture finalization deadline exceeded")), 6e4);
18678
+ try {
18679
+ await this.deps.captures.flush(runId, false, finishing);
18680
+ finishing.throwIfAborted();
18681
+ return true;
18682
+ } catch (error) {
18683
+ if (signal.aborted) return false;
18684
+ throw error;
18685
+ } finally {
18686
+ clearTimeout(timer);
18687
+ }
18213
18688
  }
18214
18689
  /** Only the local lease and pushed stop state govern host finishing work. */
18215
18690
  assertFinishingRunLive(runId, signal) {
@@ -18233,11 +18708,11 @@ var RunSupervisor = class {
18233
18708
  if (configured.length === 0) return void 0;
18234
18709
  const loaded = [];
18235
18710
  if (this.deps.adapterStateDir) {
18236
- const dir = join30(runPaths(this.deps.adapterStateDir, runId).runDir, PROFILE_SKILLS_DIR, PROFILE_SKILL_LOADS_DIR);
18711
+ const dir = join31(runPaths(this.deps.adapterStateDir, runId).runDir, PROFILE_SKILLS_DIR, PROFILE_SKILL_LOADS_DIR);
18237
18712
  try {
18238
18713
  for (const name of readdirSync8(dir).sort()) {
18239
18714
  if (!name.endsWith(".json") || loaded.length >= configured.length) continue;
18240
- const file = join30(dir, name), meta = lstatSync11(file, { throwIfNoEntry: false });
18715
+ const file = join31(dir, name), meta = lstatSync11(file, { throwIfNoEntry: false });
18241
18716
  if (!meta?.isFile() || meta.isSymbolicLink() || meta.nlink !== 1 || meta.size < 2 || meta.size > 4096) continue;
18242
18717
  const receipt = profileSkillLoadReceiptSchema.safeParse(JSON.parse(readFileSync14(file, "utf8")));
18243
18718
  if (!receipt.success || loaded.some((item) => item.id === receipt.data.id)) continue;
@@ -18381,7 +18856,7 @@ var RunSupervisor = class {
18381
18856
  try {
18382
18857
  return await withRunGitCredentials(
18383
18858
  assignment,
18384
- runPaths(this.deps.adapterStateDir ?? join30(tmpdir4(), "mikka-run-state"), runId).privateDir,
18859
+ runPaths(this.deps.adapterStateDir ?? join31(tmpdir5(), "mikka-run-state"), runId).privateDir,
18385
18860
  (env) => this.deps.worktrees.fetchBranch(
18386
18861
  repo.path,
18387
18862
  repo.push?.remote ?? "origin",
@@ -18452,7 +18927,15 @@ var RunSupervisor = class {
18452
18927
  }, { root: true, traceContext: assignment?.traceContext }).catch(async (error) => {
18453
18928
  run3.repositoryPreparing?.refuseEffects(error);
18454
18929
  run3.repositoryPreparing?.abort.abort();
18455
- await Promise.all([run3.repositoryPreparing?.done.catch(() => void 0), this.closePrepared(run3)]);
18930
+ await Promise.all([
18931
+ run3.repositoryPreparing?.done.catch(() => void 0),
18932
+ this.closePrepared(run3),
18933
+ Promise.resolve().then(() => this.deps.captures?.flush(
18934
+ runId,
18935
+ false,
18936
+ AbortSignal.abort(new Error("Capture finalization cancelled"))
18937
+ )).catch(() => void 0)
18938
+ ]);
18456
18939
  run3.runtimeTiming?.finishing();
18457
18940
  const message = error instanceof Error ? error.message : String(error);
18458
18941
  this.deps.log.error({ run_id: runId, err: this.logError(runId, error) }, "run failed");
@@ -18523,8 +19006,8 @@ var RunSupervisor = class {
18523
19006
  });
18524
19007
  if (readAbort) {
18525
19008
  let allowEffects, refuseEffects;
18526
- const entryReady = new Promise((resolve19, reject) => {
18527
- allowEffects = resolve19;
19009
+ const entryReady = new Promise((resolve20, reject) => {
19010
+ allowEffects = resolve20;
18528
19011
  refuseEffects = reject;
18529
19012
  });
18530
19013
  const authorized = Promise.all([policyReady, entryReady]);
@@ -18758,7 +19241,7 @@ var RunSupervisor = class {
18758
19241
  let followUp = assignment.followUp;
18759
19242
  if (splitChatFiles(prompt).files.length || followUp && splitChatFiles(followUp).files.length) {
18760
19243
  if (!this.deps.downloadChatFile || !this.deps.adapterStateDir) throw Error("Run attachments unavailable");
18761
- const directory = join30(this.deps.adapterStateDir, "inputs", runId);
19244
+ const directory = join31(this.deps.adapterStateDir, "inputs", runId);
18762
19245
  const download2 = (id5) => this.deps.downloadChatFile(assignment, id5, run3.abort.signal);
18763
19246
  prompt = await materializeChatFiles(prompt, directory, download2);
18764
19247
  if (followUp) followUp = await materializeChatFiles(followUp, directory, download2);
@@ -18771,7 +19254,7 @@ var RunSupervisor = class {
18771
19254
  gitWritePaths: await worktreeGitWritePaths(repo.path, worktree, runId)
18772
19255
  };
18773
19256
  const resuming = entry.sessionId !== null && adapter.capabilities.supportsResume;
18774
- const inEarlierWorktree = continued !== null || entry.worktree !== null && resolve13(entry.worktree) !== resolve13(this.deps.worktrees.pathFor(runId));
19257
+ const inEarlierWorktree = continued !== null || entry.worktree !== null && resolve14(entry.worktree) !== resolve14(this.deps.worktrees.pathFor(runId));
18775
19258
  const continueSession = !resuming && assignment.resumeSessionId && assignment.continuesRunId && inEarlierWorktree && adapter.capabilities.supportsResume ? {
18776
19259
  sessionId: assignment.resumeSessionId,
18777
19260
  runId: assignment.continuesRunId,
@@ -18780,13 +19263,13 @@ var RunSupervisor = class {
18780
19263
  if (assignment.requireSessionResume && (!assignment.resumeSessionId || !assignment.continuesRunId || !adapter.capabilities.supportsResume || !resuming && !continueSession || resuming && entry.sessionId !== assignment.resumeSessionId))
18781
19264
  throw new Error("factory_question_session_resume_required");
18782
19265
  const benchmark = assignment.benchmark;
18783
- const policyDigest = assignment.skillReceipt ? createHash11("sha256").update(runPolicyDigestInput(assignment.policy)).digest("hex") : void 0;
19266
+ const policyDigest = assignment.skillReceipt ? createHash12("sha256").update(runPolicyDigestInput(assignment.policy)).digest("hex") : void 0;
18784
19267
  if (benchmark && (!assignment.skillReceipt || assignment.harness === "mock" || !assignment.verifyCommand || benchmark.sourceCommit !== this.deps.journal.get(runId)?.baseCommit || policyDigest !== benchmark.policyDigest)) throw new Error("Frozen benchmark execution configuration mismatch");
18785
19268
  let fixtureDigest;
18786
19269
  if (benchmark) {
18787
19270
  if (runPolicy(assignment.policy).readOnly !== true) throw new Error("Benchmark fixture must be read-only");
18788
19271
  const fixed = await fixedCheckSnapshot(repo.path, worktree, benchmark.sourceCommit);
18789
- fixtureDigest = createHash11("sha256").update(fixed.sha).digest("hex");
19272
+ fixtureDigest = createHash12("sha256").update(fixed.sha).digest("hex");
18790
19273
  if (fixtureDigest !== benchmark.fixtureDigest) throw new Error("Frozen benchmark fixture digest mismatch");
18791
19274
  }
18792
19275
  const previousMount = entry.skillMount;
@@ -18827,7 +19310,7 @@ var RunSupervisor = class {
18827
19310
  if (!this.deps.adapterStateDir || assignment.harness === "mock" || !session.sessionId || resuming && session.sessionId !== entry.sessionId || assignment.requireSessionResume && session.sessionId !== assignment.resumeSessionId)
18828
19311
  throw new Error("Skill mount requires the actual original harness session");
18829
19312
  verifySkillAssignment(assignment);
18830
- const file = join30(
19313
+ const file = join31(
18831
19314
  runPaths(this.deps.adapterStateDir, runId).runDir,
18832
19315
  SKILLS_DIR,
18833
19316
  skillSlug(assignment.skills[0].name),
@@ -18944,7 +19427,7 @@ var RunSupervisor = class {
18944
19427
  try {
18945
19428
  if (assignment.benchmark && !run3.cancelRequested) {
18946
19429
  const fixed = await fixedCheckSnapshot(repo.path, worktree, assignment.benchmark.sourceCommit, finishingSignal);
18947
- if (createHash11("sha256").update(fixed.sha).digest("hex") !== assignment.benchmark.fixtureDigest)
19430
+ if (createHash12("sha256").update(fixed.sha).digest("hex") !== assignment.benchmark.fixtureDigest)
18948
19431
  throw new Error("Benchmark fixture changed during model execution");
18949
19432
  }
18950
19433
  outcome = await this.report(runId, worktree, repo, assignment, stopReason, error, event.report, finishingSignal);
@@ -18981,7 +19464,7 @@ var RunSupervisor = class {
18981
19464
  report2 = { ...report2, publish };
18982
19465
  stopReason = stopReasonOf(event, run3, assignment);
18983
19466
  }
18984
- const capturesSaved = !this.stopping && await this.flushCaptures(runId);
19467
+ const capturesSaved = !this.stopping && await this.flushCaptures(runId, finishingSignal);
18985
19468
  stopReason = stopReasonOf(event, run3, assignment);
18986
19469
  const checkpoint = await this.saveTerminalCheckpoint(runId, run3, capturesSaved);
18987
19470
  if (stopReason === "provider_failure" || stopReason === "quota_exhausted") report2 = { ...report2, providerCheckpoint: checkpoint.checkpoint };
@@ -19005,33 +19488,33 @@ var RunSupervisor = class {
19005
19488
  }
19006
19489
  }
19007
19490
  };
19008
- function trackParts(open4, chunk) {
19491
+ function trackParts(open5, chunk) {
19009
19492
  switch (chunk.type) {
19010
19493
  case "text-start":
19011
19494
  case "reasoning-start":
19012
- open4.add(`${chunk.type.split("-")[0]}:${chunk.id}`);
19495
+ open5.add(`${chunk.type.split("-")[0]}:${chunk.id}`);
19013
19496
  break;
19014
19497
  case "text-end":
19015
19498
  case "reasoning-end":
19016
- open4.delete(`${chunk.type.split("-")[0]}:${chunk.id}`);
19499
+ open5.delete(`${chunk.type.split("-")[0]}:${chunk.id}`);
19017
19500
  break;
19018
19501
  case "tool-input-start":
19019
19502
  case "tool-input-available":
19020
- open4.add(`tool:${chunk.toolCallId}`);
19503
+ open5.add(`tool:${chunk.toolCallId}`);
19021
19504
  break;
19022
19505
  case "tool-output-available":
19023
19506
  case "tool-output-error":
19024
19507
  case "tool-output-denied":
19025
- open4.delete(`tool:${chunk.toolCallId}`);
19508
+ open5.delete(`tool:${chunk.toolCallId}`);
19026
19509
  break;
19027
19510
  }
19028
19511
  }
19029
19512
  var ABORTED = /* @__PURE__ */ Symbol("aborted");
19030
19513
  function abortPromise(signal) {
19031
- return new Promise((resolve19) => {
19032
- if (signal.aborted) resolve19(ABORTED);
19514
+ return new Promise((resolve20) => {
19515
+ if (signal.aborted) resolve20(ABORTED);
19033
19516
  else
19034
- signal.addEventListener("abort", () => resolve19(ABORTED), { once: true });
19517
+ signal.addEventListener("abort", () => resolve20(ABORTED), { once: true });
19035
19518
  });
19036
19519
  }
19037
19520
  function pickAgentReport(agent) {
@@ -19040,6 +19523,8 @@ function pickAgentReport(agent) {
19040
19523
  if (agent.repositorySelection) picked.repositorySelection = agent.repositorySelection;
19041
19524
  if (agent.verificationCommand && typeof agent.verificationCommand.command === "string" && agent.verificationCommand.command.trim() && typeof agent.verificationCommand.basis === "string" && agent.verificationCommand.basis.trim())
19042
19525
  picked.verificationCommand = { command: agent.verificationCommand.command.trim().slice(0, 2e3), basis: agent.verificationCommand.basis.trim().slice(0, 2e3) };
19526
+ const visualEvidence = runVisualEvidence.safeParse(agent.visualEvidence);
19527
+ if (visualEvidence.success) picked.visualEvidence = visualEvidence.data;
19043
19528
  const verdict = reviewVerdict.safeParse(agent.reviewVerdict);
19044
19529
  if (verdict.success) picked.reviewVerdict = verdict.data;
19045
19530
  if (typeof agent.summary === "string")
@@ -19155,7 +19640,7 @@ var DeviceGatewayClosedError = class extends Error {
19155
19640
  };
19156
19641
  function runDeviceGateway(socket, options) {
19157
19642
  const pingMs = options.pingMs ?? DEVICE_GATEWAY_PING_MS;
19158
- return new Promise((resolve19, reject) => {
19643
+ return new Promise((resolve20, reject) => {
19159
19644
  let settled = false;
19160
19645
  let opened = false;
19161
19646
  let pulling = false;
@@ -19174,7 +19659,7 @@ function runDeviceGateway(socket, options) {
19174
19659
  } catch {
19175
19660
  }
19176
19661
  if (error && !options.signal.aborted) reject(error);
19177
- else resolve19();
19662
+ else resolve20();
19178
19663
  };
19179
19664
  const work = () => {
19180
19665
  if (settled) return;
@@ -19241,27 +19726,27 @@ function openDeviceGateway(url, protocol) {
19241
19726
  }
19242
19727
 
19243
19728
  // src/coding-workspace/files.ts
19244
- import { constants as constants6 } from "node:fs";
19245
- import { open, readFile as readFile4, realpath as realpath2 } from "node:fs/promises";
19246
- import { execFile as execFile6 } from "node:child_process";
19247
- import { promisify as promisify6 } from "node:util";
19248
- import { createHash as createHash12 } from "node:crypto";
19249
- import { extname, resolve as resolve14 } from "node:path";
19250
- var execute = promisify6(execFile6);
19251
- var hash = (value) => createHash12("sha256").update(value).digest("hex");
19729
+ import { constants as constants7 } from "node:fs";
19730
+ import { open as open2, readFile as readFile5, realpath as realpath2 } from "node:fs/promises";
19731
+ import { execFile as execFile7 } from "node:child_process";
19732
+ import { promisify as promisify7 } from "node:util";
19733
+ import { createHash as createHash13 } from "node:crypto";
19734
+ import { extname, resolve as resolve15 } from "node:path";
19735
+ var execute2 = promisify7(execFile7);
19736
+ var hash = (value) => createHash13("sha256").update(value).digest("hex");
19252
19737
  var denied = () => new CodingWorkspaceError("workspace_path_unavailable");
19253
19738
  function isFileReadRequest(request2) {
19254
19739
  return request2.kind === "file" || request2.kind === "tree" || request2.kind === "search" || request2.kind === "context";
19255
19740
  }
19256
19741
  var safeDotfiles2 = /* @__PURE__ */ new Set([".gitignore", ".gitattributes", ".editorconfig", ".prettierignore", ".prettierrc", ".eslintrc", ".dockerignore"]);
19257
19742
  async function mountId(handle) {
19258
- const id5 = /^mnt_id:\s*(\d+)$/m.exec(await readFile4(`/proc/self/fdinfo/${handle.fd}`, "utf8"))?.[1];
19743
+ const id5 = /^mnt_id:\s*(\d+)$/m.exec(await readFile5(`/proc/self/fdinfo/${handle.fd}`, "utf8"))?.[1];
19259
19744
  if (!id5) throw new CodingWorkspaceError("workspace_unsupported");
19260
19745
  return id5;
19261
19746
  }
19262
19747
  async function git2(root, args, maxBuffer = 2 * 1024 * 1024) {
19263
19748
  try {
19264
- const { stdout } = await execute("git", ["--no-optional-locks", "-c", "core.fsmonitor=false", "-c", "core.hooksPath=/dev/null", ...args], {
19749
+ const { stdout } = await execute2("git", ["--no-optional-locks", "-c", "core.fsmonitor=false", "-c", "core.hooksPath=/dev/null", ...args], {
19265
19750
  // chdir resolves the parent's open directory before exec closes FDs.
19266
19751
  // /proc/self works even when the visible procfs uses another PID namespace.
19267
19752
  cwd: root.gitPath,
@@ -19288,16 +19773,16 @@ async function safeFile(root, path3, use) {
19288
19773
  const parts = path3.split("/");
19289
19774
  for (let index = 0; index < parts.length; index++) {
19290
19775
  const directory = index < parts.length - 1;
19291
- const handle = await open(`/proc/self/fd/${parent.fd}/${parts[index]}`, constants6.O_RDONLY | constants6.O_NOFOLLOW | constants6.O_NONBLOCK | (directory ? constants6.O_DIRECTORY : 0));
19776
+ const handle = await open2(`/proc/self/fd/${parent.fd}/${parts[index]}`, constants7.O_RDONLY | constants7.O_NOFOLLOW | constants7.O_NONBLOCK | (directory ? constants7.O_DIRECTORY : 0));
19292
19777
  handles.push(handle);
19293
- const stat2 = await handle.stat({ bigint: true });
19294
- if (stat2.dev !== root.device || await mountId(handle) !== root.mountId || !directory && (!stat2.isFile() || stat2.nlink !== 1n)) throw denied();
19778
+ const stat3 = await handle.stat({ bigint: true });
19779
+ if (stat3.dev !== root.device || await mountId(handle) !== root.mountId || !directory && (!stat3.isFile() || stat3.nlink !== 1n)) throw denied();
19295
19780
  parent = handle;
19296
19781
  }
19297
19782
  const selected = await realpath2(`/proc/self/fd/${parent.fd}`);
19298
- if (selected !== resolve14(root.path, path3) || await realpath2(root.gitPath) !== root.path) throw denied();
19783
+ if (selected !== resolve15(root.path, path3) || await realpath2(root.gitPath) !== root.path) throw denied();
19299
19784
  const result = await use(parent);
19300
- if (await realpath2(`/proc/self/fd/${parent.fd}`) !== selected || await realpath2(resolve14(root.path, path3)) !== selected || await realpath2(root.gitPath) !== root.path) throw new CodingWorkspaceError("workspace_version_conflict");
19785
+ if (await realpath2(`/proc/self/fd/${parent.fd}`) !== selected || await realpath2(resolve15(root.path, path3)) !== selected || await realpath2(root.gitPath) !== root.path) throw new CodingWorkspaceError("workspace_version_conflict");
19301
19786
  return result;
19302
19787
  } catch (cause) {
19303
19788
  if (cause instanceof CodingWorkspaceError) throw cause;
@@ -19336,9 +19821,9 @@ async function readWorkspaceReceipt(command, entry) {
19336
19821
  const remote = entry.assignment.remoteUrl ?? entry.assignment.expectedRepoRemote;
19337
19822
  if (!remote || remoteKey(remote) !== identity.repositoryKey) throw new CodingWorkspaceError("workspace_checkout_unavailable");
19338
19823
  if (process.platform !== "linux") throw new CodingWorkspaceError("workspace_unsupported");
19339
- const path3 = resolve14(entry.worktree);
19824
+ const path3 = resolve15(entry.worktree);
19340
19825
  if (await realpath2(path3) !== path3) throw new CodingWorkspaceError("workspace_checkout_unavailable");
19341
- directory = await open(path3, constants6.O_RDONLY | constants6.O_DIRECTORY | constants6.O_NOFOLLOW);
19826
+ directory = await open2(path3, constants7.O_RDONLY | constants7.O_DIRECTORY | constants7.O_NOFOLLOW);
19342
19827
  const root = {
19343
19828
  path: path3,
19344
19829
  handle: directory,
@@ -19495,11 +19980,11 @@ async function readWorkspaceReceipt(command, entry) {
19495
19980
  }
19496
19981
 
19497
19982
  // src/coding-workspace/diff.ts
19498
- import { constants as constants7 } from "node:fs";
19499
- import { open as open2, realpath as realpath3, mkdtemp, mkdir as mkdir3, writeFile as writeFile3, rm as rm2, lstat as lstat3 } from "node:fs/promises";
19500
- import { createHash as createHash13 } from "node:crypto";
19501
- import { resolve as resolve15, dirname as dirname15, join as join31, posix } from "node:path";
19502
- import { tmpdir as tmpdir5 } from "node:os";
19983
+ import { constants as constants8 } from "node:fs";
19984
+ import { open as open3, realpath as realpath3, mkdtemp as mkdtemp2, mkdir as mkdir4, writeFile as writeFile3, rm as rm3, lstat as lstat4 } from "node:fs/promises";
19985
+ import { createHash as createHash14 } from "node:crypto";
19986
+ import { resolve as resolve16, dirname as dirname16, join as join32, posix } from "node:path";
19987
+ import { tmpdir as tmpdir6 } from "node:os";
19503
19988
  import { execa as execa13 } from "execa";
19504
19989
 
19505
19990
  // src/coding-workspace/eol.ts
@@ -19567,12 +20052,12 @@ var CRLFCleaner = class {
19567
20052
  };
19568
20053
 
19569
20054
  // src/coding-workspace/diff.ts
19570
- var digest7 = (value) => createHash13("sha256").update(value).digest("hex");
20055
+ var digest7 = (value) => createHash14("sha256").update(value).digest("hex");
19571
20056
  var fenceMode = (mode) => mode === "100644" || mode === "100755" || mode === "120000" || mode === "160000" ? mode : null;
19572
20057
  var oid2 = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/;
19573
20058
  var MAX_SCAN_BYTES = 64 * 1024 * 1024;
19574
20059
  var MAX_MANIFEST_BYTES = 1536 * 1024;
19575
- var statFence = (stat2) => digest7(`${stat2.dev}:${stat2.ino}:${stat2.mtimeNs}:${stat2.ctimeNs}:${stat2.size}:${stat2.mode}`);
20060
+ var statFence = (stat3) => digest7(`${stat3.dev}:${stat3.ino}:${stat3.mtimeNs}:${stat3.ctimeNs}:${stat3.size}:${stat3.mode}`);
19576
20061
  function pathsText(bytes) {
19577
20062
  try {
19578
20063
  return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
@@ -19592,7 +20077,7 @@ async function gitFor(repoPath, root, signal) {
19592
20077
  const env = {
19593
20078
  ...buildChildEnv({}),
19594
20079
  GIT_DIR: gitDir,
19595
- GIT_COMMON_DIR: resolve15(gitDir, "..", ".."),
20080
+ GIT_COMMON_DIR: resolve16(gitDir, "..", ".."),
19596
20081
  // cwd is resolved while the parent's FD is still open. The child does not
19597
20082
  // inherit that numeric descriptor, so its work tree must be relative to cwd.
19598
20083
  GIT_WORK_TREE: ".",
@@ -19657,7 +20142,7 @@ async function treeFiles(git3, commit) {
19657
20142
  }
19658
20143
  async function existsWithoutReading(path3) {
19659
20144
  try {
19660
- await lstat3(path3);
20145
+ await lstat4(path3);
19661
20146
  return true;
19662
20147
  } catch (error) {
19663
20148
  if (missing(error)) return false;
@@ -19676,12 +20161,12 @@ async function conversionSettings(git3) {
19676
20161
  const host = buildChildEnv({});
19677
20162
  const defaults = ["/etc/gitattributes", "/usr/etc/gitattributes", "/usr/local/etc/gitattributes"];
19678
20163
  if (!external) {
19679
- const configHome = host.XDG_CONFIG_HOME || (host.HOME ? join31(host.HOME, ".config") : void 0);
19680
- if (configHome) defaults.push(join31(configHome, "git", "attributes"));
20164
+ const configHome = host.XDG_CONFIG_HOME || (host.HOME ? join32(host.HOME, ".config") : void 0);
20165
+ if (configHome) defaults.push(join32(configHome, "git", "attributes"));
19681
20166
  }
19682
- const info = join31(git3.commonDir, "info");
20167
+ const info = join32(git3.commonDir, "info");
19683
20168
  if (await existsWithoutReading(info)) {
19684
- if (!(await lstat3(info)).isDirectory() || await existsWithoutReading(join31(info, "attributes")))
20169
+ if (!(await lstat4(info)).isDirectory() || await existsWithoutReading(join32(info, "attributes")))
19685
20170
  throw new CodingWorkspaceError("workspace_unsupported");
19686
20171
  }
19687
20172
  for (const path3 of defaults) if (await existsWithoutReading(path3)) throw new CodingWorkspaceError("workspace_unsupported");
@@ -19727,11 +20212,11 @@ async function workingConversion(git3, root, paths, head, signal, budget) {
19727
20212
  throw new CodingWorkspaceError("workspace_unsupported");
19728
20213
  attributeBytes.set(path3, bytes);
19729
20214
  }
19730
- const directory = await mkdtemp(join31(tmpdir5(), "mikka-diff-attributes-"));
20215
+ const directory = await mkdtemp2(join32(tmpdir6(), "mikka-diff-attributes-"));
19731
20216
  const actions = /* @__PURE__ */ new Map();
19732
20217
  try {
19733
- const gitDir = join31(directory, "git"), worktree = join31(directory, "worktree");
19734
- await mkdir3(worktree, { mode: 448 });
20218
+ const gitDir = join32(directory, "git"), worktree = join32(directory, "worktree");
20219
+ await mkdir4(worktree, { mode: 448 });
19735
20220
  const env = {
19736
20221
  ...buildChildEnv({}),
19737
20222
  GIT_CONFIG_NOSYSTEM: "1",
@@ -19750,8 +20235,8 @@ async function workingConversion(git3, root, paths, head, signal, budget) {
19750
20235
  killDescendants: true
19751
20236
  });
19752
20237
  for (const [path3, bytes] of attributeBytes) {
19753
- const target = join31(worktree, path3);
19754
- await mkdir3(dirname15(target), { recursive: true, mode: 448 });
20238
+ const target = join32(worktree, path3);
20239
+ await mkdir4(dirname16(target), { recursive: true, mode: 448 });
19755
20240
  await writeFile3(target, bytes, { mode: 384, flag: "wx" });
19756
20241
  }
19757
20242
  const attributes = ["text", "eol", "crlf", "filter", "working-tree-encoding", "ident"];
@@ -19793,7 +20278,7 @@ async function workingConversion(git3, root, paths, head, signal, budget) {
19793
20278
  }
19794
20279
  for (const path3 of paths) actions.set(path3, cleanAction(values.get(path3), settings.autoCRLF));
19795
20280
  } finally {
19796
- await rm2(directory, { recursive: true, force: true });
20281
+ await rm3(directory, { recursive: true, force: true });
19797
20282
  }
19798
20283
  return {
19799
20284
  index,
@@ -19833,7 +20318,7 @@ async function currentFile(root, path3, head, budget, signal, conversion, git3)
19833
20318
  budget.bytes += size;
19834
20319
  if (budget.bytes > MAX_SCAN_BYTES) throw new CodingWorkspaceError("workspace_limit_exceeded");
19835
20320
  const algorithm = head.length === 64 ? "sha256" : "sha1";
19836
- const hasher = createHash13(algorithm).update(`blob ${size}\0`), stats = new GitTextStats();
20321
+ const hasher = createHash14(algorithm).update(`blob ${size}\0`), stats = new GitTextStats();
19837
20322
  const bytes = size <= WORKSPACE_DIFF_MAX_BLOB_BYTES ? Buffer.alloc(size) : null;
19838
20323
  const chunk = Buffer.alloc(64 * 1024);
19839
20324
  let offset = 0;
@@ -19873,7 +20358,7 @@ async function currentFile(root, path3, head, budget, signal, conversion, git3)
19873
20358
  let blob = rawBlob, cleanSize = size;
19874
20359
  if (normalize) {
19875
20360
  cleanSize -= stats.crlf;
19876
- const cleaned = createHash13(algorithm).update(`blob ${cleanSize}\0`), cleaner = new CRLFCleaner();
20361
+ const cleaned = createHash14(algorithm).update(`blob ${cleanSize}\0`), cleaner = new CRLFCleaner();
19877
20362
  if (bytes) cleaned.update(cleaner.push(bytes));
19878
20363
  else {
19879
20364
  budget.bytes += size;
@@ -19943,7 +20428,7 @@ function metadata(repoId, revision2, old, next) {
19943
20428
  fileVersion: digest7(diffFileVersionMaterial(repoId, revision2, file))
19944
20429
  };
19945
20430
  }
19946
- async function snapshot2(git3, root, entry, request2, signal) {
20431
+ async function snapshot3(git3, root, entry, request2, signal) {
19947
20432
  const currentHead = (await git3(["rev-parse", "--verify", "HEAD"])).toString().trim();
19948
20433
  if (!oid2.test(currentHead)) throw new CodingWorkspaceError("workspace_checkout_unavailable");
19949
20434
  const headSha2 = request2.source === "commit" ? request2.headSha : currentHead;
@@ -20016,9 +20501,9 @@ async function readWorkspaceDiffReceipt(command, entry, repoPath) {
20016
20501
  if (!entry?.worktree || entry.assignment.runId !== identity.runId || entry.assignment.repoId !== identity.repoId || entry.assignment.deviceId !== identity.deviceId || remoteKey(entry.assignment.remoteUrl ?? entry.assignment.expectedRepoRemote ?? "") !== identity.repositoryKey)
20017
20502
  throw new CodingWorkspaceError("workspace_checkout_unavailable");
20018
20503
  if (process.platform !== "linux") throw new CodingWorkspaceError("workspace_unsupported");
20019
- const path3 = resolve15(entry.worktree);
20504
+ const path3 = resolve16(entry.worktree);
20020
20505
  if (await realpath3(path3) !== path3) throw new CodingWorkspaceError("workspace_checkout_unavailable");
20021
- directory = await open2(path3, constants7.O_RDONLY | constants7.O_DIRECTORY | constants7.O_NOFOLLOW);
20506
+ directory = await open3(path3, constants8.O_RDONLY | constants8.O_DIRECTORY | constants8.O_NOFOLLOW);
20022
20507
  const root = {
20023
20508
  path: path3,
20024
20509
  handle: directory,
@@ -20030,7 +20515,7 @@ async function readWorkspaceDiffReceipt(command, entry, repoPath) {
20030
20515
  if (remoteKey((await git3(["config", "--get", "remote.origin.url"])).toString().trim()) !== identity.repositoryKey)
20031
20516
  throw new CodingWorkspaceError("workspace_checkout_unavailable");
20032
20517
  const selection = request2.kind === "diff_snapshot" ? request2 : request2.revision.source === "working" ? { kind: "diff_snapshot", source: "working" } : { kind: "diff_snapshot", source: "commit", headSha: request2.revision.headSha, baseSha: request2.revision.baseSha };
20033
- const value = await snapshot2(git3, root, entry, selection, signal);
20518
+ const value = await snapshot3(git3, root, entry, selection, signal);
20034
20519
  if (Date.parse(expiresAt) <= Date.now()) throw new CodingWorkspaceError("workspace_request_expired");
20035
20520
  const observation2 = { ok: true, identity, revision: value.revision, availability: "online", observedAt: (/* @__PURE__ */ new Date()).toISOString() };
20036
20521
  signal.throwIfAborted();
@@ -20086,9 +20571,9 @@ async function readWorkspaceRevertPreview(command, entry, repoPath) {
20086
20571
  if (!entry?.worktree || entry.assignment.runId !== identity.runId || entry.assignment.repoId !== identity.repoId || entry.assignment.deviceId !== identity.deviceId || remoteKey(entry.assignment.remoteUrl ?? entry.assignment.expectedRepoRemote ?? "") !== identity.repositoryKey)
20087
20572
  throw new CodingWorkspaceError("workspace_checkout_unavailable");
20088
20573
  if (process.platform !== "linux") throw new CodingWorkspaceError("workspace_unsupported");
20089
- const path3 = resolve15(entry.worktree);
20574
+ const path3 = resolve16(entry.worktree);
20090
20575
  if (await realpath3(path3) !== path3) throw new CodingWorkspaceError("workspace_checkout_unavailable");
20091
- directory = await open2(path3, constants7.O_RDONLY | constants7.O_DIRECTORY | constants7.O_NOFOLLOW);
20576
+ directory = await open3(path3, constants8.O_RDONLY | constants8.O_DIRECTORY | constants8.O_NOFOLLOW);
20092
20577
  const root = {
20093
20578
  path: path3,
20094
20579
  handle: directory,
@@ -20099,7 +20584,7 @@ async function readWorkspaceRevertPreview(command, entry, repoPath) {
20099
20584
  const signal = AbortSignal.timeout(remaining), git3 = await gitFor(repoPath, root, signal);
20100
20585
  if (remoteKey((await git3(["config", "--get", "remote.origin.url"])).toString().trim()) !== identity.repositoryKey)
20101
20586
  throw new CodingWorkspaceError("workspace_checkout_unavailable");
20102
- const value = await snapshot2(git3, root, entry, { kind: "diff_snapshot", source: "working" }, signal);
20587
+ const value = await snapshot3(git3, root, entry, { kind: "diff_snapshot", source: "working" }, signal);
20103
20588
  if (value.revision.version !== request2.revision.version) throw new CodingWorkspaceError("workspace_version_conflict");
20104
20589
  const file = value.files.find((candidate) => candidate.path === request2.file.path);
20105
20590
  if (!file || file.fileVersion !== request2.file.fileVersion || file.path !== request2.file.path || file.previousPath !== request2.file.previousPath || file.status !== request2.file.status || file.oldBlob !== request2.file.oldBlob || file.newBlob !== request2.file.newBlob || file.oldMode !== request2.file.oldMode || file.newMode !== request2.file.newMode) throw new CodingWorkspaceError("workspace_version_conflict");
@@ -20155,11 +20640,11 @@ async function readWorkspaceRevertPreview(command, entry, repoPath) {
20155
20640
  }
20156
20641
 
20157
20642
  // src/coding-workspace/git.ts
20158
- import { constants as constants8 } from "node:fs";
20159
- import { lstat as lstat4, mkdtemp as mkdtemp2, open as open3, readFile as readFile5, realpath as realpath4, rm as rm3, unlink, writeFile as writeFile4 } from "node:fs/promises";
20160
- import { createHash as createHash14 } from "node:crypto";
20161
- import { join as join32, resolve as resolve16 } from "node:path";
20162
- import { tmpdir as tmpdir6 } from "node:os";
20643
+ import { constants as constants9 } from "node:fs";
20644
+ import { lstat as lstat5, mkdtemp as mkdtemp3, open as open4, readFile as readFile6, realpath as realpath4, rm as rm4, unlink, writeFile as writeFile4 } from "node:fs/promises";
20645
+ import { createHash as createHash15 } from "node:crypto";
20646
+ import { join as join33, resolve as resolve17 } from "node:path";
20647
+ import { tmpdir as tmpdir7 } from "node:os";
20163
20648
  import { execa as execa14 } from "execa";
20164
20649
 
20165
20650
  // src/coding-workspace/git-parse.ts
@@ -20292,7 +20777,7 @@ function parseHistoryCursor(cursor, headSha2) {
20292
20777
  var historyCursor = (headSha2, offset) => `${headSha2}:${offset}`;
20293
20778
 
20294
20779
  // src/coding-workspace/git.ts
20295
- var digest8 = (value) => createHash14("sha256").update(value).digest("hex");
20780
+ var digest8 = (value) => createHash15("sha256").update(value).digest("hex");
20296
20781
  var oid4 = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/;
20297
20782
  var STATUS_BYTES = 8 * 1024 * 1024;
20298
20783
  var STATUS_SCAN_BYTES = 16 * 1024 * 1024;
@@ -20314,9 +20799,9 @@ async function openPinnedRoot(command, entry) {
20314
20799
  if (!entry?.worktree || entry.assignment.runId !== identity.runId || entry.assignment.repoId !== identity.repoId || entry.assignment.deviceId !== identity.deviceId || remoteKey(entry.assignment.remoteUrl ?? entry.assignment.expectedRepoRemote ?? "") !== identity.repositoryKey)
20315
20800
  throw unavailable4();
20316
20801
  if (process.platform !== "linux") throw new CodingWorkspaceError("workspace_unsupported");
20317
- const path3 = resolve16(entry.worktree);
20802
+ const path3 = resolve17(entry.worktree);
20318
20803
  if (await realpath4(path3) !== path3) throw unavailable4();
20319
- const directory = await open3(path3, constants8.O_RDONLY | constants8.O_DIRECTORY | constants8.O_NOFOLLOW);
20804
+ const directory = await open4(path3, constants9.O_RDONLY | constants9.O_DIRECTORY | constants9.O_NOFOLLOW);
20320
20805
  try {
20321
20806
  const root = {
20322
20807
  path: path3,
@@ -20364,13 +20849,13 @@ async function openParent(root, path3) {
20364
20849
  let parent = root.handle;
20365
20850
  try {
20366
20851
  for (let index = 0; index < parts.length - 1; index++) {
20367
- const handle = await open3(
20852
+ const handle = await open4(
20368
20853
  `/proc/self/fd/${parent.fd}/${parts[index]}`,
20369
- constants8.O_RDONLY | constants8.O_DIRECTORY | constants8.O_NOFOLLOW
20854
+ constants9.O_RDONLY | constants9.O_DIRECTORY | constants9.O_NOFOLLOW
20370
20855
  );
20371
20856
  parents.push(handle);
20372
- const stat2 = await handle.stat({ bigint: true });
20373
- if (stat2.dev !== root.device || await mountId(handle) !== root.mountId) throw new CodingWorkspaceError("workspace_path_unavailable");
20857
+ const stat3 = await handle.stat({ bigint: true });
20858
+ if (stat3.dev !== root.device || await mountId(handle) !== root.mountId) throw new CodingWorkspaceError("workspace_path_unavailable");
20374
20859
  parent = handle;
20375
20860
  }
20376
20861
  return { parent, name: parts.at(-1), parents };
@@ -20396,8 +20881,8 @@ async function writePinnedFile(root, path3, bytes, executable2, expectation) {
20396
20881
  let target;
20397
20882
  try {
20398
20883
  const targetPath = `/proc/self/fd/${parent.fd}/${name}`;
20399
- const flags = constants8.O_WRONLY | constants8.O_NOFOLLOW | (expectation.createOnly ? constants8.O_CREAT | constants8.O_EXCL : 0);
20400
- target = await open3(targetPath, flags, executable2 ? 493 : 420);
20884
+ const flags = constants9.O_WRONLY | constants9.O_NOFOLLOW | (expectation.createOnly ? constants9.O_CREAT | constants9.O_EXCL : 0);
20885
+ target = await open4(targetPath, flags, executable2 ? 493 : 420);
20401
20886
  const before = await target.stat({ bigint: true });
20402
20887
  if (!before.isFile() || before.nlink !== 1n) throw new CodingWorkspaceError("workspace_path_unavailable");
20403
20888
  if (expectation.fence && statFence(before) !== expectation.fence) throw conflict();
@@ -20419,16 +20904,16 @@ async function deletePinnedFile(root, path3, expectedFence) {
20419
20904
  const { parent, name, parents } = await openParent(root, path3);
20420
20905
  try {
20421
20906
  const targetPath = `/proc/self/fd/${parent.fd}/${name}`;
20422
- const stat2 = await lstat4(targetPath, { bigint: true }).catch((error) => {
20907
+ const stat3 = await lstat5(targetPath, { bigint: true }).catch((error) => {
20423
20908
  if (!missing(error)) throw error;
20424
20909
  return null;
20425
20910
  });
20426
- if (!stat2) {
20911
+ if (!stat3) {
20427
20912
  if (expectedFence !== void 0) throw conflict();
20428
20913
  return;
20429
20914
  }
20430
- if (stat2.isSymbolicLink() || !stat2.isFile() || stat2.nlink !== 1n) throw new CodingWorkspaceError("workspace_path_unavailable");
20431
- if (expectedFence === void 0 || statFence(stat2) !== expectedFence) throw conflict();
20915
+ if (stat3.isSymbolicLink() || !stat3.isFile() || stat3.nlink !== 1n) throw new CodingWorkspaceError("workspace_path_unavailable");
20916
+ if (expectedFence === void 0 || statFence(stat3) !== expectedFence) throw conflict();
20432
20917
  await unlink(targetPath);
20433
20918
  } catch (error) {
20434
20919
  if (error instanceof CodingWorkspaceError) throw error;
@@ -20754,15 +21239,15 @@ function runGit(cwd, args, env, signal, maximum = 8 * 1024 * 1024) {
20754
21239
  }
20755
21240
  async function readTempFile(worktree, path3) {
20756
21241
  if (!visibleWorkspacePath(path3)) throw new CodingWorkspaceError("workspace_path_unavailable");
20757
- const full = join32(worktree, ...path3.split("/"));
21242
+ const full = join33(worktree, ...path3.split("/"));
20758
21243
  if (!full.startsWith(`${worktree}/`)) throw new CodingWorkspaceError("workspace_path_unavailable");
20759
21244
  try {
20760
- const stat2 = await lstat4(full);
20761
- if (stat2.isSymbolicLink()) return { exists: true, bytes: null, mode: null, reason: "unavailable" };
20762
- if (stat2.isDirectory()) return { exists: true, bytes: null, mode: null, reason: "submodule" };
20763
- if (!stat2.isFile()) return { exists: true, bytes: null, mode: null, reason: "unavailable" };
20764
- if (stat2.size > RESTORE_FILE_BYTES) return { exists: true, bytes: null, mode: null, reason: "binary" };
20765
- return { exists: true, bytes: await readFile5(full), mode: stat2.mode & 73 ? "100755" : "100644", reason: null };
21245
+ const stat3 = await lstat5(full);
21246
+ if (stat3.isSymbolicLink()) return { exists: true, bytes: null, mode: null, reason: "unavailable" };
21247
+ if (stat3.isDirectory()) return { exists: true, bytes: null, mode: null, reason: "submodule" };
21248
+ if (!stat3.isFile()) return { exists: true, bytes: null, mode: null, reason: "unavailable" };
21249
+ if (stat3.size > RESTORE_FILE_BYTES) return { exists: true, bytes: null, mode: null, reason: "binary" };
21250
+ return { exists: true, bytes: await readFile6(full), mode: stat3.mode & 73 ? "100755" : "100644", reason: null };
20766
21251
  } catch (error) {
20767
21252
  if (missing(error)) return { exists: false, bytes: null, mode: null, reason: null };
20768
21253
  throw error;
@@ -20775,8 +21260,8 @@ async function dryRunCheckpoint(git3, root, identity, statusBase, patchBase, pat
20775
21260
  } catch (error) {
20776
21261
  throw new CodingWorkspaceError("workspace_unsupported", { cause: error });
20777
21262
  }
20778
- const parent = await mkdtemp2(join32(tmpdir6(), "mikka-git-restore-"));
20779
- const worktree = join32(parent, "wt"), patchFile = join32(parent, "checkpoint.patch");
21263
+ const parent = await mkdtemp3(join33(tmpdir7(), "mikka-git-restore-"));
21264
+ const worktree = join33(parent, "wt"), patchFile = join33(parent, "checkpoint.patch");
20780
21265
  try {
20781
21266
  await writeFile4(patchFile, patch, { mode: 384 });
20782
21267
  await runGit(git3.commonDir, ["worktree", "add", "--detach", "--quiet", worktree, head], commonEnv(git3), signal);
@@ -20854,7 +21339,7 @@ async function dryRunCheckpoint(git3, root, identity, statusBase, patchBase, pat
20854
21339
  await runGit(git3.commonDir, ["worktree", "remove", "--force", worktree], commonEnv(git3), AbortSignal.timeout(5e3));
20855
21340
  } catch {
20856
21341
  }
20857
- await rm3(parent, { recursive: true, force: true });
21342
+ await rm4(parent, { recursive: true, force: true });
20858
21343
  }
20859
21344
  }
20860
21345
  function checkpointVersion(request2, plan) {
@@ -21056,9 +21541,9 @@ async function handleWorkspaceGitRequest(command, entry, repoPath) {
21056
21541
  }
21057
21542
 
21058
21543
  // src/repositories.ts
21059
- import { createHash as createHash15, randomUUID as randomUUID7 } from "node:crypto";
21544
+ import { createHash as createHash16, randomUUID as randomUUID7 } from "node:crypto";
21060
21545
  import { existsSync as existsSync7, lstatSync as lstatSync12, mkdirSync as mkdirSync17, readdirSync as readdirSync9, realpathSync as realpathSync13, renameSync as renameSync5, rmSync as rmSync20 } from "node:fs";
21061
- import { dirname as dirname16, join as join33, resolve as resolve17 } from "node:path";
21546
+ import { dirname as dirname17, join as join34, resolve as resolve18 } from "node:path";
21062
21547
  import { setTimeout as delay } from "node:timers/promises";
21063
21548
  import { execa as execa15 } from "execa";
21064
21549
  import lockfile2 from "proper-lockfile";
@@ -21082,8 +21567,8 @@ var RepositoryCache = class {
21082
21567
  retainResources;
21083
21568
  pathFor(remoteUrl) {
21084
21569
  const { key: key2 } = normalizeRepository(remoteUrl, { allowFile: this.allowFile });
21085
- const path3 = resolve17(this.root, "v2", createHash15("sha256").update(key2).digest("hex"));
21086
- if (!isInside(resolve17(this.root), path3) || path3 === resolve17(this.root)) throw new Error("Invalid repository cache path");
21570
+ const path3 = resolve18(this.root, "v2", createHash16("sha256").update(key2).digest("hex"));
21571
+ if (!isInside(resolve18(this.root), path3) || path3 === resolve18(this.root)) throw new Error("Invalid repository cache path");
21087
21572
  return path3;
21088
21573
  }
21089
21574
  /** Serialize clone/fetch against the same cache, including other processes. */
@@ -21091,7 +21576,7 @@ var RepositoryCache = class {
21091
21576
  signal?.throwIfAborted();
21092
21577
  const { remoteUrl: remote } = normalizeRepository(remoteUrl, { allowFile: this.allowFile });
21093
21578
  const path3 = this.pathFor(remote);
21094
- this.ensureParents(dirname16(path3));
21579
+ this.ensureParents(dirname17(path3));
21095
21580
  const release = await this.lock(path3, signal);
21096
21581
  try {
21097
21582
  return await withRepoConfig(path3, () => this.update(path3, remote, signal, env, diagnostics));
@@ -21102,18 +21587,18 @@ var RepositoryCache = class {
21102
21587
  async update(path3, remote, signal, env = {}, diagnostics) {
21103
21588
  signal?.throwIfAborted();
21104
21589
  const git3 = (args, cwd) => {
21105
- const execute2 = () => execa15("git", [
21590
+ const execute3 = () => execa15("git", [
21106
21591
  ...FETCH_GIT,
21107
21592
  "-c",
21108
21593
  `protocol.file.allow=${this.allowFile ? "always" : "never"}`,
21109
21594
  ...args
21110
21595
  ], { cwd, env: { ...process.env, ...env, GIT_TERMINAL_PROMPT: "0" }, stdin: "ignore", timeout: FETCH_TIMEOUT_MS, cancelSignal: signal, killDescendants: true });
21111
- if (!diagnostics) return execute2();
21596
+ if (!diagnostics) return execute3();
21112
21597
  const phase = args[0] === "clone" ? "clone" : args[0] === "fetch" ? "fetch" : args[0] === "remote" && args[1] === "set-head" ? "remote_head" : args[0] === "ls-remote" ? "remote_refs" : "local";
21113
21598
  const traced = () => daemonTracer.span(
21114
21599
  `daemon.repository.git.${phase}`,
21115
21600
  { "mikka.run.id_hash": diagnostics.runIdHash, "mikka.harness": diagnostics.harness },
21116
- execute2
21601
+ execute3
21117
21602
  );
21118
21603
  return diagnostics.timer ? diagnostics.timer.measure(phase, traced) : traced();
21119
21604
  };
@@ -21130,7 +21615,7 @@ var RepositoryCache = class {
21130
21615
  } else {
21131
21616
  this.assertClone(path3);
21132
21617
  await git3(["remote", "set-url", "origin", remote], path3);
21133
- const depth = existsSync7(join33(path3, ".git", "shallow")) ? ["--depth=50"] : [];
21618
+ const depth = existsSync7(join34(path3, ".git", "shallow")) ? ["--depth=50"] : [];
21134
21619
  await git3(["fetch", ...depth, ...this.retainResources ? [] : ["--prune"], "--no-tags", "--no-recurse-submodules", "--no-write-fetch-head", "origin"], path3);
21135
21620
  }
21136
21621
  this.assertClone(path3);
@@ -21222,28 +21707,28 @@ var RepositoryCache = class {
21222
21707
  paths() {
21223
21708
  const visit = (path3) => {
21224
21709
  if (!existsSync7(path3) || lstatSync12(path3).isSymbolicLink()) return [];
21225
- if (existsSync7(join33(path3, ".git"))) {
21710
+ if (existsSync7(join34(path3, ".git"))) {
21226
21711
  this.assertClone(path3);
21227
21712
  return [path3];
21228
21713
  }
21229
- return readdirSync9(path3, { withFileTypes: true }).flatMap((entry) => entry.isDirectory() && !entry.name.endsWith(".lock") && !entry.name.includes(".clone-") ? visit(join33(path3, entry.name)) : []);
21714
+ return readdirSync9(path3, { withFileTypes: true }).flatMap((entry) => entry.isDirectory() && !entry.name.endsWith(".lock") && !entry.name.includes(".clone-") ? visit(join34(path3, entry.name)) : []);
21230
21715
  };
21231
- return visit(resolve17(this.root));
21716
+ return visit(resolve18(this.root));
21232
21717
  }
21233
21718
  ensureParents(path3) {
21234
21719
  mkdirSync17(this.root, { recursive: true, mode: 448 });
21235
21720
  if (lstatSync12(this.root).isSymbolicLink()) throw new Error("Repository cache contains a symlink");
21236
21721
  const root = realpathSync13(this.root);
21237
- let current = resolve17(this.root);
21722
+ let current = resolve18(this.root);
21238
21723
  for (const part of path3.slice(current.length + 1).split("/").filter(Boolean)) {
21239
- current = join33(current, part);
21724
+ current = join34(current, part);
21240
21725
  if (existsSync7(current) && lstatSync12(current).isSymbolicLink()) throw new Error("Repository cache contains a symlink");
21241
21726
  mkdirSync17(current, { recursive: true, mode: 448 });
21242
21727
  if (!isInside(root, realpathSync13(current))) throw new Error("Repository cache escapes its directory");
21243
21728
  }
21244
21729
  }
21245
21730
  assertClone(path3) {
21246
- if (lstatSync12(path3).isSymbolicLink() || !lstatSync12(join33(path3, ".git")).isDirectory() || lstatSync12(join33(path3, ".git")).isSymbolicLink()) throw new Error("Repository cache is not a standard clone");
21731
+ if (lstatSync12(path3).isSymbolicLink() || !lstatSync12(join34(path3, ".git")).isDirectory() || lstatSync12(join34(path3, ".git")).isSymbolicLink()) throw new Error("Repository cache is not a standard clone");
21247
21732
  if (!isInside(realpathSync13(this.root), realpathSync13(path3))) throw new Error("Repository cache escapes its directory");
21248
21733
  }
21249
21734
  async lock(path3, signal) {
@@ -21349,11 +21834,11 @@ async function prepareRunRepository(repositories, privateDir, assignment, signal
21349
21834
  import { randomUUID as randomUUID8 } from "node:crypto";
21350
21835
  import { spawn as spawn5 } from "node:child_process";
21351
21836
  import { existsSync as existsSync8, mkdirSync as mkdirSync18, realpathSync as realpathSync14 } from "node:fs";
21352
- import { dirname as dirname17, join as join34, resolve as resolve18 } from "node:path";
21837
+ import { dirname as dirname18, join as join35, resolve as resolve19 } from "node:path";
21353
21838
  import { fileURLToPath } from "node:url";
21354
21839
 
21355
21840
  // src/official-cli-timing.ts
21356
- import { createHash as createHash16, randomBytes as randomBytes4 } from "node:crypto";
21841
+ import { createHash as createHash17, randomBytes as randomBytes4 } from "node:crypto";
21357
21842
  import { createServer as createServer4 } from "node:http";
21358
21843
 
21359
21844
  // src/mcp-http-timing.ts
@@ -21677,7 +22162,7 @@ var OfficialCliTimingCollector = class {
21677
22162
  };
21678
22163
  async function startCliTimingCollector({ runId, harness, remoteMcpServerCount, decisionCatalogue }) {
21679
22164
  const collector = new OfficialCliTimingCollector(runId, harness);
21680
- const expectedCatalogueSha256 = decisionCatalogue ? createHash16("sha256").update(JSON.stringify(decisionCatalogue)).digest("hex") : null;
22165
+ const expectedCatalogueSha256 = decisionCatalogue ? createHash17("sha256").update(JSON.stringify(decisionCatalogue)).digest("hex") : null;
21681
22166
  const mcpCollector = new McpHttpTimingCollector(runId, harness, remoteMcpServerCount, Date.now, expectedCatalogueSha256);
21682
22167
  const path3 = `/v1/logs/${randomBytes4(16).toString("hex")}`;
21683
22168
  const mcpPath = `/v1/mcp-http/${randomBytes4(16).toString("hex")}`;
@@ -21718,11 +22203,11 @@ async function startCliTimingCollector({ runId, harness, remoteMcpServerCount, d
21718
22203
  server.requestTimeout = 5e3;
21719
22204
  server.headersTimeout = 5e3;
21720
22205
  server.maxConnections = 8;
21721
- await new Promise((resolve19, reject) => {
22206
+ await new Promise((resolve20, reject) => {
21722
22207
  server.once("error", reject);
21723
22208
  server.listen(0, "127.0.0.1", () => {
21724
22209
  server.off("error", reject);
21725
- resolve19();
22210
+ resolve20();
21726
22211
  });
21727
22212
  });
21728
22213
  server.on("error", () => {
@@ -21771,7 +22256,7 @@ async function startCliTimingCollector({ runId, harness, remoteMcpServerCount, d
21771
22256
  unsetEnv,
21772
22257
  mcpHttpObservationUrl: `${origin}${mcpPath}`,
21773
22258
  close: ({ cliExitObserved = false, publish = true } = {}) => closed ??= (async () => {
21774
- await new Promise((resolve19) => {
22259
+ await new Promise((resolve20) => {
21775
22260
  const timer = setTimeout(() => {
21776
22261
  collector.truncate();
21777
22262
  mcpCollector.truncate();
@@ -21779,7 +22264,7 @@ async function startCliTimingCollector({ runId, harness, remoteMcpServerCount, d
21779
22264
  }, 1e3);
21780
22265
  server.close(() => {
21781
22266
  clearTimeout(timer);
21782
- resolve19();
22267
+ resolve20();
21783
22268
  });
21784
22269
  });
21785
22270
  const official = collector.finish(cliExitObserved), mcp = mcpCollector.finish();
@@ -21817,7 +22302,7 @@ async function runHostedCommand(worktree, script, _readOnly, timeoutMs, signal)
21817
22302
  abort();
21818
22303
  } else chunks.push(chunk);
21819
22304
  };
21820
- const result = await new Promise((resolve19, reject) => {
22305
+ const result = await new Promise((resolve20, reject) => {
21821
22306
  child = spawn5("/bin/sh", ["-c", script], {
21822
22307
  cwd: realpathSync14(worktree),
21823
22308
  env: process.env,
@@ -21827,7 +22312,7 @@ async function runHostedCommand(worktree, script, _readOnly, timeoutMs, signal)
21827
22312
  child.stdout?.on("data", (chunk) => collect("stdout", stdout, chunk));
21828
22313
  child.stderr?.on("data", (chunk) => collect("stderr", stderr, chunk));
21829
22314
  child.once("error", reject);
21830
- child.once("close", (code, term) => resolve19({ code, signal: term }));
22315
+ child.once("close", (code, term) => resolve20({ code, signal: term }));
21831
22316
  child.once("exit", abort);
21832
22317
  signal?.addEventListener("abort", abort, { once: true });
21833
22318
  if (signal?.aborted) abort();
@@ -21953,7 +22438,7 @@ async function createHostedBotRunner(host) {
21953
22438
  if (selected && (!options.model || options.model !== subscription?.first.modelId)) throw Error("binding_mismatch");
21954
22439
  const paths = runPaths(host.stateDir, assignment.runId);
21955
22440
  mkdirSync18(paths.runDir, { recursive: true, mode: 448 });
21956
- const cwd = preparation ? resolve18(options.cwd) : realpathSync14(options.cwd);
22441
+ const cwd = preparation ? resolve19(options.cwd) : realpathSync14(options.cwd);
21957
22442
  const env = Object.fromEntries(Object.entries({ ...process.env, ...options.env, ...assignment.taskEnv }).filter((entry) => typeof entry[1] === "string"));
21958
22443
  if (runDiagnosticsEnabled(assignment.taskEnv, host.collectCliTiming)) env.CLOUD_STARTUP_TIMING = "1";
21959
22444
  const selectedGithub = options.github ?? (assignment.github ? { ...assignment.github, issueId: assignment.issueId, runToken: assignment.mcp?.token } : void 0);
@@ -21984,7 +22469,7 @@ async function createHostedBotRunner(host) {
21984
22469
  });
21985
22470
  Object.assign(env, github.env);
21986
22471
  }
21987
- const ledger = join34(host.stateDir, "native-ledgers", assignment.runId + ".json");
22472
+ const ledger = join35(host.stateDir, "native-ledgers", assignment.runId + ".json");
21988
22473
  const scope = selected && subscription ? {
21989
22474
  runId: assignment.runId,
21990
22475
  bindingId: selected.bindingId,
@@ -21997,12 +22482,12 @@ async function createHostedBotRunner(host) {
21997
22482
  modelId: subscription.first.modelId
21998
22483
  } : void 0;
21999
22484
  if (continuation && existsSync8(ledger)) throw unavailable5("ledger_mismatch");
22000
- const previousLedger = continuation ? join34(host.stateDir, "native-ledgers", continuation.runId + ".json") : ledger;
22485
+ const previousLedger = continuation ? join35(host.stateDir, "native-ledgers", continuation.runId + ".json") : ledger;
22001
22486
  const previous = scope ? readJson(previousLedger) : void 0;
22002
22487
  if (preparation && previous) throw unavailable5("ledger_mismatch");
22003
22488
  const expectedScope = scope && continuation ? { ...scope, runId: continuation.runId } : scope;
22004
22489
  if (scope && (existsSync8(previousLedger) && (!previous || JSON.stringify(previous.scope) !== JSON.stringify(expectedScope) || typeof previous.sessionId !== "string") || assignment.requireSessionResume && (!previous || previous.sessionId !== assignment.resumeSessionId))) throw unavailable5("ledger_mismatch");
22005
- if (scope) mkdirSync18(dirname17(ledger), { recursive: true, mode: 448 });
22490
+ if (scope) mkdirSync18(dirname18(ledger), { recursive: true, mode: 448 });
22006
22491
  const record3 = async (sessionId) => {
22007
22492
  assertOpen();
22008
22493
  if (scope) writeJsonAtomic(ledger, { scope, sessionId });
@@ -22074,9 +22559,9 @@ async function createHostedBotRunner(host) {
22074
22559
  signal: lifetime.signal
22075
22560
  });
22076
22561
  child.stderr?.resume();
22077
- const exited = new Promise((resolve19) => {
22078
- child.once("exit", (code, signal) => resolve19({ code, signal }));
22079
- child.once("error", () => resolve19({ code: null, signal: null }));
22562
+ const exited = new Promise((resolve20) => {
22563
+ child.once("exit", (code, signal) => resolve20({ code, signal }));
22564
+ child.once("error", () => resolve20({ code: null, signal: null }));
22080
22565
  });
22081
22566
  return {
22082
22567
  process: child,
@@ -22180,9 +22665,9 @@ async function createHostedBotRunner(host) {
22180
22665
  await close();
22181
22666
  }
22182
22667
  },
22183
- send: async (text4) => {
22668
+ send: async (text4, mode) => {
22184
22669
  assertOpen();
22185
- await session.send(text4);
22670
+ await session.send(text4, mode);
22186
22671
  },
22187
22672
  cancel: async () => {
22188
22673
  try {
@@ -22263,7 +22748,7 @@ async function createHostedBotRunner(host) {
22263
22748
  import {
22264
22749
  randomBytes as randomBytes5,
22265
22750
  randomUUID as randomUUID9,
22266
- createHash as createHash18,
22751
+ createHash as createHash19,
22267
22752
  timingSafeEqual as timingSafeEqual2
22268
22753
  } from "node:crypto";
22269
22754
  import { chmodSync as chmodSync2 } from "node:fs";
@@ -22271,12 +22756,12 @@ import { createServer as createServer5 } from "node:net";
22271
22756
 
22272
22757
  // src/computer/driver.mjs
22273
22758
  import { spawn as spawn6 } from "node:child_process";
22274
- import { execFile as execFile7 } from "node:child_process";
22275
- import { promisify as promisify7 } from "node:util";
22276
- import { createHash as createHash17 } from "node:crypto";
22277
- import { readFile as readFile6, realpath as realpath5 } from "node:fs/promises";
22759
+ import { execFile as execFile8 } from "node:child_process";
22760
+ import { promisify as promisify8 } from "node:util";
22761
+ import { createHash as createHash18 } from "node:crypto";
22762
+ import { readFile as readFile7, realpath as realpath5 } from "node:fs/promises";
22278
22763
  import { createInterface } from "node:readline";
22279
- var exec3 = promisify7(execFile7);
22764
+ var exec3 = promisify8(execFile8);
22280
22765
  async function detectComputerDriver(binary = "cua-driver") {
22281
22766
  try {
22282
22767
  const { stdout: located } = await exec3("which", [binary], {
@@ -22290,7 +22775,7 @@ async function detectComputerDriver(binary = "cua-driver") {
22290
22775
  installed: true,
22291
22776
  version,
22292
22777
  path: path3,
22293
- fingerprint: createHash17("sha256").update(await readFile6(path3)).digest("hex")
22778
+ fingerprint: createHash18("sha256").update(await readFile7(path3)).digest("hex")
22294
22779
  };
22295
22780
  } catch {
22296
22781
  return null;
@@ -22357,7 +22842,7 @@ async function executeDriver(driver, input, display, leaseGuard, assertLive = ()
22357
22842
  if (display !== void 0 && !/^:[1-9][0-9]{0,3}$/.test(display))
22358
22843
  throw new Error("Invalid desktop display");
22359
22844
  const call = normalizeCall(input);
22360
- const fingerprint2 = createHash17("sha256").update(await readFile6(driver.path)).digest("hex");
22845
+ const fingerprint2 = createHash18("sha256").update(await readFile7(driver.path)).digest("hex");
22361
22846
  if (fingerprint2 !== driver.fingerprint)
22362
22847
  throw new Error("Driver changed; restart and approve a new request");
22363
22848
  const args = driverArguments(call);
@@ -22420,9 +22905,9 @@ async function executeDriver(driver, input, display, leaseGuard, assertLive = ()
22420
22905
  )
22421
22906
  )
22422
22907
  );
22423
- const request2 = (method, params) => new Promise((resolve19, reject) => {
22908
+ const request2 = (method, params) => new Promise((resolve20, reject) => {
22424
22909
  const n = ++id5;
22425
- pending.set(n, { resolve: resolve19, reject });
22910
+ pending.set(n, { resolve: resolve20, reject });
22426
22911
  child.stdin.write(
22427
22912
  JSON.stringify({ jsonrpc: "2.0", id: n, method, params }) + "\n"
22428
22913
  );
@@ -22460,6 +22945,8 @@ var ComputerBroker = class {
22460
22945
  grants = /* @__PURE__ */ new Map();
22461
22946
  // runId → when its screen recording stops by itself; only set while one runs.
22462
22947
  recordingUntil = /* @__PURE__ */ new Map();
22948
+ recordingSteps = /* @__PURE__ */ new Map();
22949
+ recordingTimingFailed = /* @__PURE__ */ new Set();
22463
22950
  pending = /* @__PURE__ */ new Map();
22464
22951
  sockets = /* @__PURE__ */ new Set();
22465
22952
  suspended = false;
@@ -22468,13 +22955,13 @@ var ComputerBroker = class {
22468
22955
  socketPath,
22469
22956
  transport = "unix",
22470
22957
  permitted,
22471
- execute: execute2 = (driver2, call, display, _runId, context) => executeDriver(driver2, call, display, void 0, context.assertLive),
22958
+ execute: execute3 = (driver2, call, display, _runId, context) => executeDriver(driver2, call, display, void 0, context.assertLive),
22472
22959
  capture,
22473
22960
  now = Date.now,
22474
22961
  ttl = 3e5,
22475
22962
  needsPerson
22476
22963
  }) {
22477
- Object.assign(this, { driver, socketPath, permitted, execute: execute2, capture, now, ttl, transport, needsPerson });
22964
+ Object.assign(this, { driver, socketPath, permitted, execute: execute3, capture, now, ttl, transport, needsPerson });
22478
22965
  }
22479
22966
  // runId → the last few action kinds, evidence for the Decisions API.
22480
22967
  recent = /* @__PURE__ */ new Map();
@@ -22536,10 +23023,10 @@ var ComputerBroker = class {
22536
23023
  })();
22537
23024
  });
22538
23025
  });
22539
- await new Promise((resolve19, reject) => {
23026
+ await new Promise((resolve20, reject) => {
22540
23027
  this.server.once("error", reject);
22541
- if (this.transport === "tcp") this.server.listen({ host: "127.0.0.1", port: 0 }, resolve19);
22542
- else this.server.listen(this.socketPath, resolve19);
23028
+ if (this.transport === "tcp") this.server.listen({ host: "127.0.0.1", port: 0 }, resolve20);
23029
+ else this.server.listen(this.socketPath, resolve20);
22543
23030
  });
22544
23031
  if (this.transport === "tcp") this.socketPath = `tcp://127.0.0.1:${this.server.address().port}`;
22545
23032
  else chmodSync2(this.socketPath, 384);
@@ -22550,23 +23037,39 @@ var ComputerBroker = class {
22550
23037
  return Promise.reject(new Error("Not permitted"));
22551
23038
  const call = normalizeCall(value);
22552
23039
  const step = actionStep(value);
22553
- return this.requestCall(token, grant, call, signal).then((result) => {
22554
- this.markStep(grant.runId, step);
22555
- return result;
22556
- });
23040
+ return this.requestCall(token, grant, call, signal, step);
22557
23041
  }
22558
- /** While this run records, a done action's description becomes a step on the recording (best effort; never fails the action). */
22559
- markStep(runId, label2) {
23042
+ /** Timings cover execution itself, excluding decision and human-approval waits. */
23043
+ async executeRecorded(driver, call, display, runId, context, step) {
23044
+ const started = this.now();
23045
+ try {
23046
+ return await this.execute(driver, call, display, runId, context);
23047
+ } finally {
23048
+ const label2 = step ?? { get_desktop_state: "Read the screen", click: "Click", type_text: "Type text", press_key: "Press a key", scroll: "Scroll" }[call.name];
23049
+ this.markStep(runId, label2, Math.max(0, Math.round(this.now() - started)));
23050
+ }
23051
+ }
23052
+ /** Pending timing writes drain before stop, so the last action cannot disappear. */
23053
+ markStep(runId, label2, durationMs) {
22560
23054
  const until = this.recordingUntil.get(runId);
22561
23055
  if (!label2 || !this.capture || until === void 0) return;
22562
- if (this.now() > until) {
23056
+ if (this.now() > until + 3e4) {
22563
23057
  this.recordingUntil.delete(runId);
22564
23058
  return;
22565
23059
  }
22566
- void Promise.resolve().then(() => this.capture(runId, { action: "step", label: label2, source: "action" })).catch(() => {
23060
+ const pending = this.recordingSteps.get(runId) ?? /* @__PURE__ */ new Set();
23061
+ const write = Promise.resolve().then(() => this.capture(runId, { action: "step", label: label2, source: "action", durationMs: Math.min(durationMs, 3e5) }, AbortSignal.timeout(5e3))).then((result) => {
23062
+ if (result?.recorded === false) this.recordingTimingFailed.add(runId);
23063
+ }).catch(() => {
23064
+ this.recordingTimingFailed.add(runId);
23065
+ }).finally(() => {
23066
+ pending.delete(write);
23067
+ if (!pending.size) this.recordingSteps.delete(runId);
22567
23068
  });
23069
+ pending.add(write);
23070
+ this.recordingSteps.set(runId, pending);
22568
23071
  }
22569
- requestCall(token, grant, call, signal) {
23072
+ requestCall(token, grant, call, signal, step) {
22570
23073
  const actionId = randomUUID9();
22571
23074
  const assertLive = () => {
22572
23075
  if (this.suspended || signal?.aborted || this.grants.get(token) !== grant || this.driver?.fingerprint !== grant.fingerprint || !this.permitted(grant.runId))
@@ -22575,7 +23078,7 @@ var ComputerBroker = class {
22575
23078
  if (grant.permission === "allow") {
22576
23079
  return Promise.resolve().then(() => {
22577
23080
  assertLive();
22578
- return this.execute(this.driver, call, grant.display, grant.runId, { actionId, assertLive });
23081
+ return this.executeRecorded(this.driver, call, grant.display, grant.runId, { actionId, assertLive }, step);
22579
23082
  });
22580
23083
  }
22581
23084
  if (this.needsPerson) {
@@ -22590,15 +23093,15 @@ var ComputerBroker = class {
22590
23093
  }).then((needsPerson) => {
22591
23094
  if (needsPerson !== false) {
22592
23095
  if (needsPerson !== true) console.warn(`Decision fallback: computer action ${call.name} reviewed as before without a judgment`);
22593
- return this.review(token, grant, call, actionId, assertLive, signal);
23096
+ return this.review(token, grant, call, actionId, assertLive, signal, step);
22594
23097
  }
22595
23098
  assertLive();
22596
- return this.execute(this.driver, call, grant.display, grant.runId, { actionId, assertLive });
23099
+ return this.executeRecorded(this.driver, call, grant.display, grant.runId, { actionId, assertLive }, step);
22597
23100
  });
22598
23101
  }
22599
- return this.review(token, grant, call, actionId, assertLive, signal);
23102
+ return this.review(token, grant, call, actionId, assertLive, signal, step);
22600
23103
  }
22601
- review(token, grant, call, actionId, assertLive, signal) {
23104
+ review(token, grant, call, actionId, assertLive, signal, step) {
22602
23105
  if (this.pending.size >= 20) return Promise.reject(new Error("Not permitted"));
22603
23106
  const request2 = {
22604
23107
  id: actionId,
@@ -22608,8 +23111,8 @@ var ComputerBroker = class {
22608
23111
  call,
22609
23112
  expiresAt: this.now() + this.ttl
22610
23113
  };
22611
- const digest9 = createHash18("sha256").update(JSON.stringify(request2)).digest("hex");
22612
- return new Promise((resolve19, reject) => {
23114
+ const digest9 = createHash19("sha256").update(JSON.stringify(request2)).digest("hex");
23115
+ return new Promise((resolve20, reject) => {
22613
23116
  const timer = setTimeout(() => {
22614
23117
  this.pending.delete(request2.id);
22615
23118
  signal?.removeEventListener("abort", cancel);
@@ -22623,10 +23126,11 @@ var ComputerBroker = class {
22623
23126
  signal?.addEventListener("abort", cancel, { once: true });
22624
23127
  this.pending.set(request2.id, {
22625
23128
  token,
23129
+ step,
22626
23130
  assertLive,
22627
23131
  cleanup: () => signal?.removeEventListener("abort", cancel),
22628
23132
  request: { ...request2, digest: digest9 },
22629
- resolve: resolve19,
23133
+ resolve: resolve20,
22630
23134
  reject,
22631
23135
  timer
22632
23136
  });
@@ -22640,9 +23144,20 @@ var ComputerBroker = class {
22640
23144
  return { error: "Not permitted" };
22641
23145
  const call = normalizeCaptureCall(value);
22642
23146
  try {
23147
+ if (call.action === "stop_recording") {
23148
+ await Promise.all(this.recordingSteps.get(grant.runId) ?? []);
23149
+ if (this.recordingTimingFailed.has(grant.runId))
23150
+ await this.capture(grant.runId, { action: "step", label: "Recording timing incomplete", source: "action" }, signal);
23151
+ }
22643
23152
  const result = await this.capture(grant.runId, call, signal);
22644
- if (call.action === "start_recording" && typeof result?.stopsAt === "string") this.recordingUntil.set(grant.runId, Date.parse(result.stopsAt));
22645
- if (call.action === "stop_recording") this.recordingUntil.delete(grant.runId);
23153
+ if (call.action === "start_recording" && typeof result?.stopsAt === "string") {
23154
+ this.recordingUntil.set(grant.runId, Date.parse(result.stopsAt));
23155
+ this.recordingTimingFailed.delete(grant.runId);
23156
+ }
23157
+ if (call.action === "stop_recording") {
23158
+ this.recordingUntil.delete(grant.runId);
23159
+ this.recordingTimingFailed.delete(grant.runId);
23160
+ }
22646
23161
  return { result };
22647
23162
  } catch (error) {
22648
23163
  const detail = typeof error?.safeMessage === "string" ? error.safeMessage.slice(0, 300) : void 0;
@@ -22687,7 +23202,7 @@ var ComputerBroker = class {
22687
23202
  throw new Error("Not permitted");
22688
23203
  };
22689
23204
  assertLive();
22690
- row.resolve(await this.execute(this.driver, call, display, runId, { actionId: id5, assertLive }));
23205
+ row.resolve(await this.executeRecorded(this.driver, call, display, runId, { actionId: id5, assertLive }, row.step));
22691
23206
  } catch (error) {
22692
23207
  row.reject(error);
22693
23208
  }
@@ -22708,15 +23223,15 @@ var ComputerBroker = class {
22708
23223
  async close() {
22709
23224
  this.suspend();
22710
23225
  for (const socket of this.sockets) socket.destroy();
22711
- if (this.server?.listening) await new Promise((resolve19) => this.server.close(resolve19));
23226
+ if (this.server?.listening) await new Promise((resolve20) => this.server.close(resolve20));
22712
23227
  }
22713
23228
  };
22714
23229
 
22715
23230
  // src/computer/credential-executor.ts
22716
- import { createHash as createHash19 } from "node:crypto";
23231
+ import { createHash as createHash20 } from "node:crypto";
22717
23232
  function credentialAwareExecutor(deps) {
22718
23233
  return async (driver, call, display, runId, context) => {
22719
- const digest9 = createHash19("sha256").update(JSON.stringify(call)).digest("hex");
23234
+ const digest9 = createHash20("sha256").update(JSON.stringify(call)).digest("hex");
22720
23235
  const resolved = await deps.consumeMatchingIntent(runId, context.actionId, digest9);
22721
23236
  context.assertLive();
22722
23237
  if (resolved.kind === "ordinary") return deps.executeOrdinary(driver, call, display, runId, context.assertLive);
@@ -22755,8 +23270,8 @@ function createHostedComputerExecutor(deps) {
22755
23270
  // src/computer/web-review.ts
22756
23271
  async function applyWebComputerDecisions(broker, decisions) {
22757
23272
  for (const decision of decisions) {
22758
- const snapshot3 = broker.list().find((row) => row.id === decision.id);
22759
- if (!snapshot3 || snapshot3.digest !== decision.digest) continue;
23273
+ const snapshot4 = broker.list().find((row) => row.id === decision.id);
23274
+ if (!snapshot4 || snapshot4.digest !== decision.digest) continue;
22760
23275
  await broker.decide(decision.id, decision.digest, decision.approve).catch(() => void 0);
22761
23276
  }
22762
23277
  }
@@ -22783,9 +23298,9 @@ async function pollWebComputerReviews(broker, deviceId, link, signal, intervalMs
22783
23298
  });
22784
23299
  try {
22785
23300
  while (!signal.aborted) {
22786
- const snapshot3 = broker.list();
22787
- const pending = snapshot3.length > 0;
22788
- const key2 = snapshotKey(snapshot3);
23301
+ const snapshot4 = broker.list();
23302
+ const pending = snapshot4.length > 0;
23303
+ const key2 = snapshotKey(snapshot4);
22789
23304
  const everyCheck = (pushes?.mode("computerReviews") ?? "legacy") !== "push";
22790
23305
  if (key2 !== synced || pending && (pushed || everyCheck || Date.now() - syncedAt >= presenceMs)) {
22791
23306
  pushed = false;
@@ -22798,11 +23313,11 @@ async function pollWebComputerReviews(broker, deviceId, link, signal, intervalMs
22798
23313
  }
22799
23314
  if (signal.aborted) break;
22800
23315
  if (pushes) await pushes.next(intervalMs, signal);
22801
- else await new Promise((resolve19) => {
23316
+ else await new Promise((resolve20) => {
22802
23317
  const done = () => {
22803
23318
  clearTimeout(timer);
22804
23319
  signal.removeEventListener("abort", done);
22805
- resolve19();
23320
+ resolve20();
22806
23321
  };
22807
23322
  const timer = setTimeout(done, intervalMs);
22808
23323
  signal.addEventListener("abort", done, { once: true });
@@ -22847,16 +23362,16 @@ var DeviceWorkSignal = class {
22847
23362
  }
22848
23363
  /** Resolves on the next push or mode change, after `ms`, or on abort. */
22849
23364
  next(ms2, signal) {
22850
- return new Promise((resolve19) => {
23365
+ return new Promise((resolve20) => {
22851
23366
  if (signal?.aborted) {
22852
- resolve19();
23367
+ resolve20();
22853
23368
  return;
22854
23369
  }
22855
23370
  const done = () => {
22856
23371
  clearTimeout(timer);
22857
23372
  off();
22858
23373
  signal?.removeEventListener("abort", done);
22859
- resolve19();
23374
+ resolve20();
22860
23375
  };
22861
23376
  const timer = setTimeout(done, Math.max(0, ms2));
22862
23377
  const off = this.subscribe(done);
@@ -22889,8 +23404,8 @@ var HARNESS_RESCAN_MS = 5 * 6e4;
22889
23404
  var MODEL_PROBE_MS = 6 * 60 * 6e4;
22890
23405
  function cloudComputerGrantMatches(assignment, runId, deviceId) {
22891
23406
  if (!assignment?.computer || !deviceId || assignment.runId !== runId || assignment.deviceId !== deviceId) return false;
22892
- const snapshot3 = assignment.policySnapshot?.payload;
22893
- return !snapshot3 || snapshot3.runId === runId && snapshot3.deviceId === deviceId && snapshot3.ownerId === assignment.computer.ownerId;
23407
+ const snapshot4 = assignment.policySnapshot?.payload;
23408
+ return !snapshot4 || snapshot4.runId === runId && snapshot4.deviceId === deviceId && snapshot4.ownerId === assignment.computer.ownerId;
22894
23409
  }
22895
23410
  var Daemon = class {
22896
23411
  constructor(options) {
@@ -22963,6 +23478,7 @@ var Daemon = class {
22963
23478
  localComputerBroker = null;
22964
23479
  /** Messages handed to an agent whose delivery the server has not taken yet. */
22965
23480
  unacked = /* @__PURE__ */ new Set();
23481
+ refusedSteers = /* @__PURE__ */ new Set();
22966
23482
  /** Runs this daemon already started cancelling for a stop request. */
22967
23483
  stopping = /* @__PURE__ */ new Set();
22968
23484
  /** Runs this daemon has ended, whose end the server may not have yet. */
@@ -23001,7 +23517,7 @@ var Daemon = class {
23001
23517
  if (this.options.credential)
23002
23518
  this.saveDevice({ credential: this.options.credential });
23003
23519
  this.journal = new RunJournal(paths.journal);
23004
- this.captureUploader = new CaptureUploader((runId) => join35(runPaths(paths.adapterState, runId).runDir, CAPTURES_DIR), this.options.link, this.log, join35(paths.dataDir, "capture-pending"));
23520
+ this.captureUploader = new CaptureUploader((runId) => join36(runPaths(paths.adapterState, runId).runDir, CAPTURES_DIR), this.options.link, this.log, join36(paths.dataDir, "capture-pending"));
23005
23521
  this.outbox = new Outbox(
23006
23522
  paths.outbox,
23007
23523
  this.options.link,
@@ -23020,7 +23536,7 @@ var Daemon = class {
23020
23536
  if (this.localComputerDriver && this.options.link.syncComputerReviews) {
23021
23537
  this.localComputerBroker = new ComputerBroker({
23022
23538
  driver: this.localComputerDriver,
23023
- socketPath: join35(paths.dataDir, "local-computer.sock"),
23539
+ socketPath: join36(paths.dataDir, "local-computer.sock"),
23024
23540
  transport: "tcp",
23025
23541
  needsPerson: this.computerNeedsPerson(),
23026
23542
  permitted: (runId) => {
@@ -23063,7 +23579,7 @@ var Daemon = class {
23063
23579
  };
23064
23580
  this.cloudComputerBroker = new ComputerBroker({
23065
23581
  driver,
23066
- socketPath: join35(paths.dataDir, "computer.sock"),
23582
+ socketPath: join36(paths.dataDir, "computer.sock"),
23067
23583
  needsPerson: this.computerNeedsPerson(),
23068
23584
  permitted: (runId) => {
23069
23585
  const entry = this.journal.get(runId);
@@ -23142,7 +23658,7 @@ var Daemon = class {
23142
23658
  ) : this.realAdapters()
23143
23659
  ]);
23144
23660
  this.supervisor = new RunSupervisor({
23145
- acquireWorkspaceControl: this.options.taskRegistered ? (assignment, signal, onLost) => acquireCloudWorkspaceControl({ runId: assignment.runId, deviceId: assignment.deviceId, signal, onLost }) : void 0,
23661
+ acquireWorkspaceControl: this.options.e2bContainerRuntime || this.options.taskRegistered ? (assignment, signal, onLost) => acquireCloudWorkspaceControl({ runId: assignment.runId, deviceId: assignment.deviceId, signal, onLost }) : void 0,
23146
23662
  collectCliTiming: this.options.collectCliTiming,
23147
23663
  journal: this.journal,
23148
23664
  adapterStateDir: this.paths.adapterState,
@@ -23157,7 +23673,7 @@ var Daemon = class {
23157
23673
  prepareRunMailbox: this.options.link.prepareRunMailbox?.bind(this.options.link),
23158
23674
  prepareRunToolApproval: this.options.link.prepareRunToolApproval?.bind(this.options.link),
23159
23675
  prepareRunGitHub: hosted ? void 0 : (assignment, signal, onCredential) => prepareLocalGitHub(assignment, {
23160
- stateDir: join35(this.paths.adapterState, "github"),
23676
+ stateDir: join36(this.paths.adapterState, "github"),
23161
23677
  link: this.options.link,
23162
23678
  signal,
23163
23679
  onCredential,
@@ -23227,7 +23743,7 @@ var Daemon = class {
23227
23743
  worktree,
23228
23744
  tree,
23229
23745
  github: { ...assignment.github, runToken: assignment.mcp?.token, issueId: assignment.issueId },
23230
- privateDir: join35(paths.adapterState, "pids"),
23746
+ privateDir: join36(paths.adapterState, "pids"),
23231
23747
  ...hosted ? { hosted: true } : {},
23232
23748
  env: hosted ? process.env : githubReceiptEnvironment(),
23233
23749
  githubEnvironment,
@@ -23274,6 +23790,7 @@ var Daemon = class {
23274
23790
  ...this.modelReports.get(info.harness),
23275
23791
  // The run's live gate stops a revoked run; Codex also verifies its
23276
23792
  // pinned interface at initialize.
23793
+ ...info.harness === "codex" && info.installed ? { activeTurnSteer: true } : {},
23277
23794
  toolApproval: this.supportsToolApproval(info),
23278
23795
  coordinator: false
23279
23796
  })) : await Promise.all(supported.map((info) => this.localHarnessReport(info)));
@@ -23324,10 +23841,13 @@ var Daemon = class {
23324
23841
  await this.pauseCommands(1e3, signal);
23325
23842
  continue;
23326
23843
  }
23327
- if (this.unacked.size > 0) {
23844
+ if (this.unacked.size > 0 || this.refusedSteers.size > 0) {
23328
23845
  const ids = [...this.unacked].slice(0, 500);
23329
- await link.ackCommands(deviceId, ids);
23846
+ const refused2 = [...this.refusedSteers].slice(0, 500);
23847
+ if (refused2.length) await link.ackCommands(deviceId, ids, refused2);
23848
+ else await link.ackCommands(deviceId, ids);
23330
23849
  for (const id5 of ids) this.unacked.delete(id5);
23850
+ for (const id5 of refused2) this.refusedSteers.delete(id5);
23331
23851
  }
23332
23852
  if (await this.holdGateway(deviceId, signal)) {
23333
23853
  backoff = 1e3;
@@ -23375,7 +23895,7 @@ var Daemon = class {
23375
23895
  await this.pauseCommands(500, signal);
23376
23896
  continue;
23377
23897
  }
23378
- if (this.unacked.size > 0) continue;
23898
+ if (this.unacked.size > 0 || this.refusedSteers.size > 0) continue;
23379
23899
  if (news) continue;
23380
23900
  if (commands.length === 0 && !signal.aborted) {
23381
23901
  const remaining = Math.max(1e3, wait * 1e3) - (performance.now() - started);
@@ -23418,10 +23938,13 @@ var Daemon = class {
23418
23938
  if (this.stopped || signal.aborted) return;
23419
23939
  await this.applyCommands(commands);
23420
23940
  if (queued.length > 0) this.claimQueued(queued);
23421
- while (this.unacked.size > 0 && !signal.aborted) {
23941
+ while ((this.unacked.size > 0 || this.refusedSteers.size > 0) && !signal.aborted) {
23422
23942
  const ids = [...this.unacked].slice(0, 500);
23423
- await this.options.link.ackCommands(deviceId, ids);
23943
+ const refused2 = [...this.refusedSteers].slice(0, 500);
23944
+ if (refused2.length) await this.options.link.ackCommands(deviceId, ids, refused2);
23945
+ else await this.options.link.ackCommands(deviceId, ids);
23424
23946
  for (const id5 of ids) this.unacked.delete(id5);
23947
+ for (const id5 of refused2) this.refusedSteers.delete(id5);
23425
23948
  }
23426
23949
  }
23427
23950
  /**
@@ -23450,8 +23973,8 @@ var Daemon = class {
23450
23973
  }
23451
23974
  if (signal.aborted) return false;
23452
23975
  const socket = openDeviceGateway(ticket.url, ticket.protocol);
23453
- void daemonTracer.span("daemon.gateway.connect", { "mikka.gateway.mode": this.runControlPush ? "push" : "legacy" }, () => new Promise((resolve19, reject) => {
23454
- gatewayOpened = resolve19;
23976
+ void daemonTracer.span("daemon.gateway.connect", { "mikka.gateway.mode": this.runControlPush ? "push" : "legacy" }, () => new Promise((resolve20, reject) => {
23977
+ gatewayOpened = resolve20;
23455
23978
  gatewayFailed = reject;
23456
23979
  }), { root: true }).catch(() => void 0);
23457
23980
  await runDeviceGateway(socket, {
@@ -23576,12 +24099,12 @@ var Daemon = class {
23576
24099
  /** Waits `ms`, or less if the daemon stops or the device registers. */
23577
24100
  pauseCommands(ms2, signal) {
23578
24101
  if (signal.aborted) return Promise.resolve();
23579
- return new Promise((resolve19) => {
24102
+ return new Promise((resolve20) => {
23580
24103
  const done = () => {
23581
24104
  clearTimeout(timer);
23582
24105
  signal.removeEventListener("abort", done);
23583
24106
  this.wakeCommands = null;
23584
- resolve19();
24107
+ resolve20();
23585
24108
  };
23586
24109
  const timer = setTimeout(done, ms2);
23587
24110
  signal.addEventListener("abort", done, { once: true });
@@ -23617,6 +24140,33 @@ var Daemon = class {
23617
24140
  for (const command of commands) {
23618
24141
  const entry = this.journal.get(command.runId);
23619
24142
  if (!entry) continue;
24143
+ if (command.kind === "steer") {
24144
+ const id5 = command.messageId;
24145
+ const prior = entry.steerReceipts?.[id5];
24146
+ if (prior === "accepted") {
24147
+ this.unacked.add(id5);
24148
+ continue;
24149
+ }
24150
+ if (prior || isTerminalRunState(entry.state)) {
24151
+ this.refusedSteers.add(id5);
24152
+ continue;
24153
+ }
24154
+ const record3 = (outcome) => this.journal.update(
24155
+ command.runId,
24156
+ { steerReceipts: { ...this.journal.get(command.runId)?.steerReceipts, [id5]: outcome } }
24157
+ );
24158
+ record3("starting");
24159
+ try {
24160
+ await this.supervisor.send(command.runId, command.text, "steer");
24161
+ record3("accepted");
24162
+ this.unacked.add(id5);
24163
+ } catch {
24164
+ record3("refused");
24165
+ this.refusedSteers.add(id5);
24166
+ }
24167
+ acted = true;
24168
+ continue;
24169
+ }
23620
24170
  if (isTerminalRunState(entry.state)) {
23621
24171
  if (command.kind === "stop")
23622
24172
  void this.supervisor.discardIfEmpty(command.runId, command.runId);
@@ -23685,6 +24235,7 @@ var Daemon = class {
23685
24235
  const report2 = {
23686
24236
  ...info,
23687
24237
  ...this.modelReports.get(info.harness),
24238
+ ...info.harness === "codex" && info.installed ? { activeTurnSteer: true } : {},
23688
24239
  toolApproval: this.supportsToolApproval(info),
23689
24240
  coordinator: false
23690
24241
  };
@@ -23825,11 +24376,11 @@ var Daemon = class {
23825
24376
  return runVerify(sandbox, {
23826
24377
  command,
23827
24378
  worktree: realpathSync15(worktree),
23828
- tmpRoot: join35(this.paths.adapterState, "verify", runId),
24379
+ tmpRoot: join36(this.paths.adapterState, "verify", runId),
23829
24380
  privateDir: paths.privateDir,
23830
24381
  pidFile: paths.pidFile.replace(/\.pgid$/, ".verify.pgid"),
23831
24382
  networkAllow: repo.networkAllow,
23832
- env: { ...buildChildEnv(), ...githubEnvironment, MIKKA_HANDOFF_FILE: join35(paths.runDir, "handoff.json") },
24383
+ env: { ...buildChildEnv(), ...githubEnvironment, MIKKA_HANDOFF_FILE: join36(paths.runDir, "handoff.json") },
23833
24384
  timeoutMs,
23834
24385
  signal,
23835
24386
  readOnly
@@ -23919,7 +24470,7 @@ var Daemon = class {
23919
24470
  }
23920
24471
  /** Idle on the push socket: no runs, nothing waiting to upload. The database can sleep. */
23921
24472
  gatewayIdle() {
23922
- return this.gatewayLive && this.server === "online" && this.supervisor.heartbeatRuns().length === 0 && this.queuedClaims.size === 0 && this.unacked.size === 0 && this.outbox.pending() === 0 && !this.draining && !this.updating && this.deviceReceiptsVersion === this.deviceReceiptsAcknowledged;
24473
+ return this.gatewayLive && this.server === "online" && this.supervisor.heartbeatRuns().length === 0 && this.queuedClaims.size === 0 && this.unacked.size === 0 && this.refusedSteers.size === 0 && this.outbox.pending() === 0 && !this.draining && !this.updating && this.deviceReceiptsVersion === this.deviceReceiptsAcknowledged;
23923
24474
  }
23924
24475
  schedule(delay2) {
23925
24476
  if (this.stopped) return;
@@ -24001,14 +24552,14 @@ var Daemon = class {
24001
24552
  }
24002
24553
  const initialRunId = this.initialRunHint;
24003
24554
  let resolveRepositories, rejectRepositories;
24004
- const repositoriesReady = initialRunId ? new Promise((resolve19, reject) => {
24005
- resolveRepositories = resolve19;
24555
+ const repositoriesReady = initialRunId ? new Promise((resolve20, reject) => {
24556
+ resolveRepositories = resolve20;
24006
24557
  rejectRepositories = reject;
24007
24558
  }) : void 0;
24008
24559
  if (initialRunId && repositoriesReady) {
24009
24560
  let received;
24010
- const repository2 = this.options.hostedSubscriptions && this.options.e2bContainerRuntime && this.journal.all().length === 0 ? new Promise((resolve19) => {
24011
- received = resolve19;
24561
+ const repository2 = this.options.hostedSubscriptions && this.options.e2bContainerRuntime && this.journal.all().length === 0 ? new Promise((resolve20) => {
24562
+ received = resolve20;
24012
24563
  }) : void 0;
24013
24564
  this.initialRepositorySync = { runId: initialRunId, ready: repositoriesReady, repository: repository2, received };
24014
24565
  void repositoriesReady.catch(() => void 0);
@@ -24437,7 +24988,7 @@ var Daemon = class {
24437
24988
  });
24438
24989
  }
24439
24990
  get updateStateFile() {
24440
- return join35(this.paths.dataDir, "auto-update.json");
24991
+ return join36(this.paths.dataDir, "auto-update.json");
24441
24992
  }
24442
24993
  /** A server named this release (heartbeat, commands poll or refused claim); older servers name none. */
24443
24994
  learnRelease(latest) {
@@ -24536,7 +25087,7 @@ function isNoDaemon(error) {
24536
25087
  }
24537
25088
  async function connectDaemon(options) {
24538
25089
  const socket = connect(options.socketPath);
24539
- await new Promise((resolve19, reject) => {
25090
+ await new Promise((resolve20, reject) => {
24540
25091
  const timer = setTimeout(() => {
24541
25092
  socket.destroy();
24542
25093
  reject(
@@ -24547,7 +25098,7 @@ async function connectDaemon(options) {
24547
25098
  }, options.timeoutMs ?? 3e3);
24548
25099
  socket.once("connect", () => {
24549
25100
  clearTimeout(timer);
24550
- resolve19();
25101
+ resolve20();
24551
25102
  });
24552
25103
  socket.once("error", (error) => {
24553
25104
  clearTimeout(timer);
@@ -24584,9 +25135,9 @@ async function connectDaemon(options) {
24584
25135
  if (isProtocolMismatch(error) && options.drainOnMismatch) {
24585
25136
  await Promise.race([
24586
25137
  connection.sendRequest("daemon.drain", {}).catch(() => void 0),
24587
- new Promise((resolve19) => {
24588
- connection.onClose(resolve19);
24589
- setTimeout(resolve19, 2e3).unref();
25138
+ new Promise((resolve20) => {
25139
+ connection.onClose(resolve20);
25140
+ setTimeout(resolve20, 2e3).unref();
24590
25141
  })
24591
25142
  ]);
24592
25143
  }
@@ -24645,8 +25196,8 @@ async function connectStartingDaemon(dataDir) {
24645
25196
  }
24646
25197
  if (!daemonProcessAlive(dataDir)) return void 0;
24647
25198
  if (revision2 !== before) continue;
24648
- await new Promise((resolve19) => {
24649
- wake = resolve19;
25199
+ await new Promise((resolve20) => {
25200
+ wake = resolve20;
24650
25201
  });
24651
25202
  wake = void 0;
24652
25203
  }