@monoclaw/machine 1.0.17 → 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
 
@@ -956,6 +956,12 @@ var SessionSettings = z3.object({
956
956
  canMessage: z3.boolean().optional(),
957
957
  /** Allow Claude Code's own cross-session messaging (ListAgents/SendMessage). Off unless the owner allows it. */
958
958
  peerMessaging: z3.boolean().optional(),
959
+ /**
960
+ * Give the session the claude.ai connectors of the login it runs on (Gmail, Drive, Docs…; plan
961
+ * draft-2026-11-26-connectors-off-by-default). Off unless the owner turns it on: a machine program from 1.0.18 opens
962
+ * the session with Claude Code's `disableClaudeAiConnectors` unless this is true.
963
+ */
964
+ connectors: z3.boolean().optional(),
959
965
  /** The organisation's tools this agent was given (plan draft-2026-11-06-modules), offered as `mcp__monoclaw-tools__<name>`. */
960
966
  tools: z3.array(SessionTool).default([]),
961
967
  /**
@@ -1627,11 +1633,11 @@ var busy = (e) => e.status === 429 && (e.code === "system_busy" || e.code === "t
1627
1633
  function elevenlabsModule(deps = {}) {
1628
1634
  const f = deps.fetch ?? ((...a) => fetch(...a));
1629
1635
  const queue = new PerKeyQueue();
1630
- const call = (key, path23, init = {}, timeoutMs = 12e4) => withRetries(
1636
+ const call = (key, path24, init = {}, timeoutMs = 12e4) => withRetries(
1631
1637
  async () => {
1632
1638
  let res;
1633
1639
  try {
1634
- 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" });
1635
1641
  } catch (e) {
1636
1642
  throw new Error(`Could not reach ElevenLabs: ${e.message}`);
1637
1643
  }
@@ -4041,6 +4047,76 @@ var SessionManager = class {
4041
4047
  openGroupIds() {
4042
4048
  return [...this.live.keys()];
4043
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
+ }
4044
4120
  /** Sessions currently mid-turn (a message sent, no `done` yet). */
4045
4121
  busyCount() {
4046
4122
  return [...this.live.values()].filter((l) => l.busy).length;
@@ -4193,6 +4269,11 @@ var SessionManager = class {
4193
4269
  return this.inLane(groupId, () => this.inboundNow(groupId, message, opts));
4194
4270
  }
4195
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
+ }
4196
4277
  if (!this.firstDelivery(groupId, message.id)) {
4197
4278
  log("info", `ignored a repeat of message ${message.id.slice(0, 8)} for ${groupId.slice(0, 8)}`);
4198
4279
  return;
@@ -4584,7 +4665,7 @@ function guessMime(name) {
4584
4665
  }
4585
4666
 
4586
4667
  // src/version.ts
4587
- var APP_VERSION = true ? "1.0.17" : fromPackage();
4668
+ var APP_VERSION = true ? "1.0.19" : fromPackage();
4588
4669
 
4589
4670
  // src/diag.ts
4590
4671
  var MAX_HELD = 200;
@@ -4774,13 +4855,17 @@ var HostClient = class {
4774
4855
  this.watchConfig();
4775
4856
  void this.connect();
4776
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();
4777
4860
  async stop() {
4778
4861
  this.stopped = true;
4862
+ this.sessions.beginStop();
4779
4863
  if (this.heartbeat) clearInterval(this.heartbeat);
4780
4864
  if (this.modulesTimer) clearTimeout(this.modulesTimer);
4781
4865
  if (this.watching) fs16.unwatchFile(configPath());
4782
4866
  this.watching = false;
4783
4867
  this.clearTimers();
4868
+ await Promise.allSettled([...this.inFlight]);
4784
4869
  await this.sessions.closeAll();
4785
4870
  this.ws?.close(1e3, "shutdown");
4786
4871
  }
@@ -4965,10 +5050,18 @@ var HostClient = class {
4965
5050
  case "session.open":
4966
5051
  await this.sessions.open(frame);
4967
5052
  return;
4968
- case "inbound":
5053
+ case "inbound": {
5054
+ if (this.sessions.refusing) return;
4969
5055
  this.send({ t: "ack", id: frame.message.id });
4970
- 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
+ }
4971
5063
  return;
5064
+ }
4972
5065
  case "approval.answer":
4973
5066
  this.sessions.answerApproval(frame.groupId, frame.id, frame.allow, frame.updatedInput);
4974
5067
  return;
@@ -5393,6 +5486,8 @@ function nodeInstallHint(platform) {
5393
5486
  }
5394
5487
  var CHECK_EVERY_MS = 6 * 60 * 6e4;
5395
5488
  var RETRY_WHEN_BUSY_MS = 10 * 6e4;
5489
+ var RETRY_WHEN_HOLDING_MS = 5e3;
5490
+ var HOLD_MAX_MS = 30 * 6e4;
5396
5491
  var BACKGROUND_WAIT_MS = 30 * 6e4;
5397
5492
  function updateWait(busy2, background, since, now) {
5398
5493
  if (busy2) return { wait: true, why: "turn", since };
@@ -5577,30 +5672,80 @@ async function ensureUpToDate(routerUrl, opts) {
5577
5672
  await reexec();
5578
5673
  return "ok";
5579
5674
  }
5580
- function startPeriodicChecks(routerUrl, hooks) {
5675
+ var POLICY_REFRESH_MS = 5 * 6e4;
5676
+ function startPeriodicChecks(routerUrl, hooks, deps = { fetchPolicy, ensureUpToDate }) {
5581
5677
  let timer = null;
5582
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;
5583
5684
  const schedule = (ms) => {
5584
5685
  if (timer) clearTimeout(timer);
5585
5686
  timer = setTimeout(tick, ms);
5586
5687
  timer.unref();
5587
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
+ };
5588
5714
  const tick = async () => {
5589
5715
  try {
5590
- const policy = await fetchPolicy(routerUrl);
5591
- 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" };
5592
5719
  if (d.action === "update") {
5593
- const w = updateWait(hooks.isBusy(), hooks.hasBackground?.() ?? false, backgroundSince, Date.now());
5720
+ const w = updateWait(hooks.isBusy(), hooks.hasBackground?.() ?? false, backgroundSince, now);
5594
5721
  backgroundSince = w.since;
5595
5722
  if (w.wait) {
5596
- 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`);
5597
- 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);
5598
5737
  }
5599
- await ensureUpToDate(routerUrl, { reason: "periodic check", onBeforeRestart: hooks.onBeforeRestart, afterInstall: hooks.afterInstall });
5600
- 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);
5601
5743
  }
5744
+ release();
5745
+ longRunning = null;
5602
5746
  if (d.action === "block") hooks.onError(new Error(d.reason));
5603
5747
  } catch (e) {
5748
+ release();
5604
5749
  hooks.onError(e);
5605
5750
  }
5606
5751
  schedule(CHECK_EVERY_MS);
@@ -6390,7 +6535,7 @@ var ClaudeSession = class {
6390
6535
  systemPrompt: { type: "preset", preset: "claude_code", append: buildAppend(s) },
6391
6536
  permissionMode: mode,
6392
6537
  allowDangerouslySkipPermissions: mode === "bypassPermissions" ? true : void 0,
6393
- ...scopeSettings(scope, !!s.peerMessaging),
6538
+ ...scopeSettings(scope, !!s.peerMessaging, !!s.connectors),
6394
6539
  model: s.model || void 0,
6395
6540
  resume: this.sessionId,
6396
6541
  forkSession: this.forkPending || void 0,
@@ -6650,10 +6795,12 @@ function scopeOptions(scope, peerMessaging = false) {
6650
6795
  if (scope === "chat") return { tools: [] };
6651
6796
  return peerMessaging ? {} : { disallowedTools: PEER_SESSION_TOOLS };
6652
6797
  }
6653
- function scopeSettings(scope, peerMessaging = false) {
6798
+ function scopeSettings(scope, peerMessaging = false, connectors = false) {
6799
+ const off = connectors ? {} : { disableClaudeAiConnectors: true };
6654
6800
  const peer = peerMessaging ? {} : { crossSessionInbound: "refuse" };
6655
- if (scope === "full") return { settingSources: SESSION_SETTING_SOURCES, ...peerMessaging ? {} : { settings: peer } };
6656
- return { settingSources: [], settings: { ...peer, disableAllHooks: true } };
6801
+ const settings = { ...off, ...peer };
6802
+ if (scope === "full") return { settingSources: SESSION_SETTING_SOURCES, ...Object.keys(settings).length ? { settings } : {} };
6803
+ return { settingSources: [], settings: { ...settings, disableAllHooks: true } };
6657
6804
  }
6658
6805
  function monoclawToolNames(s) {
6659
6806
  return [...(s.scope ?? "full") === "full" ? ["send_file"] : [], ...s.canMessage ? ["list_agents", "send"] : []];
@@ -6697,23 +6844,23 @@ function friendlyPath(p, cwd) {
6697
6844
  var clip = (s, n) => s.length > n ? `${s.slice(0, n - 1)}\u2026` : s;
6698
6845
  function describeTool(name, input, cwd) {
6699
6846
  const s = (k) => typeof input[k] === "string" ? input[k] : void 0;
6700
- const path23 = (k) => friendlyPath(s(k), cwd);
6847
+ const path24 = (k) => friendlyPath(s(k), cwd);
6701
6848
  const firstString = () => Object.values(input).find((v) => typeof v === "string" && v.trim().length > 0);
6702
6849
  switch (name) {
6703
6850
  case "Bash":
6704
6851
  return clip(s("description") ?? s("command") ?? "run a command", 120);
6705
6852
  case "Read":
6706
- return `Read ${path23("file_path") || path23("path")}`.trim();
6853
+ return `Read ${path24("file_path") || path24("path")}`.trim();
6707
6854
  case "Edit":
6708
6855
  case "Write":
6709
6856
  case "MultiEdit":
6710
- return `${name} ${path23("file_path")}`.trim();
6857
+ return `${name} ${path24("file_path")}`.trim();
6711
6858
  case "NotebookEdit":
6712
- return `Edit notebook ${path23("notebook_path")}`.trim();
6859
+ return `Edit notebook ${path24("notebook_path")}`.trim();
6713
6860
  case "Grep":
6714
- return `Grep "${clip(s("pattern") ?? "", 60)}"${s("path") ? ` in ${path23("path")}` : ""}`;
6861
+ return `Grep "${clip(s("pattern") ?? "", 60)}"${s("path") ? ` in ${path24("path")}` : ""}`;
6715
6862
  case "Glob":
6716
- return `Find ${clip(s("pattern") ?? "", 60)}${s("path") ? ` in ${path23("path")}` : ""}`;
6863
+ return `Find ${clip(s("pattern") ?? "", 60)}${s("path") ? ` in ${path24("path")}` : ""}`;
6717
6864
  case "WebSearch":
6718
6865
  return `Search "${clip(s("query") ?? "", 80)}"`;
6719
6866
  case "WebFetch": {
@@ -7078,6 +7225,36 @@ function startedByHand(foreground, env, isTTY) {
7078
7225
  return true;
7079
7226
  }
7080
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
+
7081
7258
  // src/cli.ts
7082
7259
  import { spawn as spawn5 } from "node:child_process";
7083
7260
  import os9 from "node:os";
@@ -7124,7 +7301,7 @@ program.command("enrol [token]").description("Connect this machine to your MonoC
7124
7301
  const preview = await previewToken(opts.router, token, profiles.map((p) => p.config?.hostId ?? "").filter(Boolean), opts.insecure);
7125
7302
  const plan = planEnrol(preview, profiles, opts.router, { requestedProfile: currentProfile(), defaultName: os9.hostname() });
7126
7303
  const report = (profile) => {
7127
- 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 });
7128
7305
  };
7129
7306
  if (plan.action === "already") {
7130
7307
  console.log(plan.message);
@@ -7141,16 +7318,16 @@ program.command("enrol [token]").description("Connect this machine to your MonoC
7141
7318
  }
7142
7319
  if (plan.profile) process.env.MONOCLAW_PROFILE = assertProfileName(plan.profile);
7143
7320
  const existing = loadConfig();
7144
- 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 ?? [];
7145
7322
  const unsafe = roots2.filter((r) => rootExposesConfig(r, configDir()));
7146
7323
  if (unsafe.length) {
7147
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.`);
7148
7325
  process.exit(2);
7149
7326
  }
7150
7327
  for (const r of opts.root ? roots2 : []) {
7151
- if (fs22.existsSync(r)) continue;
7328
+ if (fs23.existsSync(r)) continue;
7152
7329
  try {
7153
- fs22.mkdirSync(r, { recursive: true });
7330
+ fs23.mkdirSync(r, { recursive: true });
7154
7331
  console.log(`Created ${r} for your agents to work in.`);
7155
7332
  } catch (e) {
7156
7333
  console.error(`Could not create ${r}: ${e.message}. Create it yourself, or add another folder with: ${cmd("roots add <folder>")}`);
@@ -7159,7 +7336,7 @@ program.command("enrol [token]").description("Connect this machine to your MonoC
7159
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 });
7160
7337
  console.log(`Enrolled as "${cfg.name}"${cfg.spaceName ? ` in ${cfg.spaceName} (@${cfg.spaceHandle})` : ""}${currentProfile() ? ` under the profile "${currentProfile()}"` : ""}. Config saved to ${configPath()}.`);
7161
7338
  if (plan.reason === "second-space") {
7162
- 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 });
7163
7340
  console.log(`This computer now runs one machine per space; its modules and Claude login are shared. The first enrolment is untouched.`);
7164
7341
  }
7165
7342
  if (!cfg.roots.length) console.log(`No folders exposed yet. Add one with: ${cmd("roots add ~/command")}`);
@@ -7245,7 +7422,7 @@ provider.command("add <name>").description("Add a Claude connection; an api_key
7245
7422
  const { registry, accounts } = await makeContext(requireConfig());
7246
7423
  const moduleId = opts.type === "api_key" ? "claude-api" : "claude-subscription";
7247
7424
  if (!registry.isInstalled(moduleId)) await registry.add(moduleId).install;
7248
- 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 ?? "")));
7249
7426
  if (opts.type === "api_key") {
7250
7427
  const id = await connectModule(registry, accounts, moduleId, io, { name, id: opts.id });
7251
7428
  if (folders) accounts.upsert({ ...accounts.get(id), allowedFolders: folders });
@@ -7274,18 +7451,18 @@ var roots = program.command("roots").description("Folders this machine exposes t
7274
7451
  roots.command("list").action(() => {
7275
7452
  const cfg = requireConfig();
7276
7453
  if (!cfg.roots.length) console.log("(none) \u2014 add one with: monoclaw roots add <path>");
7277
- 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}`);
7278
7455
  });
7279
7456
  roots.command("add <path...>").action((paths) => {
7280
7457
  const cfg = requireConfig();
7281
7458
  for (const p of paths) {
7282
- const full = path22.resolve(p.replace(/^~(?=$|\/)/, process.env.HOME ?? ""));
7283
- 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()) {
7284
7461
  console.error(`not a folder: ${full}`);
7285
7462
  continue;
7286
7463
  }
7287
7464
  if (rootExposesConfig(full, configDir())) {
7288
- 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")}.`);
7289
7466
  process.exitCode = 1;
7290
7467
  continue;
7291
7468
  }
@@ -7298,7 +7475,7 @@ Restart the host for the change to reach the app.`);
7298
7475
  });
7299
7476
  roots.command("remove <path>").action((p) => {
7300
7477
  const cfg = requireConfig();
7301
- const full = path22.resolve(p);
7478
+ const full = path23.resolve(p);
7302
7479
  cfg.roots = cfg.roots.filter((r) => r !== full);
7303
7480
  saveConfig(cfg);
7304
7481
  console.log(`Exposed folders: ${cfg.roots.join(", ") || "(none)"}`);
@@ -7333,7 +7510,7 @@ program.command("start", { hidden: true }).description("Run the host in this ter
7333
7510
  process.exit(1);
7334
7511
  }
7335
7512
  process.on("exit", lock.release);
7336
- setLogDir(path22.join(configDir(), "logs"));
7513
+ setLogDir(path23.join(configDir(), "logs"));
7337
7514
  const unsafe = loaded.roots.filter((r) => rootExposesConfig(r, configDir()));
7338
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>\`).`);
7339
7516
  const cfg = unsafe.length ? { ...loaded, roots: loaded.roots.filter((r) => !unsafe.includes(r)) } : loaded;
@@ -7353,6 +7530,21 @@ program.command("start", { hidden: true }).description("Run the host in this ter
7353
7530
  };
7354
7531
  const quiesce = async () => {
7355
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
+ }
7356
7548
  };
7357
7549
  client.onUpgradeRequired = () => {
7358
7550
  ensureUpToDate(cfg.routerUrl, { reason: "router requires it", onBeforeRestart: quiesce }).catch((e) => {
@@ -7360,7 +7552,7 @@ program.command("start", { hidden: true }).description("Run the host in this ter
7360
7552
  process.exit(3);
7361
7553
  });
7362
7554
  };
7363
- 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() });
7364
7556
  const stopChecks = checks.stop;
7365
7557
  client.onReconnected = () => checks.checkSoon();
7366
7558
  client.start();
@@ -7368,6 +7560,7 @@ program.command("start", { hidden: true }).description("Run the host in this ter
7368
7560
  log("info", "shutting down");
7369
7561
  stopChecks();
7370
7562
  await client.stop();
7563
+ saveHeld(client.sessions.heldForRestart());
7371
7564
  process.exit(0);
7372
7565
  };
7373
7566
  process.on("SIGINT", shutdown);
@@ -7379,6 +7572,10 @@ program.command("start", { hidden: true }).description("Run the host in this ter
7379
7572
  });
7380
7573
  process.on("uncaughtException", (e) => {
7381
7574
  log("error", `an error nobody caught; stopping: ${e.stack ?? e.message}`);
7575
+ try {
7576
+ saveHeld(client.sessions.heldForRestart());
7577
+ } catch {
7578
+ }
7382
7579
  client.diag.report({ kind: "machine.crash", level: "error", message: `${e.name}: ${e.message}`.slice(0, 300) });
7383
7580
  void client.diag.flush().finally(() => process.exit(1));
7384
7581
  setTimeout(() => process.exit(1), 5e3).unref();
@@ -7434,14 +7631,14 @@ program.command("doctor").description("Check and repair what a working host need
7434
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>" });
7435
7632
  else {
7436
7633
  lines.push({ ok: true, what: `Enrolled as "${cfg.name}" with ${cfg.routerUrl}` });
7437
- const missing = cfg.roots.filter((r) => !fs22.existsSync(r));
7634
+ const missing = cfg.roots.filter((r) => !fs23.existsSync(r));
7438
7635
  const exposing = cfg.roots.filter((r) => rootExposesConfig(r, configDir()));
7439
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>` });
7440
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 });
7441
7638
  const names = serviceNames();
7442
- 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;
7443
- 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` });
7444
- 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 });
7445
7642
  const { registry } = await makeContext(cfg);
7446
7643
  await registry.refreshReadiness();
7447
7644
  const reports = registry.reports();
@@ -7516,16 +7713,16 @@ config.command("set <key> <value>").description("Keys: allowedPermissionModes (c
7516
7713
  });
7517
7714
  var service = program.command("service").description("Run the host in the background at login");
7518
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) => {
7519
- if (!currentProfile() && fs22.existsSync(pendingServicePath())) {
7716
+ if (!currentProfile() && fs23.existsSync(pendingServicePath())) {
7520
7717
  try {
7521
- const pending = JSON.parse(fs22.readFileSync(pendingServicePath(), "utf8"));
7718
+ const pending = JSON.parse(fs23.readFileSync(pendingServicePath(), "utf8"));
7522
7719
  if (pending.profile && Date.now() - Date.parse(pending.at ?? "") < 60 * 6e4) {
7523
7720
  process.env.MONOCLAW_PROFILE = assertProfileName(pending.profile);
7524
7721
  console.log(`Installing the service for the profile "${pending.profile}" (the enrolment just made). The first enrolment's service is untouched.`);
7525
7722
  }
7526
7723
  } catch {
7527
7724
  }
7528
- fs22.rmSync(pendingServicePath(), { force: true });
7725
+ fs23.rmSync(pendingServicePath(), { force: true });
7529
7726
  }
7530
7727
  requireConfig();
7531
7728
  if (o.print) {
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@monoclaw/machine",
3
- "version": "1.0.17",
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.17",
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.17",
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": {