@aspectlylabs/mikka 0.0.702 → 0.0.703

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
@@ -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((resolve20) => {
2106
+ return new Promise((resolve19) => {
2107
2107
  const socket = createConnection(socketPath);
2108
2108
  const done = (alive) => {
2109
2109
  socket.destroy();
2110
- resolve20(alive);
2110
+ resolve19(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((resolve20) => file.end(resolve20));
2219
+ return new Promise((resolve19) => file.end(resolve19));
2220
2220
  }
2221
2221
 
2222
2222
  // src/auto-update.ts
@@ -2248,6 +2248,7 @@ async function runServiceNpm(args) {
2248
2248
  });
2249
2249
  return stdout.trim();
2250
2250
  }
2251
+ var STABLE_VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;
2251
2252
  async function managedAutoUpdateRuntime(entry, flavor, enabled) {
2252
2253
  if (!enabled || flavor !== "prod" || !["systemd", "launchd"].includes(process.env.MIKKA_SERVICE ?? "")) return;
2253
2254
  try {
@@ -2260,6 +2261,10 @@ async function managedAutoUpdateRuntime(entry, flavor, enabled) {
2260
2261
  return {
2261
2262
  install: async (version) => {
2262
2263
  await runServiceNpm(["install", "--global", "--engine-strict", `${PACKAGE}@${version}`]);
2264
+ },
2265
+ latest: async () => {
2266
+ const version = await runServiceNpm(["view", `${PACKAGE}@latest`, "version"]).catch(() => "");
2267
+ return STABLE_VERSION.test(version) ? version : void 0;
2263
2268
  }
2264
2269
  };
2265
2270
  } catch {
@@ -4320,6 +4325,15 @@ var daemonStatusSchema = z15.object({
4320
4325
  /** Holds a device credential (it may still be refused by the server). */
4321
4326
  signedIn: z15.boolean(),
4322
4327
  server: z15.enum(["online", "offline", "unregistered"]),
4328
+ /**
4329
+ * The device session (decision 2026-11-17-2215). `update_required`: the
4330
+ * server refused this daemon version; it does nothing until it is updated.
4331
+ * `gateway_required`: the server has no device gateway, so it has no devices.
4332
+ * Absent from older daemons.
4333
+ */
4334
+ session: z15.enum(["signed_out", "connecting", "open", "update_required", "gateway_required"]).optional(),
4335
+ /** With `update_required`: the oldest version the server accepts, if it said. */
4336
+ requiredVersion: z15.string().max(40).nullable().optional(),
4323
4337
  harnesses: z15.array(harnessInfoSchema),
4324
4338
  runs: z15.array(runSummarySchema),
4325
4339
  /** Bytes used by run worktrees under the daemon's data dir. */
@@ -5447,11 +5461,10 @@ var runDecisionCatalogueSchema = z24.object({
5447
5461
  (value) => new TextEncoder().encode(JSON.stringify(value)).length <= 32768,
5448
5462
  { message: "Prepared decision catalogue is bounded" }
5449
5463
  );
5450
- var RUN_LEASE_MS = 9e4;
5451
5464
  var seg = encodeURIComponent;
5452
5465
  var DEVICE_ROUTES = {
5453
5466
  register: "/v1/devices/register",
5454
- heartbeat: "/v1/devices/:deviceId/heartbeat",
5467
+ report: "/v1/devices/:deviceId/report",
5455
5468
  repos: "/v1/devices/:deviceId/repos",
5456
5469
  pendingRuns: "/v1/devices/:deviceId/runs",
5457
5470
  claim: "/v1/devices/:deviceId/runs/:runId/claim",
@@ -5463,7 +5476,7 @@ var DEVICE_ROUTES = {
5463
5476
  };
5464
5477
  var devicePaths = {
5465
5478
  register: () => DEVICE_ROUTES.register,
5466
- heartbeat: (deviceId) => `/v1/devices/${seg(deviceId)}/heartbeat`,
5479
+ report: (deviceId) => `/v1/devices/${seg(deviceId)}/report`,
5467
5480
  repos: (deviceId) => `/v1/devices/${seg(deviceId)}/repos`,
5468
5481
  pendingRuns: (deviceId) => `/v1/devices/${seg(deviceId)}/runs?state=queued`,
5469
5482
  claim: (deviceId, runId) => `/v1/devices/${seg(deviceId)}/runs/${seg(runId)}/claim`,
@@ -5518,69 +5531,49 @@ var deviceRegistered = z24.object({
5518
5531
  environment: z24.enum(["production", "preview", "dev"]).optional()
5519
5532
  }).optional().catch(void 0)
5520
5533
  });
5521
- var heartbeatRunSchema = z24.object({
5522
- runId: id3,
5523
- /** Last tool call, turn boundary or file change (not raw output). */
5524
- lastProgressAt: isoTime,
5525
- /** Opaque third-party capabilities, refreshed only with the existing run lease. */
5526
- secretCapabilities: taskSecretRenewalSchema.optional()
5527
- });
5534
+ var DEVICE_SESSION_HEADER = "x-mikka-device-session";
5535
+ var DEVICE_SESSION_VERSION = 1;
5536
+ var DEVICE_SESSION_LOCAL_GRACE_MS = 6e4;
5537
+ var SESSION_LEASE_MS = 7 * 24 * 60 * 60 * 1e3;
5538
+ var deviceSessionReportSchema = z24.object({
5539
+ state: z24.enum(["connected", "disconnected"]),
5540
+ /** When the socket opened, or closed (or last answered a ping). */
5541
+ at: isoTime,
5542
+ /** One value per socket; a report for an older socket never overrides a newer one. */
5543
+ socketId: z24.string().regex(/^[A-Za-z0-9_-]{8,64}$/)
5544
+ }).strict();
5528
5545
  var stableVersion = z24.string().regex(/^(0|[1-9]\d{0,8})\.(0|[1-9]\d{0,8})\.(0|[1-9]\d{0,8})$/);
5529
5546
  var daemonVersionsSchema = z24.object({ min: stableVersion, latest: stableVersion.optional() });
5530
5547
  var daemonUpdateFailureSchema = z24.object({ version: stableVersion, code: z24.enum(["install_failed", "restart_failed"]), at: isoTime });
5531
5548
  var deviceManagementCommand = z24.object({ id: z24.uuid(), kind: z24.enum(["redetect", "restart", "update", "uninstall"]) });
5532
- var deviceHeartbeatSchema = z24.object({
5549
+ var deviceReportSchema = z24.object({
5533
5550
  completedDeviceCommands: z24.array(z24.uuid()).max(100).optional(),
5534
5551
  failedDeviceCommands: z24.array(z24.object({ id: z24.uuid(), error: z24.string().max(500) })).max(100).optional(),
5535
- harnesses: z24.array(harnessInfoSchema).max(20),
5552
+ harnesses: z24.array(harnessInfoSchema).max(20).optional(),
5536
5553
  computerUse: deviceComputerCapability.optional(),
5537
5554
  runner: deviceRunnerCapability.optional(),
5538
5555
  deviceType: z24.enum(["laptop", "server"]).optional(),
5539
- runs: z24.array(heartbeatRunSchema).max(500),
5540
- worktreeDiskBytes: z24.number().int().nonnegative(),
5541
- /**
5542
- * Subscription windows read on this device. Absent when the daemon is not
5543
- * polling. Numbers only, never a vendor credential (ADR 0027).
5544
- */
5556
+ worktreeDiskBytes: z24.number().int().nonnegative().optional(),
5557
+ /** Subscription windows read on this device. Numbers only, never a vendor credential (ADR 0027). */
5545
5558
  quotas: z24.array(quotaSnapshotSchema).max(6).optional(),
5546
5559
  /** Null once no automatic update has failed since the last success. */
5547
- updateFailure: daemonUpdateFailureSchema.nullable().optional()
5560
+ updateFailure: daemonUpdateFailureSchema.nullable().optional(),
5561
+ /** A cloud worker asks for its next token once, an hour before the current one expires. */
5562
+ rotateCloudCredential: z24.literal(true).optional()
5548
5563
  });
5549
- var heartbeatResultSchema = z24.object({
5564
+ var deviceReportResultSchema = z24.object({
5550
5565
  deviceCommands: z24.array(deviceManagementCommand).max(1).optional(),
5551
- /** Renewed lease expiry per run id; a run missing here is not renewed. */
5552
- leases: z24.record(z24.string(), isoTime),
5553
- /** No plaintext: only grants for current owner/device/run/claim bindings. */
5554
- taskSecrets: z24.record(z24.string(), taskSecretAccessSchema).optional(),
5555
- /**
5556
- * Runs the device reported that it no longer holds: they ended on the
5557
- * server, or went to another attempt after the lease ran out. The daemon
5558
- * stops them now instead of when their lease runs out.
5559
- */
5560
- revoked: z24.array(id3).max(500).optional(),
5561
- /** Subset of revoked caused by an explicit cancel on an otherwise current claim. */
5562
- cancelled: z24.array(id3).max(500).optional(),
5563
5566
  /** Short-lived cloud device token, returned only over its authenticated link. */
5564
5567
  cloudCredential: z24.string().regex(/^orv_[A-Za-z0-9_-]{43}$/).optional(),
5565
- /** A malformed value is dropped, never a failed heartbeat. */
5568
+ cloudCredentialExpiresAt: isoTime.optional(),
5569
+ /** A malformed value is dropped, never a failed report. */
5566
5570
  daemonVersions: daemonVersionsSchema.optional().catch(void 0)
5567
5571
  });
5568
5572
  var deviceGatewaySchema = z24.object({
5569
- url: z24.string().url().nullable(),
5570
- protocol: z24.string().regex(/^mikka-ticket-[0-9]+-[a-f0-9]{64}$/).nullable(),
5571
- /** This server wakes the device after every write that can end, pause or
5572
- * revoke one of its runs (stop, lease, credential, policy, membership), so a
5573
- * connected daemon needs no periodic run-control check (#1212). Absent from
5574
- * older servers: the daemon then keeps its one-second check. */
5575
- runControl: z24.literal("push").optional(),
5576
- /** This server wakes the device when a person decides a computer review in
5577
- * the web, so a connected daemon syncs pending reviews only on a change or a
5578
- * push, plus a presence refresh (#1212). Absent from older servers: the
5579
- * daemon then keeps syncing every second while a review is pending. */
5580
- computerReviews: z24.literal("push").optional(),
5581
- /** This server wakes the device when it writes a native Coordinator tool
5582
- * result, so the waiting tool asks once per push, not every 500 ms. */
5583
- coordinatorResults: z24.literal("push").optional()
5573
+ url: z24.string().url(),
5574
+ protocol: z24.string().regex(/^mikka-ticket-[0-9]+-[a-f0-9]{64}$/),
5575
+ /** Cloud workers only: when the current device token expires. */
5576
+ cloudCredentialExpiresAt: isoTime.optional()
5584
5577
  });
5585
5578
  var RUN_CHECKPOINT_MAX_BYTES = 8 * 1024 * 1024;
5586
5579
  var RECOVERY_WORKTREE_HEADER = "x-mikka-recovery-worktree";
@@ -5739,7 +5732,7 @@ var runAssignmentSchema = z24.object({
5739
5732
  /** Host-owned Factory check mode; the model cannot grant a check or skip verification. */
5740
5733
  factoryCheck: z24.object({ stage: z24.enum(["review", "verify"]), inferCommand: z24.boolean(), reportOnly: z24.boolean() }).strict().optional(),
5741
5734
  factoryExecuteKind: z24.enum(["repository", "report", "deliverable"]).optional(),
5742
- /** Run lease; renewed through the device heartbeat. */
5735
+ /** Run lease in the database: it lasts as long as the device session that claimed the run. */
5743
5736
  leaseExpiresAt: isoTime.optional(),
5744
5737
  /**
5745
5738
  * The Mikka MCP server for the agent inside this run: `report`, `ask` and
@@ -5874,12 +5867,10 @@ var runEventsAccepted = z24.object({
5874
5867
  /** Producer seq of the last chunk the server holds for this run. */
5875
5868
  offset: z24.string()
5876
5869
  });
5877
- var COMMANDS_MAX_WAIT_SECONDS = 25;
5878
5870
  var COMMANDS_SKIP_PARAM = "skip";
5879
5871
  var COMMANDS_MAX_SKIP = 100;
5880
5872
  var COMMANDS_DAEMON_LATEST_PARAM = "daemonLatest";
5881
5873
  var COMMANDS_SKIP_DEVICE_COMMANDS_PARAM = "skipDeviceCommands";
5882
- var COMMANDS_MAX_SKIP_DEVICE_COMMANDS = 10;
5883
5874
  var ACTIVE_TURN_STEER_HEADER = "x-mikka-active-turn-steer";
5884
5875
  var MAILBOX_NOTICE_HEADER = "x-mikka-mailbox-notices";
5885
5876
  var runCommandSchema = z24.discriminatedUnion("kind", [
@@ -5900,21 +5891,19 @@ var runCommandsResponse = z24.object({
5900
5891
  /** Owner-scoped reads, delivered only to a daemon advertising protocol v1. */
5901
5892
  workspaceRequests: z24.array(workspaceReadCommand).max(4).optional(),
5902
5893
  /**
5903
- * Runs queued for this device (outside `skip`), so it claims them now
5904
- * instead of on its next heartbeat. A queued run also ends the long-poll.
5905
- * Absent from older servers; the heartbeat still claims either way.
5894
+ * Runs queued for this device (outside `skip`), so it claims them as soon
5895
+ * as the gateway signals work.
5906
5896
  */
5907
5897
  queuedRuns: z24.array(id3).max(100).optional(),
5908
5898
  /** Only for a daemon that sent `COMMANDS_DAEMON_LATEST_PARAM`; a malformed value is dropped. */
5909
5899
  daemonVersions: daemonVersionsSchema.optional().catch(void 0),
5910
- /** The oldest pending device command (as the heartbeat's), so a person's update reaches the device now. */
5900
+ /** The oldest pending device command, so a person's update reaches the device now. */
5911
5901
  deviceCommands: z24.array(deviceManagementCommand).max(1).optional().catch(void 0)
5912
5902
  });
5913
5903
  var runCommandsAck = z24.object({
5914
5904
  delivered: z24.array(z24.uuid()).max(500),
5915
5905
  refusedSteers: z24.array(z24.uuid()).max(500).optional()
5916
5906
  });
5917
- var FS_REQUESTS_MAX_WAIT_SECONDS = 25;
5918
5907
  var FS_MAX_ENTRIES = 500;
5919
5908
  var fsBrowseRequest = z24.object({
5920
5909
  /** Absolute path on the device; omitted: the device's home folder. */
@@ -6546,19 +6535,34 @@ var ServerUnreachableError = class extends DaemonError {
6546
6535
  this.cause = cause;
6547
6536
  }
6548
6537
  };
6549
- var RunNotPinnedHereError = class extends DaemonError {
6550
- /** The server refused the claim because this daemon is too old (code `daemonUpgradeRequired`). */
6551
- upgradeRequired;
6538
+ var DaemonUpgradeRequiredError = class extends ServerUnreachableError {
6552
6539
  /** The release the refusing server names, when it names one. */
6553
6540
  latest;
6554
- constructor(runId, upgradeRequired = false, latest) {
6541
+ constructor(latest) {
6542
+ super("daemonUpgradeRequired");
6543
+ this.message = "This daemon is too old for the server; update it.";
6544
+ this.latest = latest;
6545
+ }
6546
+ };
6547
+ var DeviceGatewayRequiredError = class extends ServerUnreachableError {
6548
+ constructor() {
6549
+ super("deviceGatewayRequired");
6550
+ this.message = "The server has no device gateway.";
6551
+ }
6552
+ };
6553
+ var DeviceSessionRequiredError = class extends ServerUnreachableError {
6554
+ constructor() {
6555
+ super("deviceSessionRequired");
6556
+ this.message = "The server has no open session for this device.";
6557
+ }
6558
+ };
6559
+ var RunNotPinnedHereError = class extends DaemonError {
6560
+ constructor(runId) {
6555
6561
  super(
6556
6562
  DAEMON_RPC_ERRORS.runNotPinnedHere,
6557
6563
  `Run "${runId}" is pinned to another device`,
6558
6564
  { runId }
6559
6565
  );
6560
- this.upgradeRequired = upgradeRequired;
6561
- this.latest = latest;
6562
6566
  }
6563
6567
  };
6564
6568
  var HarnessNotSupportedError = class extends DaemonError {
@@ -6587,7 +6591,7 @@ import { join as join4 } from "node:path";
6587
6591
  // package.json
6588
6592
  var package_default = {
6589
6593
  name: "@mikka/daemon",
6590
- version: "0.0.702",
6594
+ version: "0.0.703",
6591
6595
  description: "Local Mikka daemon: runs agents through the user's own CLIs",
6592
6596
  type: "module",
6593
6597
  private: true,
@@ -6655,7 +6659,7 @@ var package_default = {
6655
6659
  engines: {
6656
6660
  node: ">=22"
6657
6661
  },
6658
- gitHead: "510757b2cbb43beaadeb284abcc4f36a262ea371"
6662
+ gitHead: "ccd7e6c6680b8485bbba714bc029b5d35db3bd13"
6659
6663
  };
6660
6664
 
6661
6665
  // src/paths.ts
@@ -6663,12 +6667,12 @@ var DAEMON_VERSION = package_default.version;
6663
6667
  function productName(flavor) {
6664
6668
  return flavor === "dev" ? "Mikka Dev" : "Mikka";
6665
6669
  }
6666
- function defaultDataDir(flavor, env = process.env, platform5 = process.platform) {
6670
+ function defaultDataDir(flavor, env = process.env, platform4 = process.platform) {
6667
6671
  if (flavor === "dev" && env.MIKKA_USER_DATA_DIR) {
6668
6672
  return env.MIKKA_USER_DATA_DIR;
6669
6673
  }
6670
6674
  const home = env.HOME || homedir3();
6671
- const base = platform5 === "darwin" ? join4(home, "Library", "Application Support") : platform5 === "win32" ? env.APPDATA || join4(home, "AppData", "Roaming") : env.XDG_CONFIG_HOME || join4(home, ".config");
6675
+ const base = platform4 === "darwin" ? join4(home, "Library", "Application Support") : platform4 === "win32" ? env.APPDATA || join4(home, "AppData", "Roaming") : env.XDG_CONFIG_HOME || join4(home, ".config");
6672
6676
  const dir = join4(base, productName(flavor));
6673
6677
  const legacy = join4(base, legacyProductName(flavor));
6674
6678
  return !existsSync(dir) && existsSync(legacy) ? legacy : dir;
@@ -6745,9 +6749,6 @@ function splitChatFiles(text4) {
6745
6749
  }
6746
6750
 
6747
6751
  // src/agents/tool-approval.ts
6748
- var RUN_CONTROL_LEGACY_MS = 1e3;
6749
- var RUN_CONTROL_FALLBACK_MS = 2e4;
6750
- var cadence = (mode) => mode === "push" ? void 0 : mode === "fallback" ? RUN_CONTROL_FALLBACK_MS : RUN_CONTROL_LEGACY_MS;
6751
6752
  var MAX_TIMER_MS = 2 ** 31 - 1;
6752
6753
  async function abortable(work, signal) {
6753
6754
  if (signal.aborted) throw new Error("cancelled");
@@ -6763,10 +6764,9 @@ async function abortable(work, signal) {
6763
6764
  }
6764
6765
  }
6765
6766
  var ToolApprovalGate = class {
6766
- constructor(runId, host, mode = "legacy") {
6767
+ constructor(runId, host) {
6767
6768
  this.runId = runId;
6768
6769
  this.host = host;
6769
- this.mode = mode;
6770
6770
  }
6771
6771
  runId;
6772
6772
  host;
@@ -6774,19 +6774,12 @@ var ToolApprovalGate = class {
6774
6774
  checking;
6775
6775
  reason;
6776
6776
  monitors = /* @__PURE__ */ new Set();
6777
- timer;
6778
- intervalMs;
6779
6777
  monitoring;
6780
6778
  dirty = false;
6781
- /** A push, mode switch or due time is waiting for the monitor loop. */
6782
- pushed = false;
6783
- mode;
6784
6779
  changes = /* @__PURE__ */ new Set();
6785
6780
  revoke(reason) {
6786
6781
  if (this.revoked) return;
6787
6782
  this.reason = reason;
6788
- clearInterval(this.timer);
6789
- this.timer = void 0;
6790
6783
  for (const monitor of this.monitors) clearTimeout(monitor.due);
6791
6784
  this.monitors.clear();
6792
6785
  this.stop.abort();
@@ -6798,9 +6791,6 @@ var ToolApprovalGate = class {
6798
6791
  get revokeReason() {
6799
6792
  return this.reason;
6800
6793
  }
6801
- get controlMode() {
6802
- return this.mode;
6803
- }
6804
6794
  onRevoke(callback) {
6805
6795
  if (this.revoked) {
6806
6796
  callback();
@@ -6820,34 +6810,22 @@ var ToolApprovalGate = class {
6820
6810
  }
6821
6811
  return this.checking;
6822
6812
  }
6823
- /** Switches how this gate learns of changes. Any switch checks again at
6824
- * once: a push may have been lost while the socket was changing state. */
6825
- setControlMode(mode) {
6826
- if (this.revoked || mode === this.mode) return;
6827
- this.mode = mode;
6828
- this.scheduleMonitor();
6829
- this.invalidate();
6830
- }
6831
- /** Resolves on the next push or mode switch, or after the mode's cadence.
6832
- * A paused run waits here instead of asking the server every second. */
6813
+ /** Resolves on the next push or revocation. A paused run waits here instead
6814
+ * of asking the server on a timer. */
6833
6815
  changed(signal) {
6834
- return new Promise((resolve20, reject) => {
6816
+ return new Promise((resolve19, reject) => {
6835
6817
  if (signal.aborted || this.revoked) {
6836
6818
  reject(new Error("cancelled"));
6837
6819
  return;
6838
6820
  }
6839
- let timer;
6840
6821
  const done = (error) => {
6841
- clearTimeout(timer);
6842
6822
  this.changes.delete(wake);
6843
6823
  signal.removeEventListener("abort", abort);
6844
6824
  if (error) reject(error);
6845
- else resolve20();
6825
+ else resolve19();
6846
6826
  };
6847
6827
  const wake = () => done(this.revoked ? new Error("cancelled") : void 0);
6848
6828
  const abort = () => done(new Error("cancelled"));
6849
- const ms2 = cadence(this.mode);
6850
- if (ms2 !== void 0) timer = setTimeout(wake, ms2);
6851
6829
  this.changes.add(wake);
6852
6830
  signal.addEventListener("abort", abort, { once: true });
6853
6831
  });
@@ -6855,37 +6833,22 @@ var ToolApprovalGate = class {
6855
6833
  wake() {
6856
6834
  for (const wake of [...this.changes]) wake();
6857
6835
  }
6858
- /** Watches the run while it lasts: one background liveness check per run,
6859
- * on each push (invalidate) and, only when the gateway cannot push, on the
6860
- * mode's cadence. Extra checks (credentials, subscription access) share each
6836
+ /** Watches the run while it lasts: one background liveness check per push
6837
+ * (invalidate). Extra checks (credentials, subscription access) share each
6861
6838
  * fresh result; a check may return an epoch ms (an expiry) by which it runs
6862
6839
  * again. Actual operations still call checkLive. Slow credential I/O never
6863
- * delays the next liveness check. `intervalMs` only shortens a timed cadence. */
6864
- watch(check, intervalMs, options = {}) {
6840
+ * delays the next liveness check. */
6841
+ watch(check, options = {}) {
6865
6842
  if (this.revoked) return () => {
6866
6843
  };
6867
- if (intervalMs !== void 0 && (!Number.isFinite(intervalMs) || intervalMs <= 0 || intervalMs > RUN_CONTROL_FALLBACK_MS)) throw new Error("Run monitor interval unavailable");
6868
- const { timedFloorMs } = options;
6869
- if (timedFloorMs !== void 0 && (!Number.isFinite(timedFloorMs) || timedFloorMs <= 0)) throw new Error("Run monitor interval unavailable");
6870
- const monitor = { check, running: false, dirty: false, intervalMs, timedFloorMs };
6844
+ const monitor = { check, running: false, dirty: false };
6871
6845
  this.monitors.add(monitor);
6872
- this.scheduleMonitor();
6873
6846
  if (options.dueAt !== void 0) this.due(monitor, options.dueAt);
6874
6847
  return () => {
6875
6848
  clearTimeout(monitor.due);
6876
6849
  this.monitors.delete(monitor);
6877
- this.scheduleMonitor();
6878
6850
  };
6879
6851
  }
6880
- scheduleMonitor() {
6881
- const base = cadence(this.mode);
6882
- const intervalMs = this.monitors.size && base !== void 0 ? Math.min(base, ...[...this.monitors].flatMap((monitor) => monitor.intervalMs ?? [])) : void 0;
6883
- if (intervalMs === this.intervalMs) return;
6884
- clearInterval(this.timer);
6885
- this.intervalMs = intervalMs;
6886
- this.timer = intervalMs === void 0 ? void 0 : setInterval(() => this.requestCheck(false), intervalMs);
6887
- this.timer?.unref();
6888
- }
6889
6852
  /** One timer per watcher at its reported due time, never a cadence. */
6890
6853
  due(monitor, at) {
6891
6854
  clearTimeout(monitor.due);
@@ -6901,20 +6864,16 @@ var ToolApprovalGate = class {
6901
6864
  /** A push invalidates an in-flight check as well as a settled one. */
6902
6865
  invalidate() {
6903
6866
  this.wake();
6904
- this.requestCheck(true);
6867
+ this.requestCheck();
6905
6868
  }
6906
- requestCheck(invalidated) {
6869
+ requestCheck() {
6907
6870
  if (this.revoked || !this.monitors.size) return;
6908
- if (this.monitoring && !invalidated) return;
6909
6871
  this.dirty = true;
6910
- if (invalidated) this.pushed = true;
6911
6872
  if (this.monitoring) return;
6912
- let olderOperation = invalidated && this.checking !== void 0;
6873
+ let olderOperation = this.checking !== void 0;
6913
6874
  this.monitoring = (async () => {
6914
6875
  while (this.dirty && !this.revoked && this.monitors.size) {
6915
6876
  this.dirty = false;
6916
- const pushed = this.pushed;
6917
- this.pushed = false;
6918
6877
  if (!await this.checkLive()) {
6919
6878
  this.revoke();
6920
6879
  return;
@@ -6922,19 +6881,16 @@ var ToolApprovalGate = class {
6922
6881
  if (olderOperation) {
6923
6882
  olderOperation = false;
6924
6883
  this.dirty = true;
6925
- this.pushed ||= pushed;
6926
6884
  continue;
6927
6885
  }
6928
6886
  for (const monitor of this.monitors) {
6929
6887
  if (!monitor.check) continue;
6930
- if (!pushed && monitor.timedFloorMs !== void 0 && monitor.lastRun !== void 0 && performance.now() - monitor.lastRun < monitor.timedFloorMs) continue;
6931
6888
  monitor.dirty = true;
6932
6889
  if (monitor.running) continue;
6933
6890
  monitor.running = true;
6934
6891
  void (async () => {
6935
6892
  while (monitor.dirty && !this.revoked && this.monitors.has(monitor)) {
6936
6893
  monitor.dirty = false;
6937
- monitor.lastRun = performance.now();
6938
6894
  const due = await monitor.check();
6939
6895
  this.due(monitor, due);
6940
6896
  }
@@ -6947,7 +6903,7 @@ var ToolApprovalGate = class {
6947
6903
  }
6948
6904
  })().finally(() => {
6949
6905
  this.monitoring = void 0;
6950
- if (this.dirty) this.requestCheck(true);
6906
+ if (this.dirty) this.requestCheck();
6951
6907
  });
6952
6908
  }
6953
6909
  };
@@ -7163,7 +7119,7 @@ var requestSchema = z34.union([
7163
7119
  ]);
7164
7120
  var unavailable = () => new Error("Run mailbox unavailable");
7165
7121
  function assertMailboxRunAuthority(input) {
7166
- if (!input.held || !input.state || isTerminalRunState(input.state) || input.stopped || input.lease === void 0 || !Number.isFinite(input.lease) || input.lease <= Date.now()) throw unavailable();
7122
+ if (!input.held || !input.state || isTerminalRunState(input.state) || input.stopped || input.lease === void 0 || Number.isNaN(input.lease) || input.lease <= Date.now()) throw unavailable();
7167
7123
  }
7168
7124
  var uncertain = { isError: true, content: [{ type: "text", text: "Mailbox outcome unconfirmed or unavailable. Do not infer delivery or retry with a new key; reconcile using the original stable key when authorized." }] };
7169
7125
  function mailboxToolResult(result) {
@@ -8160,8 +8116,8 @@ var DaemonTracer = class {
8160
8116
  let timer;
8161
8117
  await Promise.race([
8162
8118
  work,
8163
- new Promise((resolve20) => {
8164
- timer = setTimeout(resolve20, timeoutMs);
8119
+ new Promise((resolve19) => {
8120
+ timer = setTimeout(resolve19, timeoutMs);
8165
8121
  timer.unref();
8166
8122
  })
8167
8123
  ]).finally(() => {
@@ -8457,7 +8413,7 @@ var RunRuntimeTimings = class {
8457
8413
  if (!observation2 || observation2.deviceHash !== runIdHash(decodeURIComponent(github[1]))) return NOOP2;
8458
8414
  return observation2.request(this.refresh.getStore() === hash3 ? "github_credential_refresh" : "github_credential_lease", verb, false);
8459
8415
  }
8460
- const device = /^\/v1\/devices\/([^/]+)\/(heartbeat|gateway|commands|runs)$/.exec(clean);
8416
+ const device = /^\/v1\/devices\/([^/]+)\/(report|gateway|commands|runs)$/.exec(clean);
8461
8417
  if (!device) return NOOP2;
8462
8418
  const hash2 = runIdHash(decodeURIComponent(device[1]));
8463
8419
  const pending = [...this.runs.values()].filter((observation2) => observation2.deviceHash === hash2).map((observation2) => observation2.request("device_control", verb, true));
@@ -8473,6 +8429,12 @@ var runRuntimeTimings = new RunRuntimeTimings();
8473
8429
 
8474
8430
  // src/server-link-http.ts
8475
8431
  var deviceSessionRejection = z35.object({ error: z35.enum(["Unauthorized", "authRequired"]) }).strict();
8432
+ var refusalCode = (body) => {
8433
+ if (typeof body !== "object" || body === null) return void 0;
8434
+ const { code, error } = body;
8435
+ return typeof code === "string" ? code : typeof error === "string" ? error : void 0;
8436
+ };
8437
+ var deviceSessionHeaders = { [DEVICE_SESSION_HEADER]: String(DEVICE_SESSION_VERSION) };
8476
8438
  function checkId(id5) {
8477
8439
  if (id5 === "" || id5 === "." || id5 === "..") {
8478
8440
  throw new InvalidIdError(`Refusing id ${JSON.stringify(id5)} in a URL path`);
@@ -8509,15 +8471,13 @@ var HttpServerLink = class {
8509
8471
  clientVersion;
8510
8472
  protectionBypass;
8511
8473
  runControls = /* @__PURE__ */ new Set();
8512
- runControlMode = "legacy";
8474
+ upgradeListeners = /* @__PURE__ */ new Set();
8513
8475
  /** Wake local waiters; the same push drains authoritative stop commands. */
8514
8476
  invalidateRunControls() {
8515
8477
  for (const gate of this.runControls) gate.invalidate();
8516
8478
  }
8517
- /** The daemon reports whether the gateway can push run control to this run. */
8518
- setRunControlMode(mode) {
8519
- this.runControlMode = mode;
8520
- for (const gate of this.runControls) gate.setControlMode(mode);
8479
+ onUpgradeRequired(listener) {
8480
+ this.upgradeListeners.add(listener);
8521
8481
  }
8522
8482
  async downloadChatFile(assignment, id5, signal) {
8523
8483
  const transfer = await this.call("GET", `/v1/devices/${seg2(assignment.deviceId)}/runs/${seg2(assignment.runId)}/attachments/${seg2(id5)}`, { schema: chatFileTransferSchema, signal, timeoutMs: 6e4 });
@@ -8599,7 +8559,7 @@ var HttpServerLink = class {
8599
8559
  return false;
8600
8560
  }
8601
8561
  }
8602
- }, this.runControlMode);
8562
+ });
8603
8563
  this.runControls.add(gate);
8604
8564
  const abort = () => gate.revoke();
8605
8565
  gate.onRevoke(() => {
@@ -8617,7 +8577,7 @@ var HttpServerLink = class {
8617
8577
  check,
8618
8578
  endpoint: serverUrl(this.baseUrl, "/api/mcp"),
8619
8579
  fetch: (url, init) => this.taskFetch(assignment.runId, "mailbox_operation", url, init),
8620
- headers: { [CLIENT_VERSION_HEADER]: this.clientVersion, ...this.protectionBypass ? { "x-vercel-protection-bypass": this.protectionBypass } : {} }
8580
+ headers: { [CLIENT_VERSION_HEADER]: this.clientVersion, ...deviceSessionHeaders, ...this.protectionBypass ? { "x-vercel-protection-bypass": this.protectionBypass } : {} }
8621
8581
  });
8622
8582
  }
8623
8583
  async claimCoordinator(deviceId, signal) {
@@ -8688,6 +8648,7 @@ var HttpServerLink = class {
8688
8648
  [WORKSPACE_REQUEST_HEADER]: "1",
8689
8649
  [WORKSPACE_DIFF_REQUEST_HEADER]: "1",
8690
8650
  [WORKSPACE_GIT_REQUEST_HEADER]: "1",
8651
+ ...deviceSessionHeaders,
8691
8652
  ...daemonTracer.headers(),
8692
8653
  ...token ? { authorization: `Bearer ${token}` } : {},
8693
8654
  ...this.protectionBypass ? { "x-vercel-protection-bypass": this.protectionBypass } : {}
@@ -8699,6 +8660,13 @@ var HttpServerLink = class {
8699
8660
  status3 = response.status;
8700
8661
  if (response.redirected || response.status >= 300 && response.status < 400)
8701
8662
  throw new Error(`Unexpected server redirect (${response.status})`);
8663
+ if (response.status === 426) {
8664
+ const refused2 = await response.json().catch(() => null);
8665
+ const versions = typeof refused2 === "object" && refused2 !== null ? refused2.daemonVersions : void 0;
8666
+ const latest = daemonVersionsSchema.safeParse(versions).data?.latest;
8667
+ for (const listener of [...this.upgradeListeners]) listener(latest);
8668
+ throw new DaemonUpgradeRequiredError(latest);
8669
+ }
8702
8670
  if (response.status === 401) {
8703
8671
  const body2 = await response.clone().json().catch(() => null);
8704
8672
  if (!deviceSessionRejection.safeParse(body2).success)
@@ -8706,6 +8674,7 @@ var HttpServerLink = class {
8706
8674
  }
8707
8675
  return response;
8708
8676
  } catch (error) {
8677
+ if (error instanceof DaemonUpgradeRequiredError) throw error;
8709
8678
  throw new ServerUnreachableError(error);
8710
8679
  } finally {
8711
8680
  measured(status3);
@@ -8719,13 +8688,17 @@ var HttpServerLink = class {
8719
8688
  this.credential,
8720
8689
  { timeoutMs: options.timeoutMs, signal: options.signal, initialRepository: options.initialRepository }
8721
8690
  );
8691
+ if (response.status === 503 && options.gatewayRequired) {
8692
+ const body = await response.clone().json().catch(() => null);
8693
+ if (refusalCode(body) === "deviceGatewayRequired") throw new DeviceGatewayRequiredError();
8694
+ }
8722
8695
  if (response.status >= 500 || response.status === 429)
8723
8696
  throw new ServerUnreachableError(response.status);
8724
8697
  if (response.status === 401) throw new SessionRejectedError();
8725
8698
  if (response.status === 409 && options.claimOf) {
8726
8699
  const body = await response.json().catch(() => null);
8727
- const upgradeRequired = body?.code === "daemonUpgradeRequired";
8728
- throw new RunNotPinnedHereError(options.claimOf, upgradeRequired, upgradeRequired ? daemonVersionsSchema.safeParse(body?.daemonVersions).data?.latest : void 0);
8700
+ if (refusalCode(body) === "deviceSessionRequired") throw new DeviceSessionRequiredError();
8701
+ throw new RunNotPinnedHereError(options.claimOf);
8729
8702
  }
8730
8703
  if (!response.ok) {
8731
8704
  const detail = await response.json().then(
@@ -8756,10 +8729,10 @@ var HttpServerLink = class {
8756
8729
  });
8757
8730
  return { deviceId, tracing };
8758
8731
  }
8759
- async heartbeat(deviceId, status3) {
8760
- return this.call("POST", devicePaths.heartbeat(checkId(deviceId)), {
8761
- body: status3,
8762
- schema: heartbeatResultSchema
8732
+ async report(deviceId, report2) {
8733
+ return this.call("POST", devicePaths.report(checkId(deviceId)), {
8734
+ body: report2,
8735
+ schema: deviceReportResultSchema
8763
8736
  });
8764
8737
  }
8765
8738
  async listRepos(deviceId) {
@@ -8831,7 +8804,7 @@ var HttpServerLink = class {
8831
8804
  try {
8832
8805
  response = await this.taskFetch(runId, server ? "task_data" : "storage_transfer", server ? serverUrl(this.baseUrl, capturePaths.upload(checkId(runId), checkId(captureId))) : upload.url, {
8833
8806
  method: "PUT",
8834
- 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,
8807
+ headers: server ? { "content-type": contentType, [CLIENT_VERSION_HEADER]: this.clientVersion, ...deviceSessionHeaders, ...this.credential ? { authorization: `Bearer ${this.credential}` } : {}, ...this.protectionBypass ? { "x-vercel-protection-bypass": this.protectionBypass } : {} } : upload.headers,
8835
8808
  body: bytes,
8836
8809
  redirect: "error",
8837
8810
  signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(3e5)]) : AbortSignal.timeout(3e5)
@@ -8839,6 +8812,10 @@ var HttpServerLink = class {
8839
8812
  } catch (error) {
8840
8813
  throw new ServerUnreachableError(error);
8841
8814
  }
8815
+ if (response.status === 426 && server) {
8816
+ for (const listener of [...this.upgradeListeners]) listener();
8817
+ throw new DaemonUpgradeRequiredError();
8818
+ }
8842
8819
  if (response.status >= 500 || response.status === 429) throw new ServerUnreachableError(response.status);
8843
8820
  if (response.status === 401 && server) throw new SessionRejectedError();
8844
8821
  if (!response.ok) throw new DaemonError(response.status, `PUT capture failed: ${response.status}`, { status: response.status });
@@ -8872,7 +8849,9 @@ var HttpServerLink = class {
8872
8849
  return this.call("GET", devicePaths.gateway(checkId(deviceId)), {
8873
8850
  schema: deviceGatewaySchema,
8874
8851
  signal,
8875
- timeoutMs: 1e4
8852
+ timeoutMs: 1e4,
8853
+ // A server without a gateway has no devices: a refusal, not an outage.
8854
+ gatewayRequired: true
8876
8855
  });
8877
8856
  }
8878
8857
  async fetchCommands(deviceId, waitSeconds, {
@@ -8953,6 +8932,7 @@ var HttpServerLink = class {
8953
8932
  };
8954
8933
 
8955
8934
  // src/login.ts
8935
+ var updateRequired = () => new LoginError("failed", "This daemon is too old for the server. Update it first: npm install -g @aspectlylabs/mikka@latest");
8956
8936
  var DEVICE_CODE_PATH = `${AUTH_BASE_PATH}/device/code`;
8957
8937
  var DEVICE_TOKEN_PATH = `${AUTH_BASE_PATH}/device/token`;
8958
8938
  var DEVICE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
@@ -8981,7 +8961,8 @@ async function post(options, path3, body) {
8981
8961
  method: "POST",
8982
8962
  headers: {
8983
8963
  "content-type": "application/json",
8984
- [CLIENT_VERSION_HEADER]: DAEMON_VERSION
8964
+ [CLIENT_VERSION_HEADER]: DAEMON_VERSION,
8965
+ ...deviceSessionHeaders
8985
8966
  },
8986
8967
  body: JSON.stringify(body),
8987
8968
  signal: options.signal
@@ -8989,13 +8970,14 @@ async function post(options, path3, body) {
8989
8970
  } catch (error) {
8990
8971
  throw new ServerUnreachableError(error);
8991
8972
  }
8973
+ if (response.status === 426) throw updateRequired();
8992
8974
  return {
8993
8975
  status: response.status,
8994
8976
  json: await response.json().catch(() => null)
8995
8977
  };
8996
8978
  }
8997
8979
  async function deviceLogin(options) {
8998
- const sleep3 = options.sleep ?? ((ms2) => new Promise((resolve20) => setTimeout(resolve20, ms2)));
8980
+ const sleep3 = options.sleep ?? ((ms2) => new Promise((resolve19) => setTimeout(resolve19, ms2)));
8999
8981
  const started = await post(options, DEVICE_CODE_PATH, {
9000
8982
  client_id: DAEMON_CLIENT_ID,
9001
8983
  device_name: options.deviceName ?? hostname(),
@@ -9047,10 +9029,11 @@ async function registrationLogin(options) {
9047
9029
  if (!/^orv_[A-Za-z0-9_-]{43}$/.test(options.token)) throw new LoginError("failed", "Invalid registration token.");
9048
9030
  const response = await (options.fetchImpl ?? fetch)(serverUrl(options.serverUrl, "/v1/devices/enroll"), {
9049
9031
  method: "POST",
9050
- headers: { authorization: `Bearer ${options.token}` },
9032
+ headers: { authorization: `Bearer ${options.token}`, [CLIENT_VERSION_HEADER]: DAEMON_VERSION, ...deviceSessionHeaders },
9051
9033
  redirect: "error",
9052
9034
  signal: AbortSignal.timeout(3e4)
9053
9035
  });
9036
+ if (response.status === 426) throw updateRequired();
9054
9037
  const body = await response.json().catch(() => null);
9055
9038
  const parsed = tokenResponse.safeParse({ access_token: body?.credential });
9056
9039
  if (!response.ok || !parsed.success) throw new LoginError("failed", "Device registration token expired or already used.");
@@ -9067,8 +9050,8 @@ import {
9067
9050
  rmSync as rmSync21,
9068
9051
  realpathSync as realpathSync15
9069
9052
  } from "node:fs";
9070
- import { arch as arch3, hostname as hostname2, platform as platform4 } from "node:os";
9071
- import { join as join36 } from "node:path";
9053
+ import { arch as arch3, hostname as hostname2, platform as platform3 } from "node:os";
9054
+ import { join as join35 } from "node:path";
9072
9055
  import { fileURLToPath as fileURLToPath2 } from "node:url";
9073
9056
 
9074
9057
  // src/runs/quota-exhausted.ts
@@ -9287,14 +9270,14 @@ import { realpathSync as realpathSync2 } from "node:fs";
9287
9270
  function prepareAgentStart(signal, open5, diagnostics) {
9288
9271
  const lifetime = new AbortController();
9289
9272
  let accept, refuse2;
9290
- const finalOptions = new Promise((resolve20, reject) => {
9291
- accept = resolve20;
9273
+ const finalOptions = new Promise((resolve19, reject) => {
9274
+ accept = resolve19;
9292
9275
  refuse2 = reject;
9293
9276
  });
9294
9277
  void finalOptions.catch(() => void 0);
9295
9278
  let parked, failed;
9296
- const ready = new Promise((resolve20, reject) => {
9297
- parked = resolve20;
9279
+ const ready = new Promise((resolve19, reject) => {
9280
+ parked = resolve19;
9298
9281
  failed = reject;
9299
9282
  });
9300
9283
  void ready.catch(() => void 0);
@@ -9377,8 +9360,8 @@ var ClaimedPromptQueue = class {
9377
9360
  while (!this.closed) {
9378
9361
  const item = this.items.shift();
9379
9362
  if (item) yield item;
9380
- else await new Promise((resolve20) => {
9381
- this.wake = resolve20;
9363
+ else await new Promise((resolve19) => {
9364
+ this.wake = resolve19;
9382
9365
  });
9383
9366
  }
9384
9367
  }
@@ -9663,8 +9646,8 @@ var EventQueue = class {
9663
9646
  if (next.type === "exit") return;
9664
9647
  continue;
9665
9648
  }
9666
- await new Promise((resolve20) => {
9667
- this.waiter = resolve20;
9649
+ await new Promise((resolve19) => {
9650
+ this.waiter = resolve19;
9668
9651
  });
9669
9652
  }
9670
9653
  }
@@ -9741,13 +9724,13 @@ async function spawnCli(sandbox, argv, options) {
9741
9724
  stderr = (stderr + data).slice(-STDERR_TAIL * 4);
9742
9725
  });
9743
9726
  const exited = new Promise(
9744
- (resolve20) => {
9727
+ (resolve19) => {
9745
9728
  child.once("error", (error) => {
9746
9729
  stderr += `
9747
9730
  ${error.message}`;
9748
- resolve20({ code: null, signal: null });
9731
+ resolve19({ code: null, signal: null });
9749
9732
  });
9750
- child.once("exit", (code, signal) => resolve20({ code, signal }));
9733
+ child.once("exit", (code, signal) => resolve19({ code, signal }));
9751
9734
  }
9752
9735
  ).finally(() => {
9753
9736
  signalGroup(pgid, "SIGKILL");
@@ -9764,8 +9747,8 @@ ${error.message}`;
9764
9747
  let timer;
9765
9748
  await Promise.race([
9766
9749
  exited,
9767
- new Promise((resolve20) => {
9768
- timer = setTimeout(resolve20, graceMs);
9750
+ new Promise((resolve19) => {
9751
+ timer = setTimeout(resolve19, graceMs);
9769
9752
  })
9770
9753
  ]);
9771
9754
  clearTimeout(timer);
@@ -9869,11 +9852,11 @@ import { execa as execa3 } from "execa";
9869
9852
  // src/task-env.ts
9870
9853
  var RESERVED = /^(?:PATH|HOME|SHELL|USER|LOGNAME|PWD|TMPDIR|TERM|NODE_OPTIONS|NODE_PATH|NODE_TLS_REJECT_UNAUTHORIZED|NODE_EXTRA_CA_CERTS|NODE_USE_ENV_PROXY|SSL_CERT_.*|REQUESTS_CA_BUNDLE|CURL_CA_BUNDLE|HTTP_PROXY|HTTPS_PROXY|ALL_PROXY|NO_PROXY|LD_.*|DYLD_.*|PYTHONPATH|PYTHONHOME|GIT_.*|GH_.*|GITHUB_TOKEN|GITHUB_ENTERPRISE_TOKEN|SSH_.*|E2B_.*|MIKKA_.*|DOCKER_.*|INFISICAL_.*|WORKSPACE_SECRETS_KEY|CLAUDE_.*|CODEX_.*|ANTHROPIC_.*|OPENAI_.*|DATABASE_URL|BASH_ENV|ENV|PROMPT_COMMAND|PERL5OPT|RUBYOPT|JAVA_TOOL_OPTIONS|NPM_CONFIG_.*|PIP_INDEX_URL|PYTHONSTARTUP|GLOBAL_AGENT_HTTP_PROXY)$/i;
9871
9854
  var NAME = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
9872
- function withTaskEnv(platform5, taskEnv) {
9873
- const env = { ...platform5 };
9855
+ function withTaskEnv(platform4, taskEnv) {
9856
+ const env = { ...platform4 };
9874
9857
  const dropped = [];
9875
9858
  for (const [name, value] of Object.entries(taskEnv ?? {})) {
9876
- if (typeof value !== "string" || !NAME.test(name) || RESERVED.test(name) || Object.hasOwn(platform5, name)) {
9859
+ if (typeof value !== "string" || !NAME.test(name) || RESERVED.test(name) || Object.hasOwn(platform4, name)) {
9877
9860
  dropped.push(name);
9878
9861
  continue;
9879
9862
  }
@@ -9881,8 +9864,8 @@ function withTaskEnv(platform5, taskEnv) {
9881
9864
  }
9882
9865
  return { env, dropped };
9883
9866
  }
9884
- function taskExecutionEnv(platform5, options) {
9885
- const env = withTaskEnv(platform5, options.taskEnv).env;
9867
+ function taskExecutionEnv(platform4, options) {
9868
+ const env = withTaskEnv(platform4, options.taskEnv).env;
9886
9869
  for (const name of ["MIKKA_SECRET_ENDPOINTS", "MIKKA_SECRET_UNAVAILABLE"]) {
9887
9870
  const value = options.taskSecretEnv?.[name];
9888
9871
  if (typeof value === "string") env[name] = value;
@@ -10196,8 +10179,8 @@ var WorktreeManager = class {
10196
10179
  const branches = [];
10197
10180
  for (const runId of runIds) {
10198
10181
  const branch = runBranch(runId);
10199
- const exists2 = await git3.raw(["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]).then((out) => out.trim().length > 0).catch(() => false);
10200
- if (!exists2) continue;
10182
+ const exists = await git3.raw(["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]).then((out) => out.trim().length > 0).catch(() => false);
10183
+ if (!exists) continue;
10201
10184
  const ahead = await git3.raw([
10202
10185
  "rev-list",
10203
10186
  "--count",
@@ -12405,8 +12388,8 @@ var PromptQueue = class {
12405
12388
  continue;
12406
12389
  }
12407
12390
  if (this.closed) return;
12408
- await new Promise((resolve20) => {
12409
- this.waiter = resolve20;
12391
+ await new Promise((resolve19) => {
12392
+ this.waiter = resolve19;
12410
12393
  });
12411
12394
  }
12412
12395
  }
@@ -12420,8 +12403,8 @@ async function untilSpoken(spoken) {
12420
12403
  try {
12421
12404
  return await Promise.race([
12422
12405
  spoken,
12423
- new Promise((resolve20) => {
12424
- timer = setTimeout(() => resolve20(true), CONTINUE_SILENCE_MS);
12406
+ new Promise((resolve19) => {
12407
+ timer = setTimeout(() => resolve19(true), CONTINUE_SILENCE_MS);
12425
12408
  })
12426
12409
  ]);
12427
12410
  } finally {
@@ -12642,15 +12625,15 @@ var ClaudeAdapter = class {
12642
12625
  let authTimer;
12643
12626
  let stderr = "";
12644
12627
  let stderrArrived = () => void 0;
12645
- const firstStderr = new Promise((resolve20) => {
12646
- stderrArrived = resolve20;
12628
+ const firstStderr = new Promise((resolve19) => {
12629
+ stderrArrived = resolve19;
12647
12630
  });
12648
12631
  const stderrTail = () => stderr.slice(-STDERR_TAIL2).trim() || "no output";
12649
12632
  let spoke = () => void 0;
12650
- const spoken = new Promise((resolve20) => spoke = resolve20);
12633
+ const spoken = new Promise((resolve19) => spoke = resolve19);
12651
12634
  let checkingContinuation = mode === "continue";
12652
12635
  let finished = () => void 0;
12653
- const gone = new Promise((resolve20) => finished = resolve20);
12636
+ const gone = new Promise((resolve19) => finished = resolve19);
12654
12637
  let nativeExit = Promise.resolve(false);
12655
12638
  if (externalAuth && this.options.onHostedSession) {
12656
12639
  try {
@@ -12689,10 +12672,10 @@ var ClaudeAdapter = class {
12689
12672
  stderr = previousStderr.slice(-STDERR_TAIL2 * 4);
12690
12673
  stderrArrived();
12691
12674
  }
12692
- nativeExit = new Promise((resolve20) => {
12693
- child.once("exit", () => resolve20(true));
12694
- child.once("error", () => resolve20(false));
12695
- if (child.exitCode !== null || child.signalCode) resolve20(true);
12675
+ nativeExit = new Promise((resolve19) => {
12676
+ child.once("exit", () => resolve19(true));
12677
+ child.once("error", () => resolve19(false));
12678
+ if (child.exitCode !== null || child.signalCode) resolve19(true);
12696
12679
  });
12697
12680
  child.stderr?.on("data", (data) => {
12698
12681
  stderr = (stderr + data.toString()).slice(-STDERR_TAIL2 * 4);
@@ -12918,8 +12901,8 @@ var ClaudeAdapter = class {
12918
12901
  if (!message.is_error) quota = void 0;
12919
12902
  if (message.is_error && externalAuth && !stderr) {
12920
12903
  let drainTimer;
12921
- await Promise.race([firstStderr, new Promise((resolve20) => {
12922
- drainTimer = setTimeout(resolve20, 100);
12904
+ await Promise.race([firstStderr, new Promise((resolve19) => {
12905
+ drainTimer = setTimeout(resolve19, 100);
12923
12906
  })]);
12924
12907
  clearTimeout(drainTimer);
12925
12908
  }
@@ -13115,8 +13098,8 @@ import { randomBytes } from "node:crypto";
13115
13098
  import { createServer } from "node:http";
13116
13099
  var LIMIT = 4096;
13117
13100
  var CODEX_TRACE_BODY_LIMIT = 1048576;
13118
- function codexTraceEnvironment(env, platform5 = process.platform) {
13119
- if (platform5 !== "linux") return void 0;
13101
+ function codexTraceEnvironment(env, platform4 = process.platform) {
13102
+ if (platform4 !== "linux") return void 0;
13120
13103
  const append = (value) => value ? `${value},127.0.0.1` : "127.0.0.1";
13121
13104
  return { NO_PROXY: append(env.NO_PROXY ?? env.no_proxy), no_proxy: append(env.no_proxy ?? env.NO_PROXY) };
13122
13105
  }
@@ -13527,11 +13510,11 @@ async function startCodexGenerationCollector(emit) {
13527
13510
  server.requestTimeout = 1e3;
13528
13511
  server.headersTimeout = 1e3;
13529
13512
  server.maxConnections = 4;
13530
- await new Promise((resolve20, reject) => {
13513
+ await new Promise((resolve19, reject) => {
13531
13514
  server.once("error", reject);
13532
13515
  server.listen(0, "127.0.0.1", () => {
13533
13516
  server.off("error", reject);
13534
- resolve20();
13517
+ resolve19();
13535
13518
  });
13536
13519
  });
13537
13520
  server.on("error", () => collector.reject());
@@ -13551,7 +13534,7 @@ async function startCodexGenerationCollector(emit) {
13551
13534
  "-c",
13552
13535
  "otel.log_guardian_assessments=false"
13553
13536
  ],
13554
- close: (cliExitObserved = false) => closed ??= new Promise((resolve20) => {
13537
+ close: (cliExitObserved = false) => closed ??= new Promise((resolve19) => {
13555
13538
  const timer = setTimeout(() => {
13556
13539
  collector.truncate();
13557
13540
  server.closeAllConnections();
@@ -13559,7 +13542,7 @@ async function startCodexGenerationCollector(emit) {
13559
13542
  timer.unref();
13560
13543
  server.close(() => {
13561
13544
  clearTimeout(timer);
13562
- resolve20(collector.finish(cliExitObserved));
13545
+ resolve19(collector.finish(cliExitObserved));
13563
13546
  });
13564
13547
  })
13565
13548
  };
@@ -13602,11 +13585,11 @@ var JsonlWriter = class extends AbstractMessageWriter {
13602
13585
  }
13603
13586
  stream;
13604
13587
  write(message) {
13605
- return new Promise((resolve20, reject) => {
13588
+ return new Promise((resolve19, reject) => {
13606
13589
  this.stream.write(
13607
13590
  `${JSON.stringify(message)}
13608
13591
  `,
13609
- (error) => error ? reject(error) : resolve20()
13592
+ (error) => error ? reject(error) : resolve19()
13610
13593
  );
13611
13594
  });
13612
13595
  }
@@ -15128,7 +15111,7 @@ var MockAdapter = class {
15128
15111
  if (line.hang) {
15129
15112
  if (!abort.signal.aborted) {
15130
15113
  await new Promise(
15131
- (resolve20) => abort.signal.addEventListener("abort", resolve20, { once: true })
15114
+ (resolve19) => abort.signal.addEventListener("abort", resolve19, { once: true })
15132
15115
  );
15133
15116
  }
15134
15117
  yield { type: "exit", outcome: "cancelled" };
@@ -15485,8 +15468,6 @@ var NoSandbox = class {
15485
15468
  // src/fs-browse.ts
15486
15469
  import { execFile as execFile4 } from "node:child_process";
15487
15470
  import { readdir as readdir2, realpath, stat as stat2 } from "node:fs/promises";
15488
- import { homedir as homedir6, platform as platform2 } from "node:os";
15489
- import { basename as basename5, dirname as dirname14, isAbsolute as isAbsolute6, join as join22, resolve as resolve12 } from "node:path";
15490
15471
  import { promisify as promisify4 } from "node:util";
15491
15472
  var run = promisify4(execFile4);
15492
15473
  async function git(cwd, args) {
@@ -15500,86 +15481,6 @@ async function git(cwd, args) {
15500
15481
  return null;
15501
15482
  }
15502
15483
  }
15503
- async function isDir(path3) {
15504
- try {
15505
- return (await stat2(path3)).isDirectory();
15506
- } catch {
15507
- return false;
15508
- }
15509
- }
15510
- async function exists(path3) {
15511
- try {
15512
- await stat2(path3);
15513
- return true;
15514
- } catch {
15515
- return false;
15516
- }
15517
- }
15518
- async function repoAround(path3) {
15519
- const top = await git(path3, ["rev-parse", "--show-toplevel"]);
15520
- if (!top) return null;
15521
- const origin = await git(top, ["config", "--get", "remote.origin.url"]);
15522
- const first = origin ? null : (await git(top, ["remote"]))?.split("\n")[0] ?? null;
15523
- const remoteUrl = origin ?? (first ? await git(top, ["config", "--get", `remote.${first}.url`]) : null);
15524
- return { path: top, remoteUrl };
15525
- }
15526
- async function browseFolder(request2) {
15527
- const home = homedir6();
15528
- const wanted = request2.path ?? home;
15529
- if (!isAbsolute6(wanted))
15530
- return {
15531
- ok: false,
15532
- code: "not_found",
15533
- message: "Expected an absolute path."
15534
- };
15535
- const path3 = resolve12(wanted);
15536
- if (!await exists(path3))
15537
- return { ok: false, code: "not_found", message: `${path3} does not exist.` };
15538
- if (!await isDir(path3))
15539
- return {
15540
- ok: false,
15541
- code: "not_a_directory",
15542
- message: `${path3} is not a folder.`
15543
- };
15544
- let names;
15545
- try {
15546
- names = await readdir2(path3, { withFileTypes: true });
15547
- } catch (error) {
15548
- const denied2 = error.code;
15549
- return denied2 === "EACCES" || denied2 === "EPERM" ? {
15550
- ok: false,
15551
- code: "denied",
15552
- message: `Mikka may not read ${path3}. Allow access in system settings.`
15553
- } : { ok: false, code: "failed", message: `Could not read ${path3}.` };
15554
- }
15555
- const folders = [];
15556
- let truncated = false;
15557
- const dirs = names.filter((e) => e.isDirectory() || e.isSymbolicLink()).filter((e) => request2.showHidden || !e.name.startsWith(".")).sort((a, b) => a.name.localeCompare(b.name));
15558
- for (const entry of dirs) {
15559
- const full = join22(path3, entry.name);
15560
- if (entry.isSymbolicLink() && !await isDir(full)) continue;
15561
- if (folders.length >= FS_MAX_ENTRIES) {
15562
- truncated = true;
15563
- break;
15564
- }
15565
- folders.push({
15566
- name: entry.name,
15567
- path: full,
15568
- isRepo: await exists(join22(full, ".git"))
15569
- });
15570
- }
15571
- const parent = dirname14(path3);
15572
- return {
15573
- ok: true,
15574
- path: path3,
15575
- parent: parent === path3 || basename5(path3) === "" ? null : parent,
15576
- home,
15577
- platform: platform2(),
15578
- entries: folders,
15579
- truncated,
15580
- repo: await repoAround(path3)
15581
- };
15582
- }
15583
15484
  async function verifyExpectedOrigin(path3, expected2) {
15584
15485
  const key2 = (value) => /^(?:https:\/\/github\.com\/|git@github\.com:)([A-Za-z0-9][A-Za-z0-9-]*)\/([A-Za-z0-9_.-]+?)(?:\.git)?$/.exec(value)?.slice(1).join("/").toLowerCase();
15585
15486
  const top = await git(path3, ["rev-parse", "--show-toplevel"]);
@@ -15623,14 +15524,14 @@ async function detectDeviceType() {
15623
15524
 
15624
15525
  // src/harnesses.ts
15625
15526
  import { statfsSync } from "node:fs";
15626
- import { arch as arch2, platform as platform3 } from "node:os";
15527
+ import { arch as arch2, platform as platform2 } from "node:os";
15627
15528
  import { execa as execa7 } from "execa";
15628
15529
 
15629
15530
  // harness/install.mjs
15630
15531
  import { createHash as createHash8, randomBytes as randomBytes2 } from "node:crypto";
15631
15532
  import { execFile as execFile5 } from "node:child_process";
15632
15533
  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";
15633
- import { dirname as dirname15, join as join23, relative as relative5 } from "node:path";
15534
+ import { dirname as dirname14, join as join22, relative as relative5 } from "node:path";
15634
15535
  import { Readable as Readable2, Transform } from "node:stream";
15635
15536
  import { pipeline as pipeline2 } from "node:stream/promises";
15636
15537
  import { promisify as promisify5 } from "node:util";
@@ -15671,25 +15572,25 @@ var INSTALL_FORMAT = "complete-package-v1\n";
15671
15572
  var installMarker = (pin, artifact) => INSTALL_FORMAT + artifact.integrity + (pin.companions?.length ? "\n" + pin.companions.join("\n") : "");
15672
15573
  var run2 = promisify5(execFile5);
15673
15574
  var inflight = /* @__PURE__ */ new Map();
15674
- function platformKey(platform5 = process.platform, arch4 = process.arch) {
15675
- return `${platform5}-${arch4}`;
15575
+ function platformKey(platform4 = process.platform, arch4 = process.arch) {
15576
+ return `${platform4}-${arch4}`;
15676
15577
  }
15677
15578
  function resolvePin(store, harness) {
15678
15579
  const pin = (store.pins ?? HARNESS_PINS).harnesses[harness];
15679
15580
  return { pin, artifact: pin.platforms[store.platform ?? platformKey()] };
15680
15581
  }
15681
15582
  function versionDir(store, harness) {
15682
- return join23(store.root, harness, resolvePin(store, harness).pin.version);
15583
+ return join22(store.root, harness, resolvePin(store, harness).pin.version);
15683
15584
  }
15684
15585
  function harnessBinaryPath(store, harness) {
15685
- return join23(versionDir(store, harness), "bin", resolvePin(store, harness).pin.command);
15586
+ return join22(versionDir(store, harness), "bin", resolvePin(store, harness).pin.command);
15686
15587
  }
15687
15588
  function harnessInstallState(store, harness) {
15688
15589
  const { pin, artifact } = resolvePin(store, harness);
15689
15590
  if (!artifact) return { state: "unsupported", version: pin.version };
15690
15591
  let installed = false;
15691
15592
  try {
15692
- installed = readFileSync11(join23(versionDir(store, harness), MARKER), "utf8") === installMarker(pin, artifact) && runtimeFiles(store, harness).every((path3) => {
15593
+ installed = readFileSync11(join22(versionDir(store, harness), MARKER), "utf8") === installMarker(pin, artifact) && runtimeFiles(store, harness).every((path3) => {
15693
15594
  const stat3 = statSync2(path3);
15694
15595
  return stat3.isFile() && (stat3.mode & 73) !== 0;
15695
15596
  });
@@ -15699,7 +15600,7 @@ function harnessInstallState(store, harness) {
15699
15600
  }
15700
15601
  function runtimeFiles(store, harness) {
15701
15602
  const binary = harnessBinaryPath(store, harness);
15702
- return harness === "codex" ? [binary, join23(dirname15(binary), "codex-code-mode-host")] : [binary];
15603
+ return harness === "codex" ? [binary, join22(dirname14(binary), "codex-code-mode-host")] : [binary];
15703
15604
  }
15704
15605
  function ensureHarness(store, harness) {
15705
15606
  const key2 = `${store.root}\0${harness}`;
@@ -15716,27 +15617,27 @@ async function install(store, harness) {
15716
15617
  if (state2 === "unsupported") throw new Error(`${harness} has no build for ${store.platform ?? platformKey()}`);
15717
15618
  if (state2 === "installed") return binary;
15718
15619
  const { pin, artifact } = resolvePin(store, harness);
15719
- const parent = join23(store.root, harness);
15620
+ const parent = join22(store.root, harness);
15720
15621
  mkdirSync15(parent, { recursive: true, mode: 448 });
15721
- const staging = join23(parent, `.staging-${randomBytes2(6).toString("hex")}`);
15622
+ const staging = join22(parent, `.staging-${randomBytes2(6).toString("hex")}`);
15722
15623
  mkdirSync15(staging, { recursive: true, mode: 448 });
15723
15624
  try {
15724
- const tarball = join23(staging, "package.tgz");
15625
+ const tarball = join22(staging, "package.tgz");
15725
15626
  await download(`${(store.pins ?? HARNESS_PINS).registry.replace(/\/$/, "")}/${artifact.tarball}`, tarball, artifact.integrity);
15726
15627
  await run2("tar", ["-xzf", tarball, "-C", staging]);
15727
15628
  if (harness === "codex") {
15728
15629
  if (!artifact.entry.endsWith("/bin/codex")) throw new Error("Invalid Codex bundle entry");
15729
- const bundle = dirname15(dirname15(artifact.entry));
15730
- for (const name of readdirSync5(join23(staging, bundle))) symlinkSync(relative5(staging, join23(staging, bundle, name)), join23(staging, name));
15630
+ const bundle = dirname14(dirname14(artifact.entry));
15631
+ for (const name of readdirSync5(join22(staging, bundle))) symlinkSync(relative5(staging, join22(staging, bundle, name)), join22(staging, name));
15731
15632
  for (const name of ["codex", "codex-code-mode-host"]) {
15732
- const stat3 = statSync2(join23(staging, "bin", name));
15633
+ const stat3 = statSync2(join22(staging, "bin", name));
15733
15634
  if (!stat3.isFile() || (stat3.mode & 73) === 0) throw new Error("Incomplete Codex runtime bundle");
15734
15635
  }
15735
15636
  } else {
15736
- mkdirSync15(join23(staging, "bin"), { mode: 448 });
15737
- symlinkSync(relative5(join23(staging, "bin"), join23(staging, artifact.entry)), join23(staging, "bin", pin.command));
15637
+ mkdirSync15(join22(staging, "bin"), { mode: 448 });
15638
+ symlinkSync(relative5(join22(staging, "bin"), join22(staging, artifact.entry)), join22(staging, "bin", pin.command));
15738
15639
  }
15739
- writeFileSync8(join23(staging, MARKER), installMarker(pin, artifact), { mode: 384 });
15640
+ writeFileSync8(join22(staging, MARKER), installMarker(pin, artifact), { mode: 384 });
15740
15641
  const target = versionDir(store, harness);
15741
15642
  const retained = existsSync6(target) ? `${target}.retained-${randomBytes2(6).toString("hex")}` : null;
15742
15643
  if (retained) renameSync4(target, retained);
@@ -15794,7 +15695,7 @@ function freeDiskBytes(dir) {
15794
15695
  }
15795
15696
  async function deviceCapabilities(store, dataDir, docker = dockerAvailable) {
15796
15697
  return {
15797
- os: platform3(),
15698
+ os: platform2(),
15798
15699
  arch: arch2(),
15799
15700
  freeDiskBytes: freeDiskBytes(dataDir),
15800
15701
  docker: await docker(),
@@ -15818,7 +15719,7 @@ function harnessFingerprint(store) {
15818
15719
  // src/model-probe.ts
15819
15720
  import { spawn as spawn3 } from "node:child_process";
15820
15721
  import { mkdtempSync as mkdtempSync6, readdirSync as readdirSync6, rmSync as rmSync13 } from "node:fs";
15821
- import { join as join24 } from "node:path";
15722
+ import { join as join23 } from "node:path";
15822
15723
 
15823
15724
  // src/process-group.ts
15824
15725
  async function stopGroup(child, graceMs = 3e3) {
@@ -15838,12 +15739,12 @@ async function stopGroup(child, graceMs = 3e3) {
15838
15739
  };
15839
15740
  if (child.exitCode === null && child.signalCode === null) {
15840
15741
  signal("SIGTERM");
15841
- await new Promise((resolve20) => {
15842
- if (child.exitCode !== null || child.signalCode !== null) return resolve20();
15742
+ await new Promise((resolve19) => {
15743
+ if (child.exitCode !== null || child.signalCode !== null) return resolve19();
15843
15744
  const done = () => {
15844
15745
  clearTimeout(timer);
15845
15746
  child.off("exit", done);
15846
- resolve20();
15747
+ resolve19();
15847
15748
  };
15848
15749
  const timer = setTimeout(done, graceMs);
15849
15750
  child.once("exit", done);
@@ -15898,10 +15799,10 @@ function sweepModelProbeHomes(scratchDir) {
15898
15799
  } catch {
15899
15800
  return;
15900
15801
  }
15901
- for (const name of names) if (name.startsWith(HOME_PREFIX)) rmSync13(join24(scratchDir, name), { recursive: true, force: true });
15802
+ for (const name of names) if (name.startsWith(HOME_PREFIX)) rmSync13(join23(scratchDir, name), { recursive: true, force: true });
15902
15803
  }
15903
15804
  async function probeHarnessModels(harness, binary, options) {
15904
- const home = mkdtempSync6(join24(options.scratchDir, HOME_PREFIX));
15805
+ const home = mkdtempSync6(join23(options.scratchDir, HOME_PREFIX));
15905
15806
  try {
15906
15807
  return await exchange(harness, binary, home, options);
15907
15808
  } finally {
@@ -15910,15 +15811,15 @@ async function probeHarnessModels(harness, binary, options) {
15910
15811
  }
15911
15812
  function exchange(harness, binary, home, options) {
15912
15813
  const args = harness === "codex" ? ["app-server"] : ["-p", "--input-format", "stream-json", "--output-format", "stream-json", "--verbose"];
15913
- const env = { PATH: process.env.PATH ?? "", HOME: home, CODEX_HOME: home, CLAUDE_CONFIG_DIR: join24(home, ".claude"), LANG: process.env.LANG ?? "C.UTF-8" };
15914
- return new Promise((resolve20) => {
15814
+ const env = { PATH: process.env.PATH ?? "", HOME: home, CODEX_HOME: home, CLAUDE_CONFIG_DIR: join23(home, ".claude"), LANG: process.env.LANG ?? "C.UTF-8" };
15815
+ return new Promise((resolve19) => {
15915
15816
  const child = (options.spawnImpl ?? spawn3)(binary, args, { env, cwd: home, detached: process.platform !== "win32", stdio: ["pipe", "pipe", "ignore"] });
15916
15817
  let result;
15917
15818
  let stopping;
15918
15819
  const stop = () => stopping ??= Promise.resolve().then(() => stopGroup(child, 0));
15919
15820
  const done = () => {
15920
15821
  clearTimeout(timer);
15921
- resolve20(result ?? null);
15822
+ resolve19(result ?? null);
15922
15823
  };
15923
15824
  const finish = (value) => {
15924
15825
  if (result !== void 0) return;
@@ -15981,9 +15882,9 @@ function exchange(harness, binary, home, options) {
15981
15882
 
15982
15883
  // src/cloud-registration.ts
15983
15884
  import { createHash as createHash9 } from "node:crypto";
15984
- import { join as join25 } from "node:path";
15885
+ import { join as join24 } from "node:path";
15985
15886
  function writeCloudRegistration(dataDir, deviceId, workspaceId, credential) {
15986
- writeJsonAtomic(join25(dataDir, "registration.json"), {
15887
+ writeJsonAtomic(join24(dataDir, "registration.json"), {
15987
15888
  version: 1,
15988
15889
  deviceId,
15989
15890
  workspaceId,
@@ -15996,7 +15897,7 @@ import { mkdtempSync as mkdtempSync7, rmSync as rmSync14, statSync as statSync3
15996
15897
 
15997
15898
  // src/hosted-binaries.ts
15998
15899
  import { accessSync as accessSync2, constants as constants5, lstatSync as lstatSync10, readFileSync as readFileSync12, realpathSync as realpathSync12 } from "node:fs";
15999
- import { delimiter as delimiter5, isAbsolute as isAbsolute7 } from "node:path";
15900
+ import { delimiter as delimiter5, isAbsolute as isAbsolute6 } from "node:path";
16000
15901
  import { z as z37 } from "zod";
16001
15902
  var HOSTED_CLI_MANIFEST = "/opt/mikka/worker/.mikka-original-cli.json";
16002
15903
  var LEGACY_HOSTED_CLI_MANIFEST = "/opt/mikka/original-cli.json";
@@ -16029,7 +15930,7 @@ function readManifest(path3) {
16029
15930
  throw Error("hosted_official_cli_missing");
16030
15931
  for (const harness of ["claude_code", "codex"]) {
16031
15932
  const original = value.original[harness], added = value.added[harness];
16032
- if (original && (!isAbsolute7(original.path) || original.path.startsWith("/opt/mikka/")) || added && (original || !added.path.startsWith("/opt/mikka/"))) throw Error("hosted_cli_manifest_invalid");
15933
+ if (original && (!isAbsolute6(original.path) || original.path.startsWith("/opt/mikka/")) || added && (original || !added.path.startsWith("/opt/mikka/"))) throw Error("hosted_cli_manifest_invalid");
16033
15934
  }
16034
15935
  return value;
16035
15936
  }
@@ -16190,10 +16091,10 @@ async function prepareSubscriptionCredentials(assignment, host) {
16190
16091
 
16191
16092
  // src/run-scratch.ts
16192
16093
  import { rmSync as rmSync15 } from "node:fs";
16193
- import { join as join26 } from "node:path";
16094
+ import { join as join25 } from "node:path";
16194
16095
  function removeRunCredentials(stateDir, runId) {
16195
16096
  const { runDir } = runPaths(stateDir, runId);
16196
- for (const path3 of RUN_CREDENTIAL_PATHS) rmSync15(join26(runDir, path3), { recursive: true, force: true });
16097
+ for (const path3 of RUN_CREDENTIAL_PATHS) rmSync15(join25(runDir, path3), { recursive: true, force: true });
16197
16098
  }
16198
16099
 
16199
16100
  // src/subscription-local-runner.ts
@@ -16292,7 +16193,7 @@ function createLocalSubscriptionRunner(host) {
16292
16193
 
16293
16194
  // src/subscription-preflight.ts
16294
16195
  import { mkdtempSync as mkdtempSync8, rmSync as rmSync16 } from "node:fs";
16295
- import { join as join27 } from "node:path";
16196
+ import { join as join26 } from "node:path";
16296
16197
  import { execa as execa8 } from "execa";
16297
16198
  var refused = (detail, cause) => ({
16298
16199
  ready: false,
@@ -16311,7 +16212,7 @@ async function preflightLocalSubscription(harness, options) {
16311
16212
  const expected2 = (options.store.pins ?? HARNESS_PINS).harnesses[harness].version;
16312
16213
  let home;
16313
16214
  try {
16314
- home = mkdtempSync8(join27(options.scratchDir, "subscription-preflight-"));
16215
+ home = mkdtempSync8(join26(options.scratchDir, "subscription-preflight-"));
16315
16216
  const result = await execa8(binary, ["--version"], {
16316
16217
  env: { ...env, HOME: home },
16317
16218
  extendEnv: false,
@@ -16375,8 +16276,8 @@ async function acquireCloudWorkspaceControl(input, root = CLOUD_WORKSPACE_CONTRO
16375
16276
  });
16376
16277
  let acquired = false, releasing = false, settled = false, output = "";
16377
16278
  let finished;
16378
- const done = new Promise((resolve20) => {
16379
- finished = resolve20;
16279
+ const done = new Promise((resolve19) => {
16280
+ finished = resolve19;
16380
16281
  });
16381
16282
  child.stdin.on("error", () => {
16382
16283
  if (!settled && !releasing) child.kill("SIGTERM");
@@ -16389,7 +16290,7 @@ async function acquireCloudWorkspaceControl(input, root = CLOUD_WORKSPACE_CONTRO
16389
16290
  if (!acquired || settled || releasing || !child.stdin.writable) throw new CodedError("terminal_control_unavailable", { detail: "fence_lost" });
16390
16291
  child.stdin.write(JSON.stringify(value) + "\n");
16391
16292
  };
16392
- await new Promise((resolve20, reject) => {
16293
+ await new Promise((resolve19, reject) => {
16393
16294
  const fail = (cause) => reject(new CodedError("terminal_control_unavailable", { detail: "fence_unavailable", cause }));
16394
16295
  child.once("error", fail);
16395
16296
  child.stdout.on("data", (data) => {
@@ -16404,7 +16305,7 @@ async function acquireCloudWorkspaceControl(input, root = CLOUD_WORKSPACE_CONTRO
16404
16305
  fail(input.signal.reason);
16405
16306
  return;
16406
16307
  }
16407
- resolve20();
16308
+ resolve19();
16408
16309
  } else if (output.length > 32) {
16409
16310
  child.kill("SIGTERM");
16410
16311
  fail();
@@ -16444,7 +16345,8 @@ import {
16444
16345
  rmSync as rmSync17,
16445
16346
  truncateSync
16446
16347
  } from "node:fs";
16447
- import { join as join28 } from "node:path";
16348
+ import { join as join27 } from "node:path";
16349
+ var RETRY_MAX_MS = 3e4;
16448
16350
  var Outbox = class {
16449
16351
  constructor(dir, link, log, retryMs = 1e3, onUndeliverable = () => void 0, retainResources = false, traceContext = () => void 0) {
16450
16352
  this.dir = dir;
@@ -16465,14 +16367,16 @@ var Outbox = class {
16465
16367
  traceContext;
16466
16368
  chains = /* @__PURE__ */ new Map();
16467
16369
  retryTimer = null;
16370
+ /** Failed deliveries in a row: each retry waits twice as long, up to RETRY_MAX_MS. */
16371
+ failures = 0;
16468
16372
  closed = false;
16469
16373
  /** Runs whose file was checked for a torn tail since this process started. */
16470
16374
  repaired = /* @__PURE__ */ new Set();
16471
16375
  file(runId) {
16472
- return join28(this.dir, `${assertSafeId("run id", runId)}.jsonl`);
16376
+ return join27(this.dir, `${assertSafeId("run id", runId)}.jsonl`);
16473
16377
  }
16474
16378
  ackFile(runId) {
16475
- return join28(this.dir, `${assertSafeId("run id", runId)}.ack.json`);
16379
+ return join27(this.dir, `${assertSafeId("run id", runId)}.ack.json`);
16476
16380
  }
16477
16381
  parse(runId) {
16478
16382
  let data;
@@ -16622,12 +16526,14 @@ var Outbox = class {
16622
16526
  writeJsonAtomic(this.ackFile(runId), ack);
16623
16527
  }
16624
16528
  } catch (error) {
16529
+ if (error instanceof DaemonUpgradeRequiredError) return;
16625
16530
  if (!(error instanceof ServerUnreachableError)) {
16626
16531
  this.log.error({ run_id: runId, err: error }, "outbox delivery failed");
16627
16532
  }
16628
16533
  this.scheduleRetry();
16629
16534
  return;
16630
16535
  }
16536
+ this.failures = 0;
16631
16537
  if (!parsed.torn && items.at(-1)?.kind === "complete") this.remove(runId);
16632
16538
  }
16633
16539
  remove(runId) {
@@ -16635,12 +16541,15 @@ var Outbox = class {
16635
16541
  rmSync17(this.file(runId), { force: true });
16636
16542
  rmSync17(this.ackFile(runId), { force: true });
16637
16543
  }
16544
+ /** A failed delivery retries after `retryMs`, doubling up to RETRY_MAX_MS while it keeps failing. */
16638
16545
  scheduleRetry() {
16639
16546
  if (this.retryTimer || this.closed) return;
16547
+ const delay2 = Math.min(RETRY_MAX_MS, this.retryMs * 2 ** this.failures);
16548
+ this.failures = Math.min(this.failures + 1, 16);
16640
16549
  this.retryTimer = setTimeout(() => {
16641
16550
  this.retryTimer = null;
16642
16551
  void this.flushAll();
16643
- }, this.retryMs);
16552
+ }, delay2);
16644
16553
  this.retryTimer.unref();
16645
16554
  }
16646
16555
  /** Drop a run's outbox once everything is delivered and the run is over. */
@@ -16822,9 +16731,9 @@ var RpcServer = class {
16822
16731
  const { socketPath } = this.options;
16823
16732
  rmSync18(socketPath, { force: true });
16824
16733
  const server = createServer2((socket) => this.accept(socket));
16825
- await new Promise((resolve20, reject) => {
16734
+ await new Promise((resolve19, reject) => {
16826
16735
  server.once("error", reject);
16827
- server.listen(socketPath, () => resolve20());
16736
+ server.listen(socketPath, () => resolve19());
16828
16737
  });
16829
16738
  chmodSync(socketPath, 384);
16830
16739
  this.server = server;
@@ -16888,9 +16797,9 @@ var RpcServer = class {
16888
16797
  }
16889
16798
  async close() {
16890
16799
  for (const socket of this.sockets) socket.destroy();
16891
- await new Promise((resolve20) => {
16892
- if (!this.server) return resolve20();
16893
- this.server.close(() => resolve20());
16800
+ await new Promise((resolve19) => {
16801
+ if (!this.server) return resolve19();
16802
+ this.server.close(() => resolve19());
16894
16803
  });
16895
16804
  this.server = null;
16896
16805
  rmSync18(this.options.socketPath, { force: true });
@@ -17118,7 +17027,7 @@ async function startTaskSecretBridge(options) {
17118
17027
  };
17119
17028
  options.signal.addEventListener("abort", close, { once: true });
17120
17029
  try {
17121
- await new Promise((resolve20, reject) => {
17030
+ await new Promise((resolve19, reject) => {
17122
17031
  const cleanup = () => {
17123
17032
  server.off("error", failed);
17124
17033
  options.signal.removeEventListener("abort", cancelled);
@@ -17139,7 +17048,7 @@ async function startTaskSecretBridge(options) {
17139
17048
  }
17140
17049
  server.listen(0, "127.0.0.1", () => {
17141
17050
  cleanup();
17142
- resolve20();
17051
+ resolve19();
17143
17052
  });
17144
17053
  });
17145
17054
  options.signal.throwIfAborted();
@@ -17170,7 +17079,7 @@ async function startTaskSecretBridge(options) {
17170
17079
  // src/agents/chat-files.ts
17171
17080
  import { createHash as createHash10 } from "node:crypto";
17172
17081
  import { lstat as lstat3, mkdir as mkdir3, readFile as readFile4, writeFile as writeFile2 } from "node:fs/promises";
17173
- import { join as join29 } from "node:path";
17082
+ import { join as join28 } from "node:path";
17174
17083
  async function materializeChatFiles(text4, directory, download2) {
17175
17084
  const parsed = splitChatFiles(text4);
17176
17085
  if (!parsed.files.length) return text4;
@@ -17185,7 +17094,7 @@ async function materializeChatFiles(text4, directory, download2) {
17185
17094
  if (bytes.length !== file.size || bytes.toString("base64") !== file.data || createHash10("sha256").update(bytes).digest("hex") !== file.sha256)
17186
17095
  throw Error("Attachment content mismatch");
17187
17096
  const ext = /\.([a-z0-9]{1,12})$/i.exec(file.name)?.[1]?.toLowerCase() ?? "bin";
17188
- const path3 = join29(directory, `${file.id}.${ext}`);
17097
+ const path3 = join28(directory, `${file.id}.${ext}`);
17189
17098
  try {
17190
17099
  await writeFile2(path3, bytes, { flag: "wx", mode: 256 });
17191
17100
  } catch (error) {
@@ -17194,7 +17103,7 @@ async function materializeChatFiles(text4, directory, download2) {
17194
17103
  }
17195
17104
  let textPath;
17196
17105
  if (file.text !== null) {
17197
- textPath = join29(directory, `${file.id}.extracted.txt`);
17106
+ textPath = join28(directory, `${file.id}.extracted.txt`);
17198
17107
  try {
17199
17108
  await writeFile2(textPath, file.text, { flag: "wx", mode: 256 });
17200
17109
  } catch (error) {
@@ -17389,20 +17298,20 @@ function createRunMasker(secrets) {
17389
17298
  // src/runs/supervisor.ts
17390
17299
  import { stdSerializers } from "pino";
17391
17300
  import { createHash as createHash12, randomUUID as randomUUID6 } from "node:crypto";
17392
- import { join as join31, resolve as resolve14 } from "node:path";
17301
+ import { join as join30, resolve as resolve13 } from "node:path";
17393
17302
  import { tmpdir as tmpdir5 } from "node:os";
17394
17303
  import { execa as execa12 } from "execa";
17395
17304
 
17396
17305
  // src/agents/checkpoint.ts
17397
17306
  import { mkdtempSync as mkdtempSync9, rmSync as rmSync19, writeFileSync as writeFileSync9 } from "node:fs";
17398
17307
  import { tmpdir as tmpdir4 } from "node:os";
17399
- import { join as join30 } from "node:path";
17308
+ import { join as join29 } from "node:path";
17400
17309
  import { gunzipSync as gunzipSync2, gzipSync as gzipSync2 } from "node:zlib";
17401
17310
  import { execa as execa11 } from "execa";
17402
17311
 
17403
17312
  // src/coding-workspace/checkpoint.ts
17404
17313
  import { createHash as createHash11 } from "node:crypto";
17405
- import { resolve as resolve13 } from "node:path";
17314
+ import { resolve as resolve12 } from "node:path";
17406
17315
  import { execa as execa10 } from "execa";
17407
17316
  var digest6 = (value) => createHash11("sha256").update(value).digest("hex");
17408
17317
  var oid = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/;
@@ -17436,7 +17345,7 @@ async function captureCheckpointReview(input) {
17436
17345
  const env = {
17437
17346
  ...buildChildEnv({}),
17438
17347
  GIT_DIR: gitDir,
17439
- GIT_COMMON_DIR: resolve13(gitDir, "..", ".."),
17348
+ GIT_COMMON_DIR: resolve12(gitDir, "..", ".."),
17440
17349
  GIT_WORK_TREE: input.worktree,
17441
17350
  GIT_CONFIG_NOSYSTEM: "1",
17442
17351
  GIT_CONFIG_GLOBAL: "/dev/null",
@@ -17623,8 +17532,8 @@ async function takeCheckpoint(options) {
17623
17532
  }
17624
17533
  async function applyCheckpoint(options) {
17625
17534
  const git3 = await pinnedGit(options.repoPath, options.worktree);
17626
- const dir = mkdtempSync9(join30(tmpdir4(), "mikka-checkpoint-"));
17627
- const file = join30(dir, "checkpoint.patch");
17535
+ const dir = mkdtempSync9(join29(tmpdir4(), "mikka-checkpoint-"));
17536
+ const file = join29(dir, "checkpoint.patch");
17628
17537
  try {
17629
17538
  const patch = gunzipSync2(Buffer.from(options.checkpoint.patch, "base64"));
17630
17539
  if (!patch.length && options.checkpoint.files === 0) return true;
@@ -17661,7 +17570,53 @@ import { pathToFileURL as pathToFileURL3 } from "node:url";
17661
17570
  var MAX_CONTINUES = 3;
17662
17571
  var MAX_CRASH_RETRIES = 3;
17663
17572
  var MAX_FIX_ROUNDS = 3;
17664
- var DEFAULT_LEASE_MS = RUN_LEASE_MS;
17573
+ var DEFAULT_LEASE_MS = SESSION_LEASE_MS;
17574
+ var MemoryGatewaySocket = class {
17575
+ constructor(server, deviceId) {
17576
+ this.server = server;
17577
+ this.deviceId = deviceId;
17578
+ setTimeout(() => {
17579
+ if (this.readyState !== 0) return;
17580
+ if (!server.online) {
17581
+ this.readyState = 3;
17582
+ this.emit("error", {});
17583
+ return;
17584
+ }
17585
+ this.readyState = 1;
17586
+ server.sockets.add(this);
17587
+ this.emit("open", {});
17588
+ }, 0);
17589
+ }
17590
+ server;
17591
+ deviceId;
17592
+ readyState = 0;
17593
+ listeners = /* @__PURE__ */ new Map();
17594
+ send(data) {
17595
+ if (this.readyState !== 1) throw new Error("socket not open");
17596
+ if (data === "ping") queueMicrotask(() => this.message("pong"));
17597
+ }
17598
+ /** A frame from the server. */
17599
+ message(data) {
17600
+ if (this.readyState === 1) this.emit("message", { data });
17601
+ }
17602
+ close(code) {
17603
+ if (this.readyState >= 2) return;
17604
+ this.readyState = 3;
17605
+ this.server.sockets.delete(this);
17606
+ this.emit("close", { code });
17607
+ }
17608
+ addEventListener(type, listener) {
17609
+ const set = this.listeners.get(type) ?? /* @__PURE__ */ new Set();
17610
+ set.add(listener);
17611
+ this.listeners.set(type, set);
17612
+ }
17613
+ removeEventListener(type, listener) {
17614
+ this.listeners.get(type)?.delete(listener);
17615
+ }
17616
+ emit(type, event) {
17617
+ for (const listener of [...this.listeners.get(type) ?? []]) listener(event);
17618
+ }
17619
+ };
17665
17620
  var MemoryServer = class {
17666
17621
  /** `fixedDeviceId` is handed out on registration (tests, dev). */
17667
17622
  constructor(fixedDeviceId, options = {}) {
@@ -17670,7 +17625,13 @@ var MemoryServer = class {
17670
17625
  }
17671
17626
  fixedDeviceId;
17672
17627
  online = true;
17628
+ /** False: the ticket route refuses like a server without a device gateway. */
17629
+ gateway = true;
17630
+ /** True: a claim needs an open session socket for the device, as on the real server. */
17631
+ requireSession = false;
17673
17632
  devices = /* @__PURE__ */ new Map();
17633
+ /** Open device gateway sockets. */
17634
+ sockets = /* @__PURE__ */ new Set();
17674
17635
  repos = /* @__PURE__ */ new Map();
17675
17636
  runs = /* @__PURE__ */ new Map();
17676
17637
  /** Durable stream per run; the offset is the chunk count. */
@@ -17747,6 +17708,7 @@ var MemoryServer = class {
17747
17708
  patches: []
17748
17709
  });
17749
17710
  this.issueStatus.set(run3.issueId, "in_progress");
17711
+ this.pushWork(deviceId);
17750
17712
  return runId;
17751
17713
  }
17752
17714
  /** A person's message to a running agent; returns its message id. */
@@ -17764,6 +17726,20 @@ var MemoryServer = class {
17764
17726
  const wake = this.wakeCommands;
17765
17727
  this.wakeCommands = [];
17766
17728
  for (const fn of wake) fn();
17729
+ const devices = new Set([...this.stopRequests, ...[...this.inputs.values()].map((input) => input.runId)].flatMap((runId) => this.runs.get(runId)?.deviceId ?? []));
17730
+ for (const deviceId of devices) this.pushWork(deviceId);
17731
+ }
17732
+ /** The gateway's `work` signal to a device's open sockets. */
17733
+ pushWork(deviceId) {
17734
+ for (const socket of [...this.sockets]) if (socket.deviceId === deviceId) socket.message("work");
17735
+ }
17736
+ /** Whether a device holds an open session socket. */
17737
+ sessionOpen(deviceId) {
17738
+ return [...this.sockets].some((socket) => socket.deviceId === deviceId);
17739
+ }
17740
+ /** Drops every open session socket, with a close code (4001: update required). */
17741
+ closeSessions(code) {
17742
+ for (const socket of [...this.sockets]) socket.close(code);
17767
17743
  }
17768
17744
  pendingCommands(deviceId, skip) {
17769
17745
  const active = (runId) => {
@@ -17797,27 +17773,20 @@ var MemoryServer = class {
17797
17773
  ([id5, d]) => d.credential === credential && (!knownDeviceId || id5 === knownDeviceId)
17798
17774
  );
17799
17775
  const deviceId = existing?.[0] ?? this.fixedDeviceId ?? randomUUID5();
17800
- this.devices.set(deviceId, { credential, info });
17776
+ this.devices.set(deviceId, { credential, info, reports: this.devices.get(deviceId)?.reports ?? [] });
17801
17777
  return { deviceId };
17802
17778
  },
17803
- heartbeat: async (deviceId, status3) => {
17779
+ report: async (deviceId, report2) => {
17804
17780
  this.check();
17805
- const device = this.devices.get(deviceId);
17806
- if (device) device.lastHeartbeat = status3;
17807
- const leases = {};
17808
- const revoked = [];
17809
- for (const { runId } of status3.runs) {
17810
- const run3 = this.runs.get(runId);
17811
- if (!run3) continue;
17812
- if (run3.deviceId !== deviceId || isTerminalRunState(run3.state)) {
17813
- revoked.push(runId);
17814
- continue;
17815
- }
17816
- run3.leaseExpiresAt = Date.now() + this.leaseMs;
17817
- leases[runId] = new Date(run3.leaseExpiresAt).toISOString();
17818
- }
17819
- return { leases, ...revoked.length ? { revoked } : {} };
17781
+ this.devices.get(deviceId)?.reports.push(report2);
17782
+ return {};
17783
+ },
17784
+ deviceGateway: async (deviceId) => {
17785
+ this.check();
17786
+ if (!this.gateway) throw new DeviceGatewayRequiredError();
17787
+ return { url: `memory://gateway/${encodeURIComponent(deviceId)}`, protocol: `mikka-ticket-1-${"0".repeat(64)}` };
17820
17788
  },
17789
+ openDeviceGateway: (url) => new MemoryGatewaySocket(this, decodeURIComponent(url.slice("memory://gateway/".length))),
17821
17790
  listRepos: async (deviceId) => {
17822
17791
  this.check();
17823
17792
  return this.repos.get(deviceId) ?? [];
@@ -17828,6 +17797,7 @@ var MemoryServer = class {
17828
17797
  },
17829
17798
  claimRun: async (deviceId, runId) => {
17830
17799
  this.check();
17800
+ if (this.requireSession && !this.sessionOpen(deviceId)) throw new DeviceSessionRequiredError();
17831
17801
  const run3 = this.runs.get(runId);
17832
17802
  if (!run3 || run3.deviceId !== deviceId)
17833
17803
  throw new RunNotPinnedHereError(runId);
@@ -17879,12 +17849,12 @@ var MemoryServer = class {
17879
17849
  this.check();
17880
17850
  let pending = this.pendingCommands(deviceId, skip);
17881
17851
  if (pending.length === 0 && waitSeconds > 0 && !signal?.aborted) {
17882
- await new Promise((resolve20) => {
17883
- const timer = setTimeout(resolve20, waitSeconds * 1e3);
17884
- signal?.addEventListener("abort", () => resolve20(), { once: true });
17852
+ await new Promise((resolve19) => {
17853
+ const timer = setTimeout(resolve19, waitSeconds * 1e3);
17854
+ signal?.addEventListener("abort", () => resolve19(), { once: true });
17885
17855
  this.wakeCommands.push(() => {
17886
17856
  clearTimeout(timer);
17887
- resolve20();
17857
+ resolve19();
17888
17858
  });
17889
17859
  });
17890
17860
  this.check();
@@ -17918,8 +17888,10 @@ var RunSupervisor = class {
17918
17888
  }
17919
17889
  deps;
17920
17890
  active = /* @__PURE__ */ new Map();
17921
- /** Lease expiry per run (ms); runs without a server lease are absent. */
17891
+ /** Server lease expiry per held run (ms); runs without a server lease are absent. */
17922
17892
  leases = /* @__PURE__ */ new Map();
17893
+ /** Set while the device session socket is down: when held runs lose their lease. */
17894
+ sessionDeadline = null;
17923
17895
  stopping = false;
17924
17896
  /** Runs with an assistant message in progress (`start` sent, no `finish`). */
17925
17897
  openMessages = /* @__PURE__ */ new Set();
@@ -17947,61 +17919,42 @@ var RunSupervisor = class {
17947
17919
  };
17948
17920
  }
17949
17921
  liveness(runId) {
17950
- const lease = this.leases.get(runId);
17922
+ const lease = this.leaseExpiry(runId);
17951
17923
  const run3 = this.active.get(runId);
17952
17924
  return {
17953
- ...lease !== void 0 ? { leaseExpiresAt: new Date(lease).toISOString() } : {},
17925
+ ...lease !== void 0 && Number.isFinite(lease) ? { leaseExpiresAt: new Date(lease).toISOString() } : {},
17954
17926
  ...run3 ? { lastProgressAt: new Date(run3.lastProgressAt).toISOString() } : {}
17955
17927
  };
17956
17928
  }
17957
- /** Per-run part of the device heartbeat. */
17958
- heartbeatRuns() {
17959
- return [...this.active].map(([runId, run3]) => ({
17960
- runId,
17961
- lastProgressAt: new Date(run3.lastProgressAt).toISOString(),
17962
- ...this.deps.journal.get(runId)?.assignment.taskSecrets?.grants.length ? {
17963
- secretCapabilities: this.deps.journal.get(runId).assignment.taskSecrets.grants.map((grant) => grant.capability)
17964
- } : {}
17965
- }));
17966
- }
17967
- /** The heartbeat response is trusted server data. Never persist its bearers. */
17968
- renewTaskSecrets(values) {
17969
- for (const [runId, access] of Object.entries(values ?? {})) {
17970
- const active = this.active.get(runId);
17971
- const assignment = this.deps.journal.get(runId)?.assignment;
17972
- if (!active || active.forcedStop || !assignment?.taskSecrets || access.endpoint !== assignment.taskSecrets.endpoint) continue;
17973
- assignment.taskSecrets = { ...access, unavailable: assignment.taskSecrets.unavailable };
17974
- for (const grant of access.grants) this.addCredential(runId, "TASK_SECRET_CAPABILITY", grant.capability);
17975
- }
17929
+ /**
17930
+ * When a held run's local lease ends: its server lease, or the session
17931
+ * deadline while the socket is down. Undefined for a run the server never
17932
+ * leased (local dev runs); Infinity while the session is open.
17933
+ */
17934
+ leaseExpiry(runId) {
17935
+ const lease = this.leases.get(runId);
17936
+ if (lease === void 0) return void 0;
17937
+ return Math.min(lease, this.sessionDeadline ?? Number.POSITIVE_INFINITY);
17976
17938
  }
17977
- /** Applies leases renewed by the server's heartbeat answer. */
17978
- renewLeases(leases) {
17979
- for (const [runId, expiry] of Object.entries(leases)) {
17980
- if (this.active.has(runId)) this.leases.set(runId, Date.parse(expiry));
17981
- }
17939
+ /** The device session socket opened: held runs keep their lease while it stays open. */
17940
+ sessionOpened() {
17941
+ this.sessionDeadline = null;
17982
17942
  }
17983
17943
  /**
17984
- * Stops the runs the server says this device no longer holds. Runs without
17985
- * a server lease (local dev runs) were never the server's to take back.
17944
+ * The device session socket is down since `at`. Held runs stop as
17945
+ * `device_lost` once it stays down for DEVICE_SESSION_LOCAL_GRACE_MS; a
17946
+ * later drop never extends an earlier deadline.
17986
17947
  */
17987
- revokeLeases(runIds, cancelled = []) {
17988
- const explicitStops = new Set(cancelled);
17989
- for (const runId of runIds) {
17990
- const run3 = this.active.get(runId);
17991
- const lease = this.leases.get(runId);
17992
- if (!run3 || run3.forcedStop || lease === void 0) continue;
17993
- if (explicitStops.has(runId) && lease > Date.now()) {
17994
- if (!run3.cancelRequested) void this.requestCancel(runId, run3);
17995
- } else {
17996
- this.forceStop(runId, run3, "device_lost");
17997
- }
17998
- }
17948
+ sessionClosed(at = Date.now()) {
17949
+ if (this.sessionDeadline !== null) return;
17950
+ this.sessionDeadline = at + DEVICE_SESSION_LOCAL_GRACE_MS;
17999
17951
  }
18000
17952
  /**
18001
17953
  * Saves the work in progress of runs that had a tool call since their last
18002
17954
  * checkpoint, or none for `CHECKPOINT_EVERY_MS`, through `save`. The
18003
- * daemon calls it after each heartbeat; a failed save is tried again on
18004
- * the next one.
17955
+ * daemon calls it from its local timer while the device session is open;
17956
+ * a tree that did not change since the last checkpoint is not sent, so an
17957
+ * idle run makes no request. A failed save is tried again on the next call.
18005
17958
  */
18006
17959
  async saveCheckpoints(save, now = Date.now()) {
18007
17960
  for (const [runId, run3] of this.active) {
@@ -18065,12 +18018,12 @@ var RunSupervisor = class {
18065
18018
  run3.safePoint = { session: "exited", observedAt: receipt?.takenAt ?? (/* @__PURE__ */ new Date()).toISOString(), ...checkpoint };
18066
18019
  return checkpoint;
18067
18020
  }
18068
- /** Lease and watchdog pass; the daemon calls it on every tick. */
18021
+ /** Local lease and watchdog pass; the daemon calls it from its local timer (no request). */
18069
18022
  check(now = Date.now()) {
18070
18023
  const stallMs = this.deps.stallMs ?? DEFAULT_STALL_MS;
18071
18024
  for (const [runId, run3] of this.active) {
18072
18025
  if (run3.forcedStop) continue;
18073
- const lease = this.leases.get(runId);
18026
+ const lease = this.leaseExpiry(runId);
18074
18027
  if (lease !== void 0 && now > lease) {
18075
18028
  this.forceStop(runId, run3, "device_lost");
18076
18029
  } else if (now - run3.lastProgressAt > stallMs) {
@@ -18198,10 +18151,10 @@ var RunSupervisor = class {
18198
18151
  activeRunIds() {
18199
18152
  return [...this.active.keys()];
18200
18153
  }
18201
- /** Computer operations require a live run and a current server lease. */
18154
+ /** Computer operations require a live run and a current local lease. */
18202
18155
  computerRunAllowed(runId) {
18203
18156
  const run3 = this.active.get(runId);
18204
- const lease = this.leases.get(runId);
18157
+ const lease = this.leaseExpiry(runId);
18205
18158
  return !this.stopping && Boolean(run3 && !run3.cancelRequested && lease !== void 0 && lease > Date.now());
18206
18159
  }
18207
18160
  /**
@@ -18336,7 +18289,7 @@ var RunSupervisor = class {
18336
18289
  continue;
18337
18290
  }
18338
18291
  if (entry.assignment.leaseExpiresAt)
18339
- this.leases.set(entry.assignment.runId, Date.now() + DEFAULT_LEASE_MS);
18292
+ this.leases.set(entry.assignment.runId, Number.POSITIVE_INFINITY);
18340
18293
  this.launch(entry.assignment.runId, repo);
18341
18294
  }
18342
18295
  }
@@ -18351,7 +18304,7 @@ var RunSupervisor = class {
18351
18304
  held: this.active.get(runId) === run3,
18352
18305
  state: this.deps.journal.get(runId)?.state,
18353
18306
  stopped: this.stopping || run3.cancelRequested || run3.abort.signal.aborted,
18354
- lease: this.leases.get(runId)
18307
+ lease: this.leaseExpiry(runId)
18355
18308
  });
18356
18309
  check();
18357
18310
  if (run3.toolApproval.revoked) throw new Error("Run mailbox unavailable");
@@ -18372,7 +18325,7 @@ var RunSupervisor = class {
18372
18325
  const entry = this.deps.journal.get(runId);
18373
18326
  if (splitChatFiles(text4).files.length) {
18374
18327
  if (!entry || !this.deps.downloadChatFile || !this.deps.adapterStateDir) throw Error("Run attachments unavailable");
18375
- text4 = await materializeChatFiles(text4, join31(this.deps.adapterStateDir, "inputs", runId), (id5) => this.deps.downloadChatFile(entry.assignment, id5, run3.abort.signal));
18328
+ text4 = await materializeChatFiles(text4, join30(this.deps.adapterStateDir, "inputs", runId), (id5) => this.deps.downloadChatFile(entry.assignment, id5, run3.abort.signal));
18376
18329
  }
18377
18330
  await run3.session.send(text4, mode);
18378
18331
  }
@@ -18402,9 +18355,9 @@ var RunSupervisor = class {
18402
18355
  run3.abort.abort();
18403
18356
  }
18404
18357
  let timer;
18405
- const grace = new Promise((resolve20) => {
18358
+ const grace = new Promise((resolve19) => {
18406
18359
  timer = setTimeout(
18407
- resolve20,
18360
+ resolve19,
18408
18361
  this.deps.stopGraceMs ?? DEFAULT_STOP_GRACE_MS
18409
18362
  );
18410
18363
  });
@@ -18712,7 +18665,7 @@ var RunSupervisor = class {
18712
18665
  /** Only the local lease and pushed stop state govern host finishing work. */
18713
18666
  assertFinishingRunLive(runId, signal) {
18714
18667
  const run3 = this.active.get(runId);
18715
- const lease = this.leases.get(runId);
18668
+ const lease = this.leaseExpiry(runId);
18716
18669
  if (run3 && !run3.forcedStop && lease !== void 0 && lease <= Date.now())
18717
18670
  this.forceStop(runId, run3, "device_lost");
18718
18671
  signal.throwIfAborted();
@@ -18731,11 +18684,11 @@ var RunSupervisor = class {
18731
18684
  if (configured.length === 0) return void 0;
18732
18685
  const loaded = [];
18733
18686
  if (this.deps.adapterStateDir) {
18734
- const dir = join31(runPaths(this.deps.adapterStateDir, runId).runDir, PROFILE_SKILLS_DIR, PROFILE_SKILL_LOADS_DIR);
18687
+ const dir = join30(runPaths(this.deps.adapterStateDir, runId).runDir, PROFILE_SKILLS_DIR, PROFILE_SKILL_LOADS_DIR);
18735
18688
  try {
18736
18689
  for (const name of readdirSync8(dir).sort()) {
18737
18690
  if (!name.endsWith(".json") || loaded.length >= configured.length) continue;
18738
- const file = join31(dir, name), meta = lstatSync11(file, { throwIfNoEntry: false });
18691
+ const file = join30(dir, name), meta = lstatSync11(file, { throwIfNoEntry: false });
18739
18692
  if (!meta?.isFile() || meta.isSymbolicLink() || meta.nlink !== 1 || meta.size < 2 || meta.size > 4096) continue;
18740
18693
  const receipt = profileSkillLoadReceiptSchema.safeParse(JSON.parse(readFileSync14(file, "utf8")));
18741
18694
  if (!receipt.success || loaded.some((item) => item.id === receipt.data.id)) continue;
@@ -18879,7 +18832,7 @@ var RunSupervisor = class {
18879
18832
  try {
18880
18833
  return await withRunGitCredentials(
18881
18834
  assignment,
18882
- runPaths(this.deps.adapterStateDir ?? join31(tmpdir5(), "mikka-run-state"), runId).privateDir,
18835
+ runPaths(this.deps.adapterStateDir ?? join30(tmpdir5(), "mikka-run-state"), runId).privateDir,
18883
18836
  (env) => this.deps.worktrees.fetchBranch(
18884
18837
  repo.path,
18885
18838
  repo.push?.remote ?? "origin",
@@ -19029,8 +18982,8 @@ var RunSupervisor = class {
19029
18982
  });
19030
18983
  if (readAbort) {
19031
18984
  let allowEffects, refuseEffects;
19032
- const entryReady = new Promise((resolve20, reject) => {
19033
- allowEffects = resolve20;
18985
+ const entryReady = new Promise((resolve19, reject) => {
18986
+ allowEffects = resolve19;
19034
18987
  refuseEffects = reject;
19035
18988
  });
19036
18989
  const authorized = Promise.all([policyReady, entryReady]);
@@ -19041,7 +18994,7 @@ var RunSupervisor = class {
19041
18994
  }
19042
18995
  await policyReady;
19043
18996
  verifySkillAssignment(assignment);
19044
- if (assignment.skillReceipt && (this.leases.get(runId) ?? 0) <= Date.now())
18997
+ if (assignment.skillReceipt && (this.leaseExpiry(runId) ?? 0) <= Date.now())
19045
18998
  throw new Error("Receipted Skill assignment requires a current server lease");
19046
18999
  if (assignment.skillReceipt?.artifact.registryId === "mikka-team") {
19047
19000
  if (!this.deps.revalidateSkillAssignment) throw new Error("Current team Skill authorization unavailable");
@@ -19063,7 +19016,7 @@ var RunSupervisor = class {
19063
19016
  }
19064
19017
  run3.repositoryPreparing?.allowEffects();
19065
19018
  const checkMailbox = () => {
19066
- const lease = this.leases.get(runId);
19019
+ const lease = this.leaseExpiry(runId);
19067
19020
  const current = this.deps.journal.get(runId);
19068
19021
  assertMailboxRunAuthority({ held: this.active.get(runId) === run3, state: current?.state, stopped: this.stopping || run3.cancelRequested || run3.abort.signal.aborted, lease });
19069
19022
  };
@@ -19272,7 +19225,7 @@ var RunSupervisor = class {
19272
19225
  let followUp = assignment.followUp;
19273
19226
  if (splitChatFiles(prompt).files.length || followUp && splitChatFiles(followUp).files.length) {
19274
19227
  if (!this.deps.downloadChatFile || !this.deps.adapterStateDir) throw Error("Run attachments unavailable");
19275
- const directory = join31(this.deps.adapterStateDir, "inputs", runId);
19228
+ const directory = join30(this.deps.adapterStateDir, "inputs", runId);
19276
19229
  const download2 = (id5) => this.deps.downloadChatFile(assignment, id5, run3.abort.signal);
19277
19230
  prompt = await materializeChatFiles(prompt, directory, download2);
19278
19231
  if (followUp) followUp = await materializeChatFiles(followUp, directory, download2);
@@ -19285,7 +19238,7 @@ var RunSupervisor = class {
19285
19238
  gitWritePaths: await worktreeGitWritePaths(repo.path, worktree, runId)
19286
19239
  };
19287
19240
  const resuming = entry.sessionId !== null && adapter.capabilities.supportsResume;
19288
- const inEarlierWorktree = continued !== null || entry.worktree !== null && resolve14(entry.worktree) !== resolve14(this.deps.worktrees.pathFor(runId));
19241
+ const inEarlierWorktree = continued !== null || entry.worktree !== null && resolve13(entry.worktree) !== resolve13(this.deps.worktrees.pathFor(runId));
19289
19242
  const continueSession = !resuming && assignment.resumeSessionId && assignment.continuesRunId && inEarlierWorktree && adapter.capabilities.supportsResume ? {
19290
19243
  sessionId: assignment.resumeSessionId,
19291
19244
  runId: assignment.continuesRunId,
@@ -19341,7 +19294,7 @@ var RunSupervisor = class {
19341
19294
  if (!this.deps.adapterStateDir || assignment.harness === "mock" || !session.sessionId || resuming && session.sessionId !== entry.sessionId || assignment.requireSessionResume && session.sessionId !== assignment.resumeSessionId)
19342
19295
  throw new Error("Skill mount requires the actual original harness session");
19343
19296
  verifySkillAssignment(assignment);
19344
- const file = join31(
19297
+ const file = join30(
19345
19298
  runPaths(this.deps.adapterStateDir, runId).runDir,
19346
19299
  SKILLS_DIR,
19347
19300
  skillSlug(assignment.skills[0].name),
@@ -19543,10 +19496,10 @@ function trackParts(open5, chunk) {
19543
19496
  }
19544
19497
  var ABORTED = /* @__PURE__ */ Symbol("aborted");
19545
19498
  function abortPromise(signal) {
19546
- return new Promise((resolve20) => {
19547
- if (signal.aborted) resolve20(ABORTED);
19499
+ return new Promise((resolve19) => {
19500
+ if (signal.aborted) resolve19(ABORTED);
19548
19501
  else
19549
- signal.addEventListener("abort", () => resolve20(ABORTED), { once: true });
19502
+ signal.addEventListener("abort", () => resolve19(ABORTED), { once: true });
19550
19503
  });
19551
19504
  }
19552
19505
  function pickAgentReport(agent) {
@@ -19660,9 +19613,13 @@ function fixedCandidateCheck(assignment) {
19660
19613
 
19661
19614
  // src/device-gateway.ts
19662
19615
  var DEVICE_GATEWAY_PING = "ping";
19663
- var DEVICE_GATEWAY_PING_MS = 3e4;
19616
+ var DEVICE_GATEWAY_PING_MS = 1e4;
19617
+ var DEVICE_GATEWAY_SILENCE_MS = 3e4;
19664
19618
  var DEVICE_GATEWAY_HANDSHAKE_MS = 1e4;
19665
- var DEVICE_GATEWAY_PONG_TIMEOUT_MS = 9e4;
19619
+ var DEVICE_GATEWAY_RETRY_MIN_MS = 500;
19620
+ var DEVICE_GATEWAY_RETRY_MAX_MS = 3e4;
19621
+ var DEVICE_GATEWAY_STABLE_MS = 6e4;
19622
+ var DEVICE_GATEWAY_UPDATE_REQUIRED_CODE = 4001;
19666
19623
  var DeviceGatewayClosedError = class extends Error {
19667
19624
  code;
19668
19625
  constructor(code) {
@@ -19672,12 +19629,13 @@ var DeviceGatewayClosedError = class extends Error {
19672
19629
  };
19673
19630
  function runDeviceGateway(socket, options) {
19674
19631
  const pingMs = options.pingMs ?? DEVICE_GATEWAY_PING_MS;
19675
- return new Promise((resolve20, reject) => {
19632
+ const silenceMs = options.silenceMs ?? DEVICE_GATEWAY_SILENCE_MS;
19633
+ return new Promise((resolve19, reject) => {
19676
19634
  let settled = false;
19677
19635
  let opened = false;
19678
19636
  let pulling = false;
19679
19637
  let pendingWork = false;
19680
- let lastPong = 0;
19638
+ let lastMessage = 0;
19681
19639
  let ping;
19682
19640
  const finish = (error) => {
19683
19641
  if (settled) return;
@@ -19691,7 +19649,7 @@ function runDeviceGateway(socket, options) {
19691
19649
  } catch {
19692
19650
  }
19693
19651
  if (error && !options.signal.aborted) reject(error);
19694
- else resolve20();
19652
+ else resolve19();
19695
19653
  };
19696
19654
  const work = () => {
19697
19655
  if (settled) return;
@@ -19723,11 +19681,11 @@ function runDeviceGateway(socket, options) {
19723
19681
  if (settled || opened) return;
19724
19682
  opened = true;
19725
19683
  clearTimeout(handshake);
19726
- lastPong = performance.now();
19684
+ lastMessage = performance.now();
19727
19685
  options.onOpen?.();
19728
19686
  ping = setInterval(() => {
19729
- if (performance.now() - lastPong >= DEVICE_GATEWAY_PONG_TIMEOUT_MS) {
19730
- finish(new Error("device gateway pong timed out"));
19687
+ if (performance.now() - lastMessage >= silenceMs) {
19688
+ finish(new Error("device gateway went quiet"));
19731
19689
  return;
19732
19690
  }
19733
19691
  try {
@@ -19740,7 +19698,7 @@ function runDeviceGateway(socket, options) {
19740
19698
  }],
19741
19699
  ["message", (event) => {
19742
19700
  if (!opened || settled) return;
19743
- if (event.data === "pong") lastPong = performance.now();
19701
+ lastMessage = performance.now();
19744
19702
  if (event.data === "work") signalWork();
19745
19703
  }],
19746
19704
  ["close", (event) => finish(new DeviceGatewayClosedError(event.code))],
@@ -19756,6 +19714,101 @@ function openDeviceGateway(url, protocol) {
19756
19714
  const Socket = globalThis.WebSocket;
19757
19715
  return new Socket(url, [protocol]);
19758
19716
  }
19717
+ function deviceGatewayRetryDelay(failures, random = Math.random) {
19718
+ const ceiling = Math.min(DEVICE_GATEWAY_RETRY_MAX_MS, DEVICE_GATEWAY_RETRY_MIN_MS * 2 ** Math.max(0, failures - 1));
19719
+ return Math.max(DEVICE_GATEWAY_RETRY_MIN_MS, ceiling * (0.5 + random() * 0.5));
19720
+ }
19721
+ var DeviceSession = class {
19722
+ stopped = new AbortController();
19723
+ attempt = null;
19724
+ wakeUp = null;
19725
+ skipBackoff = false;
19726
+ loop = null;
19727
+ options;
19728
+ constructor(options) {
19729
+ this.options = options;
19730
+ }
19731
+ start() {
19732
+ return this.loop ??= this.run();
19733
+ }
19734
+ /**
19735
+ * Close the current socket and dial again: after the usual backoff, or at
19736
+ * once with `now` (the credential changed, so the old backoff means nothing).
19737
+ */
19738
+ redial(now = false) {
19739
+ if (now) {
19740
+ this.skipBackoff = true;
19741
+ this.wakeUp?.();
19742
+ }
19743
+ this.attempt?.abort();
19744
+ }
19745
+ /** Cut a backoff wait short: something the next attempt needed just arrived. */
19746
+ wake() {
19747
+ this.wakeUp?.();
19748
+ }
19749
+ stop() {
19750
+ this.stopped.abort();
19751
+ this.attempt?.abort();
19752
+ this.wakeUp?.();
19753
+ return this.loop ?? Promise.resolve();
19754
+ }
19755
+ async run() {
19756
+ let failures = 0;
19757
+ const { signal } = this.stopped;
19758
+ while (!signal.aborted) {
19759
+ this.skipBackoff = false;
19760
+ const attempt = new AbortController();
19761
+ this.attempt = attempt;
19762
+ let openedAt;
19763
+ let failure2;
19764
+ try {
19765
+ const { url, protocol } = await this.options.ticket(attempt.signal);
19766
+ if (attempt.signal.aborted) throw new DeviceGatewayClosedError();
19767
+ const socket = (this.options.open ?? openDeviceGateway)(url, protocol);
19768
+ await runDeviceGateway(socket, {
19769
+ signal: attempt.signal,
19770
+ onOpen: () => {
19771
+ openedAt = performance.now();
19772
+ this.options.onOpen();
19773
+ },
19774
+ onWorkAvailable: this.options.onWorkAvailable,
19775
+ onWork: () => this.options.onWork(attempt.signal)
19776
+ });
19777
+ failure2 = new DeviceGatewayClosedError();
19778
+ } catch (error) {
19779
+ failure2 = error;
19780
+ } finally {
19781
+ attempt.abort();
19782
+ if (this.attempt === attempt) this.attempt = null;
19783
+ }
19784
+ this.options.onClose(failure2, openedAt !== void 0);
19785
+ if (signal.aborted) return;
19786
+ const verdict = this.options.verdict?.(failure2) ?? "redial";
19787
+ if (verdict === "stop") return;
19788
+ if (openedAt !== void 0 && performance.now() - openedAt >= DEVICE_GATEWAY_STABLE_MS) failures = 0;
19789
+ if (this.skipBackoff) {
19790
+ this.skipBackoff = false;
19791
+ failures = 0;
19792
+ continue;
19793
+ }
19794
+ failures = Math.min(failures + 1, 32);
19795
+ await this.pause(verdict === "slow" ? DEVICE_GATEWAY_RETRY_MAX_MS : deviceGatewayRetryDelay(failures, this.options.random));
19796
+ }
19797
+ }
19798
+ /** A redial backoff, not a poll: it ends early on `wake` or `stop`. */
19799
+ pause(ms2) {
19800
+ return new Promise((resolve19) => {
19801
+ const done = () => {
19802
+ clearTimeout(timer);
19803
+ this.wakeUp = null;
19804
+ resolve19();
19805
+ };
19806
+ const timer = setTimeout(done, ms2);
19807
+ this.wakeUp = done;
19808
+ if (this.stopped.signal.aborted) done();
19809
+ });
19810
+ }
19811
+ };
19759
19812
 
19760
19813
  // src/coding-workspace/files.ts
19761
19814
  import { constants as constants7 } from "node:fs";
@@ -19763,7 +19816,7 @@ import { open as open2, readFile as readFile5, realpath as realpath2 } from "nod
19763
19816
  import { execFile as execFile7 } from "node:child_process";
19764
19817
  import { promisify as promisify7 } from "node:util";
19765
19818
  import { createHash as createHash13 } from "node:crypto";
19766
- import { extname, resolve as resolve15 } from "node:path";
19819
+ import { extname, resolve as resolve14 } from "node:path";
19767
19820
  var execute2 = promisify7(execFile7);
19768
19821
  var hash = (value) => createHash13("sha256").update(value).digest("hex");
19769
19822
  var denied = () => new CodingWorkspaceError("workspace_path_unavailable");
@@ -19812,9 +19865,9 @@ async function safeFile(root, path3, use) {
19812
19865
  parent = handle;
19813
19866
  }
19814
19867
  const selected = await realpath2(`/proc/self/fd/${parent.fd}`);
19815
- if (selected !== resolve15(root.path, path3) || await realpath2(root.gitPath) !== root.path) throw denied();
19868
+ if (selected !== resolve14(root.path, path3) || await realpath2(root.gitPath) !== root.path) throw denied();
19816
19869
  const result = await use(parent);
19817
- 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");
19870
+ 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");
19818
19871
  return result;
19819
19872
  } catch (cause) {
19820
19873
  if (cause instanceof CodingWorkspaceError) throw cause;
@@ -19853,7 +19906,7 @@ async function readWorkspaceReceipt(command, entry) {
19853
19906
  const remote = entry.assignment.remoteUrl ?? entry.assignment.expectedRepoRemote;
19854
19907
  if (!remote || remoteKey(remote) !== identity.repositoryKey) throw new CodingWorkspaceError("workspace_checkout_unavailable");
19855
19908
  if (process.platform !== "linux") throw new CodingWorkspaceError("workspace_unsupported");
19856
- const path3 = resolve15(entry.worktree);
19909
+ const path3 = resolve14(entry.worktree);
19857
19910
  if (await realpath2(path3) !== path3) throw new CodingWorkspaceError("workspace_checkout_unavailable");
19858
19911
  directory = await open2(path3, constants7.O_RDONLY | constants7.O_DIRECTORY | constants7.O_NOFOLLOW);
19859
19912
  const root = {
@@ -20015,7 +20068,7 @@ async function readWorkspaceReceipt(command, entry) {
20015
20068
  import { constants as constants8 } from "node:fs";
20016
20069
  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";
20017
20070
  import { createHash as createHash14 } from "node:crypto";
20018
- import { resolve as resolve16, dirname as dirname16, join as join32, posix } from "node:path";
20071
+ import { resolve as resolve15, dirname as dirname15, join as join31, posix } from "node:path";
20019
20072
  import { tmpdir as tmpdir6 } from "node:os";
20020
20073
  import { execa as execa13 } from "execa";
20021
20074
 
@@ -20109,7 +20162,7 @@ async function gitFor(repoPath, root, signal) {
20109
20162
  const env = {
20110
20163
  ...buildChildEnv({}),
20111
20164
  GIT_DIR: gitDir,
20112
- GIT_COMMON_DIR: resolve16(gitDir, "..", ".."),
20165
+ GIT_COMMON_DIR: resolve15(gitDir, "..", ".."),
20113
20166
  // cwd is resolved while the parent's FD is still open. The child does not
20114
20167
  // inherit that numeric descriptor, so its work tree must be relative to cwd.
20115
20168
  GIT_WORK_TREE: ".",
@@ -20193,12 +20246,12 @@ async function conversionSettings(git3) {
20193
20246
  const host = buildChildEnv({});
20194
20247
  const defaults = ["/etc/gitattributes", "/usr/etc/gitattributes", "/usr/local/etc/gitattributes"];
20195
20248
  if (!external) {
20196
- const configHome = host.XDG_CONFIG_HOME || (host.HOME ? join32(host.HOME, ".config") : void 0);
20197
- if (configHome) defaults.push(join32(configHome, "git", "attributes"));
20249
+ const configHome = host.XDG_CONFIG_HOME || (host.HOME ? join31(host.HOME, ".config") : void 0);
20250
+ if (configHome) defaults.push(join31(configHome, "git", "attributes"));
20198
20251
  }
20199
- const info = join32(git3.commonDir, "info");
20252
+ const info = join31(git3.commonDir, "info");
20200
20253
  if (await existsWithoutReading(info)) {
20201
- if (!(await lstat4(info)).isDirectory() || await existsWithoutReading(join32(info, "attributes")))
20254
+ if (!(await lstat4(info)).isDirectory() || await existsWithoutReading(join31(info, "attributes")))
20202
20255
  throw new CodingWorkspaceError("workspace_unsupported");
20203
20256
  }
20204
20257
  for (const path3 of defaults) if (await existsWithoutReading(path3)) throw new CodingWorkspaceError("workspace_unsupported");
@@ -20244,10 +20297,10 @@ async function workingConversion(git3, root, paths, head, signal, budget) {
20244
20297
  throw new CodingWorkspaceError("workspace_unsupported");
20245
20298
  attributeBytes.set(path3, bytes);
20246
20299
  }
20247
- const directory = await mkdtemp2(join32(tmpdir6(), "mikka-diff-attributes-"));
20300
+ const directory = await mkdtemp2(join31(tmpdir6(), "mikka-diff-attributes-"));
20248
20301
  const actions = /* @__PURE__ */ new Map();
20249
20302
  try {
20250
- const gitDir = join32(directory, "git"), worktree = join32(directory, "worktree");
20303
+ const gitDir = join31(directory, "git"), worktree = join31(directory, "worktree");
20251
20304
  await mkdir4(worktree, { mode: 448 });
20252
20305
  const env = {
20253
20306
  ...buildChildEnv({}),
@@ -20267,8 +20320,8 @@ async function workingConversion(git3, root, paths, head, signal, budget) {
20267
20320
  killDescendants: true
20268
20321
  });
20269
20322
  for (const [path3, bytes] of attributeBytes) {
20270
- const target = join32(worktree, path3);
20271
- await mkdir4(dirname16(target), { recursive: true, mode: 448 });
20323
+ const target = join31(worktree, path3);
20324
+ await mkdir4(dirname15(target), { recursive: true, mode: 448 });
20272
20325
  await writeFile3(target, bytes, { mode: 384, flag: "wx" });
20273
20326
  }
20274
20327
  const attributes = ["text", "eol", "crlf", "filter", "working-tree-encoding", "ident"];
@@ -20533,7 +20586,7 @@ async function readWorkspaceDiffReceipt(command, entry, repoPath) {
20533
20586
  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)
20534
20587
  throw new CodingWorkspaceError("workspace_checkout_unavailable");
20535
20588
  if (process.platform !== "linux") throw new CodingWorkspaceError("workspace_unsupported");
20536
- const path3 = resolve16(entry.worktree);
20589
+ const path3 = resolve15(entry.worktree);
20537
20590
  if (await realpath3(path3) !== path3) throw new CodingWorkspaceError("workspace_checkout_unavailable");
20538
20591
  directory = await open3(path3, constants8.O_RDONLY | constants8.O_DIRECTORY | constants8.O_NOFOLLOW);
20539
20592
  const root = {
@@ -20603,7 +20656,7 @@ async function readWorkspaceRevertPreview(command, entry, repoPath) {
20603
20656
  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)
20604
20657
  throw new CodingWorkspaceError("workspace_checkout_unavailable");
20605
20658
  if (process.platform !== "linux") throw new CodingWorkspaceError("workspace_unsupported");
20606
- const path3 = resolve16(entry.worktree);
20659
+ const path3 = resolve15(entry.worktree);
20607
20660
  if (await realpath3(path3) !== path3) throw new CodingWorkspaceError("workspace_checkout_unavailable");
20608
20661
  directory = await open3(path3, constants8.O_RDONLY | constants8.O_DIRECTORY | constants8.O_NOFOLLOW);
20609
20662
  const root = {
@@ -20675,7 +20728,7 @@ async function readWorkspaceRevertPreview(command, entry, repoPath) {
20675
20728
  import { constants as constants9 } from "node:fs";
20676
20729
  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";
20677
20730
  import { createHash as createHash15 } from "node:crypto";
20678
- import { join as join33, resolve as resolve17 } from "node:path";
20731
+ import { join as join32, resolve as resolve16 } from "node:path";
20679
20732
  import { tmpdir as tmpdir7 } from "node:os";
20680
20733
  import { execa as execa14 } from "execa";
20681
20734
 
@@ -20831,7 +20884,7 @@ async function openPinnedRoot(command, entry) {
20831
20884
  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)
20832
20885
  throw unavailable4();
20833
20886
  if (process.platform !== "linux") throw new CodingWorkspaceError("workspace_unsupported");
20834
- const path3 = resolve17(entry.worktree);
20887
+ const path3 = resolve16(entry.worktree);
20835
20888
  if (await realpath4(path3) !== path3) throw unavailable4();
20836
20889
  const directory = await open4(path3, constants9.O_RDONLY | constants9.O_DIRECTORY | constants9.O_NOFOLLOW);
20837
20890
  try {
@@ -21271,7 +21324,7 @@ function runGit(cwd, args, env, signal, maximum = 8 * 1024 * 1024) {
21271
21324
  }
21272
21325
  async function readTempFile(worktree, path3) {
21273
21326
  if (!visibleWorkspacePath(path3)) throw new CodingWorkspaceError("workspace_path_unavailable");
21274
- const full = join33(worktree, ...path3.split("/"));
21327
+ const full = join32(worktree, ...path3.split("/"));
21275
21328
  if (!full.startsWith(`${worktree}/`)) throw new CodingWorkspaceError("workspace_path_unavailable");
21276
21329
  try {
21277
21330
  const stat3 = await lstat5(full);
@@ -21292,8 +21345,8 @@ async function dryRunCheckpoint(git3, root, identity, statusBase, patchBase, pat
21292
21345
  } catch (error) {
21293
21346
  throw new CodingWorkspaceError("workspace_unsupported", { cause: error });
21294
21347
  }
21295
- const parent = await mkdtemp3(join33(tmpdir7(), "mikka-git-restore-"));
21296
- const worktree = join33(parent, "wt"), patchFile = join33(parent, "checkpoint.patch");
21348
+ const parent = await mkdtemp3(join32(tmpdir7(), "mikka-git-restore-"));
21349
+ const worktree = join32(parent, "wt"), patchFile = join32(parent, "checkpoint.patch");
21297
21350
  try {
21298
21351
  await writeFile4(patchFile, patch, { mode: 384 });
21299
21352
  await runGit(git3.commonDir, ["worktree", "add", "--detach", "--quiet", worktree, head], commonEnv(git3), signal);
@@ -21575,7 +21628,7 @@ async function handleWorkspaceGitRequest(command, entry, repoPath) {
21575
21628
  // src/repositories.ts
21576
21629
  import { createHash as createHash16, randomUUID as randomUUID7 } from "node:crypto";
21577
21630
  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";
21578
- import { dirname as dirname17, join as join34, resolve as resolve18 } from "node:path";
21631
+ import { dirname as dirname16, join as join33, resolve as resolve17 } from "node:path";
21579
21632
  import { setTimeout as delay } from "node:timers/promises";
21580
21633
  import { execa as execa15 } from "execa";
21581
21634
  import lockfile2 from "proper-lockfile";
@@ -21599,8 +21652,8 @@ var RepositoryCache = class {
21599
21652
  retainResources;
21600
21653
  pathFor(remoteUrl) {
21601
21654
  const { key: key2 } = normalizeRepository(remoteUrl, { allowFile: this.allowFile });
21602
- const path3 = resolve18(this.root, "v2", createHash16("sha256").update(key2).digest("hex"));
21603
- if (!isInside(resolve18(this.root), path3) || path3 === resolve18(this.root)) throw new Error("Invalid repository cache path");
21655
+ const path3 = resolve17(this.root, "v2", createHash16("sha256").update(key2).digest("hex"));
21656
+ if (!isInside(resolve17(this.root), path3) || path3 === resolve17(this.root)) throw new Error("Invalid repository cache path");
21604
21657
  return path3;
21605
21658
  }
21606
21659
  /** Serialize clone/fetch against the same cache, including other processes. */
@@ -21608,7 +21661,7 @@ var RepositoryCache = class {
21608
21661
  signal?.throwIfAborted();
21609
21662
  const { remoteUrl: remote } = normalizeRepository(remoteUrl, { allowFile: this.allowFile });
21610
21663
  const path3 = this.pathFor(remote);
21611
- this.ensureParents(dirname17(path3));
21664
+ this.ensureParents(dirname16(path3));
21612
21665
  const release = await this.lock(path3, signal);
21613
21666
  try {
21614
21667
  return await withRepoConfig(path3, () => this.update(path3, remote, signal, env, diagnostics));
@@ -21647,7 +21700,7 @@ var RepositoryCache = class {
21647
21700
  } else {
21648
21701
  this.assertClone(path3);
21649
21702
  await git3(["remote", "set-url", "origin", remote], path3);
21650
- const depth = existsSync7(join34(path3, ".git", "shallow")) ? ["--depth=50"] : [];
21703
+ const depth = existsSync7(join33(path3, ".git", "shallow")) ? ["--depth=50"] : [];
21651
21704
  await git3(["fetch", ...depth, ...this.retainResources ? [] : ["--prune"], "--no-tags", "--no-recurse-submodules", "--no-write-fetch-head", "origin"], path3);
21652
21705
  }
21653
21706
  this.assertClone(path3);
@@ -21739,28 +21792,28 @@ var RepositoryCache = class {
21739
21792
  paths() {
21740
21793
  const visit = (path3) => {
21741
21794
  if (!existsSync7(path3) || lstatSync12(path3).isSymbolicLink()) return [];
21742
- if (existsSync7(join34(path3, ".git"))) {
21795
+ if (existsSync7(join33(path3, ".git"))) {
21743
21796
  this.assertClone(path3);
21744
21797
  return [path3];
21745
21798
  }
21746
- return readdirSync9(path3, { withFileTypes: true }).flatMap((entry) => entry.isDirectory() && !entry.name.endsWith(".lock") && !entry.name.includes(".clone-") ? visit(join34(path3, entry.name)) : []);
21799
+ return readdirSync9(path3, { withFileTypes: true }).flatMap((entry) => entry.isDirectory() && !entry.name.endsWith(".lock") && !entry.name.includes(".clone-") ? visit(join33(path3, entry.name)) : []);
21747
21800
  };
21748
- return visit(resolve18(this.root));
21801
+ return visit(resolve17(this.root));
21749
21802
  }
21750
21803
  ensureParents(path3) {
21751
21804
  mkdirSync17(this.root, { recursive: true, mode: 448 });
21752
21805
  if (lstatSync12(this.root).isSymbolicLink()) throw new Error("Repository cache contains a symlink");
21753
21806
  const root = realpathSync13(this.root);
21754
- let current = resolve18(this.root);
21807
+ let current = resolve17(this.root);
21755
21808
  for (const part of path3.slice(current.length + 1).split("/").filter(Boolean)) {
21756
- current = join34(current, part);
21809
+ current = join33(current, part);
21757
21810
  if (existsSync7(current) && lstatSync12(current).isSymbolicLink()) throw new Error("Repository cache contains a symlink");
21758
21811
  mkdirSync17(current, { recursive: true, mode: 448 });
21759
21812
  if (!isInside(root, realpathSync13(current))) throw new Error("Repository cache escapes its directory");
21760
21813
  }
21761
21814
  }
21762
21815
  assertClone(path3) {
21763
- if (lstatSync12(path3).isSymbolicLink() || !lstatSync12(join34(path3, ".git")).isDirectory() || lstatSync12(join34(path3, ".git")).isSymbolicLink()) throw new Error("Repository cache is not a standard clone");
21816
+ if (lstatSync12(path3).isSymbolicLink() || !lstatSync12(join33(path3, ".git")).isDirectory() || lstatSync12(join33(path3, ".git")).isSymbolicLink()) throw new Error("Repository cache is not a standard clone");
21764
21817
  if (!isInside(realpathSync13(this.root), realpathSync13(path3))) throw new Error("Repository cache escapes its directory");
21765
21818
  }
21766
21819
  async lock(path3, signal) {
@@ -21866,7 +21919,7 @@ async function prepareRunRepository(repositories, privateDir, assignment, signal
21866
21919
  import { randomUUID as randomUUID8 } from "node:crypto";
21867
21920
  import { spawn as spawn5 } from "node:child_process";
21868
21921
  import { existsSync as existsSync8, mkdirSync as mkdirSync18, realpathSync as realpathSync14 } from "node:fs";
21869
- import { dirname as dirname18, join as join35, resolve as resolve19 } from "node:path";
21922
+ import { dirname as dirname17, join as join34, resolve as resolve18 } from "node:path";
21870
21923
  import { fileURLToPath } from "node:url";
21871
21924
 
21872
21925
  // src/official-cli-timing.ts
@@ -22235,11 +22288,11 @@ async function startCliTimingCollector({ runId, harness, remoteMcpServerCount, d
22235
22288
  server.requestTimeout = 5e3;
22236
22289
  server.headersTimeout = 5e3;
22237
22290
  server.maxConnections = 8;
22238
- await new Promise((resolve20, reject) => {
22291
+ await new Promise((resolve19, reject) => {
22239
22292
  server.once("error", reject);
22240
22293
  server.listen(0, "127.0.0.1", () => {
22241
22294
  server.off("error", reject);
22242
- resolve20();
22295
+ resolve19();
22243
22296
  });
22244
22297
  });
22245
22298
  server.on("error", () => {
@@ -22288,7 +22341,7 @@ async function startCliTimingCollector({ runId, harness, remoteMcpServerCount, d
22288
22341
  unsetEnv,
22289
22342
  mcpHttpObservationUrl: `${origin}${mcpPath}`,
22290
22343
  close: ({ cliExitObserved = false, publish = true } = {}) => closed ??= (async () => {
22291
- await new Promise((resolve20) => {
22344
+ await new Promise((resolve19) => {
22292
22345
  const timer = setTimeout(() => {
22293
22346
  collector.truncate();
22294
22347
  mcpCollector.truncate();
@@ -22296,7 +22349,7 @@ async function startCliTimingCollector({ runId, harness, remoteMcpServerCount, d
22296
22349
  }, 1e3);
22297
22350
  server.close(() => {
22298
22351
  clearTimeout(timer);
22299
- resolve20();
22352
+ resolve19();
22300
22353
  });
22301
22354
  });
22302
22355
  const official = collector.finish(cliExitObserved), mcp = mcpCollector.finish();
@@ -22334,7 +22387,7 @@ async function runHostedCommand(worktree, script, _readOnly, timeoutMs, signal)
22334
22387
  abort();
22335
22388
  } else chunks.push(chunk);
22336
22389
  };
22337
- const result = await new Promise((resolve20, reject) => {
22390
+ const result = await new Promise((resolve19, reject) => {
22338
22391
  child = spawn5("/bin/sh", ["-c", script], {
22339
22392
  cwd: realpathSync14(worktree),
22340
22393
  env: process.env,
@@ -22344,7 +22397,7 @@ async function runHostedCommand(worktree, script, _readOnly, timeoutMs, signal)
22344
22397
  child.stdout?.on("data", (chunk) => collect("stdout", stdout, chunk));
22345
22398
  child.stderr?.on("data", (chunk) => collect("stderr", stderr, chunk));
22346
22399
  child.once("error", reject);
22347
- child.once("close", (code, term) => resolve20({ code, signal: term }));
22400
+ child.once("close", (code, term) => resolve19({ code, signal: term }));
22348
22401
  child.once("exit", abort);
22349
22402
  signal?.addEventListener("abort", abort, { once: true });
22350
22403
  if (signal?.aborted) abort();
@@ -22470,7 +22523,7 @@ async function createHostedBotRunner(host) {
22470
22523
  if (selected && (!options.model || options.model !== subscription?.first.modelId)) throw Error("binding_mismatch");
22471
22524
  const paths = runPaths(host.stateDir, assignment.runId);
22472
22525
  mkdirSync18(paths.runDir, { recursive: true, mode: 448 });
22473
- const cwd = preparation ? resolve19(options.cwd) : realpathSync14(options.cwd);
22526
+ const cwd = preparation ? resolve18(options.cwd) : realpathSync14(options.cwd);
22474
22527
  const env = Object.fromEntries(Object.entries({ ...process.env, ...options.env, ...assignment.taskEnv }).filter((entry) => typeof entry[1] === "string"));
22475
22528
  if (runDiagnosticsEnabled(assignment.taskEnv, host.collectCliTiming)) env.CLOUD_STARTUP_TIMING = "1";
22476
22529
  const selectedGithub = options.github ?? (assignment.github ? { ...assignment.github, issueId: assignment.issueId, runToken: assignment.mcp?.token } : void 0);
@@ -22501,7 +22554,7 @@ async function createHostedBotRunner(host) {
22501
22554
  });
22502
22555
  Object.assign(env, github.env);
22503
22556
  }
22504
- const ledger = join35(host.stateDir, "native-ledgers", assignment.runId + ".json");
22557
+ const ledger = join34(host.stateDir, "native-ledgers", assignment.runId + ".json");
22505
22558
  const scope = selected && subscription ? {
22506
22559
  runId: assignment.runId,
22507
22560
  bindingId: selected.bindingId,
@@ -22514,12 +22567,12 @@ async function createHostedBotRunner(host) {
22514
22567
  modelId: subscription.first.modelId
22515
22568
  } : void 0;
22516
22569
  if (continuation && existsSync8(ledger)) throw unavailable5("ledger_mismatch");
22517
- const previousLedger = continuation ? join35(host.stateDir, "native-ledgers", continuation.runId + ".json") : ledger;
22570
+ const previousLedger = continuation ? join34(host.stateDir, "native-ledgers", continuation.runId + ".json") : ledger;
22518
22571
  const previous = scope ? readJson(previousLedger) : void 0;
22519
22572
  if (preparation && previous) throw unavailable5("ledger_mismatch");
22520
22573
  const expectedScope = scope && continuation ? { ...scope, runId: continuation.runId } : scope;
22521
22574
  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");
22522
- if (scope) mkdirSync18(dirname18(ledger), { recursive: true, mode: 448 });
22575
+ if (scope) mkdirSync18(dirname17(ledger), { recursive: true, mode: 448 });
22523
22576
  const record3 = async (sessionId) => {
22524
22577
  assertOpen();
22525
22578
  if (scope) writeJsonAtomic(ledger, { scope, sessionId });
@@ -22591,9 +22644,9 @@ async function createHostedBotRunner(host) {
22591
22644
  signal: lifetime.signal
22592
22645
  });
22593
22646
  child.stderr?.resume();
22594
- const exited = new Promise((resolve20) => {
22595
- child.once("exit", (code, signal) => resolve20({ code, signal }));
22596
- child.once("error", () => resolve20({ code: null, signal: null }));
22647
+ const exited = new Promise((resolve19) => {
22648
+ child.once("exit", (code, signal) => resolve19({ code, signal }));
22649
+ child.once("error", () => resolve19({ code: null, signal: null }));
22597
22650
  });
22598
22651
  return {
22599
22652
  process: child,
@@ -22860,14 +22913,14 @@ function normalizeCall(value) {
22860
22913
  return { name, arguments: { direction: args.direction, amount: args.amount, x: args.x, y: args.y } };
22861
22914
  throw new Error("Unsupported tool or arguments");
22862
22915
  }
22863
- function driverArguments(input, platform5 = process.platform) {
22916
+ function driverArguments(input, platform4 = process.platform) {
22864
22917
  const call = normalizeCall(input);
22865
22918
  return call.name === "click" ? {
22866
22919
  ...call.arguments,
22867
22920
  scope: "desktop",
22868
- ...platform5 === "darwin" ? {} : { coordinate_frame: "desktop" },
22921
+ ...platform4 === "darwin" ? {} : { coordinate_frame: "desktop" },
22869
22922
  delivery_mode: "foreground"
22870
- } : ["type_text", "press_key"].includes(call.name) ? { ...call.arguments, scope: "desktop", delivery_mode: "foreground" } : call.name === "scroll" ? { ...call.arguments, scope: "desktop", ...platform5 === "darwin" ? {} : { coordinate_frame: "desktop" }, delivery_mode: "foreground" } : call.arguments;
22923
+ } : ["type_text", "press_key"].includes(call.name) ? { ...call.arguments, scope: "desktop", delivery_mode: "foreground" } : call.name === "scroll" ? { ...call.arguments, scope: "desktop", ...platform4 === "darwin" ? {} : { coordinate_frame: "desktop" }, delivery_mode: "foreground" } : call.arguments;
22871
22924
  }
22872
22925
  async function executeDriver(driver, input, display, leaseGuard, assertLive = () => {
22873
22926
  }, beforeAction) {
@@ -22937,9 +22990,9 @@ async function executeDriver(driver, input, display, leaseGuard, assertLive = ()
22937
22990
  )
22938
22991
  )
22939
22992
  );
22940
- const request2 = (method, params) => new Promise((resolve20, reject) => {
22993
+ const request2 = (method, params) => new Promise((resolve19, reject) => {
22941
22994
  const n = ++id5;
22942
- pending.set(n, { resolve: resolve20, reject });
22995
+ pending.set(n, { resolve: resolve19, reject });
22943
22996
  child.stdin.write(
22944
22997
  JSON.stringify({ jsonrpc: "2.0", id: n, method, params }) + "\n"
22945
22998
  );
@@ -22973,13 +23026,39 @@ async function executeDriver(driver, input, display, leaseGuard, assertLive = ()
22973
23026
  }
22974
23027
 
22975
23028
  // src/computer/broker.mjs
23029
+ var PendingRequests = class extends Map {
23030
+ constructor(changed) {
23031
+ super();
23032
+ this.changed = changed;
23033
+ }
23034
+ set(key2, value) {
23035
+ super.set(key2, value);
23036
+ this.changed?.();
23037
+ return this;
23038
+ }
23039
+ delete(key2) {
23040
+ const had = super.delete(key2);
23041
+ if (had) this.changed?.();
23042
+ return had;
23043
+ }
23044
+ };
22976
23045
  var ComputerBroker = class {
22977
23046
  grants = /* @__PURE__ */ new Map();
22978
23047
  // runId → when its screen recording stops by itself; only set while one runs.
22979
23048
  recordingUntil = /* @__PURE__ */ new Map();
22980
23049
  recordingSteps = /* @__PURE__ */ new Map();
22981
23050
  recordingTimingFailed = /* @__PURE__ */ new Set();
22982
- pending = /* @__PURE__ */ new Map();
23051
+ pendingListeners = /* @__PURE__ */ new Set();
23052
+ pending = new PendingRequests(() => {
23053
+ for (const listener of [...this.pendingListeners]) listener();
23054
+ });
23055
+ /** Calls `listener` whenever a pending review appears or goes; returns the unsubscribe. */
23056
+ onPendingChange(listener) {
23057
+ this.pendingListeners.add(listener);
23058
+ return () => {
23059
+ this.pendingListeners.delete(listener);
23060
+ };
23061
+ }
22983
23062
  sockets = /* @__PURE__ */ new Set();
22984
23063
  suspended = false;
22985
23064
  constructor({
@@ -23055,10 +23134,10 @@ var ComputerBroker = class {
23055
23134
  })();
23056
23135
  });
23057
23136
  });
23058
- await new Promise((resolve20, reject) => {
23137
+ await new Promise((resolve19, reject) => {
23059
23138
  this.server.once("error", reject);
23060
- if (this.transport === "tcp") this.server.listen({ host: "127.0.0.1", port: 0 }, resolve20);
23061
- else this.server.listen(this.socketPath, resolve20);
23139
+ if (this.transport === "tcp") this.server.listen({ host: "127.0.0.1", port: 0 }, resolve19);
23140
+ else this.server.listen(this.socketPath, resolve19);
23062
23141
  });
23063
23142
  if (this.transport === "tcp") this.socketPath = `tcp://127.0.0.1:${this.server.address().port}`;
23064
23143
  else chmodSync2(this.socketPath, 384);
@@ -23144,7 +23223,7 @@ var ComputerBroker = class {
23144
23223
  expiresAt: this.now() + this.ttl
23145
23224
  };
23146
23225
  const digest9 = createHash19("sha256").update(JSON.stringify(request2)).digest("hex");
23147
- return new Promise((resolve20, reject) => {
23226
+ return new Promise((resolve19, reject) => {
23148
23227
  const timer = setTimeout(() => {
23149
23228
  this.pending.delete(request2.id);
23150
23229
  signal?.removeEventListener("abort", cancel);
@@ -23162,7 +23241,7 @@ var ComputerBroker = class {
23162
23241
  assertLive,
23163
23242
  cleanup: () => signal?.removeEventListener("abort", cancel),
23164
23243
  request: { ...request2, digest: digest9 },
23165
- resolve: resolve20,
23244
+ resolve: resolve19,
23166
23245
  reject,
23167
23246
  timer
23168
23247
  });
@@ -23255,7 +23334,7 @@ var ComputerBroker = class {
23255
23334
  async close() {
23256
23335
  this.suspend();
23257
23336
  for (const socket of this.sockets) socket.destroy();
23258
- if (this.server?.listening) await new Promise((resolve20) => this.server.close(resolve20));
23337
+ if (this.server?.listening) await new Promise((resolve19) => this.server.close(resolve19));
23259
23338
  }
23260
23339
  };
23261
23340
 
@@ -23316,100 +23395,87 @@ async function syncWebComputerReviews(broker, deviceId, link, signal) {
23316
23395
  if (signal?.aborted) return;
23317
23396
  await applyWebComputerDecisions(broker, decisions);
23318
23397
  }
23319
- var REVIEW_PRESENCE_MS = 5e3;
23320
23398
  function snapshotKey(requests) {
23321
23399
  return requests.map((row) => `${row.id}:${row.digest}`).sort().join(",");
23322
23400
  }
23323
- async function pollWebComputerReviews(broker, deviceId, link, signal, intervalMs = 1e3, pushes, presenceMs = REVIEW_PRESENCE_MS) {
23401
+ async function followWebComputerReviews(broker, deviceId, link, signal, pushes, onUnreachable) {
23324
23402
  if (!link.syncComputerReviews) throw new Error("Computer review transport unavailable");
23325
- let pushed = false;
23403
+ let pushed = true;
23404
+ let changed = true;
23326
23405
  let synced;
23327
- let syncedAt = 0;
23328
- const unsubscribe = pushes?.subscribe(() => {
23406
+ let wake = null;
23407
+ const nudge = () => {
23408
+ const done = wake;
23409
+ wake = null;
23410
+ done?.();
23411
+ };
23412
+ const offPush = pushes.subscribe(() => {
23329
23413
  pushed = true;
23414
+ nudge();
23415
+ });
23416
+ const offBroker = broker.onPendingChange(() => {
23417
+ changed = true;
23418
+ nudge();
23330
23419
  });
23420
+ const onAbort = () => nudge();
23421
+ signal.addEventListener("abort", onAbort, { once: true });
23331
23422
  try {
23332
23423
  while (!signal.aborted) {
23333
- const snapshot4 = broker.list();
23334
- const pending = snapshot4.length > 0;
23335
- const key2 = snapshotKey(snapshot4);
23336
- const everyCheck = (pushes?.mode("computerReviews") ?? "legacy") !== "push";
23337
- if (key2 !== synced || pending && (pushed || everyCheck || Date.now() - syncedAt >= presenceMs)) {
23338
- pushed = false;
23339
- try {
23340
- await syncWebComputerReviews(broker, deviceId, link, signal);
23341
- synced = key2;
23342
- syncedAt = Date.now();
23343
- } catch {
23424
+ if (pushes.live && (pushed || changed)) {
23425
+ const snapshot4 = broker.list();
23426
+ const key2 = snapshotKey(snapshot4);
23427
+ if (key2 !== synced || pushed && snapshot4.length > 0) {
23428
+ pushed = false;
23429
+ changed = false;
23430
+ try {
23431
+ await syncWebComputerReviews(broker, deviceId, link, signal);
23432
+ synced = key2;
23433
+ } catch (error) {
23434
+ if (error instanceof ServerUnreachableError) onUnreachable?.();
23435
+ }
23436
+ continue;
23344
23437
  }
23438
+ pushed = false;
23439
+ changed = false;
23345
23440
  }
23346
23441
  if (signal.aborted) break;
23347
- if (pushes) await pushes.next(intervalMs, signal);
23348
- else await new Promise((resolve20) => {
23349
- const done = () => {
23350
- clearTimeout(timer);
23351
- signal.removeEventListener("abort", done);
23352
- resolve20();
23353
- };
23354
- const timer = setTimeout(done, intervalMs);
23355
- signal.addEventListener("abort", done, { once: true });
23356
- if (signal.aborted) done();
23442
+ await new Promise((resolve19) => {
23443
+ wake = resolve19;
23444
+ if (signal.aborted) nudge();
23357
23445
  });
23358
23446
  }
23359
23447
  } finally {
23360
- unsubscribe?.();
23448
+ offPush();
23449
+ offBroker();
23450
+ signal.removeEventListener("abort", onAbort);
23361
23451
  }
23362
23452
  }
23363
23453
 
23364
23454
  // src/device-work-signal.ts
23365
23455
  var DeviceWorkSignal = class {
23366
23456
  connected = false;
23367
- pushed = /* @__PURE__ */ new Set();
23368
23457
  listeners = /* @__PURE__ */ new Set();
23369
- /** From the last gateway ticket: the waits this server pushes for. */
23370
- setPushedWaits(waits) {
23371
- this.pushed = new Set(waits);
23372
- this.notify();
23458
+ /** Whether the device session socket is open. */
23459
+ get live() {
23460
+ return this.connected;
23373
23461
  }
23374
- /** The gateway socket opened or dropped. Either way, read again: a push may have been lost meanwhile. */
23462
+ /** The socket opened or dropped. Opening wakes every waiter to read again. */
23375
23463
  setConnected(connected) {
23376
23464
  if (this.connected === connected) return;
23377
23465
  this.connected = connected;
23378
23466
  this.notify();
23379
23467
  }
23380
- mode(wait) {
23381
- if (!this.pushed.has(wait)) return "legacy";
23382
- return this.connected ? "push" : "fallback";
23383
- }
23384
23468
  /** A work frame arrived on the gateway socket. */
23385
23469
  notify() {
23386
23470
  for (const listener of [...this.listeners]) listener();
23387
23471
  }
23388
- /** Calls `listener` on each push or mode change; returns the unsubscribe. */
23472
+ /** Calls `listener` on each push or connection change; returns the unsubscribe. */
23389
23473
  subscribe(listener) {
23390
23474
  this.listeners.add(listener);
23391
23475
  return () => {
23392
23476
  this.listeners.delete(listener);
23393
23477
  };
23394
23478
  }
23395
- /** Resolves on the next push or mode change, after `ms`, or on abort. */
23396
- next(ms2, signal) {
23397
- return new Promise((resolve20) => {
23398
- if (signal?.aborted) {
23399
- resolve20();
23400
- return;
23401
- }
23402
- const done = () => {
23403
- clearTimeout(timer);
23404
- off();
23405
- signal?.removeEventListener("abort", done);
23406
- resolve20();
23407
- };
23408
- const timer = setTimeout(done, Math.max(0, ms2));
23409
- const off = this.subscribe(done);
23410
- signal?.addEventListener("abort", done, { once: true });
23411
- });
23412
- }
23413
23479
  };
23414
23480
 
23415
23481
  // src/computer/local-grant.mjs
@@ -23434,6 +23500,10 @@ function loadDeviceFile(raw) {
23434
23500
  }
23435
23501
  var HARNESS_RESCAN_MS = 5 * 6e4;
23436
23502
  var MODEL_PROBE_MS = 6 * 60 * 6e4;
23503
+ var LOCAL_CHECK_MS = 5e3;
23504
+ var CHECKPOINT_SCAN_MS = 15e3;
23505
+ var CLOUD_CREDENTIAL_ROTATE_BEFORE_MS = 60 * 6e4;
23506
+ var MAX_TIMER_MS3 = 2 ** 31 - 1;
23437
23507
  function cloudComputerGrantMatches(assignment, runId, deviceId) {
23438
23508
  if (!assignment?.computer || !deviceId || assignment.runId !== runId || assignment.deviceId !== deviceId) return false;
23439
23509
  const snapshot4 = assignment.policySnapshot?.payload;
@@ -23445,7 +23515,6 @@ var Daemon = class {
23445
23515
  this.paths = daemonPaths(options.dataDir);
23446
23516
  this.log = options.log ?? createLogger({ dir: this.paths.logs });
23447
23517
  this.initialRunHint = options.initialRunId;
23448
- this.runControlPush = Boolean(options.hostedSubscriptions);
23449
23518
  }
23450
23519
  options;
23451
23520
  paths;
@@ -23463,16 +23532,12 @@ var Daemon = class {
23463
23532
  device = {};
23464
23533
  harnesses = [];
23465
23534
  server = "unregistered";
23466
- timer = null;
23467
- tick = Promise.resolve();
23468
23535
  updating = false;
23469
23536
  claimsInFlight = 0;
23470
- /** Shared by the heartbeat, commands poll and RPC so one run has one claim. */
23537
+ /** Shared by session passes and RPC so one run has one claim. */
23471
23538
  claims = /* @__PURE__ */ new Map();
23472
- /** The newest release a server named; the commands poll sends it so the same news does not end every poll. */
23539
+ /** The newest release a server named; each commands read sends it. */
23473
23540
  knownLatest;
23474
- /** Device commands the commands poll already handed over; the heartbeat carries them out. */
23475
- polledDeviceCommands = [];
23476
23541
  maintenance = null;
23477
23542
  updateVersion;
23478
23543
  draining = false;
@@ -23484,25 +23549,37 @@ var Daemon = class {
23484
23549
  registered = false;
23485
23550
  /** Run ids the server sent that were refused as unsafe (reported once). */
23486
23551
  refusedRuns = /* @__PURE__ */ new Set();
23487
- /** Runs the commands poll reported queued: being claimed, or failed until the next heartbeat retries them. */
23552
+ /** Runs a commands read reported queued: being claimed, or failed until the next pass retries them. */
23488
23553
  queuedClaims = /* @__PURE__ */ new Map();
23489
23554
  quota = null;
23490
- /** Ends the commands long-poll when the daemon stops. */
23491
- commandsAbort = new AbortController();
23492
- /** The push socket is open. An idle device does not heartbeat the database. */
23493
- gatewayLive = false;
23494
- /** The server's last gateway ticket said it pushes run control (#1212). */
23495
- runControlPush = false;
23555
+ /** Aborts the daemon's own requests (claims, reads) when it stops. */
23556
+ lifetime = new AbortController();
23557
+ /** The device session: its socket is the daemon's only standing link to the server. */
23558
+ session = null;
23559
+ /** The session socket is open. */
23560
+ sessionOpen = false;
23561
+ /** Set when the daemon cannot use this server: it must update, or the server has no gateway. */
23562
+ blocked = null;
23563
+ /** The release a 426 or npm named for a daemon that must update. */
23564
+ requiredVersion;
23496
23565
  /** Gateway pushes for computer reviews (and other non-run-control waits). */
23497
23566
  workSignal = new DeviceWorkSignal();
23498
- /** The server said it has no gateway. Do not ask again on every long-poll. */
23499
- gatewayUnavailable = false;
23500
- gatewayFailures = 0;
23501
- gatewayRetryAt = 0;
23502
- deviceReceiptsVersion = 0;
23503
- deviceReceiptsAcknowledged = 0;
23504
- commandsLoop = Promise.resolve();
23505
- fsLoop = Promise.resolve();
23567
+ /** The last report the server took, as sent; a report goes out only when this changes. */
23568
+ lastReport;
23569
+ /** The socket opened since the last report: send one even if nothing changed. */
23570
+ reportOnOpen = false;
23571
+ /** A device command waiting to run (until idle, or until its runs end). */
23572
+ heldDeviceCommand;
23573
+ heldCommandPass = null;
23574
+ /** The cloud worker's token expires within the hour: the next report asks for its successor. */
23575
+ rotationDue = false;
23576
+ rotationTimer = null;
23577
+ localTimer = null;
23578
+ lastCheckpointScan = 0;
23579
+ checkpointScan = null;
23580
+ /** Resolved when a credential arrives (`device.setCredential`). */
23581
+ credentialArrived = /* @__PURE__ */ new Set();
23582
+ deviceType;
23506
23583
  reviewAbort = null;
23507
23584
  reviewLoop = Promise.resolve();
23508
23585
  cloudComputerBroker = null;
@@ -23515,13 +23592,11 @@ var Daemon = class {
23515
23592
  stopping = /* @__PURE__ */ new Set();
23516
23593
  /** Runs this daemon has ended, whose end the server may not have yet. */
23517
23594
  ended = /* @__PURE__ */ new Set();
23518
- /** The server pass in flight; the next one starts after it. */
23595
+ /** The server work in flight (a pass, a registration, a report); the next one starts after it. */
23519
23596
  syncing = Promise.resolve();
23520
23597
  initialRunHint;
23521
23598
  /** An early claim must retain the first sync's complete repository settings. */
23522
23599
  initialRepositorySync;
23523
- /** Cuts the poll loop's pause short (the device just registered). */
23524
- wakeCommands = null;
23525
23600
  async start() {
23526
23601
  this.starting = this.startInternal();
23527
23602
  try {
@@ -23549,7 +23624,7 @@ var Daemon = class {
23549
23624
  if (this.options.credential)
23550
23625
  this.saveDevice({ credential: this.options.credential });
23551
23626
  this.journal = new RunJournal(paths.journal);
23552
- this.captureUploader = new CaptureUploader((runId) => join36(runPaths(paths.adapterState, runId).runDir, CAPTURES_DIR), this.options.link, this.log, join36(paths.dataDir, "capture-pending"));
23627
+ this.captureUploader = new CaptureUploader((runId) => join35(runPaths(paths.adapterState, runId).runDir, CAPTURES_DIR), this.options.link, this.log, join35(paths.dataDir, "capture-pending"));
23553
23628
  this.outbox = new Outbox(
23554
23629
  paths.outbox,
23555
23630
  this.options.link,
@@ -23562,13 +23637,13 @@ var Daemon = class {
23562
23637
  this.worktrees = new WorktreeManager(this.options.taskRegistered ? "/workspace/worktrees" : paths.worktrees, this.options.retainResources);
23563
23638
  this.repositories = new RepositoryCache(this.options.taskRegistered ? "/workspace/repos" : paths.repos, void 0, this.options.retainResources);
23564
23639
  this.sandbox = this.options.hostedSubscriptions ? null : await this.createAgentSandbox();
23565
- if (this.runControlPush) this.options.link.setRunControlMode?.("fallback");
23640
+ this.options.link.onUpgradeRequired?.((latest) => this.enterUpdateRequired(latest));
23566
23641
  if (this.stopped) throw new Error("daemon stopped during startup");
23567
23642
  if (!this.options.hostedSubscriptions && this.sandbox) this.localComputerDriver = await detectComputerDriver();
23568
23643
  if (this.localComputerDriver && this.options.link.syncComputerReviews) {
23569
23644
  this.localComputerBroker = new ComputerBroker({
23570
23645
  driver: this.localComputerDriver,
23571
- socketPath: join36(paths.dataDir, "local-computer.sock"),
23646
+ socketPath: join35(paths.dataDir, "local-computer.sock"),
23572
23647
  transport: "tcp",
23573
23648
  needsPerson: this.computerNeedsPerson(),
23574
23649
  permitted: (runId) => {
@@ -23611,7 +23686,7 @@ var Daemon = class {
23611
23686
  };
23612
23687
  this.cloudComputerBroker = new ComputerBroker({
23613
23688
  driver,
23614
- socketPath: join36(paths.dataDir, "computer.sock"),
23689
+ socketPath: join35(paths.dataDir, "computer.sock"),
23615
23690
  needsPerson: this.computerNeedsPerson(),
23616
23691
  permitted: (runId) => {
23617
23692
  const entry = this.journal.get(runId);
@@ -23705,7 +23780,7 @@ var Daemon = class {
23705
23780
  prepareRunMailbox: this.options.link.prepareRunMailbox?.bind(this.options.link),
23706
23781
  prepareRunToolApproval: this.options.link.prepareRunToolApproval?.bind(this.options.link),
23707
23782
  prepareRunGitHub: hosted ? void 0 : (assignment, signal, onCredential) => prepareLocalGitHub(assignment, {
23708
- stateDir: join36(this.paths.adapterState, "github"),
23783
+ stateDir: join35(this.paths.adapterState, "github"),
23709
23784
  link: this.options.link,
23710
23785
  signal,
23711
23786
  onCredential,
@@ -23775,7 +23850,7 @@ var Daemon = class {
23775
23850
  worktree,
23776
23851
  tree,
23777
23852
  github: { ...assignment.github, runToken: assignment.mcp?.token, issueId: assignment.issueId },
23778
- privateDir: join36(paths.adapterState, "pids"),
23853
+ privateDir: join35(paths.adapterState, "pids"),
23779
23854
  ...hosted ? { hosted: true } : {},
23780
23855
  env: hosted ? process.env : githubReceiptEnvironment(),
23781
23856
  githubEnvironment,
@@ -23801,6 +23876,7 @@ var Daemon = class {
23801
23876
  })
23802
23877
  }
23803
23878
  });
23879
+ this.supervisor.sessionClosed();
23804
23880
  this.rpc = new RpcServer({
23805
23881
  socketPath: paths.socket,
23806
23882
  secret,
@@ -23846,103 +23922,322 @@ var Daemon = class {
23846
23922
  },
23847
23923
  "daemon started"
23848
23924
  );
23849
- this.schedule(0);
23850
- this.commandsLoop = this.pollCommands();
23925
+ this.startSession();
23851
23926
  if (this.modelProbeOn() && !preloadedModels) void this.probeModels().then((changed) => {
23852
- if (changed) return this.syncWithServer();
23927
+ if (changed) return this.reportNow();
23853
23928
  }).catch((err) => {
23854
23929
  this.log.warn({ err }, "model probe failed");
23855
23930
  });
23856
23931
  return this;
23857
23932
  }
23933
+ /** The local timer and the device session; nothing else talks to the server unasked. */
23934
+ startSession() {
23935
+ this.localTimer = setInterval(() => this.localTick(), LOCAL_CHECK_MS);
23936
+ this.localTimer.unref?.();
23937
+ this.session = new DeviceSession({
23938
+ ticket: (signal) => this.sessionTicket(signal),
23939
+ open: this.options.link.openDeviceGateway?.bind(this.options.link),
23940
+ onOpen: () => this.onSessionOpen(),
23941
+ onClose: (error, opened) => this.onSessionClose(error, opened),
23942
+ onWorkAvailable: () => {
23943
+ this.options.link.invalidateRunControls?.();
23944
+ this.workSignal.notify();
23945
+ },
23946
+ onWork: () => this.sessionPass(),
23947
+ verdict: (error) => this.sessionVerdict(error),
23948
+ random: this.options.random
23949
+ });
23950
+ void this.session.start();
23951
+ }
23952
+ /** Runs `work` after the server work already in flight, never alongside it. */
23953
+ serialized(work) {
23954
+ const run3 = this.syncing.then(work);
23955
+ this.syncing = run3.catch(() => void 0);
23956
+ return run3;
23957
+ }
23858
23958
  /**
23859
- * Long-polls the server for messages and stop requests for this device's
23860
- * runs (ADR 0018). Delivery is at least once: a message is acked after
23861
- * its session took it, so a crash in between hands it over again.
23959
+ * The next socket's ticket: waits for a credential, registers when needed,
23960
+ * then asks the server. This is the only request the session makes while
23961
+ * the socket is down, once per redial.
23862
23962
  */
23863
- async pollCommands() {
23864
- const { link } = this.options;
23865
- const signal = this.commandsAbort.signal;
23866
- const wait = this.options.commandsWaitSeconds ?? COMMANDS_MAX_WAIT_SECONDS;
23867
- let backoff = 1e3;
23868
- while (!this.stopped) {
23869
- const deviceId = this.device.deviceId;
23963
+ async sessionTicket(signal) {
23964
+ while (!this.device.credential) {
23965
+ this.server = "unregistered";
23966
+ await new Promise((resolve19) => {
23967
+ const done = () => {
23968
+ this.credentialArrived.delete(done);
23969
+ signal.removeEventListener("abort", done);
23970
+ resolve19();
23971
+ };
23972
+ this.credentialArrived.add(done);
23973
+ signal.addEventListener("abort", done, { once: true });
23974
+ });
23975
+ if (signal.aborted) throw new DeviceGatewayClosedError();
23976
+ }
23977
+ const credential = this.device.credential;
23978
+ await this.serialized(async () => {
23979
+ if (!this.registered || !this.device.deviceId) await this.register(credential);
23980
+ });
23981
+ if (signal.aborted) throw new DeviceGatewayClosedError();
23982
+ const ticket = await this.options.link.deviceGateway(this.device.deviceId, signal);
23983
+ this.armRotation(ticket.cloudCredentialExpiresAt);
23984
+ return ticket;
23985
+ }
23986
+ onSessionOpen() {
23987
+ this.sessionOpen = true;
23988
+ this.reportOnOpen = true;
23989
+ if (this.blocked === "gateway_required") {
23990
+ this.blocked = null;
23991
+ this.log.info("the server has a device gateway again");
23992
+ }
23993
+ this.supervisor.sessionOpened();
23994
+ this.workSignal.setConnected(true);
23995
+ this.options.link.invalidateRunControls?.();
23996
+ this.log.info({ device_id: this.device.deviceId }, "device session open");
23997
+ }
23998
+ onSessionClose(error, opened) {
23999
+ const wasOpen = this.sessionOpen;
24000
+ this.sessionOpen = false;
24001
+ this.workSignal.setConnected(false);
24002
+ this.supervisor.sessionClosed();
24003
+ if (this.server === "online") this.server = "offline";
24004
+ if (this.stopped || this.blocked === "update_required") return;
24005
+ if (wasOpen || opened) this.log.warn({ err: error }, "device session closed; redialing");
24006
+ else if (!(error instanceof ServerUnreachableError)) this.log.warn({ err: error }, "device session could not open; redialing");
24007
+ }
24008
+ /** What a lost socket means: stop for good, wait the longest, or redial with backoff. */
24009
+ sessionVerdict(error) {
24010
+ if (this.stopped) return "stop";
24011
+ if (error instanceof DaemonUpgradeRequiredError) {
24012
+ this.enterUpdateRequired(error.latest);
24013
+ return "stop";
24014
+ }
24015
+ if (error instanceof DeviceGatewayClosedError && error.code === DEVICE_GATEWAY_UPDATE_REQUIRED_CODE) {
24016
+ this.enterUpdateRequired();
24017
+ return "stop";
24018
+ }
24019
+ if (this.blocked === "update_required") return "stop";
24020
+ if (error instanceof DeviceGatewayRequiredError) {
24021
+ if (this.blocked !== "gateway_required")
24022
+ this.log.error("the server has no device gateway, so this device cannot work with it; retrying every 30 s");
24023
+ this.blocked = "gateway_required";
24024
+ this.server = "offline";
24025
+ return "slow";
24026
+ }
24027
+ if (error instanceof SessionRejectedError) this.rejectDeviceSession(this.device.credential);
24028
+ return "redial";
24029
+ }
24030
+ /**
24031
+ * One pass on open or on a push. A failure the server caused closes the
24032
+ * socket and the redial retries it; a refused session closes it until
24033
+ * someone signs in again.
24034
+ */
24035
+ async sessionPass() {
24036
+ const failure2 = await this.serialized(() => this.syncPass());
24037
+ if (failure2 instanceof ServerUnreachableError || failure2 instanceof SessionRejectedError) throw failure2;
24038
+ }
24039
+ /**
24040
+ * Terminal until the daemon is updated (decision 2026-11-17-2215): a 426
24041
+ * from any route or a gateway close 4001. Stops dialing and claiming; a
24042
+ * managed install updates itself as soon as no run is left.
24043
+ */
24044
+ enterUpdateRequired(latest) {
24045
+ if (this.blocked === "update_required") {
24046
+ if (latest && !this.requiredVersion) void this.findRequiredUpdate(latest);
24047
+ return;
24048
+ }
24049
+ this.blocked = "update_required";
24050
+ this.server = "offline";
24051
+ this.sessionOpen = false;
24052
+ this.workSignal.setConnected(false);
24053
+ this.supervisor?.sessionClosed();
24054
+ this.log.error(
24055
+ { version: DAEMON_VERSION, latest: latest ?? null },
24056
+ "this daemon is too old for the server and stopped connecting; update it (npm install -g @aspectlylabs/mikka@latest, or update Mikka Desktop)"
24057
+ );
24058
+ void this.session?.stop();
24059
+ void this.findRequiredUpdate(latest);
24060
+ }
24061
+ /** A managed install learns the release to install: from the refusal, else from npm (the server no longer answers this daemon). */
24062
+ async findRequiredUpdate(latest) {
24063
+ const runtime = this.options.autoUpdate;
24064
+ if (!runtime) {
24065
+ this.log.error("automatic updates are off for this daemon; update it by hand");
24066
+ return;
24067
+ }
24068
+ const version = latest ?? await runtime.latest?.().catch(() => void 0);
24069
+ if (!newerStableVersion(version, DAEMON_VERSION)) {
24070
+ this.log.error({ latest: version ?? null }, "no newer daemon release is known; update it by hand");
24071
+ return;
24072
+ }
24073
+ this.requiredVersion = version;
24074
+ this.log.warn({ version }, "installing the required daemon update once no run is active");
24075
+ this.learnRelease(version);
24076
+ this.checkAutoUpdate();
24077
+ }
24078
+ /** Local only: nothing here sends a request unless something changed and the session is open. */
24079
+ localTick() {
24080
+ if (this.stopped) return;
24081
+ this.supervisor.check();
24082
+ this.rescanHarnesses();
24083
+ if (this.requiredVersion) this.offerUpdate(this.requiredVersion);
24084
+ this.checkAutoUpdate();
24085
+ const held = this.heldDeviceCommand;
24086
+ if (held && this.sessionOpen && !this.heldCommandPass && (held.kind === "uninstall" ? this.supervisor.activeRunIds().length === 0 : this.maintenanceIdle()))
24087
+ this.heldCommandPass = this.syncWithServer().finally(() => {
24088
+ this.heldCommandPass = null;
24089
+ });
24090
+ const save = this.options.link.checkpointRun?.bind(this.options.link);
24091
+ if (save && this.sessionOpen && this.registered && !this.checkpointScan && Date.now() - this.lastCheckpointScan >= CHECKPOINT_SCAN_MS) {
24092
+ this.lastCheckpointScan = Date.now();
24093
+ this.checkpointScan = this.supervisor.saveCheckpoints(save).catch((err) => {
24094
+ this.log.warn({ err }, "checkpoint save failed");
24095
+ }).finally(() => {
24096
+ this.checkpointScan = null;
24097
+ });
24098
+ }
24099
+ }
24100
+ /**
24101
+ * One timer at the cloud worker's token expiry minus an hour: the next
24102
+ * report asks for the next token. A deadline, not a poll.
24103
+ */
24104
+ armRotation(expiresAt) {
24105
+ if (!expiresAt || !this.options.cloudComputer || this.stopped) return;
24106
+ const at = Date.parse(expiresAt) - CLOUD_CREDENTIAL_ROTATE_BEFORE_MS;
24107
+ if (!Number.isFinite(at)) return;
24108
+ if (this.rotationTimer) clearTimeout(this.rotationTimer);
24109
+ const fire = () => {
24110
+ if (Date.now() < at) {
24111
+ this.rotationTimer = setTimeout(fire, Math.min(at - Date.now(), MAX_TIMER_MS3));
24112
+ this.rotationTimer.unref();
24113
+ return;
24114
+ }
24115
+ this.rotationTimer = null;
24116
+ this.rotationDue = true;
24117
+ void this.reportNow(true);
24118
+ };
24119
+ this.rotationTimer = setTimeout(fire, Math.min(Math.max(0, at - Date.now()), MAX_TIMER_MS3));
24120
+ this.rotationTimer.unref();
24121
+ }
24122
+ /** Sends a report now when something changed (or a rotation is due), between passes. */
24123
+ reportNow(rotation = false) {
24124
+ if (this.stopped || this.blocked === "update_required" || !this.sessionOpen && !rotation) return Promise.resolve();
24125
+ return this.serialized(async () => {
23870
24126
  const credential = this.device.credential;
24127
+ const deviceId = this.device.deviceId;
24128
+ if (!credential || !deviceId || !this.registered) return;
24129
+ const result = await this.sendReport(deviceId, credential);
24130
+ if (result?.deviceCommands?.length && this.sessionOpen) void this.syncWithServer();
24131
+ }).catch((err) => {
24132
+ if (!(err instanceof ServerUnreachableError)) this.log.warn({ err }, "device report failed");
24133
+ });
24134
+ }
24135
+ /** What the report says now; only a change (or a new socket) sends it. */
24136
+ async reportFields() {
24137
+ const quotas = this.quota?.snapshot().quotas;
24138
+ return {
24139
+ completedDeviceCommands: this.device.completedDeviceCommands ?? [],
24140
+ failedDeviceCommands: this.device.failedDeviceCommands ?? [],
24141
+ harnesses: this.harnesses,
24142
+ computerUse: { installed: Boolean(this.localComputerDriver), version: this.localComputerDriver?.version ?? null },
24143
+ runner: await this.runnerReport(),
24144
+ ...this.deviceType ? { deviceType: this.deviceType } : {},
24145
+ worktreeDiskBytes: await this.worktrees.diskUsage(),
24146
+ ...quotas ? { quotas } : {},
24147
+ ...this.options.autoUpdate ? { updateFailure: reportedUpdateFailure(this.updateStateFile, DAEMON_VERSION) } : {}
24148
+ };
24149
+ }
24150
+ /** Sends the report when it changed, after a socket opened, or with a due rotation; applies the answer. */
24151
+ async sendReport(deviceId, credential) {
24152
+ const fields = await this.reportFields();
24153
+ const key2 = JSON.stringify(fields);
24154
+ if (!this.reportOnOpen && !this.rotationDue && key2 === this.lastReport) return void 0;
24155
+ const rotation = this.rotationDue;
24156
+ const result = await this.options.link.report(deviceId, { ...fields, ...rotation ? { rotateCloudCredential: true } : {} });
24157
+ this.lastReport = key2;
24158
+ this.reportOnOpen = false;
24159
+ await this.applyReportResult(result, credential, rotation);
24160
+ return result;
24161
+ }
24162
+ async applyReportResult(result, credential, rotation) {
24163
+ this.learnRelease(result.daemonVersions?.latest);
24164
+ this.checkAutoUpdate();
24165
+ this.holdDeviceCommands(result.deviceCommands ?? []);
24166
+ if (this.options.cloudComputer && result.cloudCredential && this.device.credential === credential) {
24167
+ this.saveDevice({ credential: result.cloudCredential });
24168
+ this.revokeLocalComputerGrants();
24169
+ this.registered = false;
24170
+ this.rotationDue = false;
24171
+ await this.register(result.cloudCredential);
24172
+ } else if (rotation && !result.cloudCredential) {
24173
+ this.log.warn("the server named no next cloud token; asking again on the next session");
24174
+ }
24175
+ this.armRotation(result.cloudCredentialExpiresAt);
24176
+ }
24177
+ /** A device command from the server waits here until the next pass runs it. */
24178
+ holdDeviceCommands(commands) {
24179
+ for (const command of commands) {
24180
+ if (this.device.completedDeviceCommands?.includes(command.id) || this.device.failedDeviceCommands?.some((failure2) => failure2.id === command.id)) continue;
24181
+ if (this.heldDeviceCommand?.id === command.id) continue;
24182
+ this.heldDeviceCommand ??= command;
24183
+ }
24184
+ }
24185
+ /**
24186
+ * Runs the held device command when it can run. Uninstall drains: it waits
24187
+ * for the runs to end (the local timer passes again), confirms its receipt
24188
+ * and stops the daemon. Returns true when the pass should end here.
24189
+ */
24190
+ async runHeldDeviceCommand(deviceId, credential) {
24191
+ const command = this.heldDeviceCommand;
24192
+ if (!command) return false;
24193
+ if (this.device.completedDeviceCommands?.includes(command.id) || this.device.failedDeviceCommands?.some((failure2) => failure2.id === command.id)) {
24194
+ this.heldDeviceCommand = void 0;
24195
+ return false;
24196
+ }
24197
+ if (command.kind === "uninstall") {
24198
+ this.draining = true;
24199
+ if (this.supervisor.activeRunIds().length > 0) return false;
24200
+ this.heldDeviceCommand = void 0;
24201
+ this.saveDevice({ completedDeviceCommands: [command.id], failedDeviceCommands: [] });
23871
24202
  try {
23872
- if (!this.registered || !deviceId) {
23873
- await this.pauseCommands(1e3, signal);
23874
- continue;
23875
- }
23876
- if (this.unacked.size > 0 || this.refusedSteers.size > 0) {
23877
- const ids = [...this.unacked].slice(0, 500);
23878
- const refused2 = [...this.refusedSteers].slice(0, 500);
23879
- if (refused2.length) await link.ackCommands(deviceId, ids, refused2);
23880
- else await link.ackCommands(deviceId, ids);
23881
- for (const id5 of ids) this.unacked.delete(id5);
23882
- for (const id5 of refused2) this.refusedSteers.delete(id5);
23883
- }
23884
- if (await this.holdGateway(deviceId, signal)) {
23885
- backoff = 1e3;
23886
- continue;
23887
- }
23888
- if (this.stopped || signal.aborted) return;
23889
- if (this.draining && this.supervisor.heartbeatRuns().length === 0) return;
23890
- const failedClaims = [...this.queuedClaims].flatMap(([id5, state2]) => state2 === "failed" ? [id5] : []);
23891
- const skipRuns = [...failedClaims, ...this.refusedRuns, ...this.stopping, ...this.ended].slice(
23892
- 0,
23893
- COMMANDS_MAX_SKIP
23894
- );
23895
- const started = performance.now();
23896
- let queued = [];
23897
- let news = false;
23898
- const commands = await link.fetchCommands(deviceId, wait, {
23899
- signal,
23900
- workspaceSkip: [...this.workspaceReads],
23901
- onWorkspaceRequests: (requests) => {
23902
- news = true;
23903
- this.answerWorkspaceRequests(deviceId, requests);
23904
- },
23905
- skipRuns,
23906
- onQueuedRuns: (runIds) => {
23907
- queued = runIds;
23908
- },
23909
- updates: { daemonLatest: this.knownLatest ?? DAEMON_VERSION, skipDeviceCommands: this.polledDeviceCommands },
23910
- onUpdates: ({ daemonVersions, deviceCommands }) => {
23911
- const known = this.knownLatest;
23912
- this.learnRelease(daemonVersions?.latest);
23913
- news ||= this.knownLatest !== known;
23914
- this.checkAutoUpdate();
23915
- const fresh = deviceCommands.filter((command) => !this.polledDeviceCommands.includes(command.id));
23916
- if (fresh.length === 0) return;
23917
- news = true;
23918
- this.polledDeviceCommands = [...this.polledDeviceCommands, ...fresh.map((command) => command.id)].slice(-COMMANDS_MAX_SKIP_DEVICE_COMMANDS);
23919
- void this.syncWithServer().catch(() => void 0);
23920
- }
24203
+ await this.sendReport(deviceId, credential);
24204
+ } catch {
24205
+ this.log.warn("Could not confirm uninstall receipt");
24206
+ }
24207
+ setImmediate(() => {
24208
+ void this.stop().then(() => uninstallService(() => {
24209
+ this.saveDevice({ credential: void 0 });
24210
+ rmSync21(this.paths.secret, { force: true });
24211
+ })).catch(() => {
24212
+ this.options.onDrained?.();
24213
+ });
24214
+ });
24215
+ return true;
24216
+ }
24217
+ if (command.kind !== "redetect" && !this.maintenanceIdle()) return false;
24218
+ this.heldDeviceCommand = void 0;
24219
+ try {
24220
+ if (command.kind === "redetect") {
24221
+ await this.redetectHarnesses();
24222
+ this.saveDevice({ completedDeviceCommands: [command.id], failedDeviceCommands: [] });
24223
+ await this.sendReport(deviceId, credential);
24224
+ } else {
24225
+ this.startMaintenance(async () => {
24226
+ await restartService(command.kind === "update", () => {
24227
+ if (this.stopped) throw new Error("Daemon stopped during update");
24228
+ this.saveDevice({ completedDeviceCommands: [command.id], failedDeviceCommands: [] });
24229
+ }, void 0, () => !this.stopped);
24230
+ }, () => {
24231
+ this.saveDevice({ completedDeviceCommands: [], failedDeviceCommands: [{ id: command.id, error: "Device command failed; check daemon service logs." }] });
24232
+ void this.reportNow();
23921
24233
  });
23922
- if (this.stopped || signal.aborted) return;
23923
- backoff = 1e3;
23924
- const acted = await this.applyCommands(commands);
23925
- if (queued.length > 0) {
23926
- if (this.claimQueued(queued)) continue;
23927
- await this.pauseCommands(500, signal);
23928
- continue;
23929
- }
23930
- if (this.unacked.size > 0 || this.refusedSteers.size > 0) continue;
23931
- if (news) continue;
23932
- if (commands.length === 0 && !signal.aborted) {
23933
- const remaining = Math.max(1e3, wait * 1e3) - (performance.now() - started);
23934
- if (remaining > 0) await this.pauseCommands(remaining, signal);
23935
- }
23936
- if (commands.length > 0 && !acted) await this.pauseCommands(500, signal);
23937
- } catch (error) {
23938
- if (this.stopped || signal.aborted) return;
23939
- if (error instanceof SessionRejectedError) this.rejectDeviceSession(credential);
23940
- if (!(error instanceof ServerUnreachableError))
23941
- this.log.warn({ err: error }, "fetching run commands failed");
23942
- await this.pauseCommands(backoff, signal);
23943
- backoff = Math.min(backoff * 2, 3e4);
23944
24234
  }
24235
+ } catch (err) {
24236
+ if (err instanceof ServerUnreachableError) throw err;
24237
+ this.saveDevice({ completedDeviceCommands: [], failedDeviceCommands: [{ id: command.id, error: "Device command failed; check daemon service logs." }] });
24238
+ this.log.warn({ command_id: command.id, err }, "Device command failed");
23945
24239
  }
24240
+ return false;
23946
24241
  }
23947
24242
  /** One read after a push, or right after the socket opens. Wait is zero: the signal already arrived. */
23948
24243
  async pullSignaledWork(deviceId, signal) {
@@ -23957,14 +24252,11 @@ var Daemon = class {
23957
24252
  onQueuedRuns: (runIds) => {
23958
24253
  queued = runIds;
23959
24254
  },
23960
- updates: { daemonLatest: this.knownLatest ?? DAEMON_VERSION, skipDeviceCommands: this.polledDeviceCommands },
24255
+ updates: { daemonLatest: this.knownLatest ?? DAEMON_VERSION },
23961
24256
  onUpdates: ({ daemonVersions, deviceCommands }) => {
23962
24257
  this.learnRelease(daemonVersions?.latest);
23963
24258
  this.checkAutoUpdate();
23964
- const fresh = deviceCommands.filter((command) => !this.polledDeviceCommands.includes(command.id));
23965
- if (fresh.length === 0) return;
23966
- this.polledDeviceCommands = [...this.polledDeviceCommands, ...fresh.map((command) => command.id)].slice(-COMMANDS_MAX_SKIP_DEVICE_COMMANDS);
23967
- void this.syncWithServer().catch(() => void 0);
24259
+ this.holdDeviceCommands(deviceCommands);
23968
24260
  }
23969
24261
  });
23970
24262
  if (this.stopped || signal.aborted) return;
@@ -23979,138 +24271,11 @@ var Daemon = class {
23979
24271
  for (const id5 of refused2) this.refusedSteers.delete(id5);
23980
24272
  }
23981
24273
  }
23982
- /**
23983
- * Stay on the device's push socket until it drops. Failed and short-lived
23984
- * sessions cool down independently of the responsive long-poll fallback.
23985
- */
23986
- async holdGateway(deviceId, signal) {
23987
- const mint = this.options.link.deviceGateway;
23988
- if (!mint || this.gatewayUnavailable || performance.now() < this.gatewayRetryAt) return false;
23989
- let openedAt;
23990
- let failure2;
23991
- let gatewayOpened;
23992
- let gatewayFailed;
23993
- const connection = new AbortController();
23994
- const abort = () => connection.abort();
23995
- signal.addEventListener("abort", abort, { once: true });
23996
- if (signal.aborted) connection.abort();
23997
- try {
23998
- const ticket = await mint.call(this.options.link, deviceId, connection.signal);
23999
- this.runControlPush = ticket.runControl === "push" || Boolean(this.options.hostedSubscriptions);
24000
- this.options.link.setRunControlMode?.(this.runControlPush ? "fallback" : "legacy");
24001
- this.workSignal.setPushedWaits(["computerReviews", "coordinatorResults"].filter((wait) => ticket[wait] === "push"));
24002
- if (!ticket.url || !ticket.protocol) {
24003
- this.gatewayUnavailable = true;
24004
- return false;
24005
- }
24006
- if (signal.aborted) return false;
24007
- const socket = openDeviceGateway(ticket.url, ticket.protocol);
24008
- void daemonTracer.span("daemon.gateway.connect", { "mikka.gateway.mode": this.runControlPush ? "push" : "legacy" }, () => new Promise((resolve20, reject) => {
24009
- gatewayOpened = resolve20;
24010
- gatewayFailed = reject;
24011
- }), { root: true }).catch(() => void 0);
24012
- await runDeviceGateway(socket, {
24013
- signal: connection.signal,
24014
- onOpen: () => {
24015
- gatewayOpened?.();
24016
- openedAt = performance.now();
24017
- this.gatewayLive = true;
24018
- if (this.runControlPush) this.options.link.setRunControlMode?.("push");
24019
- this.workSignal.setConnected(true);
24020
- },
24021
- onWorkAvailable: () => {
24022
- this.options.link.invalidateRunControls?.();
24023
- this.workSignal.notify();
24024
- },
24025
- onWork: async () => {
24026
- await this.pullSignaledWork(deviceId, connection.signal);
24027
- if (connection.signal.aborted || this.stopped) return;
24028
- await this.syncWithServer();
24029
- if (!connection.signal.aborted && !this.stopped)
24030
- this.schedule(this.gatewayIdle() ? null : this.options.heartbeatMs ?? 15e3);
24031
- }
24032
- });
24033
- } catch (error) {
24034
- failure2 = error;
24035
- if (!this.stopped && !signal.aborted) {
24036
- this.log.warn({ err: error }, "device gateway disconnected; using long-poll fallback");
24037
- if (error instanceof SessionRejectedError) await this.syncWithServer().catch(() => void 0);
24038
- }
24039
- } finally {
24040
- gatewayFailed?.(failure2 ?? new DeviceGatewayClosedError());
24041
- connection.abort();
24042
- signal.removeEventListener("abort", abort);
24043
- this.gatewayLive = false;
24044
- this.options.link.setRunControlMode?.(this.runControlPush ? "fallback" : "legacy");
24045
- this.options.link.invalidateRunControls?.();
24046
- this.workSignal.setConnected(false);
24047
- if (!this.stopped && !signal.aborted && !this.gatewayUnavailable) {
24048
- if (openedAt !== void 0 && performance.now() - openedAt >= 6e4) this.gatewayFailures = 0;
24049
- this.gatewayFailures = Math.min(this.gatewayFailures + 1, 5);
24050
- const ceiling = Math.min(6e4, 5e3 * 2 ** (this.gatewayFailures - 1));
24051
- const delay2 = failure2 instanceof DeviceGatewayClosedError && failure2.code === 4e3 ? 6e4 : ceiling * (0.8 + Math.random() * 0.2);
24052
- this.gatewayRetryAt = performance.now() + delay2;
24053
- if (this.timer === null) this.schedule(this.options.heartbeatMs ?? 15e3);
24054
- }
24055
- }
24056
- return false;
24057
- }
24058
- /**
24059
- * Answers the app's folder requests for the repository picker (ADR 0037):
24060
- * a second long-poll next to the run commands, so a slow folder never
24061
- * delays a stop.
24062
- */
24063
- async pollFolderRequests() {
24064
- const { link } = this.options;
24065
- if (!link.fetchFsRequests || !link.answerFsRequest) return;
24066
- const signal = this.commandsAbort.signal;
24067
- const wait = this.options.commandsWaitSeconds ?? FS_REQUESTS_MAX_WAIT_SECONDS;
24068
- let backoff = 1e3;
24069
- while (!this.stopped) {
24070
- const deviceId = this.device.deviceId;
24071
- const credential = this.device.credential;
24072
- try {
24073
- if (!this.registered || !deviceId) {
24074
- await this.pauseCommands(1e3, signal);
24075
- continue;
24076
- }
24077
- const started = performance.now();
24078
- const requests = await link.fetchFsRequests(
24079
- deviceId,
24080
- wait,
24081
- { signal }
24082
- );
24083
- if (this.stopped || signal.aborted) return;
24084
- backoff = 1e3;
24085
- if (requests.length === 0 && !signal.aborted) {
24086
- const remaining = Math.max(1e3, wait * 1e3) - (performance.now() - started);
24087
- if (remaining > 0) await this.pauseCommands(remaining, signal);
24088
- }
24089
- await Promise.all(
24090
- requests.map(async ({ id: id5, ...request2 }) => {
24091
- const result = await browseFolder(request2).catch(() => ({
24092
- ok: false,
24093
- code: "failed",
24094
- message: "Could not read that folder."
24095
- }));
24096
- await link.answerFsRequest(deviceId, id5, result);
24097
- })
24098
- );
24099
- } catch (error) {
24100
- if (this.stopped || signal.aborted) return;
24101
- if (error instanceof SessionRejectedError) this.rejectDeviceSession(credential);
24102
- if (!(error instanceof ServerUnreachableError))
24103
- this.log.warn({ err: error }, "answering folder requests failed");
24104
- await this.pauseCommands(backoff, signal);
24105
- backoff = Math.min(backoff * 2, 3e4);
24106
- }
24107
- }
24108
- }
24109
24274
  /** Starts claiming the reported queued runs; true when any claim began. */
24110
24275
  claimQueued(runIds) {
24111
24276
  let started = false;
24112
24277
  for (const runId of runIds) {
24113
- if (this.draining || this.updating || this.stopped) break;
24278
+ if (this.draining || this.updating || this.stopped || this.blocked) break;
24114
24279
  if (this.queuedClaims.has(runId) || this.refusedRuns.has(runId) || this.journal.get(runId)) continue;
24115
24280
  this.queuedClaims.set(runId, "claiming");
24116
24281
  started = true;
@@ -24122,27 +24287,16 @@ var Daemon = class {
24122
24287
  (error) => {
24123
24288
  if (this.initialRepositorySync?.runId === runId) this.initialRepositorySync.received?.();
24124
24289
  this.queuedClaims.set(runId, "failed");
24290
+ if (error instanceof DeviceSessionRequiredError) {
24291
+ this.session?.redial();
24292
+ return;
24293
+ }
24125
24294
  this.log.warn({ run_id: runId, err: error }, "could not start run");
24126
24295
  }
24127
24296
  );
24128
24297
  }
24129
24298
  return started;
24130
24299
  }
24131
- /** Waits `ms`, or less if the daemon stops or the device registers. */
24132
- pauseCommands(ms2, signal) {
24133
- if (signal.aborted) return Promise.resolve();
24134
- return new Promise((resolve20) => {
24135
- const done = () => {
24136
- clearTimeout(timer);
24137
- signal.removeEventListener("abort", done);
24138
- this.wakeCommands = null;
24139
- resolve20();
24140
- };
24141
- const timer = setTimeout(done, ms2);
24142
- signal.addEventListener("abort", done, { once: true });
24143
- this.wakeCommands = done;
24144
- });
24145
- }
24146
24300
  /** Hands commands to the runs' sessions; true when any took effect. */
24147
24301
  answerWorkspaceRequests(deviceId, requests) {
24148
24302
  const answer = this.options.link.answerWorkspaceRead;
@@ -24162,7 +24316,7 @@ var Daemon = class {
24162
24316
  }
24163
24317
  return readWorkspaceReceipt(request2, entry);
24164
24318
  });
24165
- void reading.then((receipt) => answer.call(this.options.link, deviceId, request2.id, receipt, { expiresAt: request2.expiresAt, signal: this.commandsAbort.signal })).catch(() => {
24319
+ void reading.then((receipt) => answer.call(this.options.link, deviceId, request2.id, receipt, { expiresAt: request2.expiresAt, signal: this.lifetime.signal })).catch(() => {
24166
24320
  this.log.warn({ request_id: request2.id }, "workspace read delivery failed");
24167
24321
  }).finally(() => this.workspaceReads.delete(request2.id));
24168
24322
  }
@@ -24348,12 +24502,15 @@ var Daemon = class {
24348
24502
  });
24349
24503
  return this.probingModels;
24350
24504
  }
24351
- /** Notice an agent installed after startup without spawning anything per tick. */
24505
+ /**
24506
+ * Notice an agent installed after startup without spawning anything per
24507
+ * tick: the local timer calls this, and only a changed result is reported.
24508
+ */
24352
24509
  rescanHarnesses() {
24353
24510
  const now = Date.now();
24354
24511
  if (this.modelProbeOn() && !this.probingModels && now - this.lastModelProbe >= MODEL_PROBE_MS) {
24355
24512
  void this.probeModels().then((changed) => {
24356
- if (changed) return this.syncWithServer();
24513
+ if (changed) return this.reportNow();
24357
24514
  }).catch((err) => {
24358
24515
  this.log.warn({ err }, "model probe failed");
24359
24516
  });
@@ -24362,7 +24519,7 @@ var Daemon = class {
24362
24519
  this.lastHarnessScan = now;
24363
24520
  if (harnessFingerprint(this.harnessStore()) === this.harnessPrint) return;
24364
24521
  this.rescanning = true;
24365
- void this.redetectHarnesses().then(() => this.syncWithServer()).catch((err) => {
24522
+ void this.redetectHarnesses().then(() => this.reportNow()).catch((err) => {
24366
24523
  this.log.warn({ err }, "harness rescan failed");
24367
24524
  }).finally(() => {
24368
24525
  this.rescanning = false;
@@ -24408,11 +24565,11 @@ var Daemon = class {
24408
24565
  return runVerify(sandbox, {
24409
24566
  command,
24410
24567
  worktree: realpathSync15(worktree),
24411
- tmpRoot: join36(this.paths.adapterState, "verify", runId),
24568
+ tmpRoot: join35(this.paths.adapterState, "verify", runId),
24412
24569
  privateDir: paths.privateDir,
24413
24570
  pidFile: paths.pidFile.replace(/\.pgid$/, ".verify.pgid"),
24414
24571
  networkAllow: repo.networkAllow,
24415
- env: { ...buildChildEnv(), ...githubEnvironment, MIKKA_HANDOFF_FILE: join36(paths.runDir, "handoff.json") },
24572
+ env: { ...buildChildEnv(), ...githubEnvironment, MIKKA_HANDOFF_FILE: join35(paths.runDir, "handoff.json") },
24416
24573
  timeoutMs,
24417
24574
  signal,
24418
24575
  readOnly
@@ -24496,41 +24653,22 @@ var Daemon = class {
24496
24653
  return secret;
24497
24654
  }
24498
24655
  saveDevice(patch) {
24499
- if (patch.completedDeviceCommands || patch.failedDeviceCommands) this.deviceReceiptsVersion++;
24500
24656
  this.device = { ...this.device, ...patch };
24501
24657
  writeJsonAtomic(this.paths.device, this.device);
24502
24658
  }
24503
- /** Idle on the push socket: no runs, nothing waiting to upload. The database can sleep. */
24504
- gatewayIdle() {
24505
- 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;
24506
- }
24507
- schedule(delay2) {
24508
- if (this.stopped) return;
24509
- if (this.timer) clearTimeout(this.timer);
24510
- if (delay2 === null) {
24511
- this.timer = null;
24512
- return;
24513
- }
24514
- this.timer = setTimeout(() => {
24515
- this.supervisor.check();
24516
- this.tick = this.syncWithServer().finally(
24517
- () => this.schedule(this.gatewayIdle() ? null : this.options.heartbeatMs ?? 15e3)
24518
- );
24519
- }, delay2);
24520
- this.timer.unref();
24521
- }
24522
24659
  async register(credential) {
24523
24660
  const { workspaceId, deviceId: knownDeviceId } = this.device;
24661
+ this.deviceType ??= process.env.MIKKA_DEVICE_TYPE === "server" ? "server" : process.env.MIKKA_DEVICE_TYPE === "laptop" ? "laptop" : await detectDeviceType();
24524
24662
  const { deviceId, tracing } = await daemonTracer.span("daemon.registration", {}, async () => this.options.link.registerDevice(
24525
24663
  credential,
24526
24664
  {
24527
24665
  name: hostname2(),
24528
24666
  hostname: hostname2(),
24529
- platform: platform4(),
24667
+ platform: platform3(),
24530
24668
  arch: arch3(),
24531
24669
  daemonVersion: DAEMON_VERSION,
24532
24670
  protocolVersion: DAEMON_PROTOCOL_VERSION,
24533
- deviceType: process.env.MIKKA_DEVICE_TYPE === "server" ? "server" : process.env.MIKKA_DEVICE_TYPE === "laptop" ? "laptop" : await detectDeviceType(),
24671
+ deviceType: this.deviceType,
24534
24672
  harnesses: this.harnesses,
24535
24673
  computerUse: { installed: Boolean(this.localComputerDriver), version: this.localComputerDriver?.version ?? null },
24536
24674
  runner: await this.runnerReport(),
@@ -24559,39 +24697,38 @@ var Daemon = class {
24559
24697
  this.reviewAbort?.abort();
24560
24698
  const abort = new AbortController();
24561
24699
  this.reviewAbort = abort;
24562
- this.reviewLoop = pollWebComputerReviews(computerBroker, deviceId, this.options.link, abort.signal, void 0, this.workSignal);
24700
+ this.reviewLoop = followWebComputerReviews(computerBroker, deviceId, this.options.link, abort.signal, this.workSignal, () => this.session?.redial());
24563
24701
  }
24564
- this.wakeCommands?.();
24565
24702
  }
24566
24703
  /**
24567
- * One pass of the server link loop; safe to call any time. Passes run one
24568
- * after another: overlapping ones would register two devices, or let an
24569
- * older pass's repo list overwrite a newer one.
24704
+ * One pass of the server link; safe to call any time. The session runs one
24705
+ * on every socket open and every push. Passes run one after another:
24706
+ * overlapping ones would register two devices, or let an older pass's repo
24707
+ * list overwrite a newer one.
24570
24708
  */
24571
24709
  syncWithServer() {
24572
- const pass = this.syncing.then(() => this.syncPass());
24573
- this.syncing = pass.catch(() => void 0);
24574
- return pass;
24710
+ return this.serialized(() => this.syncPass()).then(() => void 0);
24575
24711
  }
24712
+ /** Returns what made the pass fail, if anything; the session redials on a server failure. */
24576
24713
  async syncPass() {
24577
- if (this.stopped) return;
24714
+ if (this.stopped || this.blocked === "update_required") return void 0;
24578
24715
  this.checkAutoUpdate();
24579
24716
  const { link } = this.options;
24580
24717
  const { credential, workspaceId } = this.device;
24581
24718
  if (!credential) {
24582
24719
  this.server = "unregistered";
24583
- return;
24720
+ return void 0;
24584
24721
  }
24585
24722
  const initialRunId = this.initialRunHint;
24586
24723
  let resolveRepositories, rejectRepositories;
24587
- const repositoriesReady = initialRunId ? new Promise((resolve20, reject) => {
24588
- resolveRepositories = resolve20;
24724
+ const repositoriesReady = initialRunId ? new Promise((resolve19, reject) => {
24725
+ resolveRepositories = resolve19;
24589
24726
  rejectRepositories = reject;
24590
24727
  }) : void 0;
24591
24728
  if (initialRunId && repositoriesReady) {
24592
24729
  let received;
24593
- const repository2 = this.options.hostedSubscriptions && this.options.e2bContainerRuntime && this.journal.all().length === 0 ? new Promise((resolve20) => {
24594
- received = resolve20;
24730
+ const repository2 = this.options.hostedSubscriptions && this.options.e2bContainerRuntime && this.journal.all().length === 0 ? new Promise((resolve19) => {
24731
+ received = resolve19;
24595
24732
  }) : void 0;
24596
24733
  this.initialRepositorySync = { runId: initialRunId, ready: repositoriesReady, repository: repository2, received };
24597
24734
  void repositoriesReady.catch(() => void 0);
@@ -24605,111 +24742,71 @@ var Daemon = class {
24605
24742
  this.initialRunHint = void 0;
24606
24743
  if (!this.claimQueued([initialRunId])) this.initialRepositorySync?.received?.();
24607
24744
  }
24608
- const quotas = this.quota?.snapshot().quotas;
24609
- const receiptsVersion = this.deviceReceiptsVersion;
24610
- const heartbeat = {
24611
- completedDeviceCommands: this.device.completedDeviceCommands,
24612
- failedDeviceCommands: this.device.failedDeviceCommands,
24613
- harnesses: this.harnesses,
24614
- computerUse: { installed: Boolean(this.localComputerDriver), version: this.localComputerDriver?.version ?? null },
24615
- runner: await this.runnerReport(),
24616
- runs: this.supervisor.heartbeatRuns(),
24617
- worktreeDiskBytes: await this.worktrees.diskUsage(),
24618
- ...quotas ? { quotas } : {},
24619
- ...this.options.autoUpdate ? { updateFailure: reportedUpdateFailure(this.updateStateFile, DAEMON_VERSION) } : {}
24620
- };
24621
- const { leases, revoked, cancelled, cloudCredential, deviceCommands, daemonVersions, taskSecrets } = await link.heartbeat(deviceId, heartbeat);
24622
- this.deviceReceiptsAcknowledged = receiptsVersion;
24623
- this.learnRelease(daemonVersions?.latest);
24624
- this.supervisor.renewLeases(leases);
24625
- if (revoked) this.supervisor.revokeLeases(revoked, cancelled);
24626
- this.supervisor.renewTaskSecrets(taskSecrets);
24627
- if (this.options.cloudComputer && cloudCredential && this.device.credential === credential) {
24628
- this.saveDevice({ credential: cloudCredential });
24629
- this.revokeLocalComputerGrants();
24630
- this.registered = false;
24631
- }
24632
- this.rescanHarnesses();
24633
- const command = deviceCommands?.[0];
24634
- if (command?.kind === "uninstall") {
24635
- this.draining = true;
24636
- if (this.supervisor.heartbeatRuns().length === 0) {
24637
- this.saveDevice({ completedDeviceCommands: [command.id], failedDeviceCommands: [] });
24638
- try {
24639
- await link.heartbeat(deviceId, { ...heartbeat, runs: [], completedDeviceCommands: [command.id], failedDeviceCommands: [] });
24640
- } catch {
24641
- this.log.warn("Could not confirm uninstall receipt");
24642
- }
24643
- setImmediate(() => {
24644
- void this.stop().then(() => uninstallService(() => {
24645
- this.saveDevice({ credential: void 0 });
24646
- rmSync21(this.paths.secret, { force: true });
24647
- })).catch(() => {
24648
- this.options.onDrained?.();
24649
- });
24650
- });
24651
- }
24652
- return;
24653
- }
24654
- if (command && !this.device.completedDeviceCommands?.includes(command.id) && !this.device.failedDeviceCommands?.some((failure2) => failure2.id === command.id)) {
24655
- if (command.kind === "redetect" || this.maintenanceIdle()) {
24656
- try {
24657
- if (command.kind === "redetect") {
24658
- await this.redetectHarnesses();
24659
- this.saveDevice({ completedDeviceCommands: [command.id], failedDeviceCommands: [] });
24660
- void this.syncWithServer().catch(() => void 0);
24661
- } else {
24662
- this.startMaintenance(async () => {
24663
- await restartService(command.kind === "update", () => {
24664
- if (this.stopped) throw new Error("Daemon stopped during update");
24665
- this.saveDevice({ completedDeviceCommands: [command.id], failedDeviceCommands: [] });
24666
- }, void 0, () => !this.stopped);
24667
- }, () => {
24668
- this.saveDevice({ completedDeviceCommands: [], failedDeviceCommands: [{ id: command.id, error: "Device command failed; check daemon service logs." }] });
24669
- });
24670
- }
24671
- } catch (err) {
24672
- this.saveDevice({ completedDeviceCommands: [], failedDeviceCommands: [{ id: command.id, error: "Device command failed; check daemon service logs." }] });
24673
- this.log.warn({ command_id: command.id, err }, "Device command failed");
24674
- }
24675
- }
24676
- }
24677
- const checkpointRun = link.checkpointRun?.bind(link);
24678
- if (checkpointRun) await this.supervisor.saveCheckpoints(checkpointRun);
24745
+ await this.sendReport(deviceId, credential);
24746
+ if (await this.runHeldDeviceCommand(deviceId, credential)) return void 0;
24747
+ await this.pullSignaledWork(deviceId, this.lifetime.signal);
24748
+ if (await this.runHeldDeviceCommand(deviceId, credential)) return void 0;
24679
24749
  const initialRepository = await this.initialRepositorySync?.repository;
24680
24750
  this.saveDevice({ repos: initialRepository ? [initialRepository] : await link.listRepos(deviceId) });
24681
24751
  resolveRepositories?.();
24682
24752
  this.server = "online";
24683
24753
  await this.outbox.flushAll();
24684
24754
  for (const entry of this.journal.all()) if (isTerminalRunState(entry.state)) void this.captureUploader.flush(entry.assignment.runId, true);
24685
- if (!this.draining && !this.updating && !this.stopped) {
24755
+ if (!this.draining && !this.updating && !this.stopped && !this.blocked) {
24686
24756
  await this.supervisor.resumeAll(true);
24687
24757
  for (const [runId, state2] of this.queuedClaims) if (state2 === "failed") this.queuedClaims.delete(runId);
24688
24758
  for (const runId of await link.pendingRuns(deviceId)) {
24689
24759
  if (this.refusedRuns.has(runId) || this.queuedClaims.has(runId)) continue;
24690
- await this.claimAndStart(runId).catch(
24691
- (error) => this.log.warn({ run_id: runId, err: error }, "could not start run")
24692
- );
24760
+ await this.claimAndStart(runId).catch((error) => {
24761
+ if (error instanceof DeviceSessionRequiredError || error instanceof DaemonUpgradeRequiredError) throw error;
24762
+ this.log.warn({ run_id: runId, err: error }, "could not start run");
24763
+ });
24693
24764
  }
24694
24765
  }
24695
24766
  await this.pruneWorktrees();
24696
24767
  await this.sweepEmptyRuns();
24768
+ return void 0;
24697
24769
  } catch (error) {
24698
24770
  rejectRepositories?.(error);
24699
- if (this.device.credential !== credential || this.device.workspaceId !== workspaceId) return;
24771
+ if (this.device.credential !== credential || this.device.workspaceId !== workspaceId) return void 0;
24700
24772
  this.server = "offline";
24701
- if (error instanceof SessionRejectedError) {
24773
+ if (error instanceof DaemonUpgradeRequiredError) {
24774
+ this.enterUpdateRequired(error.latest);
24775
+ } else if (error instanceof SessionRejectedError) {
24776
+ if (await this.collectUninstall(credential)) return void 0;
24702
24777
  this.rejectDeviceSession(credential);
24703
24778
  } else if (!(error instanceof ServerUnreachableError)) {
24704
24779
  this.log.error({ err: error }, "server sync failed");
24705
24780
  }
24781
+ return error;
24706
24782
  } finally {
24707
24783
  rejectRepositories?.(new ServerUnreachableError("Initial repository sync unavailable"));
24708
24784
  if (this.initialRepositorySync?.ready === repositoriesReady) this.initialRepositorySync = void 0;
24709
24785
  }
24710
24786
  }
24711
- /** A refused credential stops its local work as well as future polling.
24712
- * The supervisor cancels immediately and applies its bounded CLI kill grace. */
24787
+ /**
24788
+ * A removed device's credential reaches only its report, which carries its
24789
+ * uninstall (decision 2026-11-17-2215). A push can arrive with nothing
24790
+ * changed to report, so before giving the session up, ask the report once.
24791
+ * True when an uninstall is now held: it runs here or, while runs drain,
24792
+ * from the local timer.
24793
+ */
24794
+ async collectUninstall(credential) {
24795
+ const deviceId = this.device.deviceId;
24796
+ if (!deviceId || this.device.credential !== credential) return false;
24797
+ try {
24798
+ this.reportOnOpen = true;
24799
+ await this.sendReport(deviceId, credential);
24800
+ } catch {
24801
+ return false;
24802
+ }
24803
+ if (this.heldDeviceCommand?.kind !== "uninstall") return false;
24804
+ await this.runHeldDeviceCommand(deviceId, credential);
24805
+ return true;
24806
+ }
24807
+ /** A refused credential stops its local work as well as the session until
24808
+ * someone signs in again. The supervisor cancels immediately and applies
24809
+ * its bounded CLI kill grace. */
24713
24810
  rejectDeviceSession(credential) {
24714
24811
  if (!credential || this.device.credential !== credential) return;
24715
24812
  this.server = "unregistered";
@@ -24727,25 +24824,18 @@ var Daemon = class {
24727
24824
  if (this.draining || this.updating || this.stopped) {
24728
24825
  throw new DaemonError(DAEMON_RPC_ERRORS.draining, "Daemon is draining");
24729
24826
  }
24827
+ if (this.blocked === "update_required") throw new DaemonUpgradeRequiredError(this.requiredVersion);
24828
+ if (this.blocked === "gateway_required") throw new DeviceGatewayRequiredError();
24730
24829
  const existing = this.claims.get(runId);
24731
24830
  if (existing) return await existing;
24732
24831
  this.claimsInFlight++;
24733
24832
  const claim = this.claimAndStartInternal(runId);
24734
24833
  this.claims.set(runId, claim);
24735
- let upgradeRequired = false;
24736
24834
  try {
24737
24835
  return await claim;
24738
- } catch (error) {
24739
- if (error instanceof RunNotPinnedHereError && error.upgradeRequired) {
24740
- this.log.warn({ run_id: runId }, "server requires a newer daemon; updating when idle");
24741
- this.learnRelease(error.latest);
24742
- upgradeRequired = true;
24743
- }
24744
- throw error;
24745
24836
  } finally {
24746
24837
  this.claims.delete(runId);
24747
24838
  this.claimsInFlight--;
24748
- if (upgradeRequired) this.checkAutoUpdate();
24749
24839
  }
24750
24840
  }
24751
24841
  async claimAndStartInternal(runId) {
@@ -24764,7 +24854,7 @@ var Daemon = class {
24764
24854
  let assignment;
24765
24855
  try {
24766
24856
  assignment = await daemonTracer.span("daemon.run.lease", { "mikka.run.id_hash": runIdHash(runId) }, async (span) => {
24767
- const claimed = await this.options.link.claimRun(deviceId, runId, this.commandsAbort.signal, initialSync?.received ? { initialRepository: true } : void 0);
24857
+ const claimed = await this.options.link.claimRun(deviceId, runId, this.lifetime.signal, initialSync?.received ? { initialRepository: true } : void 0);
24768
24858
  span.set("mikka.harness", claimed.harness);
24769
24859
  return claimed;
24770
24860
  }, { root: true });
@@ -24904,8 +24994,20 @@ var Daemon = class {
24904
24994
  });
24905
24995
  await this.worktrees.prune(finished, retentionMs);
24906
24996
  }
24997
+ /** The device session as `daemon status` shows it. */
24998
+ sessionState() {
24999
+ if (this.blocked) return this.blocked;
25000
+ if (!this.device.credential) return "signed_out";
25001
+ return this.sessionOpen ? "open" : "connecting";
25002
+ }
25003
+ /**
25004
+ * `session` is outside `daemonStatusSchema`, whose `server` has no state for
25005
+ * "update required" yet; a client that parses with the schema drops it.
25006
+ */
24907
25007
  status() {
24908
25008
  return {
25009
+ session: this.sessionState(),
25010
+ requiredVersion: this.requiredVersion ?? null,
24909
25011
  daemonVersion: DAEMON_VERSION,
24910
25012
  protocolVersion: DAEMON_PROTOCOL_VERSION,
24911
25013
  pid: process.pid,
@@ -24945,7 +25047,8 @@ var Daemon = class {
24945
25047
  this.revokeLocalComputerGrants();
24946
25048
  this.registered = false;
24947
25049
  this.registrationTraceContext = traceContext;
24948
- void daemonTracer.withContext(traceContext, () => this.syncWithServer());
25050
+ for (const arrived of [...this.credentialArrived]) arrived();
25051
+ this.session?.redial(true);
24949
25052
  return { ok: true };
24950
25053
  },
24951
25054
  "device.clearCredential": () => {
@@ -24955,6 +25058,7 @@ var Daemon = class {
24955
25058
  this.revokeLocalComputerGrants();
24956
25059
  this.registered = false;
24957
25060
  this.server = "unregistered";
25061
+ this.session?.redial(true);
24958
25062
  return { ok: true };
24959
25063
  },
24960
25064
  "runs.start": (raw) => {
@@ -25005,7 +25109,7 @@ var Daemon = class {
25005
25109
  }
25006
25110
  /** Graceful stop: active runs stay journaled and resume on next start. */
25007
25111
  maintenanceIdle() {
25008
- return !this.stopped && !this.draining && !this.updating && this.claimsInFlight === 0 && this.supervisor.heartbeatRuns().length === 0;
25112
+ return !this.stopped && !this.draining && !this.updating && this.claimsInFlight === 0 && this.supervisor.activeRunIds().length === 0;
25009
25113
  }
25010
25114
  startMaintenance(work, failed = () => {
25011
25115
  }) {
@@ -25020,9 +25124,9 @@ var Daemon = class {
25020
25124
  });
25021
25125
  }
25022
25126
  get updateStateFile() {
25023
- return join36(this.paths.dataDir, "auto-update.json");
25127
+ return join35(this.paths.dataDir, "auto-update.json");
25024
25128
  }
25025
- /** A server named this release (heartbeat, commands poll or refused claim); older servers name none. */
25129
+ /** A server named this release (a report answer, a commands read, a 426), or npm did for a refused daemon. */
25026
25130
  learnRelease(latest) {
25027
25131
  if (newerStableVersion(latest, this.knownLatest ?? DAEMON_VERSION)) this.knownLatest = latest;
25028
25132
  this.offerUpdate(latest);
@@ -25032,7 +25136,7 @@ var Daemon = class {
25032
25136
  if (!this.options.autoUpdate || this.updating || this.updateVersion || !newerStableVersion(latest, DAEMON_VERSION)) return;
25033
25137
  if (updateAllowed(this.updateStateFile, latest)) this.updateVersion = latest;
25034
25138
  }
25035
- /** Installs the release a server named once no run or claim is active; called again by every heartbeat. */
25139
+ /** Installs the named release once no run or claim is active; the local timer calls it again. */
25036
25140
  checkAutoUpdate() {
25037
25141
  const runtime = this.options.autoUpdate;
25038
25142
  if (!runtime || this.draining || this.updating || !this.updateVersion || !this.maintenanceIdle()) return;
@@ -25048,15 +25152,19 @@ var Daemon = class {
25048
25152
  }, void 0, () => !this.stopped);
25049
25153
  }, () => {
25050
25154
  recordUpdateFailure(this.updateStateFile, version, code);
25155
+ void this.reportNow();
25051
25156
  });
25052
25157
  }
25053
25158
  /**
25054
- * `daemon.update`: ask the server now (one heartbeat, which names its release)
25055
- * instead of waiting for the next one; never npm. The install still waits for idle.
25159
+ * `daemon.update`: ask the server now (one pass, whose commands read names
25160
+ * its release) instead of waiting for a push. A daemon the server refused
25161
+ * asks npm instead. The install still waits for idle.
25056
25162
  */
25057
25163
  async requestUpdate() {
25058
25164
  if (!this.options.autoUpdate) return "unmanaged";
25059
- if (!this.updating && !this.updateVersion) await this.syncWithServer().catch(() => void 0);
25165
+ if (this.blocked === "update_required") {
25166
+ if (!this.updating && !this.updateVersion) await this.findRequiredUpdate(this.requiredVersion);
25167
+ } else if (!this.updating && !this.updateVersion && this.sessionOpen) await this.syncWithServer().catch(() => void 0);
25060
25168
  this.checkAutoUpdate();
25061
25169
  return this.updating ? "installing" : this.updateVersion ? "waiting" : "current";
25062
25170
  }
@@ -25069,14 +25177,16 @@ var Daemon = class {
25069
25177
  this.localComputerBroker?.suspend();
25070
25178
  await this.starting?.catch(() => void 0);
25071
25179
  await this.maintenance;
25072
- if (this.timer) clearTimeout(this.timer);
25180
+ if (this.localTimer) clearInterval(this.localTimer);
25181
+ if (this.rotationTimer) clearTimeout(this.rotationTimer);
25073
25182
  await this.quota?.stop();
25074
- this.commandsAbort.abort();
25183
+ this.lifetime.abort();
25184
+ for (const arrived of [...this.credentialArrived]) arrived();
25185
+ await this.session?.stop();
25075
25186
  this.reviewAbort?.abort();
25076
25187
  await this.reviewLoop.catch(() => void 0);
25077
- await this.commandsLoop.catch(() => void 0);
25078
- await this.fsLoop.catch(() => void 0);
25079
- await this.tick;
25188
+ await this.syncing;
25189
+ await this.checkpointScan;
25080
25190
  await Promise.allSettled(this.claims.values());
25081
25191
  await this.rpc?.close();
25082
25192
  try {
@@ -25119,7 +25229,7 @@ function isNoDaemon(error) {
25119
25229
  }
25120
25230
  async function connectDaemon(options) {
25121
25231
  const socket = connect(options.socketPath);
25122
- await new Promise((resolve20, reject) => {
25232
+ await new Promise((resolve19, reject) => {
25123
25233
  const timer = setTimeout(() => {
25124
25234
  socket.destroy();
25125
25235
  reject(
@@ -25130,7 +25240,7 @@ async function connectDaemon(options) {
25130
25240
  }, options.timeoutMs ?? 3e3);
25131
25241
  socket.once("connect", () => {
25132
25242
  clearTimeout(timer);
25133
- resolve20();
25243
+ resolve19();
25134
25244
  });
25135
25245
  socket.once("error", (error) => {
25136
25246
  clearTimeout(timer);
@@ -25167,9 +25277,9 @@ async function connectDaemon(options) {
25167
25277
  if (isProtocolMismatch(error) && options.drainOnMismatch) {
25168
25278
  await Promise.race([
25169
25279
  connection.sendRequest("daemon.drain", {}).catch(() => void 0),
25170
- new Promise((resolve20) => {
25171
- connection.onClose(resolve20);
25172
- setTimeout(resolve20, 2e3).unref();
25280
+ new Promise((resolve19) => {
25281
+ connection.onClose(resolve19);
25282
+ setTimeout(resolve19, 2e3).unref();
25173
25283
  })
25174
25284
  ]);
25175
25285
  }
@@ -25228,8 +25338,8 @@ async function connectStartingDaemon(dataDir) {
25228
25338
  }
25229
25339
  if (!daemonProcessAlive(dataDir)) return void 0;
25230
25340
  if (revision2 !== before) continue;
25231
- await new Promise((resolve20) => {
25232
- wake = resolve20;
25341
+ await new Promise((resolve19) => {
25342
+ wake = resolve19;
25233
25343
  });
25234
25344
  wake = void 0;
25235
25345
  }