@monoclaw/machine 1.0.18 → 1.0.19

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/dist/cli.js CHANGED
@@ -40,8 +40,8 @@ function acquireRunLock(dir, me = process.pid, parent = process.ppid, alive = pr
40
40
  }
41
41
 
42
42
  // src/cli.ts
43
- import fs22 from "node:fs";
44
- import path22 from "node:path";
43
+ import fs23 from "node:fs";
44
+ import path23 from "node:path";
45
45
  import { Command } from "commander";
46
46
  import readline from "node:readline";
47
47
 
@@ -1633,11 +1633,11 @@ var busy = (e) => e.status === 429 && (e.code === "system_busy" || e.code === "t
1633
1633
  function elevenlabsModule(deps = {}) {
1634
1634
  const f = deps.fetch ?? ((...a) => fetch(...a));
1635
1635
  const queue = new PerKeyQueue();
1636
- const call = (key, path23, init = {}, timeoutMs = 12e4) => withRetries(
1636
+ const call = (key, path24, init = {}, timeoutMs = 12e4) => withRetries(
1637
1637
  async () => {
1638
1638
  let res;
1639
1639
  try {
1640
- res = await f(`${ELEVENLABS_BASE}${path23}`, { ...init, headers: { ...init.headers, "xi-api-key": key }, signal: AbortSignal.timeout(timeoutMs), redirect: "error" });
1640
+ res = await f(`${ELEVENLABS_BASE}${path24}`, { ...init, headers: { ...init.headers, "xi-api-key": key }, signal: AbortSignal.timeout(timeoutMs), redirect: "error" });
1641
1641
  } catch (e) {
1642
1642
  throw new Error(`Could not reach ElevenLabs: ${e.message}`);
1643
1643
  }
@@ -4047,6 +4047,76 @@ var SessionManager = class {
4047
4047
  openGroupIds() {
4048
4048
  return [...this.live.keys()];
4049
4049
  }
4050
+ /**
4051
+ * An update is due (bug draft-2026-11-26-bug-a-machine-with-agents-always-working-never-updates): no new turn starts
4052
+ * until it has run, so the machine drains in at most one turn's length. A message to a session that is not mid-turn
4053
+ * is kept here, with its session as the service opened it; the service acknowledged it, so this machine owns its
4054
+ * delivery: when the hold is released (the update failed or was withdrawn) it is delivered here, and across the
4055
+ * restart it is written to a file the new program reads. A message to a running turn still joins it.
4056
+ */
4057
+ hold = null;
4058
+ held = [];
4059
+ /** Stopping (an update's restart, a shutdown): nothing new is taken; the client acknowledges nothing from then on. */
4060
+ stopping = false;
4061
+ holdNewTurns(reason) {
4062
+ if (this.hold) return;
4063
+ this.hold = reason;
4064
+ log("info", `holding new turns: ${reason}`);
4065
+ }
4066
+ releaseNewTurns() {
4067
+ if (!this.hold) return;
4068
+ log("info", `new turns go again (${this.held.length} message${this.held.length === 1 ? "" : "s"} waited)`);
4069
+ this.hold = null;
4070
+ const waiting = this.held.splice(0);
4071
+ for (const h of waiting) void this.inbound(h.groupId, h.message, h.opts);
4072
+ }
4073
+ get holding() {
4074
+ return this.hold !== null;
4075
+ }
4076
+ /** From here on no inbound is acknowledged or taken: the service keeps it and sends it again to the next program. */
4077
+ beginStop() {
4078
+ this.stopping = true;
4079
+ }
4080
+ get refusing() {
4081
+ return this.stopping;
4082
+ }
4083
+ /** Whether a message for this group would be kept rather than start a turn: the hold is on and the session is not mid-turn, or we are stopping. */
4084
+ wouldHold(groupId) {
4085
+ if (this.stopping) return true;
4086
+ const live = this.live.get(groupId);
4087
+ return this.hold !== null && !live?.busy;
4088
+ }
4089
+ heldCount() {
4090
+ return this.held.length;
4091
+ }
4092
+ /** The groups mid-turn right now. */
4093
+ busyGroupIds() {
4094
+ return [...this.live.values()].filter((l) => l.busy).map((l) => l.groupId);
4095
+ }
4096
+ /** The session of a group as the service opened it (provider, folder, settings, account, the provider session to resume), for a message carried across a restart. */
4097
+ openFrameOf(groupId) {
4098
+ const live = this.live.get(groupId);
4099
+ if (!live) return null;
4100
+ return { t: "session.open", groupId, provider: live.providerId, cwd: live.cwd, settings: live.settings, ...live.accountId ? { providerAccountId: live.accountId } : {}, ...live.providerSessionId ?? live.resumeId ? { resumeId: live.providerSessionId ?? live.resumeId } : {} };
4101
+ }
4102
+ /**
4103
+ * The held messages, each with its session, for the program that takes over after the restart. Taken, not copied:
4104
+ * nothing is delivered twice. Call it after `closeAll` (with `beginStop` before): nothing can be kept after that.
4105
+ */
4106
+ heldForRestart() {
4107
+ return this.held.splice(0).map((h) => ({ open: h.open, groupId: h.groupId, message: h.message, opts: h.opts }));
4108
+ }
4109
+ /** After a restart: open each held message's session as it was, then deliver the message (a repeat is ignored as always). */
4110
+ async deliverHeld(records) {
4111
+ for (const r of records) {
4112
+ try {
4113
+ if (r.open && !this.live.has(r.groupId)) await this.open(r.open);
4114
+ await this.inbound(r.groupId, r.message, r.opts);
4115
+ } catch (e) {
4116
+ log("warn", `[${r.groupId.slice(0, 8)}] could not deliver a message held through the restart: ${e.message}`);
4117
+ }
4118
+ }
4119
+ }
4050
4120
  /** Sessions currently mid-turn (a message sent, no `done` yet). */
4051
4121
  busyCount() {
4052
4122
  return [...this.live.values()].filter((l) => l.busy).length;
@@ -4199,6 +4269,11 @@ var SessionManager = class {
4199
4269
  return this.inLane(groupId, () => this.inboundNow(groupId, message, opts));
4200
4270
  }
4201
4271
  async inboundNow(groupId, message, opts = {}) {
4272
+ if (this.wouldHold(groupId)) {
4273
+ if (!this.held.some((h) => h.message.id === message.id)) this.held.push({ groupId, message, opts, open: this.openFrameOf(groupId) });
4274
+ log("info", `[${groupId.slice(0, 8)}] holding message ${message.id.slice(0, 8)} until the update has run`);
4275
+ return;
4276
+ }
4202
4277
  if (!this.firstDelivery(groupId, message.id)) {
4203
4278
  log("info", `ignored a repeat of message ${message.id.slice(0, 8)} for ${groupId.slice(0, 8)}`);
4204
4279
  return;
@@ -4590,7 +4665,7 @@ function guessMime(name) {
4590
4665
  }
4591
4666
 
4592
4667
  // src/version.ts
4593
- var APP_VERSION = true ? "1.0.18" : fromPackage();
4668
+ var APP_VERSION = true ? "1.0.19" : fromPackage();
4594
4669
 
4595
4670
  // src/diag.ts
4596
4671
  var MAX_HELD = 200;
@@ -4780,13 +4855,17 @@ var HostClient = class {
4780
4855
  this.watchConfig();
4781
4856
  void this.connect();
4782
4857
  }
4858
+ /** Inbound messages acknowledged and still being handed to their session: a stop waits for them, so none is lost. */
4859
+ inFlight = /* @__PURE__ */ new Set();
4783
4860
  async stop() {
4784
4861
  this.stopped = true;
4862
+ this.sessions.beginStop();
4785
4863
  if (this.heartbeat) clearInterval(this.heartbeat);
4786
4864
  if (this.modulesTimer) clearTimeout(this.modulesTimer);
4787
4865
  if (this.watching) fs16.unwatchFile(configPath());
4788
4866
  this.watching = false;
4789
4867
  this.clearTimers();
4868
+ await Promise.allSettled([...this.inFlight]);
4790
4869
  await this.sessions.closeAll();
4791
4870
  this.ws?.close(1e3, "shutdown");
4792
4871
  }
@@ -4971,10 +5050,18 @@ var HostClient = class {
4971
5050
  case "session.open":
4972
5051
  await this.sessions.open(frame);
4973
5052
  return;
4974
- case "inbound":
5053
+ case "inbound": {
5054
+ if (this.sessions.refusing) return;
4975
5055
  this.send({ t: "ack", id: frame.message.id });
4976
- await this.sessions.inbound(frame.groupId, frame.delivery ? { ...frame.message, delivery: frame.delivery } : frame.message, { cwd: frame.cwd, providerAccountId: frame.providerAccountId });
5056
+ const delivery = this.sessions.inbound(frame.groupId, frame.delivery ? { ...frame.message, delivery: frame.delivery } : frame.message, { cwd: frame.cwd, providerAccountId: frame.providerAccountId });
5057
+ this.inFlight.add(delivery);
5058
+ try {
5059
+ await delivery;
5060
+ } finally {
5061
+ this.inFlight.delete(delivery);
5062
+ }
4977
5063
  return;
5064
+ }
4978
5065
  case "approval.answer":
4979
5066
  this.sessions.answerApproval(frame.groupId, frame.id, frame.allow, frame.updatedInput);
4980
5067
  return;
@@ -5399,6 +5486,8 @@ function nodeInstallHint(platform) {
5399
5486
  }
5400
5487
  var CHECK_EVERY_MS = 6 * 60 * 6e4;
5401
5488
  var RETRY_WHEN_BUSY_MS = 10 * 6e4;
5489
+ var RETRY_WHEN_HOLDING_MS = 5e3;
5490
+ var HOLD_MAX_MS = 30 * 6e4;
5402
5491
  var BACKGROUND_WAIT_MS = 30 * 6e4;
5403
5492
  function updateWait(busy2, background, since, now) {
5404
5493
  if (busy2) return { wait: true, why: "turn", since };
@@ -5583,30 +5672,80 @@ async function ensureUpToDate(routerUrl, opts) {
5583
5672
  await reexec();
5584
5673
  return "ok";
5585
5674
  }
5586
- function startPeriodicChecks(routerUrl, hooks) {
5675
+ var POLICY_REFRESH_MS = 5 * 6e4;
5676
+ function startPeriodicChecks(routerUrl, hooks, deps = { fetchPolicy, ensureUpToDate }) {
5587
5677
  let timer = null;
5588
5678
  let backgroundSince = null;
5679
+ let holding = false;
5680
+ let holdingSince = null;
5681
+ let longRunning = null;
5682
+ let cached2 = null;
5683
+ const clock = deps.now ?? Date.now;
5589
5684
  const schedule = (ms) => {
5590
5685
  if (timer) clearTimeout(timer);
5591
5686
  timer = setTimeout(tick, ms);
5592
5687
  timer.unref();
5593
5688
  };
5689
+ const hold = (to, now) => {
5690
+ if (holding) return;
5691
+ holding = true;
5692
+ holdingSince = now;
5693
+ hooks.holdNewTurns?.(`update to ${to}`);
5694
+ };
5695
+ const release = () => {
5696
+ if (!holding) return;
5697
+ holding = false;
5698
+ holdingSince = null;
5699
+ hooks.releaseNewTurns?.();
5700
+ };
5701
+ const readPolicy = async (now) => {
5702
+ if (holding && cached2 && now - cached2.at < POLICY_REFRESH_MS) return cached2.policy;
5703
+ const fetched = await deps.fetchPolicy(routerUrl);
5704
+ if (fetched) {
5705
+ cached2 = { policy: fetched, at: now };
5706
+ return fetched;
5707
+ }
5708
+ if (holding && cached2) {
5709
+ log("warn", "could not read the update policy; keeping the update that is due");
5710
+ return cached2.policy;
5711
+ }
5712
+ return null;
5713
+ };
5594
5714
  const tick = async () => {
5595
5715
  try {
5596
- const policy = await fetchPolicy(routerUrl);
5597
- const d = policy ? decideUpdate(APP_VERSION, policy, detectInstallMode(), { disabled: updatesDisabled() }) : { action: "none" };
5716
+ const now = clock();
5717
+ const policy = await readPolicy(now);
5718
+ const d = policy ? decideUpdate(APP_VERSION, policy, (deps.installMode ?? detectInstallMode)(), { disabled: updatesDisabled() }) : { action: "none" };
5598
5719
  if (d.action === "update") {
5599
- const w = updateWait(hooks.isBusy(), hooks.hasBackground?.() ?? false, backgroundSince, Date.now());
5720
+ const w = updateWait(hooks.isBusy(), hooks.hasBackground?.() ?? false, backgroundSince, now);
5600
5721
  backgroundSince = w.since;
5601
5722
  if (w.wait) {
5602
- log("info", w.why === "background" ? `update to ${d.to} is waiting for an agent's background work (up to ${BACKGROUND_WAIT_MS / 6e4} minutes)` : `update to ${d.to} is waiting for the current turn to finish`);
5603
- return schedule(RETRY_WHEN_BUSY_MS);
5723
+ if (longRunning) {
5724
+ if ((hooks.busyGroups?.() ?? []).some((g) => longRunning.has(g))) return schedule(RETRY_WHEN_BUSY_MS);
5725
+ longRunning = null;
5726
+ }
5727
+ if (!holding) {
5728
+ hold(d.to, now);
5729
+ log("info", `update to ${d.to} is waiting for ${w.why === "background" ? "an agent's background work" : "the current turn"} to finish; no new turn starts until it has run`);
5730
+ } else if (holdingSince !== null && now - holdingSince >= HOLD_MAX_MS) {
5731
+ log("warn", `update to ${d.to}: new turns were held for ${Math.round(HOLD_MAX_MS / 6e4)} minutes; they go again, and the update waits for a quiet moment`);
5732
+ if (w.why === "turn") longRunning = new Set(hooks.busyGroups?.() ?? []);
5733
+ release();
5734
+ return schedule(RETRY_WHEN_BUSY_MS);
5735
+ }
5736
+ return schedule(RETRY_WHEN_HOLDING_MS);
5604
5737
  }
5605
- await ensureUpToDate(routerUrl, { reason: "periodic check", onBeforeRestart: hooks.onBeforeRestart, afterInstall: hooks.afterInstall });
5606
- return;
5738
+ hold(d.to, now);
5739
+ await deps.ensureUpToDate(routerUrl, { reason: "periodic check", onBeforeRestart: hooks.onBeforeRestart, afterInstall: hooks.afterInstall });
5740
+ release();
5741
+ longRunning = null;
5742
+ return schedule(CHECK_EVERY_MS);
5607
5743
  }
5744
+ release();
5745
+ longRunning = null;
5608
5746
  if (d.action === "block") hooks.onError(new Error(d.reason));
5609
5747
  } catch (e) {
5748
+ release();
5610
5749
  hooks.onError(e);
5611
5750
  }
5612
5751
  schedule(CHECK_EVERY_MS);
@@ -6705,23 +6844,23 @@ function friendlyPath(p, cwd) {
6705
6844
  var clip = (s, n) => s.length > n ? `${s.slice(0, n - 1)}\u2026` : s;
6706
6845
  function describeTool(name, input, cwd) {
6707
6846
  const s = (k) => typeof input[k] === "string" ? input[k] : void 0;
6708
- const path23 = (k) => friendlyPath(s(k), cwd);
6847
+ const path24 = (k) => friendlyPath(s(k), cwd);
6709
6848
  const firstString = () => Object.values(input).find((v) => typeof v === "string" && v.trim().length > 0);
6710
6849
  switch (name) {
6711
6850
  case "Bash":
6712
6851
  return clip(s("description") ?? s("command") ?? "run a command", 120);
6713
6852
  case "Read":
6714
- return `Read ${path23("file_path") || path23("path")}`.trim();
6853
+ return `Read ${path24("file_path") || path24("path")}`.trim();
6715
6854
  case "Edit":
6716
6855
  case "Write":
6717
6856
  case "MultiEdit":
6718
- return `${name} ${path23("file_path")}`.trim();
6857
+ return `${name} ${path24("file_path")}`.trim();
6719
6858
  case "NotebookEdit":
6720
- return `Edit notebook ${path23("notebook_path")}`.trim();
6859
+ return `Edit notebook ${path24("notebook_path")}`.trim();
6721
6860
  case "Grep":
6722
- return `Grep "${clip(s("pattern") ?? "", 60)}"${s("path") ? ` in ${path23("path")}` : ""}`;
6861
+ return `Grep "${clip(s("pattern") ?? "", 60)}"${s("path") ? ` in ${path24("path")}` : ""}`;
6723
6862
  case "Glob":
6724
- return `Find ${clip(s("pattern") ?? "", 60)}${s("path") ? ` in ${path23("path")}` : ""}`;
6863
+ return `Find ${clip(s("pattern") ?? "", 60)}${s("path") ? ` in ${path24("path")}` : ""}`;
6725
6864
  case "WebSearch":
6726
6865
  return `Search "${clip(s("query") ?? "", 80)}"`;
6727
6866
  case "WebFetch": {
@@ -7086,6 +7225,36 @@ function startedByHand(foreground, env, isTTY) {
7086
7225
  return true;
7087
7226
  }
7088
7227
 
7228
+ // src/held.ts
7229
+ import fs22 from "node:fs";
7230
+ import path22 from "node:path";
7231
+ var heldFile = (dir = configDir()) => path22.join(dir, "held-messages.json");
7232
+ function saveHeld(records, dir = configDir()) {
7233
+ if (!records.length) return;
7234
+ fs22.mkdirSync(dir, { recursive: true });
7235
+ const f = heldFile(dir);
7236
+ const tmp = `${f}.${process.pid}.part`;
7237
+ fs22.writeFileSync(tmp, JSON.stringify({ savedAt: (/* @__PURE__ */ new Date()).toISOString(), records }), { mode: 384 });
7238
+ fs22.chmodSync(tmp, 384);
7239
+ fs22.renameSync(tmp, f);
7240
+ log("info", `kept ${records.length} held message${records.length === 1 ? "" : "s"} for after the restart`);
7241
+ }
7242
+ function loadHeld(dir = configDir()) {
7243
+ const f = heldFile(dir);
7244
+ if (!fs22.existsSync(f)) return { records: [], problem: null };
7245
+ try {
7246
+ const parsed = JSON.parse(fs22.readFileSync(f, "utf8"));
7247
+ const records = Array.isArray(parsed.records) ? parsed.records : null;
7248
+ if (!records) return { records: [], problem: "the held-messages file had no list of messages" };
7249
+ const good = records.filter((r) => !!r && typeof r === "object" && typeof r.groupId === "string" && !!r.message && typeof r.message.id === "string");
7250
+ return { records: good, problem: good.length === records.length ? null : `${records.length - good.length} of ${records.length} held messages could not be read` };
7251
+ } catch (e) {
7252
+ return { records: [], problem: `the held-messages file could not be read: ${e.message}` };
7253
+ } finally {
7254
+ fs22.rmSync(f, { force: true });
7255
+ }
7256
+ }
7257
+
7089
7258
  // src/cli.ts
7090
7259
  import { spawn as spawn5 } from "node:child_process";
7091
7260
  import os9 from "node:os";
@@ -7132,7 +7301,7 @@ program.command("enrol [token]").description("Connect this machine to your MonoC
7132
7301
  const preview = await previewToken(opts.router, token, profiles.map((p) => p.config?.hostId ?? "").filter(Boolean), opts.insecure);
7133
7302
  const plan = planEnrol(preview, profiles, opts.router, { requestedProfile: currentProfile(), defaultName: os9.hostname() });
7134
7303
  const report = (profile) => {
7135
- if (process.env.MONOCLAW_CONNECT) fs22.writeFileSync(connectResultPath(), JSON.stringify({ profile, at: (/* @__PURE__ */ new Date()).toISOString() }), { mode: 384 });
7304
+ if (process.env.MONOCLAW_CONNECT) fs23.writeFileSync(connectResultPath(), JSON.stringify({ profile, at: (/* @__PURE__ */ new Date()).toISOString() }), { mode: 384 });
7136
7305
  };
7137
7306
  if (plan.action === "already") {
7138
7307
  console.log(plan.message);
@@ -7149,16 +7318,16 @@ program.command("enrol [token]").description("Connect this machine to your MonoC
7149
7318
  }
7150
7319
  if (plan.profile) process.env.MONOCLAW_PROFILE = assertProfileName(plan.profile);
7151
7320
  const existing = loadConfig();
7152
- const roots2 = opts.root?.map((r) => path22.resolve(r)) ?? existing?.roots ?? plan.copyRootsFrom ?? [];
7321
+ const roots2 = opts.root?.map((r) => path23.resolve(r)) ?? existing?.roots ?? plan.copyRootsFrom ?? [];
7153
7322
  const unsafe = roots2.filter((r) => rootExposesConfig(r, configDir()));
7154
7323
  if (unsafe.length) {
7155
7324
  console.error(`Not exposing ${unsafe.join(", ")}: it contains this host's config folder (${configDir()}), so agents could change the machine's MonoClaw settings or read its keys. Pass a folder inside it instead, such as --root ~/command.`);
7156
7325
  process.exit(2);
7157
7326
  }
7158
7327
  for (const r of opts.root ? roots2 : []) {
7159
- if (fs22.existsSync(r)) continue;
7328
+ if (fs23.existsSync(r)) continue;
7160
7329
  try {
7161
- fs22.mkdirSync(r, { recursive: true });
7330
+ fs23.mkdirSync(r, { recursive: true });
7162
7331
  console.log(`Created ${r} for your agents to work in.`);
7163
7332
  } catch (e) {
7164
7333
  console.error(`Could not create ${r}: ${e.message}. Create it yourself, or add another folder with: ${cmd("roots add <folder>")}`);
@@ -7167,7 +7336,7 @@ program.command("enrol [token]").description("Connect this machine to your MonoC
7167
7336
  const cfg = await enrol(token, opts.router, { name: opts.name ?? (plan.reason === "second-space" ? plan.nameHint ?? void 0 : void 0), roots: roots2, insecure: opts.insecure });
7168
7337
  console.log(`Enrolled as "${cfg.name}"${cfg.spaceName ? ` in ${cfg.spaceName} (@${cfg.spaceHandle})` : ""}${currentProfile() ? ` under the profile "${currentProfile()}"` : ""}. Config saved to ${configPath()}.`);
7169
7338
  if (plan.reason === "second-space") {
7170
- fs22.writeFileSync(pendingServicePath(), JSON.stringify({ profile: currentProfile(), at: (/* @__PURE__ */ new Date()).toISOString() }), { mode: 384 });
7339
+ fs23.writeFileSync(pendingServicePath(), JSON.stringify({ profile: currentProfile(), at: (/* @__PURE__ */ new Date()).toISOString() }), { mode: 384 });
7171
7340
  console.log(`This computer now runs one machine per space; its modules and Claude login are shared. The first enrolment is untouched.`);
7172
7341
  }
7173
7342
  if (!cfg.roots.length) console.log(`No folders exposed yet. Add one with: ${cmd("roots add ~/command")}`);
@@ -7253,7 +7422,7 @@ provider.command("add <name>").description("Add a Claude connection; an api_key
7253
7422
  const { registry, accounts } = await makeContext(requireConfig());
7254
7423
  const moduleId = opts.type === "api_key" ? "claude-api" : "claude-subscription";
7255
7424
  if (!registry.isInstalled(moduleId)) await registry.add(moduleId).install;
7256
- const folders = opts.folders?.map((f) => path22.resolve(f.replace(/^~(?=$|\/)/, process.env.HOME ?? "")));
7425
+ const folders = opts.folders?.map((f) => path23.resolve(f.replace(/^~(?=$|\/)/, process.env.HOME ?? "")));
7257
7426
  if (opts.type === "api_key") {
7258
7427
  const id = await connectModule(registry, accounts, moduleId, io, { name, id: opts.id });
7259
7428
  if (folders) accounts.upsert({ ...accounts.get(id), allowedFolders: folders });
@@ -7282,18 +7451,18 @@ var roots = program.command("roots").description("Folders this machine exposes t
7282
7451
  roots.command("list").action(() => {
7283
7452
  const cfg = requireConfig();
7284
7453
  if (!cfg.roots.length) console.log("(none) \u2014 add one with: monoclaw roots add <path>");
7285
- for (const r of cfg.roots) console.log(`${fs22.existsSync(r) ? "\u2713" : "\u2717 (missing)"} ${r}`);
7454
+ for (const r of cfg.roots) console.log(`${fs23.existsSync(r) ? "\u2713" : "\u2717 (missing)"} ${r}`);
7286
7455
  });
7287
7456
  roots.command("add <path...>").action((paths) => {
7288
7457
  const cfg = requireConfig();
7289
7458
  for (const p of paths) {
7290
- const full = path22.resolve(p.replace(/^~(?=$|\/)/, process.env.HOME ?? ""));
7291
- if (!fs22.existsSync(full) || !fs22.statSync(full).isDirectory()) {
7459
+ const full = path23.resolve(p.replace(/^~(?=$|\/)/, process.env.HOME ?? ""));
7460
+ if (!fs23.existsSync(full) || !fs23.statSync(full).isDirectory()) {
7292
7461
  console.error(`not a folder: ${full}`);
7293
7462
  continue;
7294
7463
  }
7295
7464
  if (rootExposesConfig(full, configDir())) {
7296
- console.error(`not adding ${full}: it contains this host's config folder (${configDir()}), so agents could change the machine's MonoClaw settings or read its keys. Add a folder inside it, such as ${path22.join(full, "command")}.`);
7465
+ console.error(`not adding ${full}: it contains this host's config folder (${configDir()}), so agents could change the machine's MonoClaw settings or read its keys. Add a folder inside it, such as ${path23.join(full, "command")}.`);
7297
7466
  process.exitCode = 1;
7298
7467
  continue;
7299
7468
  }
@@ -7306,7 +7475,7 @@ Restart the host for the change to reach the app.`);
7306
7475
  });
7307
7476
  roots.command("remove <path>").action((p) => {
7308
7477
  const cfg = requireConfig();
7309
- const full = path22.resolve(p);
7478
+ const full = path23.resolve(p);
7310
7479
  cfg.roots = cfg.roots.filter((r) => r !== full);
7311
7480
  saveConfig(cfg);
7312
7481
  console.log(`Exposed folders: ${cfg.roots.join(", ") || "(none)"}`);
@@ -7341,7 +7510,7 @@ program.command("start", { hidden: true }).description("Run the host in this ter
7341
7510
  process.exit(1);
7342
7511
  }
7343
7512
  process.on("exit", lock.release);
7344
- setLogDir(path22.join(configDir(), "logs"));
7513
+ setLogDir(path23.join(configDir(), "logs"));
7345
7514
  const unsafe = loaded.roots.filter((r) => rootExposesConfig(r, configDir()));
7346
7515
  for (const r of unsafe) log("error", `not exposing ${r}: it contains this host's config folder (${configDir()}). Expose a folder inside it instead (\`monoclaw roots remove ${r}\`, then \`monoclaw roots add <folder>\`).`);
7347
7516
  const cfg = unsafe.length ? { ...loaded, roots: loaded.roots.filter((r) => !unsafe.includes(r)) } : loaded;
@@ -7361,6 +7530,21 @@ program.command("start", { hidden: true }).description("Run the host in this ter
7361
7530
  };
7362
7531
  const quiesce = async () => {
7363
7532
  await client.stop();
7533
+ saveHeld(client.sessions.heldForRestart());
7534
+ };
7535
+ let heldDelivered = false;
7536
+ const previousState = client.onState;
7537
+ client.onState = (s) => {
7538
+ previousState(s);
7539
+ if (s === "online" && !heldDelivered) {
7540
+ heldDelivered = true;
7541
+ const held = loadHeld();
7542
+ if (held.problem) {
7543
+ log("error", `held messages lost: ${held.problem}`);
7544
+ client.diag.report({ kind: "machine.held_messages_lost", level: "error", message: held.problem, data: { delivered: held.records.length } });
7545
+ }
7546
+ if (held.records.length) void client.sessions.deliverHeld(held.records);
7547
+ }
7364
7548
  };
7365
7549
  client.onUpgradeRequired = () => {
7366
7550
  ensureUpToDate(cfg.routerUrl, { reason: "router requires it", onBeforeRestart: quiesce }).catch((e) => {
@@ -7368,7 +7552,7 @@ program.command("start", { hidden: true }).description("Run the host in this ter
7368
7552
  process.exit(3);
7369
7553
  });
7370
7554
  };
7371
- const checks = startPeriodicChecks(cfg.routerUrl, { isBusy: () => client.sessions.busyCount() > 0, hasBackground: () => client.sessions.backgroundCount() > 0, onBeforeRestart: quiesce, onError: (e) => log("warn", `update check: ${e.message}`), afterInstall: repairBundledCli });
7555
+ const checks = startPeriodicChecks(cfg.routerUrl, { isBusy: () => client.sessions.busyCount() > 0, hasBackground: () => client.sessions.backgroundCount() > 0, onBeforeRestart: quiesce, onError: (e) => log("warn", `update check: ${e.message}`), afterInstall: repairBundledCli, holdNewTurns: (why) => client.sessions.holdNewTurns(why), releaseNewTurns: () => client.sessions.releaseNewTurns(), busyGroups: () => client.sessions.busyGroupIds() });
7372
7556
  const stopChecks = checks.stop;
7373
7557
  client.onReconnected = () => checks.checkSoon();
7374
7558
  client.start();
@@ -7376,6 +7560,7 @@ program.command("start", { hidden: true }).description("Run the host in this ter
7376
7560
  log("info", "shutting down");
7377
7561
  stopChecks();
7378
7562
  await client.stop();
7563
+ saveHeld(client.sessions.heldForRestart());
7379
7564
  process.exit(0);
7380
7565
  };
7381
7566
  process.on("SIGINT", shutdown);
@@ -7387,6 +7572,10 @@ program.command("start", { hidden: true }).description("Run the host in this ter
7387
7572
  });
7388
7573
  process.on("uncaughtException", (e) => {
7389
7574
  log("error", `an error nobody caught; stopping: ${e.stack ?? e.message}`);
7575
+ try {
7576
+ saveHeld(client.sessions.heldForRestart());
7577
+ } catch {
7578
+ }
7390
7579
  client.diag.report({ kind: "machine.crash", level: "error", message: `${e.name}: ${e.message}`.slice(0, 300) });
7391
7580
  void client.diag.flush().finally(() => process.exit(1));
7392
7581
  setTimeout(() => process.exit(1), 5e3).unref();
@@ -7442,14 +7631,14 @@ program.command("doctor").description("Check and repair what a working host need
7442
7631
  else if (!cfg) lines.push({ ok: false, info: true, what: "Not enrolled yet", fix: "Copy the command from Add a machine in the app: npx -y @monoclaw/machine@latest connect <token>" });
7443
7632
  else {
7444
7633
  lines.push({ ok: true, what: `Enrolled as "${cfg.name}" with ${cfg.routerUrl}` });
7445
- const missing = cfg.roots.filter((r) => !fs22.existsSync(r));
7634
+ const missing = cfg.roots.filter((r) => !fs23.existsSync(r));
7446
7635
  const exposing = cfg.roots.filter((r) => rootExposesConfig(r, configDir()));
7447
7636
  if (exposing.length) lines.push({ ok: false, what: `${exposing.join(", ")} contains this host's config folder, so it is not offered to agents`, fix: `monoclaw roots remove ${exposing[0]}, then monoclaw roots add <a folder inside it>` });
7448
7637
  lines.push({ ok: cfg.roots.length > 0 && !missing.length, what: cfg.roots.length ? `Exposed folders: ${cfg.roots.join(", ")}${missing.length ? ` (missing: ${missing.join(", ")})` : ""}` : "No folders exposed", fix: !cfg.roots.length ? "monoclaw roots add ~/command" : missing.length ? "Create them, or remove them with `monoclaw roots remove <path>`" : void 0 });
7449
7638
  const names = serviceNames();
7450
- const unit = process.platform === "darwin" ? path22.join(os9.homedir(), "Library", "LaunchAgents", `${names.label}.plist`) : process.platform === "linux" ? path22.join(os9.homedir(), ".config", "systemd", "user", `${names.unit}.service`) : null;
7451
- if (unit) lines.push({ ok: fs22.existsSync(unit), info: true, what: fs22.existsSync(unit) ? `Background service installed (${unit})` : "Not running as a background service (fine for now)", fix: fs22.existsSync(unit) ? void 0 : `${cmd("service install")} to run at login` });
7452
- if (unit && fs22.existsSync(unit) && lingerEnabled() === false) lines.push({ ok: false, what: "This machine goes offline when you log out of this computer (linger is off for your user)", fix: LINGER_FIX });
7639
+ const unit = process.platform === "darwin" ? path23.join(os9.homedir(), "Library", "LaunchAgents", `${names.label}.plist`) : process.platform === "linux" ? path23.join(os9.homedir(), ".config", "systemd", "user", `${names.unit}.service`) : null;
7640
+ if (unit) lines.push({ ok: fs23.existsSync(unit), info: true, what: fs23.existsSync(unit) ? `Background service installed (${unit})` : "Not running as a background service (fine for now)", fix: fs23.existsSync(unit) ? void 0 : `${cmd("service install")} to run at login` });
7641
+ if (unit && fs23.existsSync(unit) && lingerEnabled() === false) lines.push({ ok: false, what: "This machine goes offline when you log out of this computer (linger is off for your user)", fix: LINGER_FIX });
7453
7642
  const { registry } = await makeContext(cfg);
7454
7643
  await registry.refreshReadiness();
7455
7644
  const reports = registry.reports();
@@ -7524,16 +7713,16 @@ config.command("set <key> <value>").description("Keys: allowedPermissionModes (c
7524
7713
  });
7525
7714
  var service = program.command("service").description("Run the host in the background at login");
7526
7715
  service.command("install").description("Install and start the background service (re-run to restart it on the current version)").option("--print", "only write the service file and print the commands, without running them").action((o) => {
7527
- if (!currentProfile() && fs22.existsSync(pendingServicePath())) {
7716
+ if (!currentProfile() && fs23.existsSync(pendingServicePath())) {
7528
7717
  try {
7529
- const pending = JSON.parse(fs22.readFileSync(pendingServicePath(), "utf8"));
7718
+ const pending = JSON.parse(fs23.readFileSync(pendingServicePath(), "utf8"));
7530
7719
  if (pending.profile && Date.now() - Date.parse(pending.at ?? "") < 60 * 6e4) {
7531
7720
  process.env.MONOCLAW_PROFILE = assertProfileName(pending.profile);
7532
7721
  console.log(`Installing the service for the profile "${pending.profile}" (the enrolment just made). The first enrolment's service is untouched.`);
7533
7722
  }
7534
7723
  } catch {
7535
7724
  }
7536
- fs22.rmSync(pendingServicePath(), { force: true });
7725
+ fs23.rmSync(pendingServicePath(), { force: true });
7537
7726
  }
7538
7727
  requireConfig();
7539
7728
  if (o.print) {
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@monoclaw/machine",
3
- "version": "1.0.18",
3
+ "version": "1.0.19",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@monoclaw/machine",
9
- "version": "1.0.18",
9
+ "version": "1.0.19",
10
10
  "license": "UNLICENSED",
11
11
  "dependencies": {
12
12
  "@anthropic-ai/claude-agent-sdk": "0.3.302",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@monoclaw/machine",
3
- "version": "1.0.18",
3
+ "version": "1.0.19",
4
4
  "description": "Monoclaw host app: runs agents on your machine and connects them to your Monoclaw account (command.monoclaw.ai).",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {