@aspectlylabs/mikka 0.0.702 → 0.0.704

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/http-link.js CHANGED
@@ -3110,9 +3110,6 @@ var CHAT_AUDIO_EXTENSIONS = new Set("wav mp3 mpeg oga ogg flac aac m4a webm mp4
3110
3110
  var CHAT_FILE_ACCEPT = [...CHAT_TEXT_EXTENSIONS, ...CHAT_DOCUMENT_EXTENSIONS, ...CHAT_IMAGE_EXTENSIONS, ...CHAT_AUDIO_EXTENSIONS].map((ext) => `.${ext}`).join(",") + ",text/*";
3111
3111
 
3112
3112
  // src/agents/tool-approval.ts
3113
- var RUN_CONTROL_LEGACY_MS = 1e3;
3114
- var RUN_CONTROL_FALLBACK_MS = 2e4;
3115
- var cadence = (mode) => mode === "push" ? void 0 : mode === "fallback" ? RUN_CONTROL_FALLBACK_MS : RUN_CONTROL_LEGACY_MS;
3116
3113
  var MAX_TIMER_MS = 2 ** 31 - 1;
3117
3114
  async function abortable(work, signal) {
3118
3115
  if (signal.aborted) throw new Error("cancelled");
@@ -3128,10 +3125,9 @@ async function abortable(work, signal) {
3128
3125
  }
3129
3126
  }
3130
3127
  var ToolApprovalGate = class {
3131
- constructor(runId, host, mode = "legacy") {
3128
+ constructor(runId, host) {
3132
3129
  this.runId = runId;
3133
3130
  this.host = host;
3134
- this.mode = mode;
3135
3131
  }
3136
3132
  runId;
3137
3133
  host;
@@ -3139,19 +3135,12 @@ var ToolApprovalGate = class {
3139
3135
  checking;
3140
3136
  reason;
3141
3137
  monitors = /* @__PURE__ */ new Set();
3142
- timer;
3143
- intervalMs;
3144
3138
  monitoring;
3145
3139
  dirty = false;
3146
- /** A push, mode switch or due time is waiting for the monitor loop. */
3147
- pushed = false;
3148
- mode;
3149
3140
  changes = /* @__PURE__ */ new Set();
3150
3141
  revoke(reason) {
3151
3142
  if (this.revoked) return;
3152
3143
  this.reason = reason;
3153
- clearInterval(this.timer);
3154
- this.timer = void 0;
3155
3144
  for (const monitor of this.monitors) clearTimeout(monitor.due);
3156
3145
  this.monitors.clear();
3157
3146
  this.stop.abort();
@@ -3163,9 +3152,6 @@ var ToolApprovalGate = class {
3163
3152
  get revokeReason() {
3164
3153
  return this.reason;
3165
3154
  }
3166
- get controlMode() {
3167
- return this.mode;
3168
- }
3169
3155
  onRevoke(callback) {
3170
3156
  if (this.revoked) {
3171
3157
  callback();
@@ -3185,25 +3171,15 @@ var ToolApprovalGate = class {
3185
3171
  }
3186
3172
  return this.checking;
3187
3173
  }
3188
- /** Switches how this gate learns of changes. Any switch checks again at
3189
- * once: a push may have been lost while the socket was changing state. */
3190
- setControlMode(mode) {
3191
- if (this.revoked || mode === this.mode) return;
3192
- this.mode = mode;
3193
- this.scheduleMonitor();
3194
- this.invalidate();
3195
- }
3196
- /** Resolves on the next push or mode switch, or after the mode's cadence.
3197
- * A paused run waits here instead of asking the server every second. */
3174
+ /** Resolves on the next push or revocation. A paused run waits here instead
3175
+ * of asking the server on a timer. */
3198
3176
  changed(signal) {
3199
3177
  return new Promise((resolve, reject) => {
3200
3178
  if (signal.aborted || this.revoked) {
3201
3179
  reject(new Error("cancelled"));
3202
3180
  return;
3203
3181
  }
3204
- let timer;
3205
3182
  const done = (error) => {
3206
- clearTimeout(timer);
3207
3183
  this.changes.delete(wake);
3208
3184
  signal.removeEventListener("abort", abort);
3209
3185
  if (error) reject(error);
@@ -3211,8 +3187,6 @@ var ToolApprovalGate = class {
3211
3187
  };
3212
3188
  const wake = () => done(this.revoked ? new Error("cancelled") : void 0);
3213
3189
  const abort = () => done(new Error("cancelled"));
3214
- const ms2 = cadence(this.mode);
3215
- if (ms2 !== void 0) timer = setTimeout(wake, ms2);
3216
3190
  this.changes.add(wake);
3217
3191
  signal.addEventListener("abort", abort, { once: true });
3218
3192
  });
@@ -3220,37 +3194,22 @@ var ToolApprovalGate = class {
3220
3194
  wake() {
3221
3195
  for (const wake of [...this.changes]) wake();
3222
3196
  }
3223
- /** Watches the run while it lasts: one background liveness check per run,
3224
- * on each push (invalidate) and, only when the gateway cannot push, on the
3225
- * mode's cadence. Extra checks (credentials, subscription access) share each
3197
+ /** Watches the run while it lasts: one background liveness check per push
3198
+ * (invalidate). Extra checks (credentials, subscription access) share each
3226
3199
  * fresh result; a check may return an epoch ms (an expiry) by which it runs
3227
3200
  * again. Actual operations still call checkLive. Slow credential I/O never
3228
- * delays the next liveness check. `intervalMs` only shortens a timed cadence. */
3229
- watch(check, intervalMs, options = {}) {
3201
+ * delays the next liveness check. */
3202
+ watch(check, options = {}) {
3230
3203
  if (this.revoked) return () => {
3231
3204
  };
3232
- if (intervalMs !== void 0 && (!Number.isFinite(intervalMs) || intervalMs <= 0 || intervalMs > RUN_CONTROL_FALLBACK_MS)) throw new Error("Run monitor interval unavailable");
3233
- const { timedFloorMs } = options;
3234
- if (timedFloorMs !== void 0 && (!Number.isFinite(timedFloorMs) || timedFloorMs <= 0)) throw new Error("Run monitor interval unavailable");
3235
- const monitor = { check, running: false, dirty: false, intervalMs, timedFloorMs };
3205
+ const monitor = { check, running: false, dirty: false };
3236
3206
  this.monitors.add(monitor);
3237
- this.scheduleMonitor();
3238
3207
  if (options.dueAt !== void 0) this.due(monitor, options.dueAt);
3239
3208
  return () => {
3240
3209
  clearTimeout(monitor.due);
3241
3210
  this.monitors.delete(monitor);
3242
- this.scheduleMonitor();
3243
3211
  };
3244
3212
  }
3245
- scheduleMonitor() {
3246
- const base = cadence(this.mode);
3247
- const intervalMs = this.monitors.size && base !== void 0 ? Math.min(base, ...[...this.monitors].flatMap((monitor) => monitor.intervalMs ?? [])) : void 0;
3248
- if (intervalMs === this.intervalMs) return;
3249
- clearInterval(this.timer);
3250
- this.intervalMs = intervalMs;
3251
- this.timer = intervalMs === void 0 ? void 0 : setInterval(() => this.requestCheck(false), intervalMs);
3252
- this.timer?.unref();
3253
- }
3254
3213
  /** One timer per watcher at its reported due time, never a cadence. */
3255
3214
  due(monitor, at) {
3256
3215
  clearTimeout(monitor.due);
@@ -3266,20 +3225,16 @@ var ToolApprovalGate = class {
3266
3225
  /** A push invalidates an in-flight check as well as a settled one. */
3267
3226
  invalidate() {
3268
3227
  this.wake();
3269
- this.requestCheck(true);
3228
+ this.requestCheck();
3270
3229
  }
3271
- requestCheck(invalidated) {
3230
+ requestCheck() {
3272
3231
  if (this.revoked || !this.monitors.size) return;
3273
- if (this.monitoring && !invalidated) return;
3274
3232
  this.dirty = true;
3275
- if (invalidated) this.pushed = true;
3276
3233
  if (this.monitoring) return;
3277
- let olderOperation = invalidated && this.checking !== void 0;
3234
+ let olderOperation = this.checking !== void 0;
3278
3235
  this.monitoring = (async () => {
3279
3236
  while (this.dirty && !this.revoked && this.monitors.size) {
3280
3237
  this.dirty = false;
3281
- const pushed = this.pushed;
3282
- this.pushed = false;
3283
3238
  if (!await this.checkLive()) {
3284
3239
  this.revoke();
3285
3240
  return;
@@ -3287,19 +3242,16 @@ var ToolApprovalGate = class {
3287
3242
  if (olderOperation) {
3288
3243
  olderOperation = false;
3289
3244
  this.dirty = true;
3290
- this.pushed ||= pushed;
3291
3245
  continue;
3292
3246
  }
3293
3247
  for (const monitor of this.monitors) {
3294
3248
  if (!monitor.check) continue;
3295
- if (!pushed && monitor.timedFloorMs !== void 0 && monitor.lastRun !== void 0 && performance.now() - monitor.lastRun < monitor.timedFloorMs) continue;
3296
3249
  monitor.dirty = true;
3297
3250
  if (monitor.running) continue;
3298
3251
  monitor.running = true;
3299
3252
  void (async () => {
3300
3253
  while (monitor.dirty && !this.revoked && this.monitors.has(monitor)) {
3301
3254
  monitor.dirty = false;
3302
- monitor.lastRun = performance.now();
3303
3255
  const due = await monitor.check();
3304
3256
  this.due(monitor, due);
3305
3257
  }
@@ -3312,7 +3264,7 @@ var ToolApprovalGate = class {
3312
3264
  }
3313
3265
  })().finally(() => {
3314
3266
  this.monitoring = void 0;
3315
- if (this.dirty) this.requestCheck(true);
3267
+ if (this.dirty) this.requestCheck();
3316
3268
  });
3317
3269
  }
3318
3270
  };
@@ -4395,6 +4347,15 @@ var daemonStatusSchema = z23.object({
4395
4347
  /** Holds a device credential (it may still be refused by the server). */
4396
4348
  signedIn: z23.boolean(),
4397
4349
  server: z23.enum(["online", "offline", "unregistered"]),
4350
+ /**
4351
+ * The device session (decision 2026-11-17-2215). `update_required`: the
4352
+ * server refused this daemon version; it does nothing until it is updated.
4353
+ * `gateway_required`: the server has no device gateway, so it has no devices.
4354
+ * Absent from older daemons.
4355
+ */
4356
+ session: z23.enum(["signed_out", "connecting", "open", "update_required", "gateway_required"]).optional(),
4357
+ /** With `update_required`: the oldest version the server accepts, if it said. */
4358
+ requiredVersion: z23.string().max(40).nullable().optional(),
4398
4359
  harnesses: z23.array(harnessInfoSchema),
4399
4360
  runs: z23.array(runSummarySchema),
4400
4361
  /** Bytes used by run worktrees under the daemon's data dir. */
@@ -4558,7 +4519,7 @@ var runDecisionCatalogueSchema = z26.object({
4558
4519
  var seg = encodeURIComponent;
4559
4520
  var DEVICE_ROUTES = {
4560
4521
  register: "/v1/devices/register",
4561
- heartbeat: "/v1/devices/:deviceId/heartbeat",
4522
+ report: "/v1/devices/:deviceId/report",
4562
4523
  repos: "/v1/devices/:deviceId/repos",
4563
4524
  pendingRuns: "/v1/devices/:deviceId/runs",
4564
4525
  claim: "/v1/devices/:deviceId/runs/:runId/claim",
@@ -4570,7 +4531,7 @@ var DEVICE_ROUTES = {
4570
4531
  };
4571
4532
  var devicePaths = {
4572
4533
  register: () => DEVICE_ROUTES.register,
4573
- heartbeat: (deviceId) => `/v1/devices/${seg(deviceId)}/heartbeat`,
4534
+ report: (deviceId) => `/v1/devices/${seg(deviceId)}/report`,
4574
4535
  repos: (deviceId) => `/v1/devices/${seg(deviceId)}/repos`,
4575
4536
  pendingRuns: (deviceId) => `/v1/devices/${seg(deviceId)}/runs?state=queued`,
4576
4537
  claim: (deviceId, runId) => `/v1/devices/${seg(deviceId)}/runs/${seg(runId)}/claim`,
@@ -4625,69 +4586,48 @@ var deviceRegistered = z26.object({
4625
4586
  environment: z26.enum(["production", "preview", "dev"]).optional()
4626
4587
  }).optional().catch(void 0)
4627
4588
  });
4628
- var heartbeatRunSchema = z26.object({
4629
- runId: id3,
4630
- /** Last tool call, turn boundary or file change (not raw output). */
4631
- lastProgressAt: isoTime,
4632
- /** Opaque third-party capabilities, refreshed only with the existing run lease. */
4633
- secretCapabilities: taskSecretRenewalSchema.optional()
4634
- });
4589
+ var DEVICE_SESSION_HEADER = "x-mikka-device-session";
4590
+ var DEVICE_SESSION_VERSION = 1;
4591
+ var SESSION_LEASE_MS = 7 * 24 * 60 * 60 * 1e3;
4592
+ var deviceSessionReportSchema = z26.object({
4593
+ state: z26.enum(["connected", "disconnected"]),
4594
+ /** When the socket opened, or closed (or last answered a ping). */
4595
+ at: isoTime,
4596
+ /** One value per socket; a report for an older socket never overrides a newer one. */
4597
+ socketId: z26.string().regex(/^[A-Za-z0-9_-]{8,64}$/)
4598
+ }).strict();
4635
4599
  var stableVersion = z26.string().regex(/^(0|[1-9]\d{0,8})\.(0|[1-9]\d{0,8})\.(0|[1-9]\d{0,8})$/);
4636
4600
  var daemonVersionsSchema = z26.object({ min: stableVersion, latest: stableVersion.optional() });
4637
4601
  var daemonUpdateFailureSchema = z26.object({ version: stableVersion, code: z26.enum(["install_failed", "restart_failed"]), at: isoTime });
4638
4602
  var deviceManagementCommand = z26.object({ id: z26.uuid(), kind: z26.enum(["redetect", "restart", "update", "uninstall"]) });
4639
- var deviceHeartbeatSchema = z26.object({
4603
+ var deviceReportSchema = z26.object({
4640
4604
  completedDeviceCommands: z26.array(z26.uuid()).max(100).optional(),
4641
4605
  failedDeviceCommands: z26.array(z26.object({ id: z26.uuid(), error: z26.string().max(500) })).max(100).optional(),
4642
- harnesses: z26.array(harnessInfoSchema).max(20),
4606
+ harnesses: z26.array(harnessInfoSchema).max(20).optional(),
4643
4607
  computerUse: deviceComputerCapability.optional(),
4644
4608
  runner: deviceRunnerCapability.optional(),
4645
4609
  deviceType: z26.enum(["laptop", "server"]).optional(),
4646
- runs: z26.array(heartbeatRunSchema).max(500),
4647
- worktreeDiskBytes: z26.number().int().nonnegative(),
4648
- /**
4649
- * Subscription windows read on this device. Absent when the daemon is not
4650
- * polling. Numbers only, never a vendor credential (ADR 0027).
4651
- */
4610
+ worktreeDiskBytes: z26.number().int().nonnegative().optional(),
4611
+ /** Subscription windows read on this device. Numbers only, never a vendor credential (ADR 0027). */
4652
4612
  quotas: z26.array(quotaSnapshotSchema).max(6).optional(),
4653
4613
  /** Null once no automatic update has failed since the last success. */
4654
- updateFailure: daemonUpdateFailureSchema.nullable().optional()
4614
+ updateFailure: daemonUpdateFailureSchema.nullable().optional(),
4615
+ /** A cloud worker asks for its next token once, an hour before the current one expires. */
4616
+ rotateCloudCredential: z26.literal(true).optional()
4655
4617
  });
4656
- var heartbeatResultSchema = z26.object({
4618
+ var deviceReportResultSchema = z26.object({
4657
4619
  deviceCommands: z26.array(deviceManagementCommand).max(1).optional(),
4658
- /** Renewed lease expiry per run id; a run missing here is not renewed. */
4659
- leases: z26.record(z26.string(), isoTime),
4660
- /** No plaintext: only grants for current owner/device/run/claim bindings. */
4661
- taskSecrets: z26.record(z26.string(), taskSecretAccessSchema).optional(),
4662
- /**
4663
- * Runs the device reported that it no longer holds: they ended on the
4664
- * server, or went to another attempt after the lease ran out. The daemon
4665
- * stops them now instead of when their lease runs out.
4666
- */
4667
- revoked: z26.array(id3).max(500).optional(),
4668
- /** Subset of revoked caused by an explicit cancel on an otherwise current claim. */
4669
- cancelled: z26.array(id3).max(500).optional(),
4670
4620
  /** Short-lived cloud device token, returned only over its authenticated link. */
4671
4621
  cloudCredential: z26.string().regex(/^orv_[A-Za-z0-9_-]{43}$/).optional(),
4672
- /** A malformed value is dropped, never a failed heartbeat. */
4622
+ cloudCredentialExpiresAt: isoTime.optional(),
4623
+ /** A malformed value is dropped, never a failed report. */
4673
4624
  daemonVersions: daemonVersionsSchema.optional().catch(void 0)
4674
4625
  });
4675
4626
  var deviceGatewaySchema = z26.object({
4676
- url: z26.string().url().nullable(),
4677
- protocol: z26.string().regex(/^mikka-ticket-[0-9]+-[a-f0-9]{64}$/).nullable(),
4678
- /** This server wakes the device after every write that can end, pause or
4679
- * revoke one of its runs (stop, lease, credential, policy, membership), so a
4680
- * connected daemon needs no periodic run-control check (#1212). Absent from
4681
- * older servers: the daemon then keeps its one-second check. */
4682
- runControl: z26.literal("push").optional(),
4683
- /** This server wakes the device when a person decides a computer review in
4684
- * the web, so a connected daemon syncs pending reviews only on a change or a
4685
- * push, plus a presence refresh (#1212). Absent from older servers: the
4686
- * daemon then keeps syncing every second while a review is pending. */
4687
- computerReviews: z26.literal("push").optional(),
4688
- /** This server wakes the device when it writes a native Coordinator tool
4689
- * result, so the waiting tool asks once per push, not every 500 ms. */
4690
- coordinatorResults: z26.literal("push").optional()
4627
+ url: z26.string().url(),
4628
+ protocol: z26.string().regex(/^mikka-ticket-[0-9]+-[a-f0-9]{64}$/),
4629
+ /** Cloud workers only: when the current device token expires. */
4630
+ cloudCredentialExpiresAt: isoTime.optional()
4691
4631
  });
4692
4632
  var RUN_CHECKPOINT_MAX_BYTES = 8 * 1024 * 1024;
4693
4633
  var RECOVERY_WORKTREE_HEADER = "x-mikka-recovery-worktree";
@@ -4846,7 +4786,7 @@ var runAssignmentSchema = z26.object({
4846
4786
  /** Host-owned Factory check mode; the model cannot grant a check or skip verification. */
4847
4787
  factoryCheck: z26.object({ stage: z26.enum(["review", "verify"]), inferCommand: z26.boolean(), reportOnly: z26.boolean() }).strict().optional(),
4848
4788
  factoryExecuteKind: z26.enum(["repository", "report", "deliverable"]).optional(),
4849
- /** Run lease; renewed through the device heartbeat. */
4789
+ /** Run lease in the database: it lasts as long as the device session that claimed the run. */
4850
4790
  leaseExpiresAt: isoTime.optional(),
4851
4791
  /**
4852
4792
  * The Mikka MCP server for the agent inside this run: `report`, `ask` and
@@ -5004,14 +4944,13 @@ var runCommandsResponse = z26.object({
5004
4944
  /** Owner-scoped reads, delivered only to a daemon advertising protocol v1. */
5005
4945
  workspaceRequests: z26.array(workspaceReadCommand).max(4).optional(),
5006
4946
  /**
5007
- * Runs queued for this device (outside `skip`), so it claims them now
5008
- * instead of on its next heartbeat. A queued run also ends the long-poll.
5009
- * Absent from older servers; the heartbeat still claims either way.
4947
+ * Runs queued for this device (outside `skip`), so it claims them as soon
4948
+ * as the gateway signals work.
5010
4949
  */
5011
4950
  queuedRuns: z26.array(id3).max(100).optional(),
5012
4951
  /** Only for a daemon that sent `COMMANDS_DAEMON_LATEST_PARAM`; a malformed value is dropped. */
5013
4952
  daemonVersions: daemonVersionsSchema.optional().catch(void 0),
5014
- /** The oldest pending device command (as the heartbeat's), so a person's update reaches the device now. */
4953
+ /** The oldest pending device command, so a person's update reaches the device now. */
5015
4954
  deviceCommands: z26.array(deviceManagementCommand).max(1).optional().catch(void 0)
5016
4955
  });
5017
4956
  var runCommandsAck = z26.object({
@@ -5615,19 +5554,34 @@ var ServerUnreachableError = class extends DaemonError {
5615
5554
  this.cause = cause;
5616
5555
  }
5617
5556
  };
5618
- var RunNotPinnedHereError = class extends DaemonError {
5619
- /** The server refused the claim because this daemon is too old (code `daemonUpgradeRequired`). */
5620
- upgradeRequired;
5557
+ var DaemonUpgradeRequiredError = class extends ServerUnreachableError {
5621
5558
  /** The release the refusing server names, when it names one. */
5622
5559
  latest;
5623
- constructor(runId, upgradeRequired = false, latest) {
5560
+ constructor(latest) {
5561
+ super("daemonUpgradeRequired");
5562
+ this.message = "This daemon is too old for the server; update it.";
5563
+ this.latest = latest;
5564
+ }
5565
+ };
5566
+ var DeviceGatewayRequiredError = class extends ServerUnreachableError {
5567
+ constructor() {
5568
+ super("deviceGatewayRequired");
5569
+ this.message = "The server has no device gateway.";
5570
+ }
5571
+ };
5572
+ var DeviceSessionRequiredError = class extends ServerUnreachableError {
5573
+ constructor() {
5574
+ super("deviceSessionRequired");
5575
+ this.message = "The server has no open session for this device.";
5576
+ }
5577
+ };
5578
+ var RunNotPinnedHereError = class extends DaemonError {
5579
+ constructor(runId) {
5624
5580
  super(
5625
5581
  DAEMON_RPC_ERRORS.runNotPinnedHere,
5626
5582
  `Run "${runId}" is pinned to another device`,
5627
5583
  { runId }
5628
5584
  );
5629
- this.upgradeRequired = upgradeRequired;
5630
- this.latest = latest;
5631
5585
  }
5632
5586
  };
5633
5587
  var InvalidIdError = class extends DaemonError {
@@ -5639,7 +5593,7 @@ var InvalidIdError = class extends DaemonError {
5639
5593
  // package.json
5640
5594
  var package_default = {
5641
5595
  name: "@mikka/daemon",
5642
- version: "0.0.702",
5596
+ version: "0.0.704",
5643
5597
  description: "Local Mikka daemon: runs agents through the user's own CLIs",
5644
5598
  type: "module",
5645
5599
  private: true,
@@ -5707,7 +5661,7 @@ var package_default = {
5707
5661
  engines: {
5708
5662
  node: ">=22"
5709
5663
  },
5710
- gitHead: "510757b2cbb43beaadeb284abcc4f36a262ea371"
5664
+ gitHead: "a5c45e4d686a337f5dd0ea0acbac2e1e70aa9e03"
5711
5665
  };
5712
5666
 
5713
5667
  // src/paths.ts
@@ -7013,7 +6967,7 @@ var RunRuntimeTimings = class {
7013
6967
  if (!observation2 || observation2.deviceHash !== runIdHash(decodeURIComponent(github[1]))) return NOOP2;
7014
6968
  return observation2.request(this.refresh.getStore() === hash2 ? "github_credential_refresh" : "github_credential_lease", verb, false);
7015
6969
  }
7016
- const device = /^\/v1\/devices\/([^/]+)\/(heartbeat|gateway|commands|runs)$/.exec(clean);
6970
+ const device = /^\/v1\/devices\/([^/]+)\/(report|gateway|commands|runs)$/.exec(clean);
7017
6971
  if (!device) return NOOP2;
7018
6972
  const hash = runIdHash(decodeURIComponent(device[1]));
7019
6973
  const pending = [...this.runs.values()].filter((observation2) => observation2.deviceHash === hash).map((observation2) => observation2.request("device_control", verb, true));
@@ -7028,8 +6982,13 @@ var RunRuntimeTimings = class {
7028
6982
  var runRuntimeTimings = new RunRuntimeTimings();
7029
6983
 
7030
6984
  // src/server-link-http.ts
7031
- var LIVENESS_UNREACHABLE_GRACE_MS = 3e4;
7032
6985
  var deviceSessionRejection = z35.object({ error: z35.enum(["Unauthorized", "authRequired"]) }).strict();
6986
+ var refusalCode = (body) => {
6987
+ if (typeof body !== "object" || body === null) return void 0;
6988
+ const { code, error } = body;
6989
+ return typeof code === "string" ? code : typeof error === "string" ? error : void 0;
6990
+ };
6991
+ var deviceSessionHeaders = { [DEVICE_SESSION_HEADER]: String(DEVICE_SESSION_VERSION) };
7033
6992
  function checkId(id4) {
7034
6993
  if (id4 === "" || id4 === "." || id4 === "..") {
7035
6994
  throw new InvalidIdError(`Refusing id ${JSON.stringify(id4)} in a URL path`);
@@ -7066,15 +7025,13 @@ var HttpServerLink = class {
7066
7025
  clientVersion;
7067
7026
  protectionBypass;
7068
7027
  runControls = /* @__PURE__ */ new Set();
7069
- runControlMode = "legacy";
7028
+ upgradeListeners = /* @__PURE__ */ new Set();
7070
7029
  /** Wake local waiters; the same push drains authoritative stop commands. */
7071
7030
  invalidateRunControls() {
7072
7031
  for (const gate of this.runControls) gate.invalidate();
7073
7032
  }
7074
- /** The daemon reports whether the gateway can push run control to this run. */
7075
- setRunControlMode(mode) {
7076
- this.runControlMode = mode;
7077
- for (const gate of this.runControls) gate.setControlMode(mode);
7033
+ onUpgradeRequired(listener) {
7034
+ this.upgradeListeners.add(listener);
7078
7035
  }
7079
7036
  async downloadChatFile(assignment, id4, signal) {
7080
7037
  const transfer = await this.call("GET", `/v1/devices/${seg2(assignment.deviceId)}/runs/${seg2(assignment.runId)}/attachments/${seg2(id4)}`, { schema: chatFileTransferSchema, signal, timeoutMs: 6e4 });
@@ -7156,7 +7113,7 @@ var HttpServerLink = class {
7156
7113
  return false;
7157
7114
  }
7158
7115
  }
7159
- }, this.runControlMode);
7116
+ });
7160
7117
  this.runControls.add(gate);
7161
7118
  const abort = () => gate.revoke();
7162
7119
  gate.onRevoke(() => {
@@ -7174,7 +7131,7 @@ var HttpServerLink = class {
7174
7131
  check,
7175
7132
  endpoint: serverUrl(this.baseUrl, "/api/mcp"),
7176
7133
  fetch: (url, init) => this.taskFetch(assignment.runId, "mailbox_operation", url, init),
7177
- headers: { [CLIENT_VERSION_HEADER]: this.clientVersion, ...this.protectionBypass ? { "x-vercel-protection-bypass": this.protectionBypass } : {} }
7134
+ headers: { [CLIENT_VERSION_HEADER]: this.clientVersion, ...deviceSessionHeaders, ...this.protectionBypass ? { "x-vercel-protection-bypass": this.protectionBypass } : {} }
7178
7135
  });
7179
7136
  }
7180
7137
  async claimCoordinator(deviceId, signal) {
@@ -7245,6 +7202,7 @@ var HttpServerLink = class {
7245
7202
  [WORKSPACE_REQUEST_HEADER]: "1",
7246
7203
  [WORKSPACE_DIFF_REQUEST_HEADER]: "1",
7247
7204
  [WORKSPACE_GIT_REQUEST_HEADER]: "1",
7205
+ ...deviceSessionHeaders,
7248
7206
  ...daemonTracer.headers(),
7249
7207
  ...token ? { authorization: `Bearer ${token}` } : {},
7250
7208
  ...this.protectionBypass ? { "x-vercel-protection-bypass": this.protectionBypass } : {}
@@ -7256,6 +7214,13 @@ var HttpServerLink = class {
7256
7214
  status2 = response.status;
7257
7215
  if (response.redirected || response.status >= 300 && response.status < 400)
7258
7216
  throw new Error(`Unexpected server redirect (${response.status})`);
7217
+ if (response.status === 426) {
7218
+ const refused = await response.json().catch(() => null);
7219
+ const versions = typeof refused === "object" && refused !== null ? refused.daemonVersions : void 0;
7220
+ const latest = daemonVersionsSchema.safeParse(versions).data?.latest;
7221
+ for (const listener of [...this.upgradeListeners]) listener(latest);
7222
+ throw new DaemonUpgradeRequiredError(latest);
7223
+ }
7259
7224
  if (response.status === 401) {
7260
7225
  const body2 = await response.clone().json().catch(() => null);
7261
7226
  if (!deviceSessionRejection.safeParse(body2).success)
@@ -7263,6 +7228,7 @@ var HttpServerLink = class {
7263
7228
  }
7264
7229
  return response;
7265
7230
  } catch (error) {
7231
+ if (error instanceof DaemonUpgradeRequiredError) throw error;
7266
7232
  throw new ServerUnreachableError(error);
7267
7233
  } finally {
7268
7234
  measured(status2);
@@ -7276,13 +7242,17 @@ var HttpServerLink = class {
7276
7242
  this.credential,
7277
7243
  { timeoutMs: options.timeoutMs, signal: options.signal, initialRepository: options.initialRepository }
7278
7244
  );
7245
+ if (response.status === 503 && options.gatewayRequired) {
7246
+ const body = await response.clone().json().catch(() => null);
7247
+ if (refusalCode(body) === "deviceGatewayRequired") throw new DeviceGatewayRequiredError();
7248
+ }
7279
7249
  if (response.status >= 500 || response.status === 429)
7280
7250
  throw new ServerUnreachableError(response.status);
7281
7251
  if (response.status === 401) throw new SessionRejectedError();
7282
7252
  if (response.status === 409 && options.claimOf) {
7283
7253
  const body = await response.json().catch(() => null);
7284
- const upgradeRequired = body?.code === "daemonUpgradeRequired";
7285
- throw new RunNotPinnedHereError(options.claimOf, upgradeRequired, upgradeRequired ? daemonVersionsSchema.safeParse(body?.daemonVersions).data?.latest : void 0);
7254
+ if (refusalCode(body) === "deviceSessionRequired") throw new DeviceSessionRequiredError();
7255
+ throw new RunNotPinnedHereError(options.claimOf);
7286
7256
  }
7287
7257
  if (!response.ok) {
7288
7258
  const detail = await response.json().then(
@@ -7313,10 +7283,10 @@ var HttpServerLink = class {
7313
7283
  });
7314
7284
  return { deviceId, tracing };
7315
7285
  }
7316
- async heartbeat(deviceId, status2) {
7317
- return this.call("POST", devicePaths.heartbeat(checkId(deviceId)), {
7318
- body: status2,
7319
- schema: heartbeatResultSchema
7286
+ async report(deviceId, report) {
7287
+ return this.call("POST", devicePaths.report(checkId(deviceId)), {
7288
+ body: report,
7289
+ schema: deviceReportResultSchema
7320
7290
  });
7321
7291
  }
7322
7292
  async listRepos(deviceId) {
@@ -7388,7 +7358,7 @@ var HttpServerLink = class {
7388
7358
  try {
7389
7359
  response = await this.taskFetch(runId, server ? "task_data" : "storage_transfer", server ? serverUrl(this.baseUrl, capturePaths.upload(checkId(runId), checkId(captureId))) : upload.url, {
7390
7360
  method: "PUT",
7391
- headers: server ? { "content-type": contentType, [CLIENT_VERSION_HEADER]: this.clientVersion, ...this.credential ? { authorization: `Bearer ${this.credential}` } : {}, ...this.protectionBypass ? { "x-vercel-protection-bypass": this.protectionBypass } : {} } : upload.headers,
7361
+ headers: server ? { "content-type": contentType, [CLIENT_VERSION_HEADER]: this.clientVersion, ...deviceSessionHeaders, ...this.credential ? { authorization: `Bearer ${this.credential}` } : {}, ...this.protectionBypass ? { "x-vercel-protection-bypass": this.protectionBypass } : {} } : upload.headers,
7392
7362
  body: bytes,
7393
7363
  redirect: "error",
7394
7364
  signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(3e5)]) : AbortSignal.timeout(3e5)
@@ -7396,6 +7366,10 @@ var HttpServerLink = class {
7396
7366
  } catch (error) {
7397
7367
  throw new ServerUnreachableError(error);
7398
7368
  }
7369
+ if (response.status === 426 && server) {
7370
+ for (const listener of [...this.upgradeListeners]) listener();
7371
+ throw new DaemonUpgradeRequiredError();
7372
+ }
7399
7373
  if (response.status >= 500 || response.status === 429) throw new ServerUnreachableError(response.status);
7400
7374
  if (response.status === 401 && server) throw new SessionRejectedError();
7401
7375
  if (!response.ok) throw new DaemonError(response.status, `PUT capture failed: ${response.status}`, { status: response.status });
@@ -7429,7 +7403,9 @@ var HttpServerLink = class {
7429
7403
  return this.call("GET", devicePaths.gateway(checkId(deviceId)), {
7430
7404
  schema: deviceGatewaySchema,
7431
7405
  signal,
7432
- timeoutMs: 1e4
7406
+ timeoutMs: 1e4,
7407
+ // A server without a gateway has no devices: a refusal, not an outage.
7408
+ gatewayRequired: true
7433
7409
  });
7434
7410
  }
7435
7411
  async fetchCommands(deviceId, waitSeconds, {
@@ -7510,9 +7486,9 @@ var HttpServerLink = class {
7510
7486
  };
7511
7487
  export {
7512
7488
  HttpServerLink,
7513
- LIVENESS_UNREACHABLE_GRACE_MS,
7514
7489
  SessionRejectedError,
7515
7490
  checkId,
7491
+ deviceSessionHeaders,
7516
7492
  seg2 as seg,
7517
7493
  serverUrl
7518
7494
  };