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