@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/main.js CHANGED
@@ -2653,8 +2653,8 @@ import {
2653
2653
  rmSync as rmSync21,
2654
2654
  realpathSync as realpathSync15
2655
2655
  } from "node:fs";
2656
- import { arch as arch2, hostname, platform as platform3 } from "node:os";
2657
- import { join as join36 } from "node:path";
2656
+ import { arch as arch2, hostname, platform as platform2 } from "node:os";
2657
+ import { join as join35 } from "node:path";
2658
2658
  import { fileURLToPath as fileURLToPath2 } from "node:url";
2659
2659
 
2660
2660
  // ../protocol/src/accounts.ts
@@ -3937,6 +3937,15 @@ var daemonStatusSchema = z15.object({
3937
3937
  /** Holds a device credential (it may still be refused by the server). */
3938
3938
  signedIn: z15.boolean(),
3939
3939
  server: z15.enum(["online", "offline", "unregistered"]),
3940
+ /**
3941
+ * The device session (decision 2026-11-17-2215). `update_required`: the
3942
+ * server refused this daemon version; it does nothing until it is updated.
3943
+ * `gateway_required`: the server has no device gateway, so it has no devices.
3944
+ * Absent from older daemons.
3945
+ */
3946
+ session: z15.enum(["signed_out", "connecting", "open", "update_required", "gateway_required"]).optional(),
3947
+ /** With `update_required`: the oldest version the server accepts, if it said. */
3948
+ requiredVersion: z15.string().max(40).nullable().optional(),
3940
3949
  harnesses: z15.array(harnessInfoSchema),
3941
3950
  runs: z15.array(runSummarySchema),
3942
3951
  /** Bytes used by run worktrees under the daemon's data dir. */
@@ -5046,7 +5055,6 @@ var runDecisionCatalogueSchema = z24.object({
5046
5055
  (value) => new TextEncoder().encode(JSON.stringify(value)).length <= 32768,
5047
5056
  { message: "Prepared decision catalogue is bounded" }
5048
5057
  );
5049
- var RUN_LEASE_MS = 9e4;
5050
5058
  var deviceComputerCapability = z24.object({ installed: z24.boolean(), version: z24.string().max(100).nullable() }).strict();
5051
5059
  var deviceRunnerCapability = z24.object({
5052
5060
  os: z24.string().max(50),
@@ -5091,69 +5099,49 @@ var deviceRegistered = z24.object({
5091
5099
  environment: z24.enum(["production", "preview", "dev"]).optional()
5092
5100
  }).optional().catch(void 0)
5093
5101
  });
5094
- var heartbeatRunSchema = z24.object({
5095
- runId: id3,
5096
- /** Last tool call, turn boundary or file change (not raw output). */
5097
- lastProgressAt: isoTime,
5098
- /** Opaque third-party capabilities, refreshed only with the existing run lease. */
5099
- secretCapabilities: taskSecretRenewalSchema.optional()
5100
- });
5102
+ var DEVICE_SESSION_HEADER = "x-mikka-device-session";
5103
+ var DEVICE_SESSION_VERSION = 1;
5104
+ var DEVICE_SESSION_LOCAL_GRACE_MS = 6e4;
5105
+ var SESSION_LEASE_MS = 7 * 24 * 60 * 60 * 1e3;
5106
+ var deviceSessionReportSchema = z24.object({
5107
+ state: z24.enum(["connected", "disconnected"]),
5108
+ /** When the socket opened, or closed (or last answered a ping). */
5109
+ at: isoTime,
5110
+ /** One value per socket; a report for an older socket never overrides a newer one. */
5111
+ socketId: z24.string().regex(/^[A-Za-z0-9_-]{8,64}$/)
5112
+ }).strict();
5101
5113
  var stableVersion = z24.string().regex(/^(0|[1-9]\d{0,8})\.(0|[1-9]\d{0,8})\.(0|[1-9]\d{0,8})$/);
5102
5114
  var daemonVersionsSchema = z24.object({ min: stableVersion, latest: stableVersion.optional() });
5103
5115
  var daemonUpdateFailureSchema = z24.object({ version: stableVersion, code: z24.enum(["install_failed", "restart_failed"]), at: isoTime });
5104
5116
  var deviceManagementCommand = z24.object({ id: z24.uuid(), kind: z24.enum(["redetect", "restart", "update", "uninstall"]) });
5105
- var deviceHeartbeatSchema = z24.object({
5117
+ var deviceReportSchema = z24.object({
5106
5118
  completedDeviceCommands: z24.array(z24.uuid()).max(100).optional(),
5107
5119
  failedDeviceCommands: z24.array(z24.object({ id: z24.uuid(), error: z24.string().max(500) })).max(100).optional(),
5108
- harnesses: z24.array(harnessInfoSchema).max(20),
5120
+ harnesses: z24.array(harnessInfoSchema).max(20).optional(),
5109
5121
  computerUse: deviceComputerCapability.optional(),
5110
5122
  runner: deviceRunnerCapability.optional(),
5111
5123
  deviceType: z24.enum(["laptop", "server"]).optional(),
5112
- runs: z24.array(heartbeatRunSchema).max(500),
5113
- worktreeDiskBytes: z24.number().int().nonnegative(),
5114
- /**
5115
- * Subscription windows read on this device. Absent when the daemon is not
5116
- * polling. Numbers only, never a vendor credential (ADR 0027).
5117
- */
5124
+ worktreeDiskBytes: z24.number().int().nonnegative().optional(),
5125
+ /** Subscription windows read on this device. Numbers only, never a vendor credential (ADR 0027). */
5118
5126
  quotas: z24.array(quotaSnapshotSchema).max(6).optional(),
5119
5127
  /** Null once no automatic update has failed since the last success. */
5120
- updateFailure: daemonUpdateFailureSchema.nullable().optional()
5128
+ updateFailure: daemonUpdateFailureSchema.nullable().optional(),
5129
+ /** A cloud worker asks for its next token once, an hour before the current one expires. */
5130
+ rotateCloudCredential: z24.literal(true).optional()
5121
5131
  });
5122
- var heartbeatResultSchema = z24.object({
5132
+ var deviceReportResultSchema = z24.object({
5123
5133
  deviceCommands: z24.array(deviceManagementCommand).max(1).optional(),
5124
- /** Renewed lease expiry per run id; a run missing here is not renewed. */
5125
- leases: z24.record(z24.string(), isoTime),
5126
- /** No plaintext: only grants for current owner/device/run/claim bindings. */
5127
- taskSecrets: z24.record(z24.string(), taskSecretAccessSchema).optional(),
5128
- /**
5129
- * Runs the device reported that it no longer holds: they ended on the
5130
- * server, or went to another attempt after the lease ran out. The daemon
5131
- * stops them now instead of when their lease runs out.
5132
- */
5133
- revoked: z24.array(id3).max(500).optional(),
5134
- /** Subset of revoked caused by an explicit cancel on an otherwise current claim. */
5135
- cancelled: z24.array(id3).max(500).optional(),
5136
5134
  /** Short-lived cloud device token, returned only over its authenticated link. */
5137
5135
  cloudCredential: z24.string().regex(/^orv_[A-Za-z0-9_-]{43}$/).optional(),
5138
- /** A malformed value is dropped, never a failed heartbeat. */
5136
+ cloudCredentialExpiresAt: isoTime.optional(),
5137
+ /** A malformed value is dropped, never a failed report. */
5139
5138
  daemonVersions: daemonVersionsSchema.optional().catch(void 0)
5140
5139
  });
5141
5140
  var deviceGatewaySchema = z24.object({
5142
- url: z24.string().url().nullable(),
5143
- protocol: z24.string().regex(/^mikka-ticket-[0-9]+-[a-f0-9]{64}$/).nullable(),
5144
- /** This server wakes the device after every write that can end, pause or
5145
- * revoke one of its runs (stop, lease, credential, policy, membership), so a
5146
- * connected daemon needs no periodic run-control check (#1212). Absent from
5147
- * older servers: the daemon then keeps its one-second check. */
5148
- runControl: z24.literal("push").optional(),
5149
- /** This server wakes the device when a person decides a computer review in
5150
- * the web, so a connected daemon syncs pending reviews only on a change or a
5151
- * push, plus a presence refresh (#1212). Absent from older servers: the
5152
- * daemon then keeps syncing every second while a review is pending. */
5153
- computerReviews: z24.literal("push").optional(),
5154
- /** This server wakes the device when it writes a native Coordinator tool
5155
- * result, so the waiting tool asks once per push, not every 500 ms. */
5156
- coordinatorResults: z24.literal("push").optional()
5141
+ url: z24.string().url(),
5142
+ protocol: z24.string().regex(/^mikka-ticket-[0-9]+-[a-f0-9]{64}$/),
5143
+ /** Cloud workers only: when the current device token expires. */
5144
+ cloudCredentialExpiresAt: isoTime.optional()
5157
5145
  });
5158
5146
  var RUN_CHECKPOINT_MAX_BYTES = 8 * 1024 * 1024;
5159
5147
  var RUN_CHECKPOINT_RECOVERY_MAX_AGE_MS = 30 * 6e4;
@@ -5306,7 +5294,7 @@ var runAssignmentSchema = z24.object({
5306
5294
  /** Host-owned Factory check mode; the model cannot grant a check or skip verification. */
5307
5295
  factoryCheck: z24.object({ stage: z24.enum(["review", "verify"]), inferCommand: z24.boolean(), reportOnly: z24.boolean() }).strict().optional(),
5308
5296
  factoryExecuteKind: z24.enum(["repository", "report", "deliverable"]).optional(),
5309
- /** Run lease; renewed through the device heartbeat. */
5297
+ /** Run lease in the database: it lasts as long as the device session that claimed the run. */
5310
5298
  leaseExpiresAt: isoTime.optional(),
5311
5299
  /**
5312
5300
  * The Mikka MCP server for the agent inside this run: `report`, `ask` and
@@ -5441,9 +5429,7 @@ var runEventsAccepted = z24.object({
5441
5429
  /** Producer seq of the last chunk the server holds for this run. */
5442
5430
  offset: z24.string()
5443
5431
  });
5444
- var COMMANDS_MAX_WAIT_SECONDS = 25;
5445
5432
  var COMMANDS_MAX_SKIP = 100;
5446
- var COMMANDS_MAX_SKIP_DEVICE_COMMANDS = 10;
5447
5433
  var runCommandSchema = z24.discriminatedUnion("kind", [
5448
5434
  z24.object({
5449
5435
  kind: z24.literal("input"),
@@ -5462,21 +5448,19 @@ var runCommandsResponse = z24.object({
5462
5448
  /** Owner-scoped reads, delivered only to a daemon advertising protocol v1. */
5463
5449
  workspaceRequests: z24.array(workspaceReadCommand).max(4).optional(),
5464
5450
  /**
5465
- * Runs queued for this device (outside `skip`), so it claims them now
5466
- * instead of on its next heartbeat. A queued run also ends the long-poll.
5467
- * Absent from older servers; the heartbeat still claims either way.
5451
+ * Runs queued for this device (outside `skip`), so it claims them as soon
5452
+ * as the gateway signals work.
5468
5453
  */
5469
5454
  queuedRuns: z24.array(id3).max(100).optional(),
5470
5455
  /** Only for a daemon that sent `COMMANDS_DAEMON_LATEST_PARAM`; a malformed value is dropped. */
5471
5456
  daemonVersions: daemonVersionsSchema.optional().catch(void 0),
5472
- /** The oldest pending device command (as the heartbeat's), so a person's update reaches the device now. */
5457
+ /** The oldest pending device command, so a person's update reaches the device now. */
5473
5458
  deviceCommands: z24.array(deviceManagementCommand).max(1).optional().catch(void 0)
5474
5459
  });
5475
5460
  var runCommandsAck = z24.object({
5476
5461
  delivered: z24.array(z24.uuid()).max(500),
5477
5462
  refusedSteers: z24.array(z24.uuid()).max(500).optional()
5478
5463
  });
5479
- var FS_REQUESTS_MAX_WAIT_SECONDS = 25;
5480
5464
  var FS_MAX_ENTRIES = 500;
5481
5465
  var fsBrowseRequest = z24.object({
5482
5466
  /** Absolute path on the device; omitted: the device's home folder. */
@@ -6075,7 +6059,7 @@ import { join } from "node:path";
6075
6059
  // package.json
6076
6060
  var package_default = {
6077
6061
  name: "@mikka/daemon",
6078
- version: "0.0.702",
6062
+ version: "0.0.703",
6079
6063
  description: "Local Mikka daemon: runs agents through the user's own CLIs",
6080
6064
  type: "module",
6081
6065
  private: true,
@@ -6143,7 +6127,7 @@ var package_default = {
6143
6127
  engines: {
6144
6128
  node: ">=22"
6145
6129
  },
6146
- gitHead: "510757b2cbb43beaadeb284abcc4f36a262ea371"
6130
+ gitHead: "ccd7e6c6680b8485bbba714bc029b5d35db3bd13"
6147
6131
  };
6148
6132
 
6149
6133
  // src/paths.ts
@@ -6151,12 +6135,12 @@ var DAEMON_VERSION = package_default.version;
6151
6135
  function productName(flavor) {
6152
6136
  return flavor === "dev" ? "Mikka Dev" : "Mikka";
6153
6137
  }
6154
- function defaultDataDir(flavor, env = process.env, platform4 = process.platform) {
6138
+ function defaultDataDir(flavor, env = process.env, platform3 = process.platform) {
6155
6139
  if (flavor === "dev" && env.MIKKA_USER_DATA_DIR) {
6156
6140
  return env.MIKKA_USER_DATA_DIR;
6157
6141
  }
6158
6142
  const home = env.HOME || homedir();
6159
- const base = platform4 === "darwin" ? join(home, "Library", "Application Support") : platform4 === "win32" ? env.APPDATA || join(home, "AppData", "Roaming") : env.XDG_CONFIG_HOME || join(home, ".config");
6143
+ const base = platform3 === "darwin" ? join(home, "Library", "Application Support") : platform3 === "win32" ? env.APPDATA || join(home, "AppData", "Roaming") : env.XDG_CONFIG_HOME || join(home, ".config");
6160
6144
  const dir = join(base, productName(flavor));
6161
6145
  const legacy = join(base, legacyProductName(flavor));
6162
6146
  return !existsSync(dir) && existsSync(legacy) ? legacy : dir;
@@ -7120,8 +7104,8 @@ var DaemonTracer = class {
7120
7104
  let timer;
7121
7105
  await Promise.race([
7122
7106
  work,
7123
- new Promise((resolve20) => {
7124
- timer = setTimeout(resolve20, timeoutMs);
7107
+ new Promise((resolve19) => {
7108
+ timer = setTimeout(resolve19, timeoutMs);
7125
7109
  timer.unref();
7126
7110
  })
7127
7111
  ]).finally(() => {
@@ -7302,14 +7286,14 @@ import { realpathSync } from "node:fs";
7302
7286
  function prepareAgentStart(signal, open5, diagnostics) {
7303
7287
  const lifetime = new AbortController();
7304
7288
  let accept, refuse2;
7305
- const finalOptions = new Promise((resolve20, reject) => {
7306
- accept = resolve20;
7289
+ const finalOptions = new Promise((resolve19, reject) => {
7290
+ accept = resolve19;
7307
7291
  refuse2 = reject;
7308
7292
  });
7309
7293
  void finalOptions.catch(() => void 0);
7310
7294
  let parked, failed;
7311
- const ready = new Promise((resolve20, reject) => {
7312
- parked = resolve20;
7295
+ const ready = new Promise((resolve19, reject) => {
7296
+ parked = resolve19;
7313
7297
  failed = reject;
7314
7298
  });
7315
7299
  void ready.catch(() => void 0);
@@ -7392,8 +7376,8 @@ var ClaimedPromptQueue = class {
7392
7376
  while (!this.closed) {
7393
7377
  const item = this.items.shift();
7394
7378
  if (item) yield item;
7395
- else await new Promise((resolve20) => {
7396
- this.wake = resolve20;
7379
+ else await new Promise((resolve19) => {
7380
+ this.wake = resolve19;
7397
7381
  });
7398
7382
  }
7399
7383
  }
@@ -7761,7 +7745,7 @@ var RunRuntimeTimings = class {
7761
7745
  if (!observation2 || observation2.deviceHash !== runIdHash(decodeURIComponent(github[1]))) return NOOP2;
7762
7746
  return observation2.request(this.refresh.getStore() === hash3 ? "github_credential_refresh" : "github_credential_lease", verb, false);
7763
7747
  }
7764
- const device = /^\/v1\/devices\/([^/]+)\/(heartbeat|gateway|commands|runs)$/.exec(clean);
7748
+ const device = /^\/v1\/devices\/([^/]+)\/(report|gateway|commands|runs)$/.exec(clean);
7765
7749
  if (!device) return NOOP2;
7766
7750
  const hash2 = runIdHash(decodeURIComponent(device[1]));
7767
7751
  const pending = [...this.runs.values()].filter((observation2) => observation2.deviceHash === hash2).map((observation2) => observation2.request("device_control", verb, true));
@@ -7940,8 +7924,8 @@ var EventQueue = class {
7940
7924
  if (next.type === "exit") return;
7941
7925
  continue;
7942
7926
  }
7943
- await new Promise((resolve20) => {
7944
- this.waiter = resolve20;
7927
+ await new Promise((resolve19) => {
7928
+ this.waiter = resolve19;
7945
7929
  });
7946
7930
  }
7947
7931
  }
@@ -8018,13 +8002,13 @@ async function spawnCli(sandbox, argv, options) {
8018
8002
  stderr = (stderr + data).slice(-STDERR_TAIL * 4);
8019
8003
  });
8020
8004
  const exited = new Promise(
8021
- (resolve20) => {
8005
+ (resolve19) => {
8022
8006
  child.once("error", (error) => {
8023
8007
  stderr += `
8024
8008
  ${error.message}`;
8025
- resolve20({ code: null, signal: null });
8009
+ resolve19({ code: null, signal: null });
8026
8010
  });
8027
- child.once("exit", (code, signal) => resolve20({ code, signal }));
8011
+ child.once("exit", (code, signal) => resolve19({ code, signal }));
8028
8012
  }
8029
8013
  ).finally(() => {
8030
8014
  signalGroup(pgid, "SIGKILL");
@@ -8041,8 +8025,8 @@ ${error.message}`;
8041
8025
  let timer;
8042
8026
  await Promise.race([
8043
8027
  exited,
8044
- new Promise((resolve20) => {
8045
- timer = setTimeout(resolve20, graceMs);
8028
+ new Promise((resolve19) => {
8029
+ timer = setTimeout(resolve19, graceMs);
8046
8030
  })
8047
8031
  ]);
8048
8032
  clearTimeout(timer);
@@ -8189,11 +8173,11 @@ import { execa as execa3 } from "execa";
8189
8173
  // src/task-env.ts
8190
8174
  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;
8191
8175
  var NAME = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
8192
- function withTaskEnv(platform4, taskEnv) {
8193
- const env = { ...platform4 };
8176
+ function withTaskEnv(platform3, taskEnv) {
8177
+ const env = { ...platform3 };
8194
8178
  const dropped = [];
8195
8179
  for (const [name, value] of Object.entries(taskEnv ?? {})) {
8196
- if (typeof value !== "string" || !NAME.test(name) || RESERVED.test(name) || Object.hasOwn(platform4, name)) {
8180
+ if (typeof value !== "string" || !NAME.test(name) || RESERVED.test(name) || Object.hasOwn(platform3, name)) {
8197
8181
  dropped.push(name);
8198
8182
  continue;
8199
8183
  }
@@ -8201,8 +8185,8 @@ function withTaskEnv(platform4, taskEnv) {
8201
8185
  }
8202
8186
  return { env, dropped };
8203
8187
  }
8204
- function taskExecutionEnv(platform4, options) {
8205
- const env = withTaskEnv(platform4, options.taskEnv).env;
8188
+ function taskExecutionEnv(platform3, options) {
8189
+ const env = withTaskEnv(platform3, options.taskEnv).env;
8206
8190
  for (const name of ["MIKKA_SECRET_ENDPOINTS", "MIKKA_SECRET_UNAVAILABLE"]) {
8207
8191
  const value = options.taskSecretEnv?.[name];
8208
8192
  if (typeof value === "string") env[name] = value;
@@ -8516,8 +8500,8 @@ var WorktreeManager = class {
8516
8500
  const branches = [];
8517
8501
  for (const runId of runIds) {
8518
8502
  const branch = runBranch(runId);
8519
- const exists2 = await git3.raw(["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]).then((out) => out.trim().length > 0).catch(() => false);
8520
- if (!exists2) continue;
8503
+ const exists = await git3.raw(["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]).then((out) => out.trim().length > 0).catch(() => false);
8504
+ if (!exists) continue;
8521
8505
  const ahead = await git3.raw([
8522
8506
  "rev-list",
8523
8507
  "--count",
@@ -9456,19 +9440,34 @@ var ServerUnreachableError = class extends DaemonError {
9456
9440
  this.cause = cause;
9457
9441
  }
9458
9442
  };
9459
- var RunNotPinnedHereError = class extends DaemonError {
9460
- /** The server refused the claim because this daemon is too old (code `daemonUpgradeRequired`). */
9461
- upgradeRequired;
9443
+ var DaemonUpgradeRequiredError = class extends ServerUnreachableError {
9462
9444
  /** The release the refusing server names, when it names one. */
9463
9445
  latest;
9464
- constructor(runId, upgradeRequired = false, latest) {
9446
+ constructor(latest) {
9447
+ super("daemonUpgradeRequired");
9448
+ this.message = "This daemon is too old for the server; update it.";
9449
+ this.latest = latest;
9450
+ }
9451
+ };
9452
+ var DeviceGatewayRequiredError = class extends ServerUnreachableError {
9453
+ constructor() {
9454
+ super("deviceGatewayRequired");
9455
+ this.message = "The server has no device gateway.";
9456
+ }
9457
+ };
9458
+ var DeviceSessionRequiredError = class extends ServerUnreachableError {
9459
+ constructor() {
9460
+ super("deviceSessionRequired");
9461
+ this.message = "The server has no open session for this device.";
9462
+ }
9463
+ };
9464
+ var RunNotPinnedHereError = class extends DaemonError {
9465
+ constructor(runId) {
9465
9466
  super(
9466
9467
  DAEMON_RPC_ERRORS.runNotPinnedHere,
9467
9468
  `Run "${runId}" is pinned to another device`,
9468
9469
  { runId }
9469
9470
  );
9470
- this.upgradeRequired = upgradeRequired;
9471
- this.latest = latest;
9472
9471
  }
9473
9472
  };
9474
9473
  var HarnessNotSupportedError = class extends DaemonError {
@@ -10674,7 +10673,7 @@ var requestSchema = z33.union([
10674
10673
  ]);
10675
10674
  var unavailable = () => new Error("Run mailbox unavailable");
10676
10675
  function assertMailboxRunAuthority(input) {
10677
- if (!input.held || !input.state || isTerminalRunState(input.state) || input.stopped || input.lease === void 0 || !Number.isFinite(input.lease) || input.lease <= Date.now()) throw unavailable();
10676
+ if (!input.held || !input.state || isTerminalRunState(input.state) || input.stopped || input.lease === void 0 || Number.isNaN(input.lease) || input.lease <= Date.now()) throw unavailable();
10678
10677
  }
10679
10678
  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." }] };
10680
10679
  function mailboxToolResult(result) {
@@ -10985,8 +10984,8 @@ var PromptQueue = class {
10985
10984
  continue;
10986
10985
  }
10987
10986
  if (this.closed) return;
10988
- await new Promise((resolve20) => {
10989
- this.waiter = resolve20;
10987
+ await new Promise((resolve19) => {
10988
+ this.waiter = resolve19;
10990
10989
  });
10991
10990
  }
10992
10991
  }
@@ -11000,8 +10999,8 @@ async function untilSpoken(spoken) {
11000
10999
  try {
11001
11000
  return await Promise.race([
11002
11001
  spoken,
11003
- new Promise((resolve20) => {
11004
- timer = setTimeout(() => resolve20(true), CONTINUE_SILENCE_MS);
11002
+ new Promise((resolve19) => {
11003
+ timer = setTimeout(() => resolve19(true), CONTINUE_SILENCE_MS);
11005
11004
  })
11006
11005
  ]);
11007
11006
  } finally {
@@ -11222,15 +11221,15 @@ var ClaudeAdapter = class {
11222
11221
  let authTimer;
11223
11222
  let stderr = "";
11224
11223
  let stderrArrived = () => void 0;
11225
- const firstStderr = new Promise((resolve20) => {
11226
- stderrArrived = resolve20;
11224
+ const firstStderr = new Promise((resolve19) => {
11225
+ stderrArrived = resolve19;
11227
11226
  });
11228
11227
  const stderrTail = () => stderr.slice(-STDERR_TAIL2).trim() || "no output";
11229
11228
  let spoke = () => void 0;
11230
- const spoken = new Promise((resolve20) => spoke = resolve20);
11229
+ const spoken = new Promise((resolve19) => spoke = resolve19);
11231
11230
  let checkingContinuation = mode === "continue";
11232
11231
  let finished = () => void 0;
11233
- const gone = new Promise((resolve20) => finished = resolve20);
11232
+ const gone = new Promise((resolve19) => finished = resolve19);
11234
11233
  let nativeExit = Promise.resolve(false);
11235
11234
  if (externalAuth && this.options.onHostedSession) {
11236
11235
  try {
@@ -11269,10 +11268,10 @@ var ClaudeAdapter = class {
11269
11268
  stderr = previousStderr.slice(-STDERR_TAIL2 * 4);
11270
11269
  stderrArrived();
11271
11270
  }
11272
- nativeExit = new Promise((resolve20) => {
11273
- child.once("exit", () => resolve20(true));
11274
- child.once("error", () => resolve20(false));
11275
- if (child.exitCode !== null || child.signalCode) resolve20(true);
11271
+ nativeExit = new Promise((resolve19) => {
11272
+ child.once("exit", () => resolve19(true));
11273
+ child.once("error", () => resolve19(false));
11274
+ if (child.exitCode !== null || child.signalCode) resolve19(true);
11276
11275
  });
11277
11276
  child.stderr?.on("data", (data) => {
11278
11277
  stderr = (stderr + data.toString()).slice(-STDERR_TAIL2 * 4);
@@ -11498,8 +11497,8 @@ var ClaudeAdapter = class {
11498
11497
  if (!message.is_error) quota = void 0;
11499
11498
  if (message.is_error && externalAuth && !stderr) {
11500
11499
  let drainTimer;
11501
- await Promise.race([firstStderr, new Promise((resolve20) => {
11502
- drainTimer = setTimeout(resolve20, 100);
11500
+ await Promise.race([firstStderr, new Promise((resolve19) => {
11501
+ drainTimer = setTimeout(resolve19, 100);
11503
11502
  })]);
11504
11503
  clearTimeout(drainTimer);
11505
11504
  }
@@ -11695,8 +11694,8 @@ import { randomBytes } from "node:crypto";
11695
11694
  import { createServer } from "node:http";
11696
11695
  var LIMIT = 4096;
11697
11696
  var CODEX_TRACE_BODY_LIMIT = 1048576;
11698
- function codexTraceEnvironment(env, platform4 = process.platform) {
11699
- if (platform4 !== "linux") return void 0;
11697
+ function codexTraceEnvironment(env, platform3 = process.platform) {
11698
+ if (platform3 !== "linux") return void 0;
11700
11699
  const append = (value) => value ? `${value},127.0.0.1` : "127.0.0.1";
11701
11700
  return { NO_PROXY: append(env.NO_PROXY ?? env.no_proxy), no_proxy: append(env.no_proxy ?? env.NO_PROXY) };
11702
11701
  }
@@ -12107,11 +12106,11 @@ async function startCodexGenerationCollector(emit) {
12107
12106
  server.requestTimeout = 1e3;
12108
12107
  server.headersTimeout = 1e3;
12109
12108
  server.maxConnections = 4;
12110
- await new Promise((resolve20, reject) => {
12109
+ await new Promise((resolve19, reject) => {
12111
12110
  server.once("error", reject);
12112
12111
  server.listen(0, "127.0.0.1", () => {
12113
12112
  server.off("error", reject);
12114
- resolve20();
12113
+ resolve19();
12115
12114
  });
12116
12115
  });
12117
12116
  server.on("error", () => collector.reject());
@@ -12131,7 +12130,7 @@ async function startCodexGenerationCollector(emit) {
12131
12130
  "-c",
12132
12131
  "otel.log_guardian_assessments=false"
12133
12132
  ],
12134
- close: (cliExitObserved = false) => closed ??= new Promise((resolve20) => {
12133
+ close: (cliExitObserved = false) => closed ??= new Promise((resolve19) => {
12135
12134
  const timer = setTimeout(() => {
12136
12135
  collector.truncate();
12137
12136
  server.closeAllConnections();
@@ -12139,7 +12138,7 @@ async function startCodexGenerationCollector(emit) {
12139
12138
  timer.unref();
12140
12139
  server.close(() => {
12141
12140
  clearTimeout(timer);
12142
- resolve20(collector.finish(cliExitObserved));
12141
+ resolve19(collector.finish(cliExitObserved));
12143
12142
  });
12144
12143
  })
12145
12144
  };
@@ -12182,11 +12181,11 @@ var JsonlWriter = class extends AbstractMessageWriter {
12182
12181
  }
12183
12182
  stream;
12184
12183
  write(message) {
12185
- return new Promise((resolve20, reject) => {
12184
+ return new Promise((resolve19, reject) => {
12186
12185
  this.stream.write(
12187
12186
  `${JSON.stringify(message)}
12188
12187
  `,
12189
- (error) => error ? reject(error) : resolve20()
12188
+ (error) => error ? reject(error) : resolve19()
12190
12189
  );
12191
12190
  });
12192
12191
  }
@@ -13708,7 +13707,7 @@ var MockAdapter = class {
13708
13707
  if (line.hang) {
13709
13708
  if (!abort.signal.aborted) {
13710
13709
  await new Promise(
13711
- (resolve20) => abort.signal.addEventListener("abort", resolve20, { once: true })
13710
+ (resolve19) => abort.signal.addEventListener("abort", resolve19, { once: true })
13712
13711
  );
13713
13712
  }
13714
13713
  yield { type: "exit", outcome: "cancelled" };
@@ -14065,8 +14064,6 @@ var NoSandbox = class {
14065
14064
  // src/fs-browse.ts
14066
14065
  import { execFile as execFile2 } from "node:child_process";
14067
14066
  import { readdir as readdir2, realpath, stat as stat2 } from "node:fs/promises";
14068
- import { homedir as homedir4, platform } from "node:os";
14069
- import { basename as basename5, dirname as dirname12, isAbsolute as isAbsolute6, join as join19, resolve as resolve10 } from "node:path";
14070
14067
  import { promisify as promisify2 } from "node:util";
14071
14068
  var run = promisify2(execFile2);
14072
14069
  async function git(cwd, args) {
@@ -14080,86 +14077,6 @@ async function git(cwd, args) {
14080
14077
  return null;
14081
14078
  }
14082
14079
  }
14083
- async function isDir(path3) {
14084
- try {
14085
- return (await stat2(path3)).isDirectory();
14086
- } catch {
14087
- return false;
14088
- }
14089
- }
14090
- async function exists(path3) {
14091
- try {
14092
- await stat2(path3);
14093
- return true;
14094
- } catch {
14095
- return false;
14096
- }
14097
- }
14098
- async function repoAround(path3) {
14099
- const top = await git(path3, ["rev-parse", "--show-toplevel"]);
14100
- if (!top) return null;
14101
- const origin = await git(top, ["config", "--get", "remote.origin.url"]);
14102
- const first = origin ? null : (await git(top, ["remote"]))?.split("\n")[0] ?? null;
14103
- const remoteUrl = origin ?? (first ? await git(top, ["config", "--get", `remote.${first}.url`]) : null);
14104
- return { path: top, remoteUrl };
14105
- }
14106
- async function browseFolder(request2) {
14107
- const home = homedir4();
14108
- const wanted = request2.path ?? home;
14109
- if (!isAbsolute6(wanted))
14110
- return {
14111
- ok: false,
14112
- code: "not_found",
14113
- message: "Expected an absolute path."
14114
- };
14115
- const path3 = resolve10(wanted);
14116
- if (!await exists(path3))
14117
- return { ok: false, code: "not_found", message: `${path3} does not exist.` };
14118
- if (!await isDir(path3))
14119
- return {
14120
- ok: false,
14121
- code: "not_a_directory",
14122
- message: `${path3} is not a folder.`
14123
- };
14124
- let names;
14125
- try {
14126
- names = await readdir2(path3, { withFileTypes: true });
14127
- } catch (error) {
14128
- const denied2 = error.code;
14129
- return denied2 === "EACCES" || denied2 === "EPERM" ? {
14130
- ok: false,
14131
- code: "denied",
14132
- message: `Mikka may not read ${path3}. Allow access in system settings.`
14133
- } : { ok: false, code: "failed", message: `Could not read ${path3}.` };
14134
- }
14135
- const folders = [];
14136
- let truncated = false;
14137
- const dirs = names.filter((e) => e.isDirectory() || e.isSymbolicLink()).filter((e) => request2.showHidden || !e.name.startsWith(".")).sort((a, b) => a.name.localeCompare(b.name));
14138
- for (const entry of dirs) {
14139
- const full = join19(path3, entry.name);
14140
- if (entry.isSymbolicLink() && !await isDir(full)) continue;
14141
- if (folders.length >= FS_MAX_ENTRIES) {
14142
- truncated = true;
14143
- break;
14144
- }
14145
- folders.push({
14146
- name: entry.name,
14147
- path: full,
14148
- isRepo: await exists(join19(full, ".git"))
14149
- });
14150
- }
14151
- const parent = dirname12(path3);
14152
- return {
14153
- ok: true,
14154
- path: path3,
14155
- parent: parent === path3 || basename5(path3) === "" ? null : parent,
14156
- home,
14157
- platform: platform(),
14158
- entries: folders,
14159
- truncated,
14160
- repo: await repoAround(path3)
14161
- };
14162
- }
14163
14080
  async function verifyExpectedOrigin(path3, expected2) {
14164
14081
  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();
14165
14082
  const top = await git(path3, ["rev-parse", "--show-toplevel"]);
@@ -14175,8 +14092,8 @@ async function verifyExpectedOrigin(path3, expected2) {
14175
14092
  // src/auto-update.ts
14176
14093
  import { execFile as execFile3 } from "node:child_process";
14177
14094
  import { realpathSync as realpathSync11 } from "node:fs";
14178
- import { homedir as homedir5 } from "node:os";
14179
- import { dirname as dirname13, join as join20, resolve as resolve11 } from "node:path";
14095
+ import { homedir as homedir4 } from "node:os";
14096
+ import { dirname as dirname12, join as join19, resolve as resolve10 } from "node:path";
14180
14097
  import { promisify as promisify3 } from "node:util";
14181
14098
  var exec = promisify3(execFile3);
14182
14099
  function newerStableVersion(candidate, current) {
@@ -14187,16 +14104,16 @@ function newerStableVersion(candidate, current) {
14187
14104
  return false;
14188
14105
  }
14189
14106
  function serviceNpmEnvironment(entry, home, env) {
14190
- const prefix = join20(home, ".mikka/npm");
14191
- return resolve11(entry) === join20(prefix, "lib/node_modules/@aspectlylabs/mikka/mikka.js") ? { ...env, npm_config_prefix: prefix, npm_config_cache: join20(home, ".mikka/npm-cache") } : env;
14107
+ const prefix = join19(home, ".mikka/npm");
14108
+ return resolve10(entry) === join19(prefix, "lib/node_modules/@aspectlylabs/mikka/mikka.js") ? { ...env, npm_config_prefix: prefix, npm_config_cache: join19(home, ".mikka/npm-cache") } : env;
14192
14109
  }
14193
14110
  async function runServiceNpm(args) {
14194
- const npm = realpathSync11(join20(dirname13(process.execPath), "npm"));
14111
+ const npm = realpathSync11(join19(dirname12(process.execPath), "npm"));
14195
14112
  const { stdout } = await exec(process.execPath, [npm, ...args], {
14196
- cwd: homedir5(),
14113
+ cwd: homedir4(),
14197
14114
  timeout: 3e5,
14198
14115
  maxBuffer: 1024 * 1024,
14199
- env: { ...serviceNpmEnvironment(realpathSync11(process.argv[1]), homedir5(), process.env), PATH: `${dirname13(process.execPath)}:${process.env.PATH ?? ""}` }
14116
+ env: { ...serviceNpmEnvironment(realpathSync11(process.argv[1]), homedir4(), process.env), PATH: `${dirname12(process.execPath)}:${process.env.PATH ?? ""}` }
14200
14117
  });
14201
14118
  return stdout.trim();
14202
14119
  }
@@ -14221,8 +14138,8 @@ function reportedUpdateFailure(file, current) {
14221
14138
  import { execFile as execFile4 } from "node:child_process";
14222
14139
  import { promisify as promisify4 } from "node:util";
14223
14140
  import { mkdir as mkdir2, readFile as readFile2, writeFile, rm as rm2 } from "node:fs/promises";
14224
- import { homedir as homedir6 } from "node:os";
14225
- import { dirname as dirname14, join as join21, resolve as resolve12 } from "node:path";
14141
+ import { homedir as homedir5 } from "node:os";
14142
+ import { dirname as dirname13, join as join20, resolve as resolve11 } from "node:path";
14226
14143
  var exec2 = promisify4(execFile4);
14227
14144
  var label = "com.aspectlylabs.mikka.daemon";
14228
14145
  async function restartService(update, beforeRestart, dependencies = {
@@ -14245,7 +14162,7 @@ async function restartService(update, beforeRestart, dependencies = {
14245
14162
  }
14246
14163
  async function uninstallService(clearCredential, dependencies = {
14247
14164
  manager: process.env.MIKKA_SERVICE,
14248
- home: homedir6(),
14165
+ home: homedir5(),
14249
14166
  uid: process.getuid?.() ?? 0,
14250
14167
  run: async (program, args) => {
14251
14168
  await exec2(program, args, { timeout: 1e4 });
@@ -14257,10 +14174,10 @@ async function uninstallService(clearCredential, dependencies = {
14257
14174
  try {
14258
14175
  if (dependencies.manager === "systemd") {
14259
14176
  await dependencies.run("systemctl", ["--user", "disable", "mikka-daemon.service"]);
14260
- await rm2(join21(dependencies.home, ".config/systemd/user/mikka-daemon.service"), { force: true });
14177
+ await rm2(join20(dependencies.home, ".config/systemd/user/mikka-daemon.service"), { force: true });
14261
14178
  await dependencies.run("systemctl", ["--user", "daemon-reload"]);
14262
14179
  } else if (dependencies.manager === "launchd") {
14263
- await rm2(join21(dependencies.home, "Library/LaunchAgents", `${label}.plist`), { force: true });
14180
+ await rm2(join20(dependencies.home, "Library/LaunchAgents", `${label}.plist`), { force: true });
14264
14181
  }
14265
14182
  } finally {
14266
14183
  clearCredential();
@@ -14303,14 +14220,14 @@ async function detectDeviceType() {
14303
14220
 
14304
14221
  // src/harnesses.ts
14305
14222
  import { statfsSync } from "node:fs";
14306
- import { arch, platform as platform2 } from "node:os";
14223
+ import { arch, platform } from "node:os";
14307
14224
  import { execa as execa7 } from "execa";
14308
14225
 
14309
14226
  // harness/install.mjs
14310
14227
  import { createHash as createHash8, randomBytes as randomBytes2 } from "node:crypto";
14311
14228
  import { execFile as execFile5 } from "node:child_process";
14312
14229
  import { createWriteStream as createWriteStream2, existsSync as existsSync6, mkdirSync as mkdirSync14, readdirSync as readdirSync5, readFileSync as readFileSync10, renameSync as renameSync4, rmSync as rmSync11, statSync as statSync2, symlinkSync, writeFileSync as writeFileSync8 } from "node:fs";
14313
- import { dirname as dirname15, join as join22, relative as relative5 } from "node:path";
14230
+ import { dirname as dirname14, join as join21, relative as relative5 } from "node:path";
14314
14231
  import { Readable as Readable2, Transform } from "node:stream";
14315
14232
  import { pipeline as pipeline2 } from "node:stream/promises";
14316
14233
  import { promisify as promisify5 } from "node:util";
@@ -14351,25 +14268,25 @@ var INSTALL_FORMAT = "complete-package-v1\n";
14351
14268
  var installMarker = (pin, artifact) => INSTALL_FORMAT + artifact.integrity + (pin.companions?.length ? "\n" + pin.companions.join("\n") : "");
14352
14269
  var run2 = promisify5(execFile5);
14353
14270
  var inflight = /* @__PURE__ */ new Map();
14354
- function platformKey(platform4 = process.platform, arch3 = process.arch) {
14355
- return `${platform4}-${arch3}`;
14271
+ function platformKey(platform3 = process.platform, arch3 = process.arch) {
14272
+ return `${platform3}-${arch3}`;
14356
14273
  }
14357
14274
  function resolvePin(store, harness) {
14358
14275
  const pin = (store.pins ?? HARNESS_PINS).harnesses[harness];
14359
14276
  return { pin, artifact: pin.platforms[store.platform ?? platformKey()] };
14360
14277
  }
14361
14278
  function versionDir(store, harness) {
14362
- return join22(store.root, harness, resolvePin(store, harness).pin.version);
14279
+ return join21(store.root, harness, resolvePin(store, harness).pin.version);
14363
14280
  }
14364
14281
  function harnessBinaryPath(store, harness) {
14365
- return join22(versionDir(store, harness), "bin", resolvePin(store, harness).pin.command);
14282
+ return join21(versionDir(store, harness), "bin", resolvePin(store, harness).pin.command);
14366
14283
  }
14367
14284
  function harnessInstallState(store, harness) {
14368
14285
  const { pin, artifact } = resolvePin(store, harness);
14369
14286
  if (!artifact) return { state: "unsupported", version: pin.version };
14370
14287
  let installed = false;
14371
14288
  try {
14372
- installed = readFileSync10(join22(versionDir(store, harness), MARKER), "utf8") === installMarker(pin, artifact) && runtimeFiles(store, harness).every((path3) => {
14289
+ installed = readFileSync10(join21(versionDir(store, harness), MARKER), "utf8") === installMarker(pin, artifact) && runtimeFiles(store, harness).every((path3) => {
14373
14290
  const stat3 = statSync2(path3);
14374
14291
  return stat3.isFile() && (stat3.mode & 73) !== 0;
14375
14292
  });
@@ -14379,7 +14296,7 @@ function harnessInstallState(store, harness) {
14379
14296
  }
14380
14297
  function runtimeFiles(store, harness) {
14381
14298
  const binary = harnessBinaryPath(store, harness);
14382
- return harness === "codex" ? [binary, join22(dirname15(binary), "codex-code-mode-host")] : [binary];
14299
+ return harness === "codex" ? [binary, join21(dirname14(binary), "codex-code-mode-host")] : [binary];
14383
14300
  }
14384
14301
  function ensureHarness(store, harness) {
14385
14302
  const key2 = `${store.root}\0${harness}`;
@@ -14396,27 +14313,27 @@ async function install(store, harness) {
14396
14313
  if (state2 === "unsupported") throw new Error(`${harness} has no build for ${store.platform ?? platformKey()}`);
14397
14314
  if (state2 === "installed") return binary;
14398
14315
  const { pin, artifact } = resolvePin(store, harness);
14399
- const parent = join22(store.root, harness);
14316
+ const parent = join21(store.root, harness);
14400
14317
  mkdirSync14(parent, { recursive: true, mode: 448 });
14401
- const staging = join22(parent, `.staging-${randomBytes2(6).toString("hex")}`);
14318
+ const staging = join21(parent, `.staging-${randomBytes2(6).toString("hex")}`);
14402
14319
  mkdirSync14(staging, { recursive: true, mode: 448 });
14403
14320
  try {
14404
- const tarball = join22(staging, "package.tgz");
14321
+ const tarball = join21(staging, "package.tgz");
14405
14322
  await download(`${(store.pins ?? HARNESS_PINS).registry.replace(/\/$/, "")}/${artifact.tarball}`, tarball, artifact.integrity);
14406
14323
  await run2("tar", ["-xzf", tarball, "-C", staging]);
14407
14324
  if (harness === "codex") {
14408
14325
  if (!artifact.entry.endsWith("/bin/codex")) throw new Error("Invalid Codex bundle entry");
14409
- const bundle = dirname15(dirname15(artifact.entry));
14410
- for (const name of readdirSync5(join22(staging, bundle))) symlinkSync(relative5(staging, join22(staging, bundle, name)), join22(staging, name));
14326
+ const bundle = dirname14(dirname14(artifact.entry));
14327
+ for (const name of readdirSync5(join21(staging, bundle))) symlinkSync(relative5(staging, join21(staging, bundle, name)), join21(staging, name));
14411
14328
  for (const name of ["codex", "codex-code-mode-host"]) {
14412
- const stat3 = statSync2(join22(staging, "bin", name));
14329
+ const stat3 = statSync2(join21(staging, "bin", name));
14413
14330
  if (!stat3.isFile() || (stat3.mode & 73) === 0) throw new Error("Incomplete Codex runtime bundle");
14414
14331
  }
14415
14332
  } else {
14416
- mkdirSync14(join22(staging, "bin"), { mode: 448 });
14417
- symlinkSync(relative5(join22(staging, "bin"), join22(staging, artifact.entry)), join22(staging, "bin", pin.command));
14333
+ mkdirSync14(join21(staging, "bin"), { mode: 448 });
14334
+ symlinkSync(relative5(join21(staging, "bin"), join21(staging, artifact.entry)), join21(staging, "bin", pin.command));
14418
14335
  }
14419
- writeFileSync8(join22(staging, MARKER), installMarker(pin, artifact), { mode: 384 });
14336
+ writeFileSync8(join21(staging, MARKER), installMarker(pin, artifact), { mode: 384 });
14420
14337
  const target = versionDir(store, harness);
14421
14338
  const retained = existsSync6(target) ? `${target}.retained-${randomBytes2(6).toString("hex")}` : null;
14422
14339
  if (retained) renameSync4(target, retained);
@@ -14474,7 +14391,7 @@ function freeDiskBytes(dir) {
14474
14391
  }
14475
14392
  async function deviceCapabilities(store, dataDir, docker = dockerAvailable) {
14476
14393
  return {
14477
- os: platform2(),
14394
+ os: platform(),
14478
14395
  arch: arch(),
14479
14396
  freeDiskBytes: freeDiskBytes(dataDir),
14480
14397
  docker: await docker(),
@@ -14498,7 +14415,7 @@ function harnessFingerprint(store) {
14498
14415
  // src/model-probe.ts
14499
14416
  import { spawn as spawn3 } from "node:child_process";
14500
14417
  import { mkdtempSync as mkdtempSync6, readdirSync as readdirSync6, rmSync as rmSync12 } from "node:fs";
14501
- import { join as join23 } from "node:path";
14418
+ import { join as join22 } from "node:path";
14502
14419
 
14503
14420
  // src/process-group.ts
14504
14421
  async function stopGroup(child, graceMs = 3e3) {
@@ -14518,12 +14435,12 @@ async function stopGroup(child, graceMs = 3e3) {
14518
14435
  };
14519
14436
  if (child.exitCode === null && child.signalCode === null) {
14520
14437
  signal("SIGTERM");
14521
- await new Promise((resolve20) => {
14522
- if (child.exitCode !== null || child.signalCode !== null) return resolve20();
14438
+ await new Promise((resolve19) => {
14439
+ if (child.exitCode !== null || child.signalCode !== null) return resolve19();
14523
14440
  const done = () => {
14524
14441
  clearTimeout(timer);
14525
14442
  child.off("exit", done);
14526
- resolve20();
14443
+ resolve19();
14527
14444
  };
14528
14445
  const timer = setTimeout(done, graceMs);
14529
14446
  child.once("exit", done);
@@ -14578,10 +14495,10 @@ function sweepModelProbeHomes(scratchDir) {
14578
14495
  } catch {
14579
14496
  return;
14580
14497
  }
14581
- for (const name of names) if (name.startsWith(HOME_PREFIX)) rmSync12(join23(scratchDir, name), { recursive: true, force: true });
14498
+ for (const name of names) if (name.startsWith(HOME_PREFIX)) rmSync12(join22(scratchDir, name), { recursive: true, force: true });
14582
14499
  }
14583
14500
  async function probeHarnessModels(harness, binary, options) {
14584
- const home = mkdtempSync6(join23(options.scratchDir, HOME_PREFIX));
14501
+ const home = mkdtempSync6(join22(options.scratchDir, HOME_PREFIX));
14585
14502
  try {
14586
14503
  return await exchange(harness, binary, home, options);
14587
14504
  } finally {
@@ -14590,15 +14507,15 @@ async function probeHarnessModels(harness, binary, options) {
14590
14507
  }
14591
14508
  function exchange(harness, binary, home, options) {
14592
14509
  const args = harness === "codex" ? ["app-server"] : ["-p", "--input-format", "stream-json", "--output-format", "stream-json", "--verbose"];
14593
- const env = { PATH: process.env.PATH ?? "", HOME: home, CODEX_HOME: home, CLAUDE_CONFIG_DIR: join23(home, ".claude"), LANG: process.env.LANG ?? "C.UTF-8" };
14594
- return new Promise((resolve20) => {
14510
+ const env = { PATH: process.env.PATH ?? "", HOME: home, CODEX_HOME: home, CLAUDE_CONFIG_DIR: join22(home, ".claude"), LANG: process.env.LANG ?? "C.UTF-8" };
14511
+ return new Promise((resolve19) => {
14595
14512
  const child = (options.spawnImpl ?? spawn3)(binary, args, { env, cwd: home, detached: process.platform !== "win32", stdio: ["pipe", "pipe", "ignore"] });
14596
14513
  let result;
14597
14514
  let stopping;
14598
14515
  const stop = () => stopping ??= Promise.resolve().then(() => stopGroup(child, 0));
14599
14516
  const done = () => {
14600
14517
  clearTimeout(timer);
14601
- resolve20(result ?? null);
14518
+ resolve19(result ?? null);
14602
14519
  };
14603
14520
  const finish = (value) => {
14604
14521
  if (result !== void 0) return;
@@ -14661,9 +14578,9 @@ function exchange(harness, binary, home, options) {
14661
14578
 
14662
14579
  // src/cloud-registration.ts
14663
14580
  import { createHash as createHash9 } from "node:crypto";
14664
- import { join as join24 } from "node:path";
14581
+ import { join as join23 } from "node:path";
14665
14582
  function writeCloudRegistration(dataDir, deviceId, workspaceId, credential) {
14666
- writeJsonAtomic(join24(dataDir, "registration.json"), {
14583
+ writeJsonAtomic(join23(dataDir, "registration.json"), {
14667
14584
  version: 1,
14668
14585
  deviceId,
14669
14586
  workspaceId,
@@ -14676,7 +14593,7 @@ import { mkdtempSync as mkdtempSync7, rmSync as rmSync13, statSync as statSync3
14676
14593
 
14677
14594
  // src/hosted-binaries.ts
14678
14595
  import { accessSync as accessSync2, constants as constants5, lstatSync as lstatSync10, readFileSync as readFileSync11, realpathSync as realpathSync12 } from "node:fs";
14679
- import { delimiter as delimiter5, isAbsolute as isAbsolute7 } from "node:path";
14596
+ import { delimiter as delimiter5, isAbsolute as isAbsolute6 } from "node:path";
14680
14597
  import { z as z34 } from "zod";
14681
14598
  var HOSTED_CLI_MANIFEST = "/opt/mikka/worker/.mikka-original-cli.json";
14682
14599
  var LEGACY_HOSTED_CLI_MANIFEST = "/opt/mikka/original-cli.json";
@@ -14709,7 +14626,7 @@ function readManifest(path3) {
14709
14626
  throw Error("hosted_official_cli_missing");
14710
14627
  for (const harness of ["claude_code", "codex"]) {
14711
14628
  const original = value.original[harness], added = value.added[harness];
14712
- if (original && (!isAbsolute7(original.path) || original.path.startsWith("/opt/mikka/")) || added && (original || !added.path.startsWith("/opt/mikka/"))) throw Error("hosted_cli_manifest_invalid");
14629
+ if (original && (!isAbsolute6(original.path) || original.path.startsWith("/opt/mikka/")) || added && (original || !added.path.startsWith("/opt/mikka/"))) throw Error("hosted_cli_manifest_invalid");
14713
14630
  }
14714
14631
  return value;
14715
14632
  }
@@ -14870,10 +14787,10 @@ async function prepareSubscriptionCredentials(assignment, host) {
14870
14787
 
14871
14788
  // src/run-scratch.ts
14872
14789
  import { rmSync as rmSync14 } from "node:fs";
14873
- import { join as join25 } from "node:path";
14790
+ import { join as join24 } from "node:path";
14874
14791
  function removeRunCredentials(stateDir, runId) {
14875
14792
  const { runDir } = runPaths(stateDir, runId);
14876
- for (const path3 of RUN_CREDENTIAL_PATHS) rmSync14(join25(runDir, path3), { recursive: true, force: true });
14793
+ for (const path3 of RUN_CREDENTIAL_PATHS) rmSync14(join24(runDir, path3), { recursive: true, force: true });
14877
14794
  }
14878
14795
 
14879
14796
  // src/subscription-local-runner.ts
@@ -14972,7 +14889,7 @@ function createLocalSubscriptionRunner(host) {
14972
14889
 
14973
14890
  // src/subscription-preflight.ts
14974
14891
  import { mkdtempSync as mkdtempSync8, rmSync as rmSync15 } from "node:fs";
14975
- import { join as join26 } from "node:path";
14892
+ import { join as join25 } from "node:path";
14976
14893
  import { execa as execa8 } from "execa";
14977
14894
  var refused = (detail, cause) => ({
14978
14895
  ready: false,
@@ -14991,7 +14908,7 @@ async function preflightLocalSubscription(harness, options) {
14991
14908
  const expected2 = (options.store.pins ?? HARNESS_PINS).harnesses[harness].version;
14992
14909
  let home;
14993
14910
  try {
14994
- home = mkdtempSync8(join26(options.scratchDir, "subscription-preflight-"));
14911
+ home = mkdtempSync8(join25(options.scratchDir, "subscription-preflight-"));
14995
14912
  const result = await execa8(binary, ["--version"], {
14996
14913
  env: { ...env, HOME: home },
14997
14914
  extendEnv: false,
@@ -15055,8 +14972,8 @@ async function acquireCloudWorkspaceControl(input, root = CLOUD_WORKSPACE_CONTRO
15055
14972
  });
15056
14973
  let acquired = false, releasing = false, settled = false, output = "";
15057
14974
  let finished;
15058
- const done = new Promise((resolve20) => {
15059
- finished = resolve20;
14975
+ const done = new Promise((resolve19) => {
14976
+ finished = resolve19;
15060
14977
  });
15061
14978
  child.stdin.on("error", () => {
15062
14979
  if (!settled && !releasing) child.kill("SIGTERM");
@@ -15069,7 +14986,7 @@ async function acquireCloudWorkspaceControl(input, root = CLOUD_WORKSPACE_CONTRO
15069
14986
  if (!acquired || settled || releasing || !child.stdin.writable) throw new CodedError("terminal_control_unavailable", { detail: "fence_lost" });
15070
14987
  child.stdin.write(JSON.stringify(value) + "\n");
15071
14988
  };
15072
- await new Promise((resolve20, reject) => {
14989
+ await new Promise((resolve19, reject) => {
15073
14990
  const fail = (cause) => reject(new CodedError("terminal_control_unavailable", { detail: "fence_unavailable", cause }));
15074
14991
  child.once("error", fail);
15075
14992
  child.stdout.on("data", (data) => {
@@ -15084,7 +15001,7 @@ async function acquireCloudWorkspaceControl(input, root = CLOUD_WORKSPACE_CONTRO
15084
15001
  fail(input.signal.reason);
15085
15002
  return;
15086
15003
  }
15087
- resolve20();
15004
+ resolve19();
15088
15005
  } else if (output.length > 32) {
15089
15006
  child.kill("SIGTERM");
15090
15007
  fail();
@@ -15118,7 +15035,7 @@ async function acquireCloudWorkspaceControl(input, root = CLOUD_WORKSPACE_CONTRO
15118
15035
  // src/lock.ts
15119
15036
  import { mkdirSync as mkdirSync15, readFileSync as readFileSync12, rmSync as rmSync16 } from "node:fs";
15120
15037
  import { createConnection } from "node:net";
15121
- import { join as join27 } from "node:path";
15038
+ import { join as join26 } from "node:path";
15122
15039
  import { setTimeout as sleep2 } from "node:timers/promises";
15123
15040
  import lockfile from "proper-lockfile";
15124
15041
  var DaemonAlreadyRunningError = class extends Error {
@@ -15133,7 +15050,7 @@ var LOCK_STALE_MS = 5 * 6e4;
15133
15050
  var LOCK_UPDATE_MS = 3e4;
15134
15051
  var LOCK_TAKEOVER_MS = 6e3;
15135
15052
  function pidFile(dataDir) {
15136
- return join27(dataDir, "daemon.pid");
15053
+ return join26(dataDir, "daemon.pid");
15137
15054
  }
15138
15055
  function holderPid(dataDir) {
15139
15056
  try {
@@ -15152,11 +15069,11 @@ function processAlive(pid) {
15152
15069
  }
15153
15070
  }
15154
15071
  function socketAnswers(socketPath) {
15155
- return new Promise((resolve20) => {
15072
+ return new Promise((resolve19) => {
15156
15073
  const socket = createConnection(socketPath);
15157
15074
  const done = (alive) => {
15158
15075
  socket.destroy();
15159
- resolve20(alive);
15076
+ resolve19(alive);
15160
15077
  };
15161
15078
  socket.once("connect", () => done(true));
15162
15079
  socket.once("error", () => done(false));
@@ -15265,7 +15182,7 @@ function closeLogger(logger) {
15265
15182
  const file = files.get(logger);
15266
15183
  if (!file) return Promise.resolve();
15267
15184
  files.delete(logger);
15268
- return new Promise((resolve20) => file.end(resolve20));
15185
+ return new Promise((resolve19) => file.end(resolve19));
15269
15186
  }
15270
15187
 
15271
15188
  // src/outbox.ts
@@ -15277,7 +15194,8 @@ import {
15277
15194
  rmSync as rmSync17,
15278
15195
  truncateSync
15279
15196
  } from "node:fs";
15280
- import { join as join28 } from "node:path";
15197
+ import { join as join27 } from "node:path";
15198
+ var RETRY_MAX_MS = 3e4;
15281
15199
  var Outbox = class {
15282
15200
  constructor(dir, link, log, retryMs = 1e3, onUndeliverable = () => void 0, retainResources = false, traceContext = () => void 0) {
15283
15201
  this.dir = dir;
@@ -15298,14 +15216,16 @@ var Outbox = class {
15298
15216
  traceContext;
15299
15217
  chains = /* @__PURE__ */ new Map();
15300
15218
  retryTimer = null;
15219
+ /** Failed deliveries in a row: each retry waits twice as long, up to RETRY_MAX_MS. */
15220
+ failures = 0;
15301
15221
  closed = false;
15302
15222
  /** Runs whose file was checked for a torn tail since this process started. */
15303
15223
  repaired = /* @__PURE__ */ new Set();
15304
15224
  file(runId) {
15305
- return join28(this.dir, `${assertSafeId("run id", runId)}.jsonl`);
15225
+ return join27(this.dir, `${assertSafeId("run id", runId)}.jsonl`);
15306
15226
  }
15307
15227
  ackFile(runId) {
15308
- return join28(this.dir, `${assertSafeId("run id", runId)}.ack.json`);
15228
+ return join27(this.dir, `${assertSafeId("run id", runId)}.ack.json`);
15309
15229
  }
15310
15230
  parse(runId) {
15311
15231
  let data;
@@ -15455,12 +15375,14 @@ var Outbox = class {
15455
15375
  writeJsonAtomic(this.ackFile(runId), ack);
15456
15376
  }
15457
15377
  } catch (error) {
15378
+ if (error instanceof DaemonUpgradeRequiredError) return;
15458
15379
  if (!(error instanceof ServerUnreachableError)) {
15459
15380
  this.log.error({ run_id: runId, err: error }, "outbox delivery failed");
15460
15381
  }
15461
15382
  this.scheduleRetry();
15462
15383
  return;
15463
15384
  }
15385
+ this.failures = 0;
15464
15386
  if (!parsed.torn && items.at(-1)?.kind === "complete") this.remove(runId);
15465
15387
  }
15466
15388
  remove(runId) {
@@ -15468,12 +15390,15 @@ var Outbox = class {
15468
15390
  rmSync17(this.file(runId), { force: true });
15469
15391
  rmSync17(this.ackFile(runId), { force: true });
15470
15392
  }
15393
+ /** A failed delivery retries after `retryMs`, doubling up to RETRY_MAX_MS while it keeps failing. */
15471
15394
  scheduleRetry() {
15472
15395
  if (this.retryTimer || this.closed) return;
15396
+ const delay2 = Math.min(RETRY_MAX_MS, this.retryMs * 2 ** this.failures);
15397
+ this.failures = Math.min(this.failures + 1, 16);
15473
15398
  this.retryTimer = setTimeout(() => {
15474
15399
  this.retryTimer = null;
15475
15400
  void this.flushAll();
15476
- }, this.retryMs);
15401
+ }, delay2);
15477
15402
  this.retryTimer.unref();
15478
15403
  }
15479
15404
  /** Drop a run's outbox once everything is delivered and the run is over. */
@@ -15655,9 +15580,9 @@ var RpcServer = class {
15655
15580
  const { socketPath } = this.options;
15656
15581
  rmSync18(socketPath, { force: true });
15657
15582
  const server = createServer2((socket) => this.accept(socket));
15658
- await new Promise((resolve20, reject) => {
15583
+ await new Promise((resolve19, reject) => {
15659
15584
  server.once("error", reject);
15660
- server.listen(socketPath, () => resolve20());
15585
+ server.listen(socketPath, () => resolve19());
15661
15586
  });
15662
15587
  chmodSync(socketPath, 384);
15663
15588
  this.server = server;
@@ -15721,9 +15646,9 @@ var RpcServer = class {
15721
15646
  }
15722
15647
  async close() {
15723
15648
  for (const socket of this.sockets) socket.destroy();
15724
- await new Promise((resolve20) => {
15725
- if (!this.server) return resolve20();
15726
- this.server.close(() => resolve20());
15649
+ await new Promise((resolve19) => {
15650
+ if (!this.server) return resolve19();
15651
+ this.server.close(() => resolve19());
15727
15652
  });
15728
15653
  this.server = null;
15729
15654
  rmSync18(this.options.socketPath, { force: true });
@@ -15951,7 +15876,7 @@ async function startTaskSecretBridge(options) {
15951
15876
  };
15952
15877
  options.signal.addEventListener("abort", close, { once: true });
15953
15878
  try {
15954
- await new Promise((resolve20, reject) => {
15879
+ await new Promise((resolve19, reject) => {
15955
15880
  const cleanup = () => {
15956
15881
  server.off("error", failed);
15957
15882
  options.signal.removeEventListener("abort", cancelled);
@@ -15972,7 +15897,7 @@ async function startTaskSecretBridge(options) {
15972
15897
  }
15973
15898
  server.listen(0, "127.0.0.1", () => {
15974
15899
  cleanup();
15975
- resolve20();
15900
+ resolve19();
15976
15901
  });
15977
15902
  });
15978
15903
  options.signal.throwIfAborted();
@@ -16003,7 +15928,7 @@ async function startTaskSecretBridge(options) {
16003
15928
  // src/agents/chat-files.ts
16004
15929
  import { createHash as createHash10 } from "node:crypto";
16005
15930
  import { lstat as lstat3, mkdir as mkdir3, readFile as readFile4, writeFile as writeFile2 } from "node:fs/promises";
16006
- import { join as join29 } from "node:path";
15931
+ import { join as join28 } from "node:path";
16007
15932
 
16008
15933
  // ../protocol/src/chat-attachments.ts
16009
15934
  import { z as z35 } from "zod";
@@ -16066,7 +15991,7 @@ async function materializeChatFiles(text4, directory, download2) {
16066
15991
  if (bytes.length !== file.size || bytes.toString("base64") !== file.data || createHash10("sha256").update(bytes).digest("hex") !== file.sha256)
16067
15992
  throw Error("Attachment content mismatch");
16068
15993
  const ext = /\.([a-z0-9]{1,12})$/i.exec(file.name)?.[1]?.toLowerCase() ?? "bin";
16069
- const path3 = join29(directory, `${file.id}.${ext}`);
15994
+ const path3 = join28(directory, `${file.id}.${ext}`);
16070
15995
  try {
16071
15996
  await writeFile2(path3, bytes, { flag: "wx", mode: 256 });
16072
15997
  } catch (error) {
@@ -16075,7 +16000,7 @@ async function materializeChatFiles(text4, directory, download2) {
16075
16000
  }
16076
16001
  let textPath;
16077
16002
  if (file.text !== null) {
16078
- textPath = join29(directory, `${file.id}.extracted.txt`);
16003
+ textPath = join28(directory, `${file.id}.extracted.txt`);
16079
16004
  try {
16080
16005
  await writeFile2(textPath, file.text, { flag: "wx", mode: 256 });
16081
16006
  } catch (error) {
@@ -16270,20 +16195,20 @@ function createRunMasker(secrets) {
16270
16195
  // src/runs/supervisor.ts
16271
16196
  import { stdSerializers } from "pino";
16272
16197
  import { createHash as createHash12, randomUUID as randomUUID6 } from "node:crypto";
16273
- import { join as join31, resolve as resolve14 } from "node:path";
16198
+ import { join as join30, resolve as resolve13 } from "node:path";
16274
16199
  import { tmpdir as tmpdir5 } from "node:os";
16275
16200
  import { execa as execa12 } from "execa";
16276
16201
 
16277
16202
  // src/agents/checkpoint.ts
16278
16203
  import { mkdtempSync as mkdtempSync9, rmSync as rmSync19, writeFileSync as writeFileSync9 } from "node:fs";
16279
16204
  import { tmpdir as tmpdir4 } from "node:os";
16280
- import { join as join30 } from "node:path";
16205
+ import { join as join29 } from "node:path";
16281
16206
  import { gunzipSync as gunzipSync2, gzipSync as gzipSync2 } from "node:zlib";
16282
16207
  import { execa as execa11 } from "execa";
16283
16208
 
16284
16209
  // src/coding-workspace/checkpoint.ts
16285
16210
  import { createHash as createHash11 } from "node:crypto";
16286
- import { resolve as resolve13 } from "node:path";
16211
+ import { resolve as resolve12 } from "node:path";
16287
16212
  import { execa as execa10 } from "execa";
16288
16213
  var digest6 = (value) => createHash11("sha256").update(value).digest("hex");
16289
16214
  var oid = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/;
@@ -16317,7 +16242,7 @@ async function captureCheckpointReview(input) {
16317
16242
  const env = {
16318
16243
  ...buildChildEnv({}),
16319
16244
  GIT_DIR: gitDir,
16320
- GIT_COMMON_DIR: resolve13(gitDir, "..", ".."),
16245
+ GIT_COMMON_DIR: resolve12(gitDir, "..", ".."),
16321
16246
  GIT_WORK_TREE: input.worktree,
16322
16247
  GIT_CONFIG_NOSYSTEM: "1",
16323
16248
  GIT_CONFIG_GLOBAL: "/dev/null",
@@ -16504,8 +16429,8 @@ async function takeCheckpoint(options) {
16504
16429
  }
16505
16430
  async function applyCheckpoint(options) {
16506
16431
  const git3 = await pinnedGit(options.repoPath, options.worktree);
16507
- const dir = mkdtempSync9(join30(tmpdir4(), "mikka-checkpoint-"));
16508
- const file = join30(dir, "checkpoint.patch");
16432
+ const dir = mkdtempSync9(join29(tmpdir4(), "mikka-checkpoint-"));
16433
+ const file = join29(dir, "checkpoint.patch");
16509
16434
  try {
16510
16435
  const patch = gunzipSync2(Buffer.from(options.checkpoint.patch, "base64"));
16511
16436
  if (!patch.length && options.checkpoint.files === 0) return true;
@@ -16542,7 +16467,53 @@ import { pathToFileURL as pathToFileURL3 } from "node:url";
16542
16467
  var MAX_CONTINUES = 3;
16543
16468
  var MAX_CRASH_RETRIES = 3;
16544
16469
  var MAX_FIX_ROUNDS = 3;
16545
- var DEFAULT_LEASE_MS = RUN_LEASE_MS;
16470
+ var DEFAULT_LEASE_MS = SESSION_LEASE_MS;
16471
+ var MemoryGatewaySocket = class {
16472
+ constructor(server, deviceId) {
16473
+ this.server = server;
16474
+ this.deviceId = deviceId;
16475
+ setTimeout(() => {
16476
+ if (this.readyState !== 0) return;
16477
+ if (!server.online) {
16478
+ this.readyState = 3;
16479
+ this.emit("error", {});
16480
+ return;
16481
+ }
16482
+ this.readyState = 1;
16483
+ server.sockets.add(this);
16484
+ this.emit("open", {});
16485
+ }, 0);
16486
+ }
16487
+ server;
16488
+ deviceId;
16489
+ readyState = 0;
16490
+ listeners = /* @__PURE__ */ new Map();
16491
+ send(data) {
16492
+ if (this.readyState !== 1) throw new Error("socket not open");
16493
+ if (data === "ping") queueMicrotask(() => this.message("pong"));
16494
+ }
16495
+ /** A frame from the server. */
16496
+ message(data) {
16497
+ if (this.readyState === 1) this.emit("message", { data });
16498
+ }
16499
+ close(code) {
16500
+ if (this.readyState >= 2) return;
16501
+ this.readyState = 3;
16502
+ this.server.sockets.delete(this);
16503
+ this.emit("close", { code });
16504
+ }
16505
+ addEventListener(type, listener) {
16506
+ const set = this.listeners.get(type) ?? /* @__PURE__ */ new Set();
16507
+ set.add(listener);
16508
+ this.listeners.set(type, set);
16509
+ }
16510
+ removeEventListener(type, listener) {
16511
+ this.listeners.get(type)?.delete(listener);
16512
+ }
16513
+ emit(type, event) {
16514
+ for (const listener of [...this.listeners.get(type) ?? []]) listener(event);
16515
+ }
16516
+ };
16546
16517
  var MemoryServer = class {
16547
16518
  /** `fixedDeviceId` is handed out on registration (tests, dev). */
16548
16519
  constructor(fixedDeviceId, options = {}) {
@@ -16551,7 +16522,13 @@ var MemoryServer = class {
16551
16522
  }
16552
16523
  fixedDeviceId;
16553
16524
  online = true;
16525
+ /** False: the ticket route refuses like a server without a device gateway. */
16526
+ gateway = true;
16527
+ /** True: a claim needs an open session socket for the device, as on the real server. */
16528
+ requireSession = false;
16554
16529
  devices = /* @__PURE__ */ new Map();
16530
+ /** Open device gateway sockets. */
16531
+ sockets = /* @__PURE__ */ new Set();
16555
16532
  repos = /* @__PURE__ */ new Map();
16556
16533
  runs = /* @__PURE__ */ new Map();
16557
16534
  /** Durable stream per run; the offset is the chunk count. */
@@ -16628,6 +16605,7 @@ var MemoryServer = class {
16628
16605
  patches: []
16629
16606
  });
16630
16607
  this.issueStatus.set(run3.issueId, "in_progress");
16608
+ this.pushWork(deviceId);
16631
16609
  return runId;
16632
16610
  }
16633
16611
  /** A person's message to a running agent; returns its message id. */
@@ -16645,6 +16623,20 @@ var MemoryServer = class {
16645
16623
  const wake = this.wakeCommands;
16646
16624
  this.wakeCommands = [];
16647
16625
  for (const fn of wake) fn();
16626
+ const devices = new Set([...this.stopRequests, ...[...this.inputs.values()].map((input) => input.runId)].flatMap((runId) => this.runs.get(runId)?.deviceId ?? []));
16627
+ for (const deviceId of devices) this.pushWork(deviceId);
16628
+ }
16629
+ /** The gateway's `work` signal to a device's open sockets. */
16630
+ pushWork(deviceId) {
16631
+ for (const socket of [...this.sockets]) if (socket.deviceId === deviceId) socket.message("work");
16632
+ }
16633
+ /** Whether a device holds an open session socket. */
16634
+ sessionOpen(deviceId) {
16635
+ return [...this.sockets].some((socket) => socket.deviceId === deviceId);
16636
+ }
16637
+ /** Drops every open session socket, with a close code (4001: update required). */
16638
+ closeSessions(code) {
16639
+ for (const socket of [...this.sockets]) socket.close(code);
16648
16640
  }
16649
16641
  pendingCommands(deviceId, skip) {
16650
16642
  const active = (runId) => {
@@ -16678,27 +16670,20 @@ var MemoryServer = class {
16678
16670
  ([id5, d]) => d.credential === credential && (!knownDeviceId || id5 === knownDeviceId)
16679
16671
  );
16680
16672
  const deviceId = existing?.[0] ?? this.fixedDeviceId ?? randomUUID5();
16681
- this.devices.set(deviceId, { credential, info });
16673
+ this.devices.set(deviceId, { credential, info, reports: this.devices.get(deviceId)?.reports ?? [] });
16682
16674
  return { deviceId };
16683
16675
  },
16684
- heartbeat: async (deviceId, status3) => {
16676
+ report: async (deviceId, report2) => {
16685
16677
  this.check();
16686
- const device = this.devices.get(deviceId);
16687
- if (device) device.lastHeartbeat = status3;
16688
- const leases = {};
16689
- const revoked = [];
16690
- for (const { runId } of status3.runs) {
16691
- const run3 = this.runs.get(runId);
16692
- if (!run3) continue;
16693
- if (run3.deviceId !== deviceId || isTerminalRunState(run3.state)) {
16694
- revoked.push(runId);
16695
- continue;
16696
- }
16697
- run3.leaseExpiresAt = Date.now() + this.leaseMs;
16698
- leases[runId] = new Date(run3.leaseExpiresAt).toISOString();
16699
- }
16700
- return { leases, ...revoked.length ? { revoked } : {} };
16678
+ this.devices.get(deviceId)?.reports.push(report2);
16679
+ return {};
16680
+ },
16681
+ deviceGateway: async (deviceId) => {
16682
+ this.check();
16683
+ if (!this.gateway) throw new DeviceGatewayRequiredError();
16684
+ return { url: `memory://gateway/${encodeURIComponent(deviceId)}`, protocol: `mikka-ticket-1-${"0".repeat(64)}` };
16701
16685
  },
16686
+ openDeviceGateway: (url) => new MemoryGatewaySocket(this, decodeURIComponent(url.slice("memory://gateway/".length))),
16702
16687
  listRepos: async (deviceId) => {
16703
16688
  this.check();
16704
16689
  return this.repos.get(deviceId) ?? [];
@@ -16709,6 +16694,7 @@ var MemoryServer = class {
16709
16694
  },
16710
16695
  claimRun: async (deviceId, runId) => {
16711
16696
  this.check();
16697
+ if (this.requireSession && !this.sessionOpen(deviceId)) throw new DeviceSessionRequiredError();
16712
16698
  const run3 = this.runs.get(runId);
16713
16699
  if (!run3 || run3.deviceId !== deviceId)
16714
16700
  throw new RunNotPinnedHereError(runId);
@@ -16760,12 +16746,12 @@ var MemoryServer = class {
16760
16746
  this.check();
16761
16747
  let pending = this.pendingCommands(deviceId, skip);
16762
16748
  if (pending.length === 0 && waitSeconds > 0 && !signal?.aborted) {
16763
- await new Promise((resolve20) => {
16764
- const timer = setTimeout(resolve20, waitSeconds * 1e3);
16765
- signal?.addEventListener("abort", () => resolve20(), { once: true });
16749
+ await new Promise((resolve19) => {
16750
+ const timer = setTimeout(resolve19, waitSeconds * 1e3);
16751
+ signal?.addEventListener("abort", () => resolve19(), { once: true });
16766
16752
  this.wakeCommands.push(() => {
16767
16753
  clearTimeout(timer);
16768
- resolve20();
16754
+ resolve19();
16769
16755
  });
16770
16756
  });
16771
16757
  this.check();
@@ -16799,8 +16785,10 @@ var RunSupervisor = class {
16799
16785
  }
16800
16786
  deps;
16801
16787
  active = /* @__PURE__ */ new Map();
16802
- /** Lease expiry per run (ms); runs without a server lease are absent. */
16788
+ /** Server lease expiry per held run (ms); runs without a server lease are absent. */
16803
16789
  leases = /* @__PURE__ */ new Map();
16790
+ /** Set while the device session socket is down: when held runs lose their lease. */
16791
+ sessionDeadline = null;
16804
16792
  stopping = false;
16805
16793
  /** Runs with an assistant message in progress (`start` sent, no `finish`). */
16806
16794
  openMessages = /* @__PURE__ */ new Set();
@@ -16828,61 +16816,42 @@ var RunSupervisor = class {
16828
16816
  };
16829
16817
  }
16830
16818
  liveness(runId) {
16831
- const lease = this.leases.get(runId);
16819
+ const lease = this.leaseExpiry(runId);
16832
16820
  const run3 = this.active.get(runId);
16833
16821
  return {
16834
- ...lease !== void 0 ? { leaseExpiresAt: new Date(lease).toISOString() } : {},
16822
+ ...lease !== void 0 && Number.isFinite(lease) ? { leaseExpiresAt: new Date(lease).toISOString() } : {},
16835
16823
  ...run3 ? { lastProgressAt: new Date(run3.lastProgressAt).toISOString() } : {}
16836
16824
  };
16837
16825
  }
16838
- /** Per-run part of the device heartbeat. */
16839
- heartbeatRuns() {
16840
- return [...this.active].map(([runId, run3]) => ({
16841
- runId,
16842
- lastProgressAt: new Date(run3.lastProgressAt).toISOString(),
16843
- ...this.deps.journal.get(runId)?.assignment.taskSecrets?.grants.length ? {
16844
- secretCapabilities: this.deps.journal.get(runId).assignment.taskSecrets.grants.map((grant) => grant.capability)
16845
- } : {}
16846
- }));
16847
- }
16848
- /** The heartbeat response is trusted server data. Never persist its bearers. */
16849
- renewTaskSecrets(values) {
16850
- for (const [runId, access] of Object.entries(values ?? {})) {
16851
- const active = this.active.get(runId);
16852
- const assignment = this.deps.journal.get(runId)?.assignment;
16853
- if (!active || active.forcedStop || !assignment?.taskSecrets || access.endpoint !== assignment.taskSecrets.endpoint) continue;
16854
- assignment.taskSecrets = { ...access, unavailable: assignment.taskSecrets.unavailable };
16855
- for (const grant of access.grants) this.addCredential(runId, "TASK_SECRET_CAPABILITY", grant.capability);
16856
- }
16826
+ /**
16827
+ * When a held run's local lease ends: its server lease, or the session
16828
+ * deadline while the socket is down. Undefined for a run the server never
16829
+ * leased (local dev runs); Infinity while the session is open.
16830
+ */
16831
+ leaseExpiry(runId) {
16832
+ const lease = this.leases.get(runId);
16833
+ if (lease === void 0) return void 0;
16834
+ return Math.min(lease, this.sessionDeadline ?? Number.POSITIVE_INFINITY);
16857
16835
  }
16858
- /** Applies leases renewed by the server's heartbeat answer. */
16859
- renewLeases(leases) {
16860
- for (const [runId, expiry] of Object.entries(leases)) {
16861
- if (this.active.has(runId)) this.leases.set(runId, Date.parse(expiry));
16862
- }
16836
+ /** The device session socket opened: held runs keep their lease while it stays open. */
16837
+ sessionOpened() {
16838
+ this.sessionDeadline = null;
16863
16839
  }
16864
16840
  /**
16865
- * Stops the runs the server says this device no longer holds. Runs without
16866
- * a server lease (local dev runs) were never the server's to take back.
16841
+ * The device session socket is down since `at`. Held runs stop as
16842
+ * `device_lost` once it stays down for DEVICE_SESSION_LOCAL_GRACE_MS; a
16843
+ * later drop never extends an earlier deadline.
16867
16844
  */
16868
- revokeLeases(runIds, cancelled = []) {
16869
- const explicitStops = new Set(cancelled);
16870
- for (const runId of runIds) {
16871
- const run3 = this.active.get(runId);
16872
- const lease = this.leases.get(runId);
16873
- if (!run3 || run3.forcedStop || lease === void 0) continue;
16874
- if (explicitStops.has(runId) && lease > Date.now()) {
16875
- if (!run3.cancelRequested) void this.requestCancel(runId, run3);
16876
- } else {
16877
- this.forceStop(runId, run3, "device_lost");
16878
- }
16879
- }
16845
+ sessionClosed(at = Date.now()) {
16846
+ if (this.sessionDeadline !== null) return;
16847
+ this.sessionDeadline = at + DEVICE_SESSION_LOCAL_GRACE_MS;
16880
16848
  }
16881
16849
  /**
16882
16850
  * Saves the work in progress of runs that had a tool call since their last
16883
16851
  * checkpoint, or none for `CHECKPOINT_EVERY_MS`, through `save`. The
16884
- * daemon calls it after each heartbeat; a failed save is tried again on
16885
- * the next one.
16852
+ * daemon calls it from its local timer while the device session is open;
16853
+ * a tree that did not change since the last checkpoint is not sent, so an
16854
+ * idle run makes no request. A failed save is tried again on the next call.
16886
16855
  */
16887
16856
  async saveCheckpoints(save, now = Date.now()) {
16888
16857
  for (const [runId, run3] of this.active) {
@@ -16946,12 +16915,12 @@ var RunSupervisor = class {
16946
16915
  run3.safePoint = { session: "exited", observedAt: receipt?.takenAt ?? (/* @__PURE__ */ new Date()).toISOString(), ...checkpoint };
16947
16916
  return checkpoint;
16948
16917
  }
16949
- /** Lease and watchdog pass; the daemon calls it on every tick. */
16918
+ /** Local lease and watchdog pass; the daemon calls it from its local timer (no request). */
16950
16919
  check(now = Date.now()) {
16951
16920
  const stallMs = this.deps.stallMs ?? DEFAULT_STALL_MS;
16952
16921
  for (const [runId, run3] of this.active) {
16953
16922
  if (run3.forcedStop) continue;
16954
- const lease = this.leases.get(runId);
16923
+ const lease = this.leaseExpiry(runId);
16955
16924
  if (lease !== void 0 && now > lease) {
16956
16925
  this.forceStop(runId, run3, "device_lost");
16957
16926
  } else if (now - run3.lastProgressAt > stallMs) {
@@ -17079,10 +17048,10 @@ var RunSupervisor = class {
17079
17048
  activeRunIds() {
17080
17049
  return [...this.active.keys()];
17081
17050
  }
17082
- /** Computer operations require a live run and a current server lease. */
17051
+ /** Computer operations require a live run and a current local lease. */
17083
17052
  computerRunAllowed(runId) {
17084
17053
  const run3 = this.active.get(runId);
17085
- const lease = this.leases.get(runId);
17054
+ const lease = this.leaseExpiry(runId);
17086
17055
  return !this.stopping && Boolean(run3 && !run3.cancelRequested && lease !== void 0 && lease > Date.now());
17087
17056
  }
17088
17057
  /**
@@ -17217,7 +17186,7 @@ var RunSupervisor = class {
17217
17186
  continue;
17218
17187
  }
17219
17188
  if (entry.assignment.leaseExpiresAt)
17220
- this.leases.set(entry.assignment.runId, Date.now() + DEFAULT_LEASE_MS);
17189
+ this.leases.set(entry.assignment.runId, Number.POSITIVE_INFINITY);
17221
17190
  this.launch(entry.assignment.runId, repo);
17222
17191
  }
17223
17192
  }
@@ -17232,7 +17201,7 @@ var RunSupervisor = class {
17232
17201
  held: this.active.get(runId) === run3,
17233
17202
  state: this.deps.journal.get(runId)?.state,
17234
17203
  stopped: this.stopping || run3.cancelRequested || run3.abort.signal.aborted,
17235
- lease: this.leases.get(runId)
17204
+ lease: this.leaseExpiry(runId)
17236
17205
  });
17237
17206
  check();
17238
17207
  if (run3.toolApproval.revoked) throw new Error("Run mailbox unavailable");
@@ -17253,7 +17222,7 @@ var RunSupervisor = class {
17253
17222
  const entry = this.deps.journal.get(runId);
17254
17223
  if (splitChatFiles(text4).files.length) {
17255
17224
  if (!entry || !this.deps.downloadChatFile || !this.deps.adapterStateDir) throw Error("Run attachments unavailable");
17256
- text4 = await materializeChatFiles(text4, join31(this.deps.adapterStateDir, "inputs", runId), (id5) => this.deps.downloadChatFile(entry.assignment, id5, run3.abort.signal));
17225
+ text4 = await materializeChatFiles(text4, join30(this.deps.adapterStateDir, "inputs", runId), (id5) => this.deps.downloadChatFile(entry.assignment, id5, run3.abort.signal));
17257
17226
  }
17258
17227
  await run3.session.send(text4, mode);
17259
17228
  }
@@ -17283,9 +17252,9 @@ var RunSupervisor = class {
17283
17252
  run3.abort.abort();
17284
17253
  }
17285
17254
  let timer;
17286
- const grace = new Promise((resolve20) => {
17255
+ const grace = new Promise((resolve19) => {
17287
17256
  timer = setTimeout(
17288
- resolve20,
17257
+ resolve19,
17289
17258
  this.deps.stopGraceMs ?? DEFAULT_STOP_GRACE_MS
17290
17259
  );
17291
17260
  });
@@ -17593,7 +17562,7 @@ var RunSupervisor = class {
17593
17562
  /** Only the local lease and pushed stop state govern host finishing work. */
17594
17563
  assertFinishingRunLive(runId, signal) {
17595
17564
  const run3 = this.active.get(runId);
17596
- const lease = this.leases.get(runId);
17565
+ const lease = this.leaseExpiry(runId);
17597
17566
  if (run3 && !run3.forcedStop && lease !== void 0 && lease <= Date.now())
17598
17567
  this.forceStop(runId, run3, "device_lost");
17599
17568
  signal.throwIfAborted();
@@ -17612,11 +17581,11 @@ var RunSupervisor = class {
17612
17581
  if (configured.length === 0) return void 0;
17613
17582
  const loaded = [];
17614
17583
  if (this.deps.adapterStateDir) {
17615
- const dir = join31(runPaths(this.deps.adapterStateDir, runId).runDir, PROFILE_SKILLS_DIR, PROFILE_SKILL_LOADS_DIR);
17584
+ const dir = join30(runPaths(this.deps.adapterStateDir, runId).runDir, PROFILE_SKILLS_DIR, PROFILE_SKILL_LOADS_DIR);
17616
17585
  try {
17617
17586
  for (const name of readdirSync8(dir).sort()) {
17618
17587
  if (!name.endsWith(".json") || loaded.length >= configured.length) continue;
17619
- const file = join31(dir, name), meta = lstatSync11(file, { throwIfNoEntry: false });
17588
+ const file = join30(dir, name), meta = lstatSync11(file, { throwIfNoEntry: false });
17620
17589
  if (!meta?.isFile() || meta.isSymbolicLink() || meta.nlink !== 1 || meta.size < 2 || meta.size > 4096) continue;
17621
17590
  const receipt = profileSkillLoadReceiptSchema.safeParse(JSON.parse(readFileSync14(file, "utf8")));
17622
17591
  if (!receipt.success || loaded.some((item) => item.id === receipt.data.id)) continue;
@@ -17760,7 +17729,7 @@ var RunSupervisor = class {
17760
17729
  try {
17761
17730
  return await withRunGitCredentials(
17762
17731
  assignment,
17763
- runPaths(this.deps.adapterStateDir ?? join31(tmpdir5(), "mikka-run-state"), runId).privateDir,
17732
+ runPaths(this.deps.adapterStateDir ?? join30(tmpdir5(), "mikka-run-state"), runId).privateDir,
17764
17733
  (env) => this.deps.worktrees.fetchBranch(
17765
17734
  repo.path,
17766
17735
  repo.push?.remote ?? "origin",
@@ -17910,8 +17879,8 @@ var RunSupervisor = class {
17910
17879
  });
17911
17880
  if (readAbort) {
17912
17881
  let allowEffects, refuseEffects;
17913
- const entryReady = new Promise((resolve20, reject) => {
17914
- allowEffects = resolve20;
17882
+ const entryReady = new Promise((resolve19, reject) => {
17883
+ allowEffects = resolve19;
17915
17884
  refuseEffects = reject;
17916
17885
  });
17917
17886
  const authorized = Promise.all([policyReady, entryReady]);
@@ -17922,7 +17891,7 @@ var RunSupervisor = class {
17922
17891
  }
17923
17892
  await policyReady;
17924
17893
  verifySkillAssignment(assignment);
17925
- if (assignment.skillReceipt && (this.leases.get(runId) ?? 0) <= Date.now())
17894
+ if (assignment.skillReceipt && (this.leaseExpiry(runId) ?? 0) <= Date.now())
17926
17895
  throw new Error("Receipted Skill assignment requires a current server lease");
17927
17896
  if (assignment.skillReceipt?.artifact.registryId === "mikka-team") {
17928
17897
  if (!this.deps.revalidateSkillAssignment) throw new Error("Current team Skill authorization unavailable");
@@ -17944,7 +17913,7 @@ var RunSupervisor = class {
17944
17913
  }
17945
17914
  run3.repositoryPreparing?.allowEffects();
17946
17915
  const checkMailbox = () => {
17947
- const lease = this.leases.get(runId);
17916
+ const lease = this.leaseExpiry(runId);
17948
17917
  const current = this.deps.journal.get(runId);
17949
17918
  assertMailboxRunAuthority({ held: this.active.get(runId) === run3, state: current?.state, stopped: this.stopping || run3.cancelRequested || run3.abort.signal.aborted, lease });
17950
17919
  };
@@ -18153,7 +18122,7 @@ var RunSupervisor = class {
18153
18122
  let followUp = assignment.followUp;
18154
18123
  if (splitChatFiles(prompt).files.length || followUp && splitChatFiles(followUp).files.length) {
18155
18124
  if (!this.deps.downloadChatFile || !this.deps.adapterStateDir) throw Error("Run attachments unavailable");
18156
- const directory = join31(this.deps.adapterStateDir, "inputs", runId);
18125
+ const directory = join30(this.deps.adapterStateDir, "inputs", runId);
18157
18126
  const download2 = (id5) => this.deps.downloadChatFile(assignment, id5, run3.abort.signal);
18158
18127
  prompt = await materializeChatFiles(prompt, directory, download2);
18159
18128
  if (followUp) followUp = await materializeChatFiles(followUp, directory, download2);
@@ -18166,7 +18135,7 @@ var RunSupervisor = class {
18166
18135
  gitWritePaths: await worktreeGitWritePaths(repo.path, worktree, runId)
18167
18136
  };
18168
18137
  const resuming = entry.sessionId !== null && adapter.capabilities.supportsResume;
18169
- const inEarlierWorktree = continued !== null || entry.worktree !== null && resolve14(entry.worktree) !== resolve14(this.deps.worktrees.pathFor(runId));
18138
+ const inEarlierWorktree = continued !== null || entry.worktree !== null && resolve13(entry.worktree) !== resolve13(this.deps.worktrees.pathFor(runId));
18170
18139
  const continueSession = !resuming && assignment.resumeSessionId && assignment.continuesRunId && inEarlierWorktree && adapter.capabilities.supportsResume ? {
18171
18140
  sessionId: assignment.resumeSessionId,
18172
18141
  runId: assignment.continuesRunId,
@@ -18222,7 +18191,7 @@ var RunSupervisor = class {
18222
18191
  if (!this.deps.adapterStateDir || assignment.harness === "mock" || !session.sessionId || resuming && session.sessionId !== entry.sessionId || assignment.requireSessionResume && session.sessionId !== assignment.resumeSessionId)
18223
18192
  throw new Error("Skill mount requires the actual original harness session");
18224
18193
  verifySkillAssignment(assignment);
18225
- const file = join31(
18194
+ const file = join30(
18226
18195
  runPaths(this.deps.adapterStateDir, runId).runDir,
18227
18196
  SKILLS_DIR,
18228
18197
  skillSlug(assignment.skills[0].name),
@@ -18424,10 +18393,10 @@ function trackParts(open5, chunk) {
18424
18393
  }
18425
18394
  var ABORTED = /* @__PURE__ */ Symbol("aborted");
18426
18395
  function abortPromise(signal) {
18427
- return new Promise((resolve20) => {
18428
- if (signal.aborted) resolve20(ABORTED);
18396
+ return new Promise((resolve19) => {
18397
+ if (signal.aborted) resolve19(ABORTED);
18429
18398
  else
18430
- signal.addEventListener("abort", () => resolve20(ABORTED), { once: true });
18399
+ signal.addEventListener("abort", () => resolve19(ABORTED), { once: true });
18431
18400
  });
18432
18401
  }
18433
18402
  function pickAgentReport(agent) {
@@ -18541,9 +18510,13 @@ function fixedCandidateCheck(assignment) {
18541
18510
 
18542
18511
  // src/device-gateway.ts
18543
18512
  var DEVICE_GATEWAY_PING = "ping";
18544
- var DEVICE_GATEWAY_PING_MS = 3e4;
18513
+ var DEVICE_GATEWAY_PING_MS = 1e4;
18514
+ var DEVICE_GATEWAY_SILENCE_MS = 3e4;
18545
18515
  var DEVICE_GATEWAY_HANDSHAKE_MS = 1e4;
18546
- var DEVICE_GATEWAY_PONG_TIMEOUT_MS = 9e4;
18516
+ var DEVICE_GATEWAY_RETRY_MIN_MS = 500;
18517
+ var DEVICE_GATEWAY_RETRY_MAX_MS = 3e4;
18518
+ var DEVICE_GATEWAY_STABLE_MS = 6e4;
18519
+ var DEVICE_GATEWAY_UPDATE_REQUIRED_CODE = 4001;
18547
18520
  var DeviceGatewayClosedError = class extends Error {
18548
18521
  code;
18549
18522
  constructor(code) {
@@ -18553,12 +18526,13 @@ var DeviceGatewayClosedError = class extends Error {
18553
18526
  };
18554
18527
  function runDeviceGateway(socket, options) {
18555
18528
  const pingMs = options.pingMs ?? DEVICE_GATEWAY_PING_MS;
18556
- return new Promise((resolve20, reject) => {
18529
+ const silenceMs = options.silenceMs ?? DEVICE_GATEWAY_SILENCE_MS;
18530
+ return new Promise((resolve19, reject) => {
18557
18531
  let settled = false;
18558
18532
  let opened = false;
18559
18533
  let pulling = false;
18560
18534
  let pendingWork = false;
18561
- let lastPong = 0;
18535
+ let lastMessage = 0;
18562
18536
  let ping;
18563
18537
  const finish = (error) => {
18564
18538
  if (settled) return;
@@ -18572,7 +18546,7 @@ function runDeviceGateway(socket, options) {
18572
18546
  } catch {
18573
18547
  }
18574
18548
  if (error && !options.signal.aborted) reject(error);
18575
- else resolve20();
18549
+ else resolve19();
18576
18550
  };
18577
18551
  const work = () => {
18578
18552
  if (settled) return;
@@ -18604,11 +18578,11 @@ function runDeviceGateway(socket, options) {
18604
18578
  if (settled || opened) return;
18605
18579
  opened = true;
18606
18580
  clearTimeout(handshake);
18607
- lastPong = performance.now();
18581
+ lastMessage = performance.now();
18608
18582
  options.onOpen?.();
18609
18583
  ping = setInterval(() => {
18610
- if (performance.now() - lastPong >= DEVICE_GATEWAY_PONG_TIMEOUT_MS) {
18611
- finish(new Error("device gateway pong timed out"));
18584
+ if (performance.now() - lastMessage >= silenceMs) {
18585
+ finish(new Error("device gateway went quiet"));
18612
18586
  return;
18613
18587
  }
18614
18588
  try {
@@ -18621,7 +18595,7 @@ function runDeviceGateway(socket, options) {
18621
18595
  }],
18622
18596
  ["message", (event) => {
18623
18597
  if (!opened || settled) return;
18624
- if (event.data === "pong") lastPong = performance.now();
18598
+ lastMessage = performance.now();
18625
18599
  if (event.data === "work") signalWork();
18626
18600
  }],
18627
18601
  ["close", (event) => finish(new DeviceGatewayClosedError(event.code))],
@@ -18637,10 +18611,106 @@ function openDeviceGateway(url, protocol) {
18637
18611
  const Socket = globalThis.WebSocket;
18638
18612
  return new Socket(url, [protocol]);
18639
18613
  }
18614
+ function deviceGatewayRetryDelay(failures, random = Math.random) {
18615
+ const ceiling = Math.min(DEVICE_GATEWAY_RETRY_MAX_MS, DEVICE_GATEWAY_RETRY_MIN_MS * 2 ** Math.max(0, failures - 1));
18616
+ return Math.max(DEVICE_GATEWAY_RETRY_MIN_MS, ceiling * (0.5 + random() * 0.5));
18617
+ }
18618
+ var DeviceSession = class {
18619
+ stopped = new AbortController();
18620
+ attempt = null;
18621
+ wakeUp = null;
18622
+ skipBackoff = false;
18623
+ loop = null;
18624
+ options;
18625
+ constructor(options) {
18626
+ this.options = options;
18627
+ }
18628
+ start() {
18629
+ return this.loop ??= this.run();
18630
+ }
18631
+ /**
18632
+ * Close the current socket and dial again: after the usual backoff, or at
18633
+ * once with `now` (the credential changed, so the old backoff means nothing).
18634
+ */
18635
+ redial(now = false) {
18636
+ if (now) {
18637
+ this.skipBackoff = true;
18638
+ this.wakeUp?.();
18639
+ }
18640
+ this.attempt?.abort();
18641
+ }
18642
+ /** Cut a backoff wait short: something the next attempt needed just arrived. */
18643
+ wake() {
18644
+ this.wakeUp?.();
18645
+ }
18646
+ stop() {
18647
+ this.stopped.abort();
18648
+ this.attempt?.abort();
18649
+ this.wakeUp?.();
18650
+ return this.loop ?? Promise.resolve();
18651
+ }
18652
+ async run() {
18653
+ let failures = 0;
18654
+ const { signal } = this.stopped;
18655
+ while (!signal.aborted) {
18656
+ this.skipBackoff = false;
18657
+ const attempt = new AbortController();
18658
+ this.attempt = attempt;
18659
+ let openedAt;
18660
+ let failure2;
18661
+ try {
18662
+ const { url, protocol } = await this.options.ticket(attempt.signal);
18663
+ if (attempt.signal.aborted) throw new DeviceGatewayClosedError();
18664
+ const socket = (this.options.open ?? openDeviceGateway)(url, protocol);
18665
+ await runDeviceGateway(socket, {
18666
+ signal: attempt.signal,
18667
+ onOpen: () => {
18668
+ openedAt = performance.now();
18669
+ this.options.onOpen();
18670
+ },
18671
+ onWorkAvailable: this.options.onWorkAvailable,
18672
+ onWork: () => this.options.onWork(attempt.signal)
18673
+ });
18674
+ failure2 = new DeviceGatewayClosedError();
18675
+ } catch (error) {
18676
+ failure2 = error;
18677
+ } finally {
18678
+ attempt.abort();
18679
+ if (this.attempt === attempt) this.attempt = null;
18680
+ }
18681
+ this.options.onClose(failure2, openedAt !== void 0);
18682
+ if (signal.aborted) return;
18683
+ const verdict = this.options.verdict?.(failure2) ?? "redial";
18684
+ if (verdict === "stop") return;
18685
+ if (openedAt !== void 0 && performance.now() - openedAt >= DEVICE_GATEWAY_STABLE_MS) failures = 0;
18686
+ if (this.skipBackoff) {
18687
+ this.skipBackoff = false;
18688
+ failures = 0;
18689
+ continue;
18690
+ }
18691
+ failures = Math.min(failures + 1, 32);
18692
+ await this.pause(verdict === "slow" ? DEVICE_GATEWAY_RETRY_MAX_MS : deviceGatewayRetryDelay(failures, this.options.random));
18693
+ }
18694
+ }
18695
+ /** A redial backoff, not a poll: it ends early on `wake` or `stop`. */
18696
+ pause(ms2) {
18697
+ return new Promise((resolve19) => {
18698
+ const done = () => {
18699
+ clearTimeout(timer);
18700
+ this.wakeUp = null;
18701
+ resolve19();
18702
+ };
18703
+ const timer = setTimeout(done, ms2);
18704
+ this.wakeUp = done;
18705
+ if (this.stopped.signal.aborted) done();
18706
+ });
18707
+ }
18708
+ };
18640
18709
 
18641
18710
  // src/server-link-http.ts
18642
18711
  import { z as z36 } from "zod";
18643
18712
  var deviceSessionRejection = z36.object({ error: z36.enum(["Unauthorized", "authRequired"]) }).strict();
18713
+ var deviceSessionHeaders = { [DEVICE_SESSION_HEADER]: String(DEVICE_SESSION_VERSION) };
18644
18714
  var SessionRejectedError = class extends DaemonError {
18645
18715
  constructor() {
18646
18716
  super(
@@ -18656,7 +18726,7 @@ import { open as open2, readFile as readFile5, realpath as realpath2 } from "nod
18656
18726
  import { execFile as execFile7 } from "node:child_process";
18657
18727
  import { promisify as promisify7 } from "node:util";
18658
18728
  import { createHash as createHash13 } from "node:crypto";
18659
- import { extname, resolve as resolve15 } from "node:path";
18729
+ import { extname, resolve as resolve14 } from "node:path";
18660
18730
  var execute2 = promisify7(execFile7);
18661
18731
  var hash = (value) => createHash13("sha256").update(value).digest("hex");
18662
18732
  var denied = () => new CodingWorkspaceError("workspace_path_unavailable");
@@ -18705,9 +18775,9 @@ async function safeFile(root, path3, use) {
18705
18775
  parent = handle;
18706
18776
  }
18707
18777
  const selected = await realpath2(`/proc/self/fd/${parent.fd}`);
18708
- if (selected !== resolve15(root.path, path3) || await realpath2(root.gitPath) !== root.path) throw denied();
18778
+ if (selected !== resolve14(root.path, path3) || await realpath2(root.gitPath) !== root.path) throw denied();
18709
18779
  const result = await use(parent);
18710
- 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");
18780
+ 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");
18711
18781
  return result;
18712
18782
  } catch (cause) {
18713
18783
  if (cause instanceof CodingWorkspaceError) throw cause;
@@ -18746,7 +18816,7 @@ async function readWorkspaceReceipt(command, entry) {
18746
18816
  const remote = entry.assignment.remoteUrl ?? entry.assignment.expectedRepoRemote;
18747
18817
  if (!remote || remoteKey(remote) !== identity.repositoryKey) throw new CodingWorkspaceError("workspace_checkout_unavailable");
18748
18818
  if (process.platform !== "linux") throw new CodingWorkspaceError("workspace_unsupported");
18749
- const path3 = resolve15(entry.worktree);
18819
+ const path3 = resolve14(entry.worktree);
18750
18820
  if (await realpath2(path3) !== path3) throw new CodingWorkspaceError("workspace_checkout_unavailable");
18751
18821
  directory = await open2(path3, constants7.O_RDONLY | constants7.O_DIRECTORY | constants7.O_NOFOLLOW);
18752
18822
  const root = {
@@ -18908,7 +18978,7 @@ async function readWorkspaceReceipt(command, entry) {
18908
18978
  import { constants as constants8 } from "node:fs";
18909
18979
  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";
18910
18980
  import { createHash as createHash14 } from "node:crypto";
18911
- import { resolve as resolve16, dirname as dirname16, join as join32, posix } from "node:path";
18981
+ import { resolve as resolve15, dirname as dirname15, join as join31, posix } from "node:path";
18912
18982
  import { tmpdir as tmpdir6 } from "node:os";
18913
18983
  import { execa as execa13 } from "execa";
18914
18984
 
@@ -19002,7 +19072,7 @@ async function gitFor(repoPath, root, signal) {
19002
19072
  const env = {
19003
19073
  ...buildChildEnv({}),
19004
19074
  GIT_DIR: gitDir,
19005
- GIT_COMMON_DIR: resolve16(gitDir, "..", ".."),
19075
+ GIT_COMMON_DIR: resolve15(gitDir, "..", ".."),
19006
19076
  // cwd is resolved while the parent's FD is still open. The child does not
19007
19077
  // inherit that numeric descriptor, so its work tree must be relative to cwd.
19008
19078
  GIT_WORK_TREE: ".",
@@ -19086,12 +19156,12 @@ async function conversionSettings(git3) {
19086
19156
  const host = buildChildEnv({});
19087
19157
  const defaults = ["/etc/gitattributes", "/usr/etc/gitattributes", "/usr/local/etc/gitattributes"];
19088
19158
  if (!external) {
19089
- const configHome = host.XDG_CONFIG_HOME || (host.HOME ? join32(host.HOME, ".config") : void 0);
19090
- if (configHome) defaults.push(join32(configHome, "git", "attributes"));
19159
+ const configHome = host.XDG_CONFIG_HOME || (host.HOME ? join31(host.HOME, ".config") : void 0);
19160
+ if (configHome) defaults.push(join31(configHome, "git", "attributes"));
19091
19161
  }
19092
- const info = join32(git3.commonDir, "info");
19162
+ const info = join31(git3.commonDir, "info");
19093
19163
  if (await existsWithoutReading(info)) {
19094
- if (!(await lstat4(info)).isDirectory() || await existsWithoutReading(join32(info, "attributes")))
19164
+ if (!(await lstat4(info)).isDirectory() || await existsWithoutReading(join31(info, "attributes")))
19095
19165
  throw new CodingWorkspaceError("workspace_unsupported");
19096
19166
  }
19097
19167
  for (const path3 of defaults) if (await existsWithoutReading(path3)) throw new CodingWorkspaceError("workspace_unsupported");
@@ -19137,10 +19207,10 @@ async function workingConversion(git3, root, paths, head, signal, budget) {
19137
19207
  throw new CodingWorkspaceError("workspace_unsupported");
19138
19208
  attributeBytes.set(path3, bytes);
19139
19209
  }
19140
- const directory = await mkdtemp2(join32(tmpdir6(), "mikka-diff-attributes-"));
19210
+ const directory = await mkdtemp2(join31(tmpdir6(), "mikka-diff-attributes-"));
19141
19211
  const actions = /* @__PURE__ */ new Map();
19142
19212
  try {
19143
- const gitDir = join32(directory, "git"), worktree = join32(directory, "worktree");
19213
+ const gitDir = join31(directory, "git"), worktree = join31(directory, "worktree");
19144
19214
  await mkdir4(worktree, { mode: 448 });
19145
19215
  const env = {
19146
19216
  ...buildChildEnv({}),
@@ -19160,8 +19230,8 @@ async function workingConversion(git3, root, paths, head, signal, budget) {
19160
19230
  killDescendants: true
19161
19231
  });
19162
19232
  for (const [path3, bytes] of attributeBytes) {
19163
- const target = join32(worktree, path3);
19164
- await mkdir4(dirname16(target), { recursive: true, mode: 448 });
19233
+ const target = join31(worktree, path3);
19234
+ await mkdir4(dirname15(target), { recursive: true, mode: 448 });
19165
19235
  await writeFile3(target, bytes, { mode: 384, flag: "wx" });
19166
19236
  }
19167
19237
  const attributes = ["text", "eol", "crlf", "filter", "working-tree-encoding", "ident"];
@@ -19426,7 +19496,7 @@ async function readWorkspaceDiffReceipt(command, entry, repoPath) {
19426
19496
  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)
19427
19497
  throw new CodingWorkspaceError("workspace_checkout_unavailable");
19428
19498
  if (process.platform !== "linux") throw new CodingWorkspaceError("workspace_unsupported");
19429
- const path3 = resolve16(entry.worktree);
19499
+ const path3 = resolve15(entry.worktree);
19430
19500
  if (await realpath3(path3) !== path3) throw new CodingWorkspaceError("workspace_checkout_unavailable");
19431
19501
  directory = await open3(path3, constants8.O_RDONLY | constants8.O_DIRECTORY | constants8.O_NOFOLLOW);
19432
19502
  const root = {
@@ -19496,7 +19566,7 @@ async function readWorkspaceRevertPreview(command, entry, repoPath) {
19496
19566
  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)
19497
19567
  throw new CodingWorkspaceError("workspace_checkout_unavailable");
19498
19568
  if (process.platform !== "linux") throw new CodingWorkspaceError("workspace_unsupported");
19499
- const path3 = resolve16(entry.worktree);
19569
+ const path3 = resolve15(entry.worktree);
19500
19570
  if (await realpath3(path3) !== path3) throw new CodingWorkspaceError("workspace_checkout_unavailable");
19501
19571
  directory = await open3(path3, constants8.O_RDONLY | constants8.O_DIRECTORY | constants8.O_NOFOLLOW);
19502
19572
  const root = {
@@ -19568,7 +19638,7 @@ async function readWorkspaceRevertPreview(command, entry, repoPath) {
19568
19638
  import { constants as constants9 } from "node:fs";
19569
19639
  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";
19570
19640
  import { createHash as createHash15 } from "node:crypto";
19571
- import { join as join33, resolve as resolve17 } from "node:path";
19641
+ import { join as join32, resolve as resolve16 } from "node:path";
19572
19642
  import { tmpdir as tmpdir7 } from "node:os";
19573
19643
  import { execa as execa14 } from "execa";
19574
19644
 
@@ -19724,7 +19794,7 @@ async function openPinnedRoot(command, entry) {
19724
19794
  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)
19725
19795
  throw unavailable4();
19726
19796
  if (process.platform !== "linux") throw new CodingWorkspaceError("workspace_unsupported");
19727
- const path3 = resolve17(entry.worktree);
19797
+ const path3 = resolve16(entry.worktree);
19728
19798
  if (await realpath4(path3) !== path3) throw unavailable4();
19729
19799
  const directory = await open4(path3, constants9.O_RDONLY | constants9.O_DIRECTORY | constants9.O_NOFOLLOW);
19730
19800
  try {
@@ -20164,7 +20234,7 @@ function runGit(cwd, args, env, signal, maximum = 8 * 1024 * 1024) {
20164
20234
  }
20165
20235
  async function readTempFile(worktree, path3) {
20166
20236
  if (!visibleWorkspacePath(path3)) throw new CodingWorkspaceError("workspace_path_unavailable");
20167
- const full = join33(worktree, ...path3.split("/"));
20237
+ const full = join32(worktree, ...path3.split("/"));
20168
20238
  if (!full.startsWith(`${worktree}/`)) throw new CodingWorkspaceError("workspace_path_unavailable");
20169
20239
  try {
20170
20240
  const stat3 = await lstat5(full);
@@ -20185,8 +20255,8 @@ async function dryRunCheckpoint(git3, root, identity, statusBase, patchBase, pat
20185
20255
  } catch (error) {
20186
20256
  throw new CodingWorkspaceError("workspace_unsupported", { cause: error });
20187
20257
  }
20188
- const parent = await mkdtemp3(join33(tmpdir7(), "mikka-git-restore-"));
20189
- const worktree = join33(parent, "wt"), patchFile = join33(parent, "checkpoint.patch");
20258
+ const parent = await mkdtemp3(join32(tmpdir7(), "mikka-git-restore-"));
20259
+ const worktree = join32(parent, "wt"), patchFile = join32(parent, "checkpoint.patch");
20190
20260
  try {
20191
20261
  await writeFile4(patchFile, patch, { mode: 384 });
20192
20262
  await runGit(git3.commonDir, ["worktree", "add", "--detach", "--quiet", worktree, head], commonEnv(git3), signal);
@@ -20468,7 +20538,7 @@ async function handleWorkspaceGitRequest(command, entry, repoPath) {
20468
20538
  // src/repositories.ts
20469
20539
  import { createHash as createHash16, randomUUID as randomUUID7 } from "node:crypto";
20470
20540
  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";
20471
- import { dirname as dirname17, join as join34, resolve as resolve18 } from "node:path";
20541
+ import { dirname as dirname16, join as join33, resolve as resolve17 } from "node:path";
20472
20542
  import { setTimeout as delay } from "node:timers/promises";
20473
20543
  import { execa as execa15 } from "execa";
20474
20544
  import lockfile2 from "proper-lockfile";
@@ -20492,8 +20562,8 @@ var RepositoryCache = class {
20492
20562
  retainResources;
20493
20563
  pathFor(remoteUrl) {
20494
20564
  const { key: key2 } = normalizeRepository(remoteUrl, { allowFile: this.allowFile });
20495
- const path3 = resolve18(this.root, "v2", createHash16("sha256").update(key2).digest("hex"));
20496
- if (!isInside(resolve18(this.root), path3) || path3 === resolve18(this.root)) throw new Error("Invalid repository cache path");
20565
+ const path3 = resolve17(this.root, "v2", createHash16("sha256").update(key2).digest("hex"));
20566
+ if (!isInside(resolve17(this.root), path3) || path3 === resolve17(this.root)) throw new Error("Invalid repository cache path");
20497
20567
  return path3;
20498
20568
  }
20499
20569
  /** Serialize clone/fetch against the same cache, including other processes. */
@@ -20501,7 +20571,7 @@ var RepositoryCache = class {
20501
20571
  signal?.throwIfAborted();
20502
20572
  const { remoteUrl: remote } = normalizeRepository(remoteUrl, { allowFile: this.allowFile });
20503
20573
  const path3 = this.pathFor(remote);
20504
- this.ensureParents(dirname17(path3));
20574
+ this.ensureParents(dirname16(path3));
20505
20575
  const release = await this.lock(path3, signal);
20506
20576
  try {
20507
20577
  return await withRepoConfig(path3, () => this.update(path3, remote, signal, env, diagnostics));
@@ -20540,7 +20610,7 @@ var RepositoryCache = class {
20540
20610
  } else {
20541
20611
  this.assertClone(path3);
20542
20612
  await git3(["remote", "set-url", "origin", remote], path3);
20543
- const depth = existsSync7(join34(path3, ".git", "shallow")) ? ["--depth=50"] : [];
20613
+ const depth = existsSync7(join33(path3, ".git", "shallow")) ? ["--depth=50"] : [];
20544
20614
  await git3(["fetch", ...depth, ...this.retainResources ? [] : ["--prune"], "--no-tags", "--no-recurse-submodules", "--no-write-fetch-head", "origin"], path3);
20545
20615
  }
20546
20616
  this.assertClone(path3);
@@ -20632,28 +20702,28 @@ var RepositoryCache = class {
20632
20702
  paths() {
20633
20703
  const visit = (path3) => {
20634
20704
  if (!existsSync7(path3) || lstatSync12(path3).isSymbolicLink()) return [];
20635
- if (existsSync7(join34(path3, ".git"))) {
20705
+ if (existsSync7(join33(path3, ".git"))) {
20636
20706
  this.assertClone(path3);
20637
20707
  return [path3];
20638
20708
  }
20639
- return readdirSync9(path3, { withFileTypes: true }).flatMap((entry) => entry.isDirectory() && !entry.name.endsWith(".lock") && !entry.name.includes(".clone-") ? visit(join34(path3, entry.name)) : []);
20709
+ return readdirSync9(path3, { withFileTypes: true }).flatMap((entry) => entry.isDirectory() && !entry.name.endsWith(".lock") && !entry.name.includes(".clone-") ? visit(join33(path3, entry.name)) : []);
20640
20710
  };
20641
- return visit(resolve18(this.root));
20711
+ return visit(resolve17(this.root));
20642
20712
  }
20643
20713
  ensureParents(path3) {
20644
20714
  mkdirSync17(this.root, { recursive: true, mode: 448 });
20645
20715
  if (lstatSync12(this.root).isSymbolicLink()) throw new Error("Repository cache contains a symlink");
20646
20716
  const root = realpathSync13(this.root);
20647
- let current = resolve18(this.root);
20717
+ let current = resolve17(this.root);
20648
20718
  for (const part of path3.slice(current.length + 1).split("/").filter(Boolean)) {
20649
- current = join34(current, part);
20719
+ current = join33(current, part);
20650
20720
  if (existsSync7(current) && lstatSync12(current).isSymbolicLink()) throw new Error("Repository cache contains a symlink");
20651
20721
  mkdirSync17(current, { recursive: true, mode: 448 });
20652
20722
  if (!isInside(root, realpathSync13(current))) throw new Error("Repository cache escapes its directory");
20653
20723
  }
20654
20724
  }
20655
20725
  assertClone(path3) {
20656
- if (lstatSync12(path3).isSymbolicLink() || !lstatSync12(join34(path3, ".git")).isDirectory() || lstatSync12(join34(path3, ".git")).isSymbolicLink()) throw new Error("Repository cache is not a standard clone");
20726
+ if (lstatSync12(path3).isSymbolicLink() || !lstatSync12(join33(path3, ".git")).isDirectory() || lstatSync12(join33(path3, ".git")).isSymbolicLink()) throw new Error("Repository cache is not a standard clone");
20657
20727
  if (!isInside(realpathSync13(this.root), realpathSync13(path3))) throw new Error("Repository cache escapes its directory");
20658
20728
  }
20659
20729
  async lock(path3, signal) {
@@ -20759,7 +20829,7 @@ async function prepareRunRepository(repositories, privateDir, assignment, signal
20759
20829
  import { randomUUID as randomUUID8 } from "node:crypto";
20760
20830
  import { spawn as spawn5 } from "node:child_process";
20761
20831
  import { existsSync as existsSync8, mkdirSync as mkdirSync18, realpathSync as realpathSync14 } from "node:fs";
20762
- import { dirname as dirname18, join as join35, resolve as resolve19 } from "node:path";
20832
+ import { dirname as dirname17, join as join34, resolve as resolve18 } from "node:path";
20763
20833
  import { fileURLToPath } from "node:url";
20764
20834
 
20765
20835
  // src/official-cli-timing.ts
@@ -21128,11 +21198,11 @@ async function startCliTimingCollector({ runId, harness, remoteMcpServerCount, d
21128
21198
  server.requestTimeout = 5e3;
21129
21199
  server.headersTimeout = 5e3;
21130
21200
  server.maxConnections = 8;
21131
- await new Promise((resolve20, reject) => {
21201
+ await new Promise((resolve19, reject) => {
21132
21202
  server.once("error", reject);
21133
21203
  server.listen(0, "127.0.0.1", () => {
21134
21204
  server.off("error", reject);
21135
- resolve20();
21205
+ resolve19();
21136
21206
  });
21137
21207
  });
21138
21208
  server.on("error", () => {
@@ -21181,7 +21251,7 @@ async function startCliTimingCollector({ runId, harness, remoteMcpServerCount, d
21181
21251
  unsetEnv,
21182
21252
  mcpHttpObservationUrl: `${origin}${mcpPath}`,
21183
21253
  close: ({ cliExitObserved = false, publish = true } = {}) => closed ??= (async () => {
21184
- await new Promise((resolve20) => {
21254
+ await new Promise((resolve19) => {
21185
21255
  const timer = setTimeout(() => {
21186
21256
  collector.truncate();
21187
21257
  mcpCollector.truncate();
@@ -21189,7 +21259,7 @@ async function startCliTimingCollector({ runId, harness, remoteMcpServerCount, d
21189
21259
  }, 1e3);
21190
21260
  server.close(() => {
21191
21261
  clearTimeout(timer);
21192
- resolve20();
21262
+ resolve19();
21193
21263
  });
21194
21264
  });
21195
21265
  const official = collector.finish(cliExitObserved), mcp = mcpCollector.finish();
@@ -21227,7 +21297,7 @@ async function runHostedCommand(worktree, script, _readOnly, timeoutMs, signal)
21227
21297
  abort();
21228
21298
  } else chunks.push(chunk);
21229
21299
  };
21230
- const result = await new Promise((resolve20, reject) => {
21300
+ const result = await new Promise((resolve19, reject) => {
21231
21301
  child = spawn5("/bin/sh", ["-c", script], {
21232
21302
  cwd: realpathSync14(worktree),
21233
21303
  env: process.env,
@@ -21237,7 +21307,7 @@ async function runHostedCommand(worktree, script, _readOnly, timeoutMs, signal)
21237
21307
  child.stdout?.on("data", (chunk) => collect("stdout", stdout, chunk));
21238
21308
  child.stderr?.on("data", (chunk) => collect("stderr", stderr, chunk));
21239
21309
  child.once("error", reject);
21240
- child.once("close", (code, term) => resolve20({ code, signal: term }));
21310
+ child.once("close", (code, term) => resolve19({ code, signal: term }));
21241
21311
  child.once("exit", abort);
21242
21312
  signal?.addEventListener("abort", abort, { once: true });
21243
21313
  if (signal?.aborted) abort();
@@ -21363,7 +21433,7 @@ async function createHostedBotRunner(host) {
21363
21433
  if (selected && (!options.model || options.model !== subscription?.first.modelId)) throw Error("binding_mismatch");
21364
21434
  const paths = runPaths(host.stateDir, assignment.runId);
21365
21435
  mkdirSync18(paths.runDir, { recursive: true, mode: 448 });
21366
- const cwd = preparation ? resolve19(options.cwd) : realpathSync14(options.cwd);
21436
+ const cwd = preparation ? resolve18(options.cwd) : realpathSync14(options.cwd);
21367
21437
  const env = Object.fromEntries(Object.entries({ ...process.env, ...options.env, ...assignment.taskEnv }).filter((entry) => typeof entry[1] === "string"));
21368
21438
  if (runDiagnosticsEnabled(assignment.taskEnv, host.collectCliTiming)) env.CLOUD_STARTUP_TIMING = "1";
21369
21439
  const selectedGithub = options.github ?? (assignment.github ? { ...assignment.github, issueId: assignment.issueId, runToken: assignment.mcp?.token } : void 0);
@@ -21394,7 +21464,7 @@ async function createHostedBotRunner(host) {
21394
21464
  });
21395
21465
  Object.assign(env, github.env);
21396
21466
  }
21397
- const ledger = join35(host.stateDir, "native-ledgers", assignment.runId + ".json");
21467
+ const ledger = join34(host.stateDir, "native-ledgers", assignment.runId + ".json");
21398
21468
  const scope = selected && subscription ? {
21399
21469
  runId: assignment.runId,
21400
21470
  bindingId: selected.bindingId,
@@ -21407,12 +21477,12 @@ async function createHostedBotRunner(host) {
21407
21477
  modelId: subscription.first.modelId
21408
21478
  } : void 0;
21409
21479
  if (continuation && existsSync8(ledger)) throw unavailable5("ledger_mismatch");
21410
- const previousLedger = continuation ? join35(host.stateDir, "native-ledgers", continuation.runId + ".json") : ledger;
21480
+ const previousLedger = continuation ? join34(host.stateDir, "native-ledgers", continuation.runId + ".json") : ledger;
21411
21481
  const previous = scope ? readJson(previousLedger) : void 0;
21412
21482
  if (preparation && previous) throw unavailable5("ledger_mismatch");
21413
21483
  const expectedScope = scope && continuation ? { ...scope, runId: continuation.runId } : scope;
21414
21484
  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");
21415
- if (scope) mkdirSync18(dirname18(ledger), { recursive: true, mode: 448 });
21485
+ if (scope) mkdirSync18(dirname17(ledger), { recursive: true, mode: 448 });
21416
21486
  const record3 = async (sessionId) => {
21417
21487
  assertOpen();
21418
21488
  if (scope) writeJsonAtomic(ledger, { scope, sessionId });
@@ -21484,9 +21554,9 @@ async function createHostedBotRunner(host) {
21484
21554
  signal: lifetime.signal
21485
21555
  });
21486
21556
  child.stderr?.resume();
21487
- const exited = new Promise((resolve20) => {
21488
- child.once("exit", (code, signal) => resolve20({ code, signal }));
21489
- child.once("error", () => resolve20({ code: null, signal: null }));
21557
+ const exited = new Promise((resolve19) => {
21558
+ child.once("exit", (code, signal) => resolve19({ code, signal }));
21559
+ child.once("error", () => resolve19({ code: null, signal: null }));
21490
21560
  });
21491
21561
  return {
21492
21562
  process: child,
@@ -21753,14 +21823,14 @@ function normalizeCall(value) {
21753
21823
  return { name, arguments: { direction: args.direction, amount: args.amount, x: args.x, y: args.y } };
21754
21824
  throw new Error("Unsupported tool or arguments");
21755
21825
  }
21756
- function driverArguments(input, platform4 = process.platform) {
21826
+ function driverArguments(input, platform3 = process.platform) {
21757
21827
  const call = normalizeCall(input);
21758
21828
  return call.name === "click" ? {
21759
21829
  ...call.arguments,
21760
21830
  scope: "desktop",
21761
- ...platform4 === "darwin" ? {} : { coordinate_frame: "desktop" },
21831
+ ...platform3 === "darwin" ? {} : { coordinate_frame: "desktop" },
21762
21832
  delivery_mode: "foreground"
21763
- } : ["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;
21833
+ } : ["type_text", "press_key"].includes(call.name) ? { ...call.arguments, scope: "desktop", delivery_mode: "foreground" } : call.name === "scroll" ? { ...call.arguments, scope: "desktop", ...platform3 === "darwin" ? {} : { coordinate_frame: "desktop" }, delivery_mode: "foreground" } : call.arguments;
21764
21834
  }
21765
21835
  async function executeDriver(driver, input, display, leaseGuard, assertLive = () => {
21766
21836
  }, beforeAction) {
@@ -21830,9 +21900,9 @@ async function executeDriver(driver, input, display, leaseGuard, assertLive = ()
21830
21900
  )
21831
21901
  )
21832
21902
  );
21833
- const request2 = (method, params) => new Promise((resolve20, reject) => {
21903
+ const request2 = (method, params) => new Promise((resolve19, reject) => {
21834
21904
  const n = ++id5;
21835
- pending.set(n, { resolve: resolve20, reject });
21905
+ pending.set(n, { resolve: resolve19, reject });
21836
21906
  child.stdin.write(
21837
21907
  JSON.stringify({ jsonrpc: "2.0", id: n, method, params }) + "\n"
21838
21908
  );
@@ -21866,13 +21936,39 @@ async function executeDriver(driver, input, display, leaseGuard, assertLive = ()
21866
21936
  }
21867
21937
 
21868
21938
  // src/computer/broker.mjs
21939
+ var PendingRequests = class extends Map {
21940
+ constructor(changed) {
21941
+ super();
21942
+ this.changed = changed;
21943
+ }
21944
+ set(key2, value) {
21945
+ super.set(key2, value);
21946
+ this.changed?.();
21947
+ return this;
21948
+ }
21949
+ delete(key2) {
21950
+ const had = super.delete(key2);
21951
+ if (had) this.changed?.();
21952
+ return had;
21953
+ }
21954
+ };
21869
21955
  var ComputerBroker = class {
21870
21956
  grants = /* @__PURE__ */ new Map();
21871
21957
  // runId → when its screen recording stops by itself; only set while one runs.
21872
21958
  recordingUntil = /* @__PURE__ */ new Map();
21873
21959
  recordingSteps = /* @__PURE__ */ new Map();
21874
21960
  recordingTimingFailed = /* @__PURE__ */ new Set();
21875
- pending = /* @__PURE__ */ new Map();
21961
+ pendingListeners = /* @__PURE__ */ new Set();
21962
+ pending = new PendingRequests(() => {
21963
+ for (const listener of [...this.pendingListeners]) listener();
21964
+ });
21965
+ /** Calls `listener` whenever a pending review appears or goes; returns the unsubscribe. */
21966
+ onPendingChange(listener) {
21967
+ this.pendingListeners.add(listener);
21968
+ return () => {
21969
+ this.pendingListeners.delete(listener);
21970
+ };
21971
+ }
21876
21972
  sockets = /* @__PURE__ */ new Set();
21877
21973
  suspended = false;
21878
21974
  constructor({
@@ -21948,10 +22044,10 @@ var ComputerBroker = class {
21948
22044
  })();
21949
22045
  });
21950
22046
  });
21951
- await new Promise((resolve20, reject) => {
22047
+ await new Promise((resolve19, reject) => {
21952
22048
  this.server.once("error", reject);
21953
- if (this.transport === "tcp") this.server.listen({ host: "127.0.0.1", port: 0 }, resolve20);
21954
- else this.server.listen(this.socketPath, resolve20);
22049
+ if (this.transport === "tcp") this.server.listen({ host: "127.0.0.1", port: 0 }, resolve19);
22050
+ else this.server.listen(this.socketPath, resolve19);
21955
22051
  });
21956
22052
  if (this.transport === "tcp") this.socketPath = `tcp://127.0.0.1:${this.server.address().port}`;
21957
22053
  else chmodSync2(this.socketPath, 384);
@@ -22037,7 +22133,7 @@ var ComputerBroker = class {
22037
22133
  expiresAt: this.now() + this.ttl
22038
22134
  };
22039
22135
  const digest9 = createHash19("sha256").update(JSON.stringify(request2)).digest("hex");
22040
- return new Promise((resolve20, reject) => {
22136
+ return new Promise((resolve19, reject) => {
22041
22137
  const timer = setTimeout(() => {
22042
22138
  this.pending.delete(request2.id);
22043
22139
  signal?.removeEventListener("abort", cancel);
@@ -22055,7 +22151,7 @@ var ComputerBroker = class {
22055
22151
  assertLive,
22056
22152
  cleanup: () => signal?.removeEventListener("abort", cancel),
22057
22153
  request: { ...request2, digest: digest9 },
22058
- resolve: resolve20,
22154
+ resolve: resolve19,
22059
22155
  reject,
22060
22156
  timer
22061
22157
  });
@@ -22148,7 +22244,7 @@ var ComputerBroker = class {
22148
22244
  async close() {
22149
22245
  this.suspend();
22150
22246
  for (const socket of this.sockets) socket.destroy();
22151
- if (this.server?.listening) await new Promise((resolve20) => this.server.close(resolve20));
22247
+ if (this.server?.listening) await new Promise((resolve19) => this.server.close(resolve19));
22152
22248
  }
22153
22249
  };
22154
22250
 
@@ -22209,100 +22305,87 @@ async function syncWebComputerReviews(broker, deviceId, link, signal) {
22209
22305
  if (signal?.aborted) return;
22210
22306
  await applyWebComputerDecisions(broker, decisions);
22211
22307
  }
22212
- var REVIEW_PRESENCE_MS = 5e3;
22213
22308
  function snapshotKey(requests) {
22214
22309
  return requests.map((row) => `${row.id}:${row.digest}`).sort().join(",");
22215
22310
  }
22216
- async function pollWebComputerReviews(broker, deviceId, link, signal, intervalMs = 1e3, pushes, presenceMs = REVIEW_PRESENCE_MS) {
22311
+ async function followWebComputerReviews(broker, deviceId, link, signal, pushes, onUnreachable) {
22217
22312
  if (!link.syncComputerReviews) throw new Error("Computer review transport unavailable");
22218
- let pushed = false;
22313
+ let pushed = true;
22314
+ let changed = true;
22219
22315
  let synced;
22220
- let syncedAt = 0;
22221
- const unsubscribe = pushes?.subscribe(() => {
22316
+ let wake = null;
22317
+ const nudge = () => {
22318
+ const done = wake;
22319
+ wake = null;
22320
+ done?.();
22321
+ };
22322
+ const offPush = pushes.subscribe(() => {
22222
22323
  pushed = true;
22324
+ nudge();
22325
+ });
22326
+ const offBroker = broker.onPendingChange(() => {
22327
+ changed = true;
22328
+ nudge();
22223
22329
  });
22330
+ const onAbort = () => nudge();
22331
+ signal.addEventListener("abort", onAbort, { once: true });
22224
22332
  try {
22225
22333
  while (!signal.aborted) {
22226
- const snapshot4 = broker.list();
22227
- const pending = snapshot4.length > 0;
22228
- const key2 = snapshotKey(snapshot4);
22229
- const everyCheck = (pushes?.mode("computerReviews") ?? "legacy") !== "push";
22230
- if (key2 !== synced || pending && (pushed || everyCheck || Date.now() - syncedAt >= presenceMs)) {
22231
- pushed = false;
22232
- try {
22233
- await syncWebComputerReviews(broker, deviceId, link, signal);
22234
- synced = key2;
22235
- syncedAt = Date.now();
22236
- } catch {
22334
+ if (pushes.live && (pushed || changed)) {
22335
+ const snapshot4 = broker.list();
22336
+ const key2 = snapshotKey(snapshot4);
22337
+ if (key2 !== synced || pushed && snapshot4.length > 0) {
22338
+ pushed = false;
22339
+ changed = false;
22340
+ try {
22341
+ await syncWebComputerReviews(broker, deviceId, link, signal);
22342
+ synced = key2;
22343
+ } catch (error) {
22344
+ if (error instanceof ServerUnreachableError) onUnreachable?.();
22345
+ }
22346
+ continue;
22237
22347
  }
22348
+ pushed = false;
22349
+ changed = false;
22238
22350
  }
22239
22351
  if (signal.aborted) break;
22240
- if (pushes) await pushes.next(intervalMs, signal);
22241
- else await new Promise((resolve20) => {
22242
- const done = () => {
22243
- clearTimeout(timer);
22244
- signal.removeEventListener("abort", done);
22245
- resolve20();
22246
- };
22247
- const timer = setTimeout(done, intervalMs);
22248
- signal.addEventListener("abort", done, { once: true });
22249
- if (signal.aborted) done();
22352
+ await new Promise((resolve19) => {
22353
+ wake = resolve19;
22354
+ if (signal.aborted) nudge();
22250
22355
  });
22251
22356
  }
22252
22357
  } finally {
22253
- unsubscribe?.();
22358
+ offPush();
22359
+ offBroker();
22360
+ signal.removeEventListener("abort", onAbort);
22254
22361
  }
22255
22362
  }
22256
22363
 
22257
22364
  // src/device-work-signal.ts
22258
22365
  var DeviceWorkSignal = class {
22259
22366
  connected = false;
22260
- pushed = /* @__PURE__ */ new Set();
22261
22367
  listeners = /* @__PURE__ */ new Set();
22262
- /** From the last gateway ticket: the waits this server pushes for. */
22263
- setPushedWaits(waits) {
22264
- this.pushed = new Set(waits);
22265
- this.notify();
22368
+ /** Whether the device session socket is open. */
22369
+ get live() {
22370
+ return this.connected;
22266
22371
  }
22267
- /** The gateway socket opened or dropped. Either way, read again: a push may have been lost meanwhile. */
22372
+ /** The socket opened or dropped. Opening wakes every waiter to read again. */
22268
22373
  setConnected(connected) {
22269
22374
  if (this.connected === connected) return;
22270
22375
  this.connected = connected;
22271
22376
  this.notify();
22272
22377
  }
22273
- mode(wait) {
22274
- if (!this.pushed.has(wait)) return "legacy";
22275
- return this.connected ? "push" : "fallback";
22276
- }
22277
22378
  /** A work frame arrived on the gateway socket. */
22278
22379
  notify() {
22279
22380
  for (const listener of [...this.listeners]) listener();
22280
22381
  }
22281
- /** Calls `listener` on each push or mode change; returns the unsubscribe. */
22382
+ /** Calls `listener` on each push or connection change; returns the unsubscribe. */
22282
22383
  subscribe(listener) {
22283
22384
  this.listeners.add(listener);
22284
22385
  return () => {
22285
22386
  this.listeners.delete(listener);
22286
22387
  };
22287
22388
  }
22288
- /** Resolves on the next push or mode change, after `ms`, or on abort. */
22289
- next(ms2, signal) {
22290
- return new Promise((resolve20) => {
22291
- if (signal?.aborted) {
22292
- resolve20();
22293
- return;
22294
- }
22295
- const done = () => {
22296
- clearTimeout(timer);
22297
- off();
22298
- signal?.removeEventListener("abort", done);
22299
- resolve20();
22300
- };
22301
- const timer = setTimeout(done, Math.max(0, ms2));
22302
- const off = this.subscribe(done);
22303
- signal?.addEventListener("abort", done, { once: true });
22304
- });
22305
- }
22306
22389
  };
22307
22390
 
22308
22391
  // src/computer/local-grant.mjs
@@ -22327,6 +22410,10 @@ function loadDeviceFile(raw) {
22327
22410
  }
22328
22411
  var HARNESS_RESCAN_MS = 5 * 6e4;
22329
22412
  var MODEL_PROBE_MS = 6 * 60 * 6e4;
22413
+ var LOCAL_CHECK_MS = 5e3;
22414
+ var CHECKPOINT_SCAN_MS = 15e3;
22415
+ var CLOUD_CREDENTIAL_ROTATE_BEFORE_MS = 60 * 6e4;
22416
+ var MAX_TIMER_MS3 = 2 ** 31 - 1;
22330
22417
  function cloudComputerGrantMatches(assignment, runId, deviceId) {
22331
22418
  if (!assignment?.computer || !deviceId || assignment.runId !== runId || assignment.deviceId !== deviceId) return false;
22332
22419
  const snapshot4 = assignment.policySnapshot?.payload;
@@ -22338,7 +22425,6 @@ var Daemon = class {
22338
22425
  this.paths = daemonPaths(options.dataDir);
22339
22426
  this.log = options.log ?? createLogger({ dir: this.paths.logs });
22340
22427
  this.initialRunHint = options.initialRunId;
22341
- this.runControlPush = Boolean(options.hostedSubscriptions);
22342
22428
  }
22343
22429
  options;
22344
22430
  paths;
@@ -22356,16 +22442,12 @@ var Daemon = class {
22356
22442
  device = {};
22357
22443
  harnesses = [];
22358
22444
  server = "unregistered";
22359
- timer = null;
22360
- tick = Promise.resolve();
22361
22445
  updating = false;
22362
22446
  claimsInFlight = 0;
22363
- /** Shared by the heartbeat, commands poll and RPC so one run has one claim. */
22447
+ /** Shared by session passes and RPC so one run has one claim. */
22364
22448
  claims = /* @__PURE__ */ new Map();
22365
- /** The newest release a server named; the commands poll sends it so the same news does not end every poll. */
22449
+ /** The newest release a server named; each commands read sends it. */
22366
22450
  knownLatest;
22367
- /** Device commands the commands poll already handed over; the heartbeat carries them out. */
22368
- polledDeviceCommands = [];
22369
22451
  maintenance = null;
22370
22452
  updateVersion;
22371
22453
  draining = false;
@@ -22377,25 +22459,37 @@ var Daemon = class {
22377
22459
  registered = false;
22378
22460
  /** Run ids the server sent that were refused as unsafe (reported once). */
22379
22461
  refusedRuns = /* @__PURE__ */ new Set();
22380
- /** Runs the commands poll reported queued: being claimed, or failed until the next heartbeat retries them. */
22462
+ /** Runs a commands read reported queued: being claimed, or failed until the next pass retries them. */
22381
22463
  queuedClaims = /* @__PURE__ */ new Map();
22382
22464
  quota = null;
22383
- /** Ends the commands long-poll when the daemon stops. */
22384
- commandsAbort = new AbortController();
22385
- /** The push socket is open. An idle device does not heartbeat the database. */
22386
- gatewayLive = false;
22387
- /** The server's last gateway ticket said it pushes run control (#1212). */
22388
- runControlPush = false;
22465
+ /** Aborts the daemon's own requests (claims, reads) when it stops. */
22466
+ lifetime = new AbortController();
22467
+ /** The device session: its socket is the daemon's only standing link to the server. */
22468
+ session = null;
22469
+ /** The session socket is open. */
22470
+ sessionOpen = false;
22471
+ /** Set when the daemon cannot use this server: it must update, or the server has no gateway. */
22472
+ blocked = null;
22473
+ /** The release a 426 or npm named for a daemon that must update. */
22474
+ requiredVersion;
22389
22475
  /** Gateway pushes for computer reviews (and other non-run-control waits). */
22390
22476
  workSignal = new DeviceWorkSignal();
22391
- /** The server said it has no gateway. Do not ask again on every long-poll. */
22392
- gatewayUnavailable = false;
22393
- gatewayFailures = 0;
22394
- gatewayRetryAt = 0;
22395
- deviceReceiptsVersion = 0;
22396
- deviceReceiptsAcknowledged = 0;
22397
- commandsLoop = Promise.resolve();
22398
- fsLoop = Promise.resolve();
22477
+ /** The last report the server took, as sent; a report goes out only when this changes. */
22478
+ lastReport;
22479
+ /** The socket opened since the last report: send one even if nothing changed. */
22480
+ reportOnOpen = false;
22481
+ /** A device command waiting to run (until idle, or until its runs end). */
22482
+ heldDeviceCommand;
22483
+ heldCommandPass = null;
22484
+ /** The cloud worker's token expires within the hour: the next report asks for its successor. */
22485
+ rotationDue = false;
22486
+ rotationTimer = null;
22487
+ localTimer = null;
22488
+ lastCheckpointScan = 0;
22489
+ checkpointScan = null;
22490
+ /** Resolved when a credential arrives (`device.setCredential`). */
22491
+ credentialArrived = /* @__PURE__ */ new Set();
22492
+ deviceType;
22399
22493
  reviewAbort = null;
22400
22494
  reviewLoop = Promise.resolve();
22401
22495
  cloudComputerBroker = null;
@@ -22408,13 +22502,11 @@ var Daemon = class {
22408
22502
  stopping = /* @__PURE__ */ new Set();
22409
22503
  /** Runs this daemon has ended, whose end the server may not have yet. */
22410
22504
  ended = /* @__PURE__ */ new Set();
22411
- /** The server pass in flight; the next one starts after it. */
22505
+ /** The server work in flight (a pass, a registration, a report); the next one starts after it. */
22412
22506
  syncing = Promise.resolve();
22413
22507
  initialRunHint;
22414
22508
  /** An early claim must retain the first sync's complete repository settings. */
22415
22509
  initialRepositorySync;
22416
- /** Cuts the poll loop's pause short (the device just registered). */
22417
- wakeCommands = null;
22418
22510
  async start() {
22419
22511
  this.starting = this.startInternal();
22420
22512
  try {
@@ -22442,7 +22534,7 @@ var Daemon = class {
22442
22534
  if (this.options.credential)
22443
22535
  this.saveDevice({ credential: this.options.credential });
22444
22536
  this.journal = new RunJournal(paths.journal);
22445
- this.captureUploader = new CaptureUploader((runId) => join36(runPaths(paths.adapterState, runId).runDir, CAPTURES_DIR), this.options.link, this.log, join36(paths.dataDir, "capture-pending"));
22537
+ this.captureUploader = new CaptureUploader((runId) => join35(runPaths(paths.adapterState, runId).runDir, CAPTURES_DIR), this.options.link, this.log, join35(paths.dataDir, "capture-pending"));
22446
22538
  this.outbox = new Outbox(
22447
22539
  paths.outbox,
22448
22540
  this.options.link,
@@ -22455,13 +22547,13 @@ var Daemon = class {
22455
22547
  this.worktrees = new WorktreeManager(this.options.taskRegistered ? "/workspace/worktrees" : paths.worktrees, this.options.retainResources);
22456
22548
  this.repositories = new RepositoryCache(this.options.taskRegistered ? "/workspace/repos" : paths.repos, void 0, this.options.retainResources);
22457
22549
  this.sandbox = this.options.hostedSubscriptions ? null : await this.createAgentSandbox();
22458
- if (this.runControlPush) this.options.link.setRunControlMode?.("fallback");
22550
+ this.options.link.onUpgradeRequired?.((latest) => this.enterUpdateRequired(latest));
22459
22551
  if (this.stopped) throw new Error("daemon stopped during startup");
22460
22552
  if (!this.options.hostedSubscriptions && this.sandbox) this.localComputerDriver = await detectComputerDriver();
22461
22553
  if (this.localComputerDriver && this.options.link.syncComputerReviews) {
22462
22554
  this.localComputerBroker = new ComputerBroker({
22463
22555
  driver: this.localComputerDriver,
22464
- socketPath: join36(paths.dataDir, "local-computer.sock"),
22556
+ socketPath: join35(paths.dataDir, "local-computer.sock"),
22465
22557
  transport: "tcp",
22466
22558
  needsPerson: this.computerNeedsPerson(),
22467
22559
  permitted: (runId) => {
@@ -22504,7 +22596,7 @@ var Daemon = class {
22504
22596
  };
22505
22597
  this.cloudComputerBroker = new ComputerBroker({
22506
22598
  driver,
22507
- socketPath: join36(paths.dataDir, "computer.sock"),
22599
+ socketPath: join35(paths.dataDir, "computer.sock"),
22508
22600
  needsPerson: this.computerNeedsPerson(),
22509
22601
  permitted: (runId) => {
22510
22602
  const entry = this.journal.get(runId);
@@ -22598,7 +22690,7 @@ var Daemon = class {
22598
22690
  prepareRunMailbox: this.options.link.prepareRunMailbox?.bind(this.options.link),
22599
22691
  prepareRunToolApproval: this.options.link.prepareRunToolApproval?.bind(this.options.link),
22600
22692
  prepareRunGitHub: hosted ? void 0 : (assignment, signal, onCredential) => prepareLocalGitHub(assignment, {
22601
- stateDir: join36(this.paths.adapterState, "github"),
22693
+ stateDir: join35(this.paths.adapterState, "github"),
22602
22694
  link: this.options.link,
22603
22695
  signal,
22604
22696
  onCredential,
@@ -22668,7 +22760,7 @@ var Daemon = class {
22668
22760
  worktree,
22669
22761
  tree,
22670
22762
  github: { ...assignment.github, runToken: assignment.mcp?.token, issueId: assignment.issueId },
22671
- privateDir: join36(paths.adapterState, "pids"),
22763
+ privateDir: join35(paths.adapterState, "pids"),
22672
22764
  ...hosted ? { hosted: true } : {},
22673
22765
  env: hosted ? process.env : githubReceiptEnvironment(),
22674
22766
  githubEnvironment,
@@ -22694,6 +22786,7 @@ var Daemon = class {
22694
22786
  })
22695
22787
  }
22696
22788
  });
22789
+ this.supervisor.sessionClosed();
22697
22790
  this.rpc = new RpcServer({
22698
22791
  socketPath: paths.socket,
22699
22792
  secret,
@@ -22739,103 +22832,322 @@ var Daemon = class {
22739
22832
  },
22740
22833
  "daemon started"
22741
22834
  );
22742
- this.schedule(0);
22743
- this.commandsLoop = this.pollCommands();
22835
+ this.startSession();
22744
22836
  if (this.modelProbeOn() && !preloadedModels) void this.probeModels().then((changed) => {
22745
- if (changed) return this.syncWithServer();
22837
+ if (changed) return this.reportNow();
22746
22838
  }).catch((err) => {
22747
22839
  this.log.warn({ err }, "model probe failed");
22748
22840
  });
22749
22841
  return this;
22750
22842
  }
22843
+ /** The local timer and the device session; nothing else talks to the server unasked. */
22844
+ startSession() {
22845
+ this.localTimer = setInterval(() => this.localTick(), LOCAL_CHECK_MS);
22846
+ this.localTimer.unref?.();
22847
+ this.session = new DeviceSession({
22848
+ ticket: (signal) => this.sessionTicket(signal),
22849
+ open: this.options.link.openDeviceGateway?.bind(this.options.link),
22850
+ onOpen: () => this.onSessionOpen(),
22851
+ onClose: (error, opened) => this.onSessionClose(error, opened),
22852
+ onWorkAvailable: () => {
22853
+ this.options.link.invalidateRunControls?.();
22854
+ this.workSignal.notify();
22855
+ },
22856
+ onWork: () => this.sessionPass(),
22857
+ verdict: (error) => this.sessionVerdict(error),
22858
+ random: this.options.random
22859
+ });
22860
+ void this.session.start();
22861
+ }
22862
+ /** Runs `work` after the server work already in flight, never alongside it. */
22863
+ serialized(work) {
22864
+ const run3 = this.syncing.then(work);
22865
+ this.syncing = run3.catch(() => void 0);
22866
+ return run3;
22867
+ }
22751
22868
  /**
22752
- * Long-polls the server for messages and stop requests for this device's
22753
- * runs (ADR 0018). Delivery is at least once: a message is acked after
22754
- * its session took it, so a crash in between hands it over again.
22869
+ * The next socket's ticket: waits for a credential, registers when needed,
22870
+ * then asks the server. This is the only request the session makes while
22871
+ * the socket is down, once per redial.
22755
22872
  */
22756
- async pollCommands() {
22757
- const { link } = this.options;
22758
- const signal = this.commandsAbort.signal;
22759
- const wait = this.options.commandsWaitSeconds ?? COMMANDS_MAX_WAIT_SECONDS;
22760
- let backoff = 1e3;
22761
- while (!this.stopped) {
22762
- const deviceId = this.device.deviceId;
22873
+ async sessionTicket(signal) {
22874
+ while (!this.device.credential) {
22875
+ this.server = "unregistered";
22876
+ await new Promise((resolve19) => {
22877
+ const done = () => {
22878
+ this.credentialArrived.delete(done);
22879
+ signal.removeEventListener("abort", done);
22880
+ resolve19();
22881
+ };
22882
+ this.credentialArrived.add(done);
22883
+ signal.addEventListener("abort", done, { once: true });
22884
+ });
22885
+ if (signal.aborted) throw new DeviceGatewayClosedError();
22886
+ }
22887
+ const credential = this.device.credential;
22888
+ await this.serialized(async () => {
22889
+ if (!this.registered || !this.device.deviceId) await this.register(credential);
22890
+ });
22891
+ if (signal.aborted) throw new DeviceGatewayClosedError();
22892
+ const ticket = await this.options.link.deviceGateway(this.device.deviceId, signal);
22893
+ this.armRotation(ticket.cloudCredentialExpiresAt);
22894
+ return ticket;
22895
+ }
22896
+ onSessionOpen() {
22897
+ this.sessionOpen = true;
22898
+ this.reportOnOpen = true;
22899
+ if (this.blocked === "gateway_required") {
22900
+ this.blocked = null;
22901
+ this.log.info("the server has a device gateway again");
22902
+ }
22903
+ this.supervisor.sessionOpened();
22904
+ this.workSignal.setConnected(true);
22905
+ this.options.link.invalidateRunControls?.();
22906
+ this.log.info({ device_id: this.device.deviceId }, "device session open");
22907
+ }
22908
+ onSessionClose(error, opened) {
22909
+ const wasOpen = this.sessionOpen;
22910
+ this.sessionOpen = false;
22911
+ this.workSignal.setConnected(false);
22912
+ this.supervisor.sessionClosed();
22913
+ if (this.server === "online") this.server = "offline";
22914
+ if (this.stopped || this.blocked === "update_required") return;
22915
+ if (wasOpen || opened) this.log.warn({ err: error }, "device session closed; redialing");
22916
+ else if (!(error instanceof ServerUnreachableError)) this.log.warn({ err: error }, "device session could not open; redialing");
22917
+ }
22918
+ /** What a lost socket means: stop for good, wait the longest, or redial with backoff. */
22919
+ sessionVerdict(error) {
22920
+ if (this.stopped) return "stop";
22921
+ if (error instanceof DaemonUpgradeRequiredError) {
22922
+ this.enterUpdateRequired(error.latest);
22923
+ return "stop";
22924
+ }
22925
+ if (error instanceof DeviceGatewayClosedError && error.code === DEVICE_GATEWAY_UPDATE_REQUIRED_CODE) {
22926
+ this.enterUpdateRequired();
22927
+ return "stop";
22928
+ }
22929
+ if (this.blocked === "update_required") return "stop";
22930
+ if (error instanceof DeviceGatewayRequiredError) {
22931
+ if (this.blocked !== "gateway_required")
22932
+ this.log.error("the server has no device gateway, so this device cannot work with it; retrying every 30 s");
22933
+ this.blocked = "gateway_required";
22934
+ this.server = "offline";
22935
+ return "slow";
22936
+ }
22937
+ if (error instanceof SessionRejectedError) this.rejectDeviceSession(this.device.credential);
22938
+ return "redial";
22939
+ }
22940
+ /**
22941
+ * One pass on open or on a push. A failure the server caused closes the
22942
+ * socket and the redial retries it; a refused session closes it until
22943
+ * someone signs in again.
22944
+ */
22945
+ async sessionPass() {
22946
+ const failure2 = await this.serialized(() => this.syncPass());
22947
+ if (failure2 instanceof ServerUnreachableError || failure2 instanceof SessionRejectedError) throw failure2;
22948
+ }
22949
+ /**
22950
+ * Terminal until the daemon is updated (decision 2026-11-17-2215): a 426
22951
+ * from any route or a gateway close 4001. Stops dialing and claiming; a
22952
+ * managed install updates itself as soon as no run is left.
22953
+ */
22954
+ enterUpdateRequired(latest) {
22955
+ if (this.blocked === "update_required") {
22956
+ if (latest && !this.requiredVersion) void this.findRequiredUpdate(latest);
22957
+ return;
22958
+ }
22959
+ this.blocked = "update_required";
22960
+ this.server = "offline";
22961
+ this.sessionOpen = false;
22962
+ this.workSignal.setConnected(false);
22963
+ this.supervisor?.sessionClosed();
22964
+ this.log.error(
22965
+ { version: DAEMON_VERSION, latest: latest ?? null },
22966
+ "this daemon is too old for the server and stopped connecting; update it (npm install -g @aspectlylabs/mikka@latest, or update Mikka Desktop)"
22967
+ );
22968
+ void this.session?.stop();
22969
+ void this.findRequiredUpdate(latest);
22970
+ }
22971
+ /** A managed install learns the release to install: from the refusal, else from npm (the server no longer answers this daemon). */
22972
+ async findRequiredUpdate(latest) {
22973
+ const runtime = this.options.autoUpdate;
22974
+ if (!runtime) {
22975
+ this.log.error("automatic updates are off for this daemon; update it by hand");
22976
+ return;
22977
+ }
22978
+ const version = latest ?? await runtime.latest?.().catch(() => void 0);
22979
+ if (!newerStableVersion(version, DAEMON_VERSION)) {
22980
+ this.log.error({ latest: version ?? null }, "no newer daemon release is known; update it by hand");
22981
+ return;
22982
+ }
22983
+ this.requiredVersion = version;
22984
+ this.log.warn({ version }, "installing the required daemon update once no run is active");
22985
+ this.learnRelease(version);
22986
+ this.checkAutoUpdate();
22987
+ }
22988
+ /** Local only: nothing here sends a request unless something changed and the session is open. */
22989
+ localTick() {
22990
+ if (this.stopped) return;
22991
+ this.supervisor.check();
22992
+ this.rescanHarnesses();
22993
+ if (this.requiredVersion) this.offerUpdate(this.requiredVersion);
22994
+ this.checkAutoUpdate();
22995
+ const held = this.heldDeviceCommand;
22996
+ if (held && this.sessionOpen && !this.heldCommandPass && (held.kind === "uninstall" ? this.supervisor.activeRunIds().length === 0 : this.maintenanceIdle()))
22997
+ this.heldCommandPass = this.syncWithServer().finally(() => {
22998
+ this.heldCommandPass = null;
22999
+ });
23000
+ const save = this.options.link.checkpointRun?.bind(this.options.link);
23001
+ if (save && this.sessionOpen && this.registered && !this.checkpointScan && Date.now() - this.lastCheckpointScan >= CHECKPOINT_SCAN_MS) {
23002
+ this.lastCheckpointScan = Date.now();
23003
+ this.checkpointScan = this.supervisor.saveCheckpoints(save).catch((err) => {
23004
+ this.log.warn({ err }, "checkpoint save failed");
23005
+ }).finally(() => {
23006
+ this.checkpointScan = null;
23007
+ });
23008
+ }
23009
+ }
23010
+ /**
23011
+ * One timer at the cloud worker's token expiry minus an hour: the next
23012
+ * report asks for the next token. A deadline, not a poll.
23013
+ */
23014
+ armRotation(expiresAt) {
23015
+ if (!expiresAt || !this.options.cloudComputer || this.stopped) return;
23016
+ const at = Date.parse(expiresAt) - CLOUD_CREDENTIAL_ROTATE_BEFORE_MS;
23017
+ if (!Number.isFinite(at)) return;
23018
+ if (this.rotationTimer) clearTimeout(this.rotationTimer);
23019
+ const fire = () => {
23020
+ if (Date.now() < at) {
23021
+ this.rotationTimer = setTimeout(fire, Math.min(at - Date.now(), MAX_TIMER_MS3));
23022
+ this.rotationTimer.unref();
23023
+ return;
23024
+ }
23025
+ this.rotationTimer = null;
23026
+ this.rotationDue = true;
23027
+ void this.reportNow(true);
23028
+ };
23029
+ this.rotationTimer = setTimeout(fire, Math.min(Math.max(0, at - Date.now()), MAX_TIMER_MS3));
23030
+ this.rotationTimer.unref();
23031
+ }
23032
+ /** Sends a report now when something changed (or a rotation is due), between passes. */
23033
+ reportNow(rotation = false) {
23034
+ if (this.stopped || this.blocked === "update_required" || !this.sessionOpen && !rotation) return Promise.resolve();
23035
+ return this.serialized(async () => {
22763
23036
  const credential = this.device.credential;
23037
+ const deviceId = this.device.deviceId;
23038
+ if (!credential || !deviceId || !this.registered) return;
23039
+ const result = await this.sendReport(deviceId, credential);
23040
+ if (result?.deviceCommands?.length && this.sessionOpen) void this.syncWithServer();
23041
+ }).catch((err) => {
23042
+ if (!(err instanceof ServerUnreachableError)) this.log.warn({ err }, "device report failed");
23043
+ });
23044
+ }
23045
+ /** What the report says now; only a change (or a new socket) sends it. */
23046
+ async reportFields() {
23047
+ const quotas = this.quota?.snapshot().quotas;
23048
+ return {
23049
+ completedDeviceCommands: this.device.completedDeviceCommands ?? [],
23050
+ failedDeviceCommands: this.device.failedDeviceCommands ?? [],
23051
+ harnesses: this.harnesses,
23052
+ computerUse: { installed: Boolean(this.localComputerDriver), version: this.localComputerDriver?.version ?? null },
23053
+ runner: await this.runnerReport(),
23054
+ ...this.deviceType ? { deviceType: this.deviceType } : {},
23055
+ worktreeDiskBytes: await this.worktrees.diskUsage(),
23056
+ ...quotas ? { quotas } : {},
23057
+ ...this.options.autoUpdate ? { updateFailure: reportedUpdateFailure(this.updateStateFile, DAEMON_VERSION) } : {}
23058
+ };
23059
+ }
23060
+ /** Sends the report when it changed, after a socket opened, or with a due rotation; applies the answer. */
23061
+ async sendReport(deviceId, credential) {
23062
+ const fields = await this.reportFields();
23063
+ const key2 = JSON.stringify(fields);
23064
+ if (!this.reportOnOpen && !this.rotationDue && key2 === this.lastReport) return void 0;
23065
+ const rotation = this.rotationDue;
23066
+ const result = await this.options.link.report(deviceId, { ...fields, ...rotation ? { rotateCloudCredential: true } : {} });
23067
+ this.lastReport = key2;
23068
+ this.reportOnOpen = false;
23069
+ await this.applyReportResult(result, credential, rotation);
23070
+ return result;
23071
+ }
23072
+ async applyReportResult(result, credential, rotation) {
23073
+ this.learnRelease(result.daemonVersions?.latest);
23074
+ this.checkAutoUpdate();
23075
+ this.holdDeviceCommands(result.deviceCommands ?? []);
23076
+ if (this.options.cloudComputer && result.cloudCredential && this.device.credential === credential) {
23077
+ this.saveDevice({ credential: result.cloudCredential });
23078
+ this.revokeLocalComputerGrants();
23079
+ this.registered = false;
23080
+ this.rotationDue = false;
23081
+ await this.register(result.cloudCredential);
23082
+ } else if (rotation && !result.cloudCredential) {
23083
+ this.log.warn("the server named no next cloud token; asking again on the next session");
23084
+ }
23085
+ this.armRotation(result.cloudCredentialExpiresAt);
23086
+ }
23087
+ /** A device command from the server waits here until the next pass runs it. */
23088
+ holdDeviceCommands(commands) {
23089
+ for (const command of commands) {
23090
+ if (this.device.completedDeviceCommands?.includes(command.id) || this.device.failedDeviceCommands?.some((failure2) => failure2.id === command.id)) continue;
23091
+ if (this.heldDeviceCommand?.id === command.id) continue;
23092
+ this.heldDeviceCommand ??= command;
23093
+ }
23094
+ }
23095
+ /**
23096
+ * Runs the held device command when it can run. Uninstall drains: it waits
23097
+ * for the runs to end (the local timer passes again), confirms its receipt
23098
+ * and stops the daemon. Returns true when the pass should end here.
23099
+ */
23100
+ async runHeldDeviceCommand(deviceId, credential) {
23101
+ const command = this.heldDeviceCommand;
23102
+ if (!command) return false;
23103
+ if (this.device.completedDeviceCommands?.includes(command.id) || this.device.failedDeviceCommands?.some((failure2) => failure2.id === command.id)) {
23104
+ this.heldDeviceCommand = void 0;
23105
+ return false;
23106
+ }
23107
+ if (command.kind === "uninstall") {
23108
+ this.draining = true;
23109
+ if (this.supervisor.activeRunIds().length > 0) return false;
23110
+ this.heldDeviceCommand = void 0;
23111
+ this.saveDevice({ completedDeviceCommands: [command.id], failedDeviceCommands: [] });
22764
23112
  try {
22765
- if (!this.registered || !deviceId) {
22766
- await this.pauseCommands(1e3, signal);
22767
- continue;
22768
- }
22769
- if (this.unacked.size > 0 || this.refusedSteers.size > 0) {
22770
- const ids = [...this.unacked].slice(0, 500);
22771
- const refused2 = [...this.refusedSteers].slice(0, 500);
22772
- if (refused2.length) await link.ackCommands(deviceId, ids, refused2);
22773
- else await link.ackCommands(deviceId, ids);
22774
- for (const id5 of ids) this.unacked.delete(id5);
22775
- for (const id5 of refused2) this.refusedSteers.delete(id5);
22776
- }
22777
- if (await this.holdGateway(deviceId, signal)) {
22778
- backoff = 1e3;
22779
- continue;
22780
- }
22781
- if (this.stopped || signal.aborted) return;
22782
- if (this.draining && this.supervisor.heartbeatRuns().length === 0) return;
22783
- const failedClaims = [...this.queuedClaims].flatMap(([id5, state2]) => state2 === "failed" ? [id5] : []);
22784
- const skipRuns = [...failedClaims, ...this.refusedRuns, ...this.stopping, ...this.ended].slice(
22785
- 0,
22786
- COMMANDS_MAX_SKIP
22787
- );
22788
- const started = performance.now();
22789
- let queued = [];
22790
- let news = false;
22791
- const commands = await link.fetchCommands(deviceId, wait, {
22792
- signal,
22793
- workspaceSkip: [...this.workspaceReads],
22794
- onWorkspaceRequests: (requests) => {
22795
- news = true;
22796
- this.answerWorkspaceRequests(deviceId, requests);
22797
- },
22798
- skipRuns,
22799
- onQueuedRuns: (runIds) => {
22800
- queued = runIds;
22801
- },
22802
- updates: { daemonLatest: this.knownLatest ?? DAEMON_VERSION, skipDeviceCommands: this.polledDeviceCommands },
22803
- onUpdates: ({ daemonVersions, deviceCommands }) => {
22804
- const known = this.knownLatest;
22805
- this.learnRelease(daemonVersions?.latest);
22806
- news ||= this.knownLatest !== known;
22807
- this.checkAutoUpdate();
22808
- const fresh = deviceCommands.filter((command) => !this.polledDeviceCommands.includes(command.id));
22809
- if (fresh.length === 0) return;
22810
- news = true;
22811
- this.polledDeviceCommands = [...this.polledDeviceCommands, ...fresh.map((command) => command.id)].slice(-COMMANDS_MAX_SKIP_DEVICE_COMMANDS);
22812
- void this.syncWithServer().catch(() => void 0);
22813
- }
23113
+ await this.sendReport(deviceId, credential);
23114
+ } catch {
23115
+ this.log.warn("Could not confirm uninstall receipt");
23116
+ }
23117
+ setImmediate(() => {
23118
+ void this.stop().then(() => uninstallService(() => {
23119
+ this.saveDevice({ credential: void 0 });
23120
+ rmSync21(this.paths.secret, { force: true });
23121
+ })).catch(() => {
23122
+ this.options.onDrained?.();
23123
+ });
23124
+ });
23125
+ return true;
23126
+ }
23127
+ if (command.kind !== "redetect" && !this.maintenanceIdle()) return false;
23128
+ this.heldDeviceCommand = void 0;
23129
+ try {
23130
+ if (command.kind === "redetect") {
23131
+ await this.redetectHarnesses();
23132
+ this.saveDevice({ completedDeviceCommands: [command.id], failedDeviceCommands: [] });
23133
+ await this.sendReport(deviceId, credential);
23134
+ } else {
23135
+ this.startMaintenance(async () => {
23136
+ await restartService(command.kind === "update", () => {
23137
+ if (this.stopped) throw new Error("Daemon stopped during update");
23138
+ this.saveDevice({ completedDeviceCommands: [command.id], failedDeviceCommands: [] });
23139
+ }, void 0, () => !this.stopped);
23140
+ }, () => {
23141
+ this.saveDevice({ completedDeviceCommands: [], failedDeviceCommands: [{ id: command.id, error: "Device command failed; check daemon service logs." }] });
23142
+ void this.reportNow();
22814
23143
  });
22815
- if (this.stopped || signal.aborted) return;
22816
- backoff = 1e3;
22817
- const acted = await this.applyCommands(commands);
22818
- if (queued.length > 0) {
22819
- if (this.claimQueued(queued)) continue;
22820
- await this.pauseCommands(500, signal);
22821
- continue;
22822
- }
22823
- if (this.unacked.size > 0 || this.refusedSteers.size > 0) continue;
22824
- if (news) continue;
22825
- if (commands.length === 0 && !signal.aborted) {
22826
- const remaining = Math.max(1e3, wait * 1e3) - (performance.now() - started);
22827
- if (remaining > 0) await this.pauseCommands(remaining, signal);
22828
- }
22829
- if (commands.length > 0 && !acted) await this.pauseCommands(500, signal);
22830
- } catch (error) {
22831
- if (this.stopped || signal.aborted) return;
22832
- if (error instanceof SessionRejectedError) this.rejectDeviceSession(credential);
22833
- if (!(error instanceof ServerUnreachableError))
22834
- this.log.warn({ err: error }, "fetching run commands failed");
22835
- await this.pauseCommands(backoff, signal);
22836
- backoff = Math.min(backoff * 2, 3e4);
22837
23144
  }
23145
+ } catch (err) {
23146
+ if (err instanceof ServerUnreachableError) throw err;
23147
+ this.saveDevice({ completedDeviceCommands: [], failedDeviceCommands: [{ id: command.id, error: "Device command failed; check daemon service logs." }] });
23148
+ this.log.warn({ command_id: command.id, err }, "Device command failed");
22838
23149
  }
23150
+ return false;
22839
23151
  }
22840
23152
  /** One read after a push, or right after the socket opens. Wait is zero: the signal already arrived. */
22841
23153
  async pullSignaledWork(deviceId, signal) {
@@ -22850,14 +23162,11 @@ var Daemon = class {
22850
23162
  onQueuedRuns: (runIds) => {
22851
23163
  queued = runIds;
22852
23164
  },
22853
- updates: { daemonLatest: this.knownLatest ?? DAEMON_VERSION, skipDeviceCommands: this.polledDeviceCommands },
23165
+ updates: { daemonLatest: this.knownLatest ?? DAEMON_VERSION },
22854
23166
  onUpdates: ({ daemonVersions, deviceCommands }) => {
22855
23167
  this.learnRelease(daemonVersions?.latest);
22856
23168
  this.checkAutoUpdate();
22857
- const fresh = deviceCommands.filter((command) => !this.polledDeviceCommands.includes(command.id));
22858
- if (fresh.length === 0) return;
22859
- this.polledDeviceCommands = [...this.polledDeviceCommands, ...fresh.map((command) => command.id)].slice(-COMMANDS_MAX_SKIP_DEVICE_COMMANDS);
22860
- void this.syncWithServer().catch(() => void 0);
23169
+ this.holdDeviceCommands(deviceCommands);
22861
23170
  }
22862
23171
  });
22863
23172
  if (this.stopped || signal.aborted) return;
@@ -22872,138 +23181,11 @@ var Daemon = class {
22872
23181
  for (const id5 of refused2) this.refusedSteers.delete(id5);
22873
23182
  }
22874
23183
  }
22875
- /**
22876
- * Stay on the device's push socket until it drops. Failed and short-lived
22877
- * sessions cool down independently of the responsive long-poll fallback.
22878
- */
22879
- async holdGateway(deviceId, signal) {
22880
- const mint = this.options.link.deviceGateway;
22881
- if (!mint || this.gatewayUnavailable || performance.now() < this.gatewayRetryAt) return false;
22882
- let openedAt;
22883
- let failure2;
22884
- let gatewayOpened;
22885
- let gatewayFailed;
22886
- const connection = new AbortController();
22887
- const abort = () => connection.abort();
22888
- signal.addEventListener("abort", abort, { once: true });
22889
- if (signal.aborted) connection.abort();
22890
- try {
22891
- const ticket = await mint.call(this.options.link, deviceId, connection.signal);
22892
- this.runControlPush = ticket.runControl === "push" || Boolean(this.options.hostedSubscriptions);
22893
- this.options.link.setRunControlMode?.(this.runControlPush ? "fallback" : "legacy");
22894
- this.workSignal.setPushedWaits(["computerReviews", "coordinatorResults"].filter((wait) => ticket[wait] === "push"));
22895
- if (!ticket.url || !ticket.protocol) {
22896
- this.gatewayUnavailable = true;
22897
- return false;
22898
- }
22899
- if (signal.aborted) return false;
22900
- const socket = openDeviceGateway(ticket.url, ticket.protocol);
22901
- void daemonTracer.span("daemon.gateway.connect", { "mikka.gateway.mode": this.runControlPush ? "push" : "legacy" }, () => new Promise((resolve20, reject) => {
22902
- gatewayOpened = resolve20;
22903
- gatewayFailed = reject;
22904
- }), { root: true }).catch(() => void 0);
22905
- await runDeviceGateway(socket, {
22906
- signal: connection.signal,
22907
- onOpen: () => {
22908
- gatewayOpened?.();
22909
- openedAt = performance.now();
22910
- this.gatewayLive = true;
22911
- if (this.runControlPush) this.options.link.setRunControlMode?.("push");
22912
- this.workSignal.setConnected(true);
22913
- },
22914
- onWorkAvailable: () => {
22915
- this.options.link.invalidateRunControls?.();
22916
- this.workSignal.notify();
22917
- },
22918
- onWork: async () => {
22919
- await this.pullSignaledWork(deviceId, connection.signal);
22920
- if (connection.signal.aborted || this.stopped) return;
22921
- await this.syncWithServer();
22922
- if (!connection.signal.aborted && !this.stopped)
22923
- this.schedule(this.gatewayIdle() ? null : this.options.heartbeatMs ?? 15e3);
22924
- }
22925
- });
22926
- } catch (error) {
22927
- failure2 = error;
22928
- if (!this.stopped && !signal.aborted) {
22929
- this.log.warn({ err: error }, "device gateway disconnected; using long-poll fallback");
22930
- if (error instanceof SessionRejectedError) await this.syncWithServer().catch(() => void 0);
22931
- }
22932
- } finally {
22933
- gatewayFailed?.(failure2 ?? new DeviceGatewayClosedError());
22934
- connection.abort();
22935
- signal.removeEventListener("abort", abort);
22936
- this.gatewayLive = false;
22937
- this.options.link.setRunControlMode?.(this.runControlPush ? "fallback" : "legacy");
22938
- this.options.link.invalidateRunControls?.();
22939
- this.workSignal.setConnected(false);
22940
- if (!this.stopped && !signal.aborted && !this.gatewayUnavailable) {
22941
- if (openedAt !== void 0 && performance.now() - openedAt >= 6e4) this.gatewayFailures = 0;
22942
- this.gatewayFailures = Math.min(this.gatewayFailures + 1, 5);
22943
- const ceiling = Math.min(6e4, 5e3 * 2 ** (this.gatewayFailures - 1));
22944
- const delay2 = failure2 instanceof DeviceGatewayClosedError && failure2.code === 4e3 ? 6e4 : ceiling * (0.8 + Math.random() * 0.2);
22945
- this.gatewayRetryAt = performance.now() + delay2;
22946
- if (this.timer === null) this.schedule(this.options.heartbeatMs ?? 15e3);
22947
- }
22948
- }
22949
- return false;
22950
- }
22951
- /**
22952
- * Answers the app's folder requests for the repository picker (ADR 0037):
22953
- * a second long-poll next to the run commands, so a slow folder never
22954
- * delays a stop.
22955
- */
22956
- async pollFolderRequests() {
22957
- const { link } = this.options;
22958
- if (!link.fetchFsRequests || !link.answerFsRequest) return;
22959
- const signal = this.commandsAbort.signal;
22960
- const wait = this.options.commandsWaitSeconds ?? FS_REQUESTS_MAX_WAIT_SECONDS;
22961
- let backoff = 1e3;
22962
- while (!this.stopped) {
22963
- const deviceId = this.device.deviceId;
22964
- const credential = this.device.credential;
22965
- try {
22966
- if (!this.registered || !deviceId) {
22967
- await this.pauseCommands(1e3, signal);
22968
- continue;
22969
- }
22970
- const started = performance.now();
22971
- const requests = await link.fetchFsRequests(
22972
- deviceId,
22973
- wait,
22974
- { signal }
22975
- );
22976
- if (this.stopped || signal.aborted) return;
22977
- backoff = 1e3;
22978
- if (requests.length === 0 && !signal.aborted) {
22979
- const remaining = Math.max(1e3, wait * 1e3) - (performance.now() - started);
22980
- if (remaining > 0) await this.pauseCommands(remaining, signal);
22981
- }
22982
- await Promise.all(
22983
- requests.map(async ({ id: id5, ...request2 }) => {
22984
- const result = await browseFolder(request2).catch(() => ({
22985
- ok: false,
22986
- code: "failed",
22987
- message: "Could not read that folder."
22988
- }));
22989
- await link.answerFsRequest(deviceId, id5, result);
22990
- })
22991
- );
22992
- } catch (error) {
22993
- if (this.stopped || signal.aborted) return;
22994
- if (error instanceof SessionRejectedError) this.rejectDeviceSession(credential);
22995
- if (!(error instanceof ServerUnreachableError))
22996
- this.log.warn({ err: error }, "answering folder requests failed");
22997
- await this.pauseCommands(backoff, signal);
22998
- backoff = Math.min(backoff * 2, 3e4);
22999
- }
23000
- }
23001
- }
23002
23184
  /** Starts claiming the reported queued runs; true when any claim began. */
23003
23185
  claimQueued(runIds) {
23004
23186
  let started = false;
23005
23187
  for (const runId of runIds) {
23006
- if (this.draining || this.updating || this.stopped) break;
23188
+ if (this.draining || this.updating || this.stopped || this.blocked) break;
23007
23189
  if (this.queuedClaims.has(runId) || this.refusedRuns.has(runId) || this.journal.get(runId)) continue;
23008
23190
  this.queuedClaims.set(runId, "claiming");
23009
23191
  started = true;
@@ -23015,27 +23197,16 @@ var Daemon = class {
23015
23197
  (error) => {
23016
23198
  if (this.initialRepositorySync?.runId === runId) this.initialRepositorySync.received?.();
23017
23199
  this.queuedClaims.set(runId, "failed");
23200
+ if (error instanceof DeviceSessionRequiredError) {
23201
+ this.session?.redial();
23202
+ return;
23203
+ }
23018
23204
  this.log.warn({ run_id: runId, err: error }, "could not start run");
23019
23205
  }
23020
23206
  );
23021
23207
  }
23022
23208
  return started;
23023
23209
  }
23024
- /** Waits `ms`, or less if the daemon stops or the device registers. */
23025
- pauseCommands(ms2, signal) {
23026
- if (signal.aborted) return Promise.resolve();
23027
- return new Promise((resolve20) => {
23028
- const done = () => {
23029
- clearTimeout(timer);
23030
- signal.removeEventListener("abort", done);
23031
- this.wakeCommands = null;
23032
- resolve20();
23033
- };
23034
- const timer = setTimeout(done, ms2);
23035
- signal.addEventListener("abort", done, { once: true });
23036
- this.wakeCommands = done;
23037
- });
23038
- }
23039
23210
  /** Hands commands to the runs' sessions; true when any took effect. */
23040
23211
  answerWorkspaceRequests(deviceId, requests) {
23041
23212
  const answer = this.options.link.answerWorkspaceRead;
@@ -23055,7 +23226,7 @@ var Daemon = class {
23055
23226
  }
23056
23227
  return readWorkspaceReceipt(request2, entry);
23057
23228
  });
23058
- void reading.then((receipt) => answer.call(this.options.link, deviceId, request2.id, receipt, { expiresAt: request2.expiresAt, signal: this.commandsAbort.signal })).catch(() => {
23229
+ void reading.then((receipt) => answer.call(this.options.link, deviceId, request2.id, receipt, { expiresAt: request2.expiresAt, signal: this.lifetime.signal })).catch(() => {
23059
23230
  this.log.warn({ request_id: request2.id }, "workspace read delivery failed");
23060
23231
  }).finally(() => this.workspaceReads.delete(request2.id));
23061
23232
  }
@@ -23241,12 +23412,15 @@ var Daemon = class {
23241
23412
  });
23242
23413
  return this.probingModels;
23243
23414
  }
23244
- /** Notice an agent installed after startup without spawning anything per tick. */
23415
+ /**
23416
+ * Notice an agent installed after startup without spawning anything per
23417
+ * tick: the local timer calls this, and only a changed result is reported.
23418
+ */
23245
23419
  rescanHarnesses() {
23246
23420
  const now = Date.now();
23247
23421
  if (this.modelProbeOn() && !this.probingModels && now - this.lastModelProbe >= MODEL_PROBE_MS) {
23248
23422
  void this.probeModels().then((changed) => {
23249
- if (changed) return this.syncWithServer();
23423
+ if (changed) return this.reportNow();
23250
23424
  }).catch((err) => {
23251
23425
  this.log.warn({ err }, "model probe failed");
23252
23426
  });
@@ -23255,7 +23429,7 @@ var Daemon = class {
23255
23429
  this.lastHarnessScan = now;
23256
23430
  if (harnessFingerprint(this.harnessStore()) === this.harnessPrint) return;
23257
23431
  this.rescanning = true;
23258
- void this.redetectHarnesses().then(() => this.syncWithServer()).catch((err) => {
23432
+ void this.redetectHarnesses().then(() => this.reportNow()).catch((err) => {
23259
23433
  this.log.warn({ err }, "harness rescan failed");
23260
23434
  }).finally(() => {
23261
23435
  this.rescanning = false;
@@ -23301,11 +23475,11 @@ var Daemon = class {
23301
23475
  return runVerify(sandbox, {
23302
23476
  command,
23303
23477
  worktree: realpathSync15(worktree),
23304
- tmpRoot: join36(this.paths.adapterState, "verify", runId),
23478
+ tmpRoot: join35(this.paths.adapterState, "verify", runId),
23305
23479
  privateDir: paths.privateDir,
23306
23480
  pidFile: paths.pidFile.replace(/\.pgid$/, ".verify.pgid"),
23307
23481
  networkAllow: repo.networkAllow,
23308
- env: { ...buildChildEnv(), ...githubEnvironment, MIKKA_HANDOFF_FILE: join36(paths.runDir, "handoff.json") },
23482
+ env: { ...buildChildEnv(), ...githubEnvironment, MIKKA_HANDOFF_FILE: join35(paths.runDir, "handoff.json") },
23309
23483
  timeoutMs,
23310
23484
  signal,
23311
23485
  readOnly
@@ -23389,41 +23563,22 @@ var Daemon = class {
23389
23563
  return secret;
23390
23564
  }
23391
23565
  saveDevice(patch) {
23392
- if (patch.completedDeviceCommands || patch.failedDeviceCommands) this.deviceReceiptsVersion++;
23393
23566
  this.device = { ...this.device, ...patch };
23394
23567
  writeJsonAtomic(this.paths.device, this.device);
23395
23568
  }
23396
- /** Idle on the push socket: no runs, nothing waiting to upload. The database can sleep. */
23397
- gatewayIdle() {
23398
- 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;
23399
- }
23400
- schedule(delay2) {
23401
- if (this.stopped) return;
23402
- if (this.timer) clearTimeout(this.timer);
23403
- if (delay2 === null) {
23404
- this.timer = null;
23405
- return;
23406
- }
23407
- this.timer = setTimeout(() => {
23408
- this.supervisor.check();
23409
- this.tick = this.syncWithServer().finally(
23410
- () => this.schedule(this.gatewayIdle() ? null : this.options.heartbeatMs ?? 15e3)
23411
- );
23412
- }, delay2);
23413
- this.timer.unref();
23414
- }
23415
23569
  async register(credential) {
23416
23570
  const { workspaceId, deviceId: knownDeviceId } = this.device;
23571
+ this.deviceType ??= process.env.MIKKA_DEVICE_TYPE === "server" ? "server" : process.env.MIKKA_DEVICE_TYPE === "laptop" ? "laptop" : await detectDeviceType();
23417
23572
  const { deviceId, tracing } = await daemonTracer.span("daemon.registration", {}, async () => this.options.link.registerDevice(
23418
23573
  credential,
23419
23574
  {
23420
23575
  name: hostname(),
23421
23576
  hostname: hostname(),
23422
- platform: platform3(),
23577
+ platform: platform2(),
23423
23578
  arch: arch2(),
23424
23579
  daemonVersion: DAEMON_VERSION,
23425
23580
  protocolVersion: DAEMON_PROTOCOL_VERSION,
23426
- deviceType: process.env.MIKKA_DEVICE_TYPE === "server" ? "server" : process.env.MIKKA_DEVICE_TYPE === "laptop" ? "laptop" : await detectDeviceType(),
23581
+ deviceType: this.deviceType,
23427
23582
  harnesses: this.harnesses,
23428
23583
  computerUse: { installed: Boolean(this.localComputerDriver), version: this.localComputerDriver?.version ?? null },
23429
23584
  runner: await this.runnerReport(),
@@ -23452,39 +23607,38 @@ var Daemon = class {
23452
23607
  this.reviewAbort?.abort();
23453
23608
  const abort = new AbortController();
23454
23609
  this.reviewAbort = abort;
23455
- this.reviewLoop = pollWebComputerReviews(computerBroker, deviceId, this.options.link, abort.signal, void 0, this.workSignal);
23610
+ this.reviewLoop = followWebComputerReviews(computerBroker, deviceId, this.options.link, abort.signal, this.workSignal, () => this.session?.redial());
23456
23611
  }
23457
- this.wakeCommands?.();
23458
23612
  }
23459
23613
  /**
23460
- * One pass of the server link loop; safe to call any time. Passes run one
23461
- * after another: overlapping ones would register two devices, or let an
23462
- * older pass's repo list overwrite a newer one.
23614
+ * One pass of the server link; safe to call any time. The session runs one
23615
+ * on every socket open and every push. Passes run one after another:
23616
+ * overlapping ones would register two devices, or let an older pass's repo
23617
+ * list overwrite a newer one.
23463
23618
  */
23464
23619
  syncWithServer() {
23465
- const pass = this.syncing.then(() => this.syncPass());
23466
- this.syncing = pass.catch(() => void 0);
23467
- return pass;
23620
+ return this.serialized(() => this.syncPass()).then(() => void 0);
23468
23621
  }
23622
+ /** Returns what made the pass fail, if anything; the session redials on a server failure. */
23469
23623
  async syncPass() {
23470
- if (this.stopped) return;
23624
+ if (this.stopped || this.blocked === "update_required") return void 0;
23471
23625
  this.checkAutoUpdate();
23472
23626
  const { link } = this.options;
23473
23627
  const { credential, workspaceId } = this.device;
23474
23628
  if (!credential) {
23475
23629
  this.server = "unregistered";
23476
- return;
23630
+ return void 0;
23477
23631
  }
23478
23632
  const initialRunId = this.initialRunHint;
23479
23633
  let resolveRepositories, rejectRepositories;
23480
- const repositoriesReady = initialRunId ? new Promise((resolve20, reject) => {
23481
- resolveRepositories = resolve20;
23634
+ const repositoriesReady = initialRunId ? new Promise((resolve19, reject) => {
23635
+ resolveRepositories = resolve19;
23482
23636
  rejectRepositories = reject;
23483
23637
  }) : void 0;
23484
23638
  if (initialRunId && repositoriesReady) {
23485
23639
  let received;
23486
- const repository2 = this.options.hostedSubscriptions && this.options.e2bContainerRuntime && this.journal.all().length === 0 ? new Promise((resolve20) => {
23487
- received = resolve20;
23640
+ const repository2 = this.options.hostedSubscriptions && this.options.e2bContainerRuntime && this.journal.all().length === 0 ? new Promise((resolve19) => {
23641
+ received = resolve19;
23488
23642
  }) : void 0;
23489
23643
  this.initialRepositorySync = { runId: initialRunId, ready: repositoriesReady, repository: repository2, received };
23490
23644
  void repositoriesReady.catch(() => void 0);
@@ -23498,111 +23652,71 @@ var Daemon = class {
23498
23652
  this.initialRunHint = void 0;
23499
23653
  if (!this.claimQueued([initialRunId])) this.initialRepositorySync?.received?.();
23500
23654
  }
23501
- const quotas = this.quota?.snapshot().quotas;
23502
- const receiptsVersion = this.deviceReceiptsVersion;
23503
- const heartbeat = {
23504
- completedDeviceCommands: this.device.completedDeviceCommands,
23505
- failedDeviceCommands: this.device.failedDeviceCommands,
23506
- harnesses: this.harnesses,
23507
- computerUse: { installed: Boolean(this.localComputerDriver), version: this.localComputerDriver?.version ?? null },
23508
- runner: await this.runnerReport(),
23509
- runs: this.supervisor.heartbeatRuns(),
23510
- worktreeDiskBytes: await this.worktrees.diskUsage(),
23511
- ...quotas ? { quotas } : {},
23512
- ...this.options.autoUpdate ? { updateFailure: reportedUpdateFailure(this.updateStateFile, DAEMON_VERSION) } : {}
23513
- };
23514
- const { leases, revoked, cancelled, cloudCredential, deviceCommands, daemonVersions, taskSecrets } = await link.heartbeat(deviceId, heartbeat);
23515
- this.deviceReceiptsAcknowledged = receiptsVersion;
23516
- this.learnRelease(daemonVersions?.latest);
23517
- this.supervisor.renewLeases(leases);
23518
- if (revoked) this.supervisor.revokeLeases(revoked, cancelled);
23519
- this.supervisor.renewTaskSecrets(taskSecrets);
23520
- if (this.options.cloudComputer && cloudCredential && this.device.credential === credential) {
23521
- this.saveDevice({ credential: cloudCredential });
23522
- this.revokeLocalComputerGrants();
23523
- this.registered = false;
23524
- }
23525
- this.rescanHarnesses();
23526
- const command = deviceCommands?.[0];
23527
- if (command?.kind === "uninstall") {
23528
- this.draining = true;
23529
- if (this.supervisor.heartbeatRuns().length === 0) {
23530
- this.saveDevice({ completedDeviceCommands: [command.id], failedDeviceCommands: [] });
23531
- try {
23532
- await link.heartbeat(deviceId, { ...heartbeat, runs: [], completedDeviceCommands: [command.id], failedDeviceCommands: [] });
23533
- } catch {
23534
- this.log.warn("Could not confirm uninstall receipt");
23535
- }
23536
- setImmediate(() => {
23537
- void this.stop().then(() => uninstallService(() => {
23538
- this.saveDevice({ credential: void 0 });
23539
- rmSync21(this.paths.secret, { force: true });
23540
- })).catch(() => {
23541
- this.options.onDrained?.();
23542
- });
23543
- });
23544
- }
23545
- return;
23546
- }
23547
- if (command && !this.device.completedDeviceCommands?.includes(command.id) && !this.device.failedDeviceCommands?.some((failure2) => failure2.id === command.id)) {
23548
- if (command.kind === "redetect" || this.maintenanceIdle()) {
23549
- try {
23550
- if (command.kind === "redetect") {
23551
- await this.redetectHarnesses();
23552
- this.saveDevice({ completedDeviceCommands: [command.id], failedDeviceCommands: [] });
23553
- void this.syncWithServer().catch(() => void 0);
23554
- } else {
23555
- this.startMaintenance(async () => {
23556
- await restartService(command.kind === "update", () => {
23557
- if (this.stopped) throw new Error("Daemon stopped during update");
23558
- this.saveDevice({ completedDeviceCommands: [command.id], failedDeviceCommands: [] });
23559
- }, void 0, () => !this.stopped);
23560
- }, () => {
23561
- this.saveDevice({ completedDeviceCommands: [], failedDeviceCommands: [{ id: command.id, error: "Device command failed; check daemon service logs." }] });
23562
- });
23563
- }
23564
- } catch (err) {
23565
- this.saveDevice({ completedDeviceCommands: [], failedDeviceCommands: [{ id: command.id, error: "Device command failed; check daemon service logs." }] });
23566
- this.log.warn({ command_id: command.id, err }, "Device command failed");
23567
- }
23568
- }
23569
- }
23570
- const checkpointRun = link.checkpointRun?.bind(link);
23571
- if (checkpointRun) await this.supervisor.saveCheckpoints(checkpointRun);
23655
+ await this.sendReport(deviceId, credential);
23656
+ if (await this.runHeldDeviceCommand(deviceId, credential)) return void 0;
23657
+ await this.pullSignaledWork(deviceId, this.lifetime.signal);
23658
+ if (await this.runHeldDeviceCommand(deviceId, credential)) return void 0;
23572
23659
  const initialRepository = await this.initialRepositorySync?.repository;
23573
23660
  this.saveDevice({ repos: initialRepository ? [initialRepository] : await link.listRepos(deviceId) });
23574
23661
  resolveRepositories?.();
23575
23662
  this.server = "online";
23576
23663
  await this.outbox.flushAll();
23577
23664
  for (const entry of this.journal.all()) if (isTerminalRunState(entry.state)) void this.captureUploader.flush(entry.assignment.runId, true);
23578
- if (!this.draining && !this.updating && !this.stopped) {
23665
+ if (!this.draining && !this.updating && !this.stopped && !this.blocked) {
23579
23666
  await this.supervisor.resumeAll(true);
23580
23667
  for (const [runId, state2] of this.queuedClaims) if (state2 === "failed") this.queuedClaims.delete(runId);
23581
23668
  for (const runId of await link.pendingRuns(deviceId)) {
23582
23669
  if (this.refusedRuns.has(runId) || this.queuedClaims.has(runId)) continue;
23583
- await this.claimAndStart(runId).catch(
23584
- (error) => this.log.warn({ run_id: runId, err: error }, "could not start run")
23585
- );
23670
+ await this.claimAndStart(runId).catch((error) => {
23671
+ if (error instanceof DeviceSessionRequiredError || error instanceof DaemonUpgradeRequiredError) throw error;
23672
+ this.log.warn({ run_id: runId, err: error }, "could not start run");
23673
+ });
23586
23674
  }
23587
23675
  }
23588
23676
  await this.pruneWorktrees();
23589
23677
  await this.sweepEmptyRuns();
23678
+ return void 0;
23590
23679
  } catch (error) {
23591
23680
  rejectRepositories?.(error);
23592
- if (this.device.credential !== credential || this.device.workspaceId !== workspaceId) return;
23681
+ if (this.device.credential !== credential || this.device.workspaceId !== workspaceId) return void 0;
23593
23682
  this.server = "offline";
23594
- if (error instanceof SessionRejectedError) {
23683
+ if (error instanceof DaemonUpgradeRequiredError) {
23684
+ this.enterUpdateRequired(error.latest);
23685
+ } else if (error instanceof SessionRejectedError) {
23686
+ if (await this.collectUninstall(credential)) return void 0;
23595
23687
  this.rejectDeviceSession(credential);
23596
23688
  } else if (!(error instanceof ServerUnreachableError)) {
23597
23689
  this.log.error({ err: error }, "server sync failed");
23598
23690
  }
23691
+ return error;
23599
23692
  } finally {
23600
23693
  rejectRepositories?.(new ServerUnreachableError("Initial repository sync unavailable"));
23601
23694
  if (this.initialRepositorySync?.ready === repositoriesReady) this.initialRepositorySync = void 0;
23602
23695
  }
23603
23696
  }
23604
- /** A refused credential stops its local work as well as future polling.
23605
- * The supervisor cancels immediately and applies its bounded CLI kill grace. */
23697
+ /**
23698
+ * A removed device's credential reaches only its report, which carries its
23699
+ * uninstall (decision 2026-11-17-2215). A push can arrive with nothing
23700
+ * changed to report, so before giving the session up, ask the report once.
23701
+ * True when an uninstall is now held: it runs here or, while runs drain,
23702
+ * from the local timer.
23703
+ */
23704
+ async collectUninstall(credential) {
23705
+ const deviceId = this.device.deviceId;
23706
+ if (!deviceId || this.device.credential !== credential) return false;
23707
+ try {
23708
+ this.reportOnOpen = true;
23709
+ await this.sendReport(deviceId, credential);
23710
+ } catch {
23711
+ return false;
23712
+ }
23713
+ if (this.heldDeviceCommand?.kind !== "uninstall") return false;
23714
+ await this.runHeldDeviceCommand(deviceId, credential);
23715
+ return true;
23716
+ }
23717
+ /** A refused credential stops its local work as well as the session until
23718
+ * someone signs in again. The supervisor cancels immediately and applies
23719
+ * its bounded CLI kill grace. */
23606
23720
  rejectDeviceSession(credential) {
23607
23721
  if (!credential || this.device.credential !== credential) return;
23608
23722
  this.server = "unregistered";
@@ -23620,25 +23734,18 @@ var Daemon = class {
23620
23734
  if (this.draining || this.updating || this.stopped) {
23621
23735
  throw new DaemonError(DAEMON_RPC_ERRORS.draining, "Daemon is draining");
23622
23736
  }
23737
+ if (this.blocked === "update_required") throw new DaemonUpgradeRequiredError(this.requiredVersion);
23738
+ if (this.blocked === "gateway_required") throw new DeviceGatewayRequiredError();
23623
23739
  const existing = this.claims.get(runId);
23624
23740
  if (existing) return await existing;
23625
23741
  this.claimsInFlight++;
23626
23742
  const claim = this.claimAndStartInternal(runId);
23627
23743
  this.claims.set(runId, claim);
23628
- let upgradeRequired = false;
23629
23744
  try {
23630
23745
  return await claim;
23631
- } catch (error) {
23632
- if (error instanceof RunNotPinnedHereError && error.upgradeRequired) {
23633
- this.log.warn({ run_id: runId }, "server requires a newer daemon; updating when idle");
23634
- this.learnRelease(error.latest);
23635
- upgradeRequired = true;
23636
- }
23637
- throw error;
23638
23746
  } finally {
23639
23747
  this.claims.delete(runId);
23640
23748
  this.claimsInFlight--;
23641
- if (upgradeRequired) this.checkAutoUpdate();
23642
23749
  }
23643
23750
  }
23644
23751
  async claimAndStartInternal(runId) {
@@ -23657,7 +23764,7 @@ var Daemon = class {
23657
23764
  let assignment;
23658
23765
  try {
23659
23766
  assignment = await daemonTracer.span("daemon.run.lease", { "mikka.run.id_hash": runIdHash(runId) }, async (span) => {
23660
- const claimed = await this.options.link.claimRun(deviceId, runId, this.commandsAbort.signal, initialSync?.received ? { initialRepository: true } : void 0);
23767
+ const claimed = await this.options.link.claimRun(deviceId, runId, this.lifetime.signal, initialSync?.received ? { initialRepository: true } : void 0);
23661
23768
  span.set("mikka.harness", claimed.harness);
23662
23769
  return claimed;
23663
23770
  }, { root: true });
@@ -23797,8 +23904,20 @@ var Daemon = class {
23797
23904
  });
23798
23905
  await this.worktrees.prune(finished, retentionMs);
23799
23906
  }
23907
+ /** The device session as `daemon status` shows it. */
23908
+ sessionState() {
23909
+ if (this.blocked) return this.blocked;
23910
+ if (!this.device.credential) return "signed_out";
23911
+ return this.sessionOpen ? "open" : "connecting";
23912
+ }
23913
+ /**
23914
+ * `session` is outside `daemonStatusSchema`, whose `server` has no state for
23915
+ * "update required" yet; a client that parses with the schema drops it.
23916
+ */
23800
23917
  status() {
23801
23918
  return {
23919
+ session: this.sessionState(),
23920
+ requiredVersion: this.requiredVersion ?? null,
23802
23921
  daemonVersion: DAEMON_VERSION,
23803
23922
  protocolVersion: DAEMON_PROTOCOL_VERSION,
23804
23923
  pid: process.pid,
@@ -23838,7 +23957,8 @@ var Daemon = class {
23838
23957
  this.revokeLocalComputerGrants();
23839
23958
  this.registered = false;
23840
23959
  this.registrationTraceContext = traceContext;
23841
- void daemonTracer.withContext(traceContext, () => this.syncWithServer());
23960
+ for (const arrived of [...this.credentialArrived]) arrived();
23961
+ this.session?.redial(true);
23842
23962
  return { ok: true };
23843
23963
  },
23844
23964
  "device.clearCredential": () => {
@@ -23848,6 +23968,7 @@ var Daemon = class {
23848
23968
  this.revokeLocalComputerGrants();
23849
23969
  this.registered = false;
23850
23970
  this.server = "unregistered";
23971
+ this.session?.redial(true);
23851
23972
  return { ok: true };
23852
23973
  },
23853
23974
  "runs.start": (raw) => {
@@ -23898,7 +24019,7 @@ var Daemon = class {
23898
24019
  }
23899
24020
  /** Graceful stop: active runs stay journaled and resume on next start. */
23900
24021
  maintenanceIdle() {
23901
- return !this.stopped && !this.draining && !this.updating && this.claimsInFlight === 0 && this.supervisor.heartbeatRuns().length === 0;
24022
+ return !this.stopped && !this.draining && !this.updating && this.claimsInFlight === 0 && this.supervisor.activeRunIds().length === 0;
23902
24023
  }
23903
24024
  startMaintenance(work, failed = () => {
23904
24025
  }) {
@@ -23913,9 +24034,9 @@ var Daemon = class {
23913
24034
  });
23914
24035
  }
23915
24036
  get updateStateFile() {
23916
- return join36(this.paths.dataDir, "auto-update.json");
24037
+ return join35(this.paths.dataDir, "auto-update.json");
23917
24038
  }
23918
- /** A server named this release (heartbeat, commands poll or refused claim); older servers name none. */
24039
+ /** A server named this release (a report answer, a commands read, a 426), or npm did for a refused daemon. */
23919
24040
  learnRelease(latest) {
23920
24041
  if (newerStableVersion(latest, this.knownLatest ?? DAEMON_VERSION)) this.knownLatest = latest;
23921
24042
  this.offerUpdate(latest);
@@ -23925,7 +24046,7 @@ var Daemon = class {
23925
24046
  if (!this.options.autoUpdate || this.updating || this.updateVersion || !newerStableVersion(latest, DAEMON_VERSION)) return;
23926
24047
  if (updateAllowed(this.updateStateFile, latest)) this.updateVersion = latest;
23927
24048
  }
23928
- /** Installs the release a server named once no run or claim is active; called again by every heartbeat. */
24049
+ /** Installs the named release once no run or claim is active; the local timer calls it again. */
23929
24050
  checkAutoUpdate() {
23930
24051
  const runtime = this.options.autoUpdate;
23931
24052
  if (!runtime || this.draining || this.updating || !this.updateVersion || !this.maintenanceIdle()) return;
@@ -23941,15 +24062,19 @@ var Daemon = class {
23941
24062
  }, void 0, () => !this.stopped);
23942
24063
  }, () => {
23943
24064
  recordUpdateFailure(this.updateStateFile, version, code);
24065
+ void this.reportNow();
23944
24066
  });
23945
24067
  }
23946
24068
  /**
23947
- * `daemon.update`: ask the server now (one heartbeat, which names its release)
23948
- * instead of waiting for the next one; never npm. The install still waits for idle.
24069
+ * `daemon.update`: ask the server now (one pass, whose commands read names
24070
+ * its release) instead of waiting for a push. A daemon the server refused
24071
+ * asks npm instead. The install still waits for idle.
23949
24072
  */
23950
24073
  async requestUpdate() {
23951
24074
  if (!this.options.autoUpdate) return "unmanaged";
23952
- if (!this.updating && !this.updateVersion) await this.syncWithServer().catch(() => void 0);
24075
+ if (this.blocked === "update_required") {
24076
+ if (!this.updating && !this.updateVersion) await this.findRequiredUpdate(this.requiredVersion);
24077
+ } else if (!this.updating && !this.updateVersion && this.sessionOpen) await this.syncWithServer().catch(() => void 0);
23953
24078
  this.checkAutoUpdate();
23954
24079
  return this.updating ? "installing" : this.updateVersion ? "waiting" : "current";
23955
24080
  }
@@ -23962,14 +24087,16 @@ var Daemon = class {
23962
24087
  this.localComputerBroker?.suspend();
23963
24088
  await this.starting?.catch(() => void 0);
23964
24089
  await this.maintenance;
23965
- if (this.timer) clearTimeout(this.timer);
24090
+ if (this.localTimer) clearInterval(this.localTimer);
24091
+ if (this.rotationTimer) clearTimeout(this.rotationTimer);
23966
24092
  await this.quota?.stop();
23967
- this.commandsAbort.abort();
24093
+ this.lifetime.abort();
24094
+ for (const arrived of [...this.credentialArrived]) arrived();
24095
+ await this.session?.stop();
23968
24096
  this.reviewAbort?.abort();
23969
24097
  await this.reviewLoop.catch(() => void 0);
23970
- await this.commandsLoop.catch(() => void 0);
23971
- await this.fsLoop.catch(() => void 0);
23972
- await this.tick;
24098
+ await this.syncing;
24099
+ await this.checkpointScan;
23973
24100
  await Promise.allSettled(this.claims.values());
23974
24101
  await this.rpc?.close();
23975
24102
  try {
@@ -23996,6 +24123,7 @@ async function startDaemon(options) {
23996
24123
  export {
23997
24124
  DAEMON_VERSION,
23998
24125
  DEFAULT_LEASE_MS,
24126
+ DEVICE_SESSION_LOCAL_GRACE_MS,
23999
24127
  Daemon,
24000
24128
  MAX_CONTINUES,
24001
24129
  MAX_CRASH_RETRIES,