@monoclaw/machine 1.1.0-rc.1 → 1.1.0-rc.2

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 fs28 from "node:fs";
44
- import path28 from "node:path";
43
+ import fs30 from "node:fs";
44
+ import path30 from "node:path";
45
45
  import { Command } from "commander";
46
46
  import readline from "node:readline";
47
47
 
@@ -1995,11 +1995,11 @@ var busy = (e) => e.status === 429 && (e.code === "system_busy" || e.code === "t
1995
1995
  function elevenlabsModule(deps = {}) {
1996
1996
  const f = deps.fetch ?? ((...a) => fetch(...a));
1997
1997
  const queue = new PerKeyQueue();
1998
- const call = (key, path29, init = {}, timeoutMs = 12e4) => withRetries(
1998
+ const call = (key, path31, init = {}, timeoutMs = 12e4) => withRetries(
1999
1999
  async () => {
2000
2000
  let res;
2001
2001
  try {
2002
- res = await f(`${ELEVENLABS_BASE}${path29}`, { ...init, headers: { ...init.headers, "xi-api-key": key }, signal: AbortSignal.timeout(timeoutMs), redirect: "error" });
2002
+ res = await f(`${ELEVENLABS_BASE}${path31}`, { ...init, headers: { ...init.headers, "xi-api-key": key }, signal: AbortSignal.timeout(timeoutMs), redirect: "error" });
2003
2003
  } catch (e) {
2004
2004
  throw new Error(`Could not reach ElevenLabs: ${e.message}`);
2005
2005
  }
@@ -4627,7 +4627,8 @@ function loadComputer(base = baseDir()) {
4627
4627
  }
4628
4628
  if (typeof parsed.version === "number" && parsed.version > COMPUTER_FILE_VERSION) throw new NewerComputerFile(parsed.version);
4629
4629
  if (typeof parsed.id !== "string" || !Array.isArray(parsed.attachments)) return null;
4630
- return { version: COMPUTER_FILE_VERSION, id: parsed.id, createdAt: parsed.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(), mergedAt: parsed.mergedAt ?? null, attachments: parsed.attachments, unitsLeft: Array.isArray(parsed.unitsLeft) ? parsed.unitsLeft : [] };
4630
+ const program2 = parsed.program && typeof parsed.program === "object" && typeof parsed.program.dir === "string" ? { dir: parsed.program.dir, createdAt: parsed.program.createdAt ?? "", profileLine: parsed.program.profileLine && typeof parsed.program.profileLine.file === "string" && typeof parsed.program.profileLine.line === "string" ? { file: parsed.program.profileLine.file, line: parsed.program.profileLine.line } : null } : null;
4631
+ return { version: COMPUTER_FILE_VERSION, id: parsed.id, createdAt: parsed.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(), mergedAt: parsed.mergedAt ?? null, attachments: parsed.attachments, unitsLeft: Array.isArray(parsed.unitsLeft) ? parsed.unitsLeft : [], program: program2 };
4631
4632
  }
4632
4633
  function saveComputer(record, base = baseDir()) {
4633
4634
  fs13.mkdirSync(base, { recursive: true, mode: 448 });
@@ -4645,6 +4646,12 @@ function ensureComputer(base = baseDir(), now = () => /* @__PURE__ */ new Date()
4645
4646
  saveComputer(record, base);
4646
4647
  return record;
4647
4648
  }
4649
+ function recordProgram(program2, base = baseDir(), now = () => /* @__PURE__ */ new Date()) {
4650
+ const record = ensureComputer(base, now);
4651
+ record.program = program2;
4652
+ saveComputer(record, base);
4653
+ return record;
4654
+ }
4648
4655
  function mergeAttachments(opts = {}) {
4649
4656
  const started = Date.now();
4650
4657
  const base = opts.base ?? baseDir();
@@ -4683,19 +4690,95 @@ function mergeAttachments(opts = {}) {
4683
4690
  return { record, attachments, merged: changed, unitsRemoved, unitsLeft, notes, ms: Date.now() - started };
4684
4691
  }
4685
4692
 
4693
+ // src/prefix.ts
4694
+ import { execFile as execFile4 } from "node:child_process";
4695
+ import fs14 from "node:fs";
4696
+ import os5 from "node:os";
4697
+ import path14 from "node:path";
4698
+ import { promisify as promisify4 } from "node:util";
4699
+ function programDir(env = process.env, home = os5.homedir()) {
4700
+ return env.MONOCLAW_PROGRAM_DIR || path14.join(home, ".monoclaw", "program");
4701
+ }
4702
+ function layout(prefix, platform = process.platform) {
4703
+ const p = platform === "win32" ? path14.win32 : path14.posix;
4704
+ const modulesDir = platform === "win32" ? p.join(prefix, "node_modules") : p.join(prefix, "lib", "node_modules");
4705
+ return { script: p.join(modulesDir, "@monoclaw", "machine", "bin", "monoclaw.js"), binDir: platform === "win32" ? prefix : p.join(prefix, "bin"), modulesDir };
4706
+ }
4707
+ function ownPrefix(entry = process.argv[1] ?? "", platform = process.platform) {
4708
+ let real = entry;
4709
+ try {
4710
+ real = fs14.realpathSync(entry);
4711
+ } catch {
4712
+ }
4713
+ const p = real.replace(/\\/g, "/");
4714
+ if (/\/_npx\//.test(p)) return null;
4715
+ const m = /^(.*?)\/(lib\/)?node_modules\/@monoclaw\/machine\//.exec(p);
4716
+ if (!m) return null;
4717
+ return platform === "win32" ? m[1].replace(/\//g, "\\") : m[1];
4718
+ }
4719
+ function prefixWritable(prefix, platform = process.platform, deps = {}) {
4720
+ const access = deps.access ?? ((p) => fs14.accessSync(p, fs14.constants.W_OK));
4721
+ const exists = deps.exists ?? fs14.existsSync;
4722
+ const l = layout(prefix, platform);
4723
+ const pth = platform === "win32" ? path14.win32 : path14.posix;
4724
+ const check = (dir) => {
4725
+ let d = dir;
4726
+ while (!exists(d)) {
4727
+ const up = pth.dirname(d);
4728
+ if (up === d) return false;
4729
+ d = up;
4730
+ }
4731
+ try {
4732
+ access(d);
4733
+ return true;
4734
+ } catch {
4735
+ return false;
4736
+ }
4737
+ };
4738
+ return check(l.modulesDir) && check(l.binDir);
4739
+ }
4740
+ async function npmPrefixDefault() {
4741
+ const npm = process.platform === "win32" ? "npm.cmd" : "npm";
4742
+ const { stdout } = await promisify4(execFile4)(npm, ["prefix", "-g"], { shell: process.platform === "win32", timeout: 3e4 });
4743
+ return stdout.trim();
4744
+ }
4745
+ function versionUnder(prefix, platform = process.platform) {
4746
+ try {
4747
+ const pkg = path14.join(path14.dirname(path14.dirname(layout(prefix, platform).script)), "package.json");
4748
+ return JSON.parse(fs14.readFileSync(pkg, "utf8")).version ?? null;
4749
+ } catch {
4750
+ return null;
4751
+ }
4752
+ }
4753
+ function installedCopies(npmPrefix, own = programDir(), platform = process.platform) {
4754
+ const out = [];
4755
+ for (const [prefix, isOwn] of [[npmPrefix, false], [own, true]]) {
4756
+ if (!prefix) continue;
4757
+ const version = versionUnder(prefix, platform);
4758
+ if (version) out.push({ prefix, version, own: isOwn });
4759
+ }
4760
+ return out.sort((a, b) => compareVersions(b.version, a.version));
4761
+ }
4762
+ function describeInstall(mode, prefix, own = programDir(), home = os5.homedir()) {
4763
+ if (mode === "checkout") return "from a checkout";
4764
+ if (mode !== "npm-global" || !prefix) return "installed in an unknown way";
4765
+ const shown = prefix.startsWith(home) ? `~${prefix.slice(home.length)}` : prefix;
4766
+ return prefix === own ? `installed with npm in ${shown} (its own folder, because npm's folder was not writable)` : `installed with npm in ${shown}`;
4767
+ }
4768
+
4686
4769
  // src/client.ts
4687
- import fs19 from "node:fs";
4688
- import os6 from "node:os";
4689
- import path19 from "node:path";
4770
+ import fs20 from "node:fs";
4771
+ import os7 from "node:os";
4772
+ import path20 from "node:path";
4690
4773
  import WebSocket from "ws";
4691
4774
 
4692
4775
  // src/folders-record.ts
4693
- import fs14 from "node:fs";
4694
- import path14 from "node:path";
4695
- var foldersFile = (dir) => path14.join(dir, "folders.json");
4776
+ import fs15 from "node:fs";
4777
+ import path15 from "node:path";
4778
+ var foldersFile = (dir) => path15.join(dir, "folders.json");
4696
4779
  function readFolders(dir) {
4697
4780
  try {
4698
- const parsed = JSON.parse(fs14.readFileSync(foldersFile(dir), "utf8"));
4781
+ const parsed = JSON.parse(fs15.readFileSync(foldersFile(dir), "utf8"));
4699
4782
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
4700
4783
  const out = {};
4701
4784
  for (const [cwd, v] of Object.entries(parsed)) {
@@ -4711,8 +4794,8 @@ function readFolders(dir) {
4711
4794
  }
4712
4795
  }
4713
4796
  function write(dir, all2) {
4714
- fs14.mkdirSync(dir, { recursive: true, mode: 448 });
4715
- fs14.writeFileSync(foldersFile(dir), `${JSON.stringify(all2, null, 2)}
4797
+ fs15.mkdirSync(dir, { recursive: true, mode: 448 });
4798
+ fs15.writeFileSync(foldersFile(dir), `${JSON.stringify(all2, null, 2)}
4716
4799
  `, { mode: 384 });
4717
4800
  }
4718
4801
  function update(dir, cwd, fn, now) {
@@ -4736,13 +4819,13 @@ function recordSavedFile(dir, cwd, file, bytes, now = /* @__PURE__ */ new Date()
4736
4819
  }
4737
4820
 
4738
4821
  // src/sessions.ts
4739
- import fs16 from "node:fs";
4740
- import os5 from "node:os";
4741
- import path16 from "node:path";
4822
+ import fs17 from "node:fs";
4823
+ import os6 from "node:os";
4824
+ import path17 from "node:path";
4742
4825
 
4743
4826
  // src/tools.ts
4744
- import fs15 from "node:fs";
4745
- import path15 from "node:path";
4827
+ import fs16 from "node:fs";
4828
+ import path16 from "node:path";
4746
4829
  var TOOLS_SERVER = "monoclaw-tools";
4747
4830
  var TOOL_TIMEOUT_MS = 3 * 6e4;
4748
4831
  var STT_TOOL_TIMEOUT_MS = 11 * 6e4;
@@ -4772,7 +4855,7 @@ function formatToolResult(tool2, r, cwd) {
4772
4855
  else lines.push(`${f.name} (attachment:${f.attachmentId}) could not be fetched to show you.`);
4773
4856
  continue;
4774
4857
  }
4775
- const where = f.path ? cwd ? path15.relative(cwd, f.path) || f.path : f.path : "";
4858
+ const where = f.path ? cwd ? path16.relative(cwd, f.path) || f.path : f.path : "";
4776
4859
  lines.push(where ? `Saved ${where} (attachment:${f.attachmentId})` : `Made ${f.name} (attachment:${f.attachmentId}; not saved to the folder in this scope)`);
4777
4860
  }
4778
4861
  if (made.length) lines.push(`The people in the project see ${made.every((f) => f.mime.startsWith("audio/")) ? "this audio" : made.every((f) => f.mime.startsWith("image/")) ? made.length === 1 ? "this image" : "these images" : made.length === 1 ? "this file" : "these files"} in your steps.`);
@@ -4866,7 +4949,7 @@ var SessionToolRunner = class {
4866
4949
  if ("error" in file) return formatToolResult(t, { error: file.error, files: [] });
4867
4950
  const callArgs = toolCallArgs(t, args2);
4868
4951
  if (t.askBeforeUse) {
4869
- const ok = await this.approve(toolMcpName(t), { file: given, ...callArgs }, `${t.name}: ${path15.basename(file.path)}`);
4952
+ const ok = await this.approve(toolMcpName(t), { file: given, ...callArgs }, `${t.name}: ${path16.basename(file.path)}`);
4870
4953
  if (!ok) return formatToolResult(t, { error: "The user declined this tool call.", files: [] });
4871
4954
  }
4872
4955
  const id = newId();
@@ -4934,29 +5017,29 @@ var SessionToolRunner = class {
4934
5017
  };
4935
5018
  function resolveToolFile(given, cwd, scope) {
4936
5019
  if (!given) return { error: "Name the file." };
4937
- const abs = path15.resolve(cwd, given.replace(/^~(?=$|\/)/, process.env.HOME ?? "~"));
5020
+ const abs = path16.resolve(cwd, given.replace(/^~(?=$|\/)/, process.env.HOME ?? "~"));
4938
5021
  let real;
4939
5022
  try {
4940
- real = fs15.realpathSync(abs);
5023
+ real = fs16.realpathSync(abs);
4941
5024
  } catch {
4942
5025
  return { error: `There is no file at ${given}.` };
4943
5026
  }
4944
5027
  if (scope !== "full") {
4945
- const root = fs15.realpathSync(cwd);
4946
- if (real !== root && !real.startsWith(root + path15.sep)) return { error: "Only files inside your folder can be given to a tool." };
5028
+ const root = fs16.realpathSync(cwd);
5029
+ if (real !== root && !real.startsWith(root + path16.sep)) return { error: "Only files inside your folder can be given to a tool." };
4947
5030
  }
4948
- const stat = fs15.statSync(real);
5031
+ const stat = fs16.statSync(real);
4949
5032
  if (!stat.isFile()) return { error: `${given} isn't a file.` };
4950
5033
  if (stat.size > 20 * 1024 * 1024) return { error: `${given} is larger than 20 MB.` };
4951
5034
  return { path: real };
4952
5035
  }
4953
5036
  function uniqueFileName(dir, name) {
4954
- const base = path15.basename(name).replace(/[^\w.() -]/g, "_").replace(/^\.+/, "").slice(0, 100) || "image";
4955
- const ext = path15.extname(base);
5037
+ const base = path16.basename(name).replace(/[^\w.() -]/g, "_").replace(/^\.+/, "").slice(0, 100) || "image";
5038
+ const ext = path16.extname(base);
4956
5039
  const stem = base.slice(0, base.length - ext.length) || "image";
4957
5040
  let candidate = `${stem}${ext}`;
4958
- for (let i = 2; fs15.existsSync(path15.join(dir, candidate)); i++) candidate = `${stem}-${i}${ext}`;
4959
- return path15.join(dir, candidate);
5041
+ for (let i = 2; fs16.existsSync(path16.join(dir, candidate)); i++) candidate = `${stem}-${i}${ext}`;
5042
+ return path16.join(dir, candidate);
4960
5043
  }
4961
5044
 
4962
5045
  // src/sessions.ts
@@ -4965,17 +5048,17 @@ var SessionManager = class {
4965
5048
  constructor(providers2, emit, download, policy, accounts = { resolveCwd: (_id, cwd) => resolveInsideRoots(policy().roots, cwd), envFor: async () => ({}), providerOf: () => void 0 }, saveFile = async (f, dir) => {
4966
5049
  const tmp = await download({ id: f.attachmentId, name: f.name, mime: f.mime, size: 0, url: f.url, kind: "image" }, dir);
4967
5050
  const dest = uniqueFileName(dir, f.name);
4968
- fs16.renameSync(tmp, dest);
5051
+ fs17.renameSync(tmp, dest);
4969
5052
  return dest;
4970
5053
  }, fetchFile = async (f, cap) => {
4971
- const dir = fs16.mkdtempSync(path16.join(os5.tmpdir(), "mc-show-"));
5054
+ const dir = fs17.mkdtempSync(path17.join(os6.tmpdir(), "mc-show-"));
4972
5055
  try {
4973
5056
  const tmp = await download({ id: f.attachmentId, name: f.name, mime: f.mime, size: 0, url: f.url, kind: "image" }, dir);
4974
- const bytes = fs16.readFileSync(tmp);
5057
+ const bytes = fs17.readFileSync(tmp);
4975
5058
  if (bytes.length > cap) throw new Error(`${f.name} is larger than ${Math.round(cap / (1024 * 1024))} MB`);
4976
5059
  return bytes;
4977
5060
  } finally {
4978
- fs16.rmSync(dir, { recursive: true, force: true });
5061
+ fs17.rmSync(dir, { recursive: true, force: true });
4979
5062
  }
4980
5063
  }) {
4981
5064
  this.emit = emit;
@@ -5160,7 +5243,7 @@ var SessionManager = class {
5160
5243
  this.emit(frame.groupId, { kind: "error", message: refused, fatal: true });
5161
5244
  return;
5162
5245
  }
5163
- if (!fs16.existsSync(cwd) || !fs16.statSync(cwd).isDirectory()) {
5246
+ if (!fs17.existsSync(cwd) || !fs17.statSync(cwd).isDirectory()) {
5164
5247
  this.emit(frame.groupId, { kind: "error", message: `folder ${frame.cwd} does not exist on this host`, fatal: true });
5165
5248
  return;
5166
5249
  }
@@ -5180,7 +5263,7 @@ var SessionManager = class {
5180
5263
  forkFrom = void 0;
5181
5264
  }
5182
5265
  }
5183
- const inboxDir = path16.join(cwd, ".monoclaw", "inbox");
5266
+ const inboxDir = path17.join(cwd, ".monoclaw", "inbox");
5184
5267
  const env = await this.accounts.envFor(frame.providerAccountId);
5185
5268
  const session = provider2.openSession({
5186
5269
  groupId: frame.groupId,
@@ -5281,7 +5364,7 @@ var SessionManager = class {
5281
5364
  this.emit(groupId, { kind: "done", interrupted: false });
5282
5365
  return;
5283
5366
  }
5284
- const inboxDir = path16.join(live.cwd, ".monoclaw", "inbox");
5367
+ const inboxDir = path17.join(live.cwd, ".monoclaw", "inbox");
5285
5368
  const attachments = [];
5286
5369
  for (const att2 of message.attachments) {
5287
5370
  try {
@@ -5334,13 +5417,13 @@ var SessionManager = class {
5334
5417
  }
5335
5418
  try {
5336
5419
  const sub = f.mime.startsWith("audio/") ? "audio" : f.mime.startsWith("image/") ? "images" : "files";
5337
- const existed = fs16.existsSync(path16.join(live.cwd, sub));
5420
+ const existed = fs17.existsSync(path17.join(live.cwd, sub));
5338
5421
  const dir = filesDirIn(live.cwd, sub);
5339
5422
  if (!existed) this.recordCreatedDir(live.cwd, sub);
5340
5423
  const saved = await this.saveFile(f, dir);
5341
5424
  files.push({ ...base, path: saved });
5342
5425
  try {
5343
- this.recordSavedFile(live.cwd, saved, fs16.statSync(saved).size);
5426
+ this.recordSavedFile(live.cwd, saved, fs17.statSync(saved).size);
5344
5427
  } catch {
5345
5428
  }
5346
5429
  } catch (e) {
@@ -5428,41 +5511,41 @@ var SessionManager = class {
5428
5511
  }
5429
5512
  };
5430
5513
  function filesDirIn(cwd, name) {
5431
- const dir = path16.join(cwd, name);
5432
- fs16.mkdirSync(dir, { recursive: true });
5433
- const realCwd = fs16.realpathSync(cwd);
5434
- const real = fs16.realpathSync(dir);
5435
- if (real !== path16.join(realCwd, name) && !real.startsWith(realCwd + path16.sep)) throw new Error(`the ${name} folder points outside the agent's folder; not saving there`);
5436
- if (fs16.lstatSync(dir).isSymbolicLink()) throw new Error(`the ${name} folder is a link; not saving there`);
5514
+ const dir = path17.join(cwd, name);
5515
+ fs17.mkdirSync(dir, { recursive: true });
5516
+ const realCwd = fs17.realpathSync(cwd);
5517
+ const real = fs17.realpathSync(dir);
5518
+ if (real !== path17.join(realCwd, name) && !real.startsWith(realCwd + path17.sep)) throw new Error(`the ${name} folder points outside the agent's folder; not saving there`);
5519
+ if (fs17.lstatSync(dir).isSymbolicLink()) throw new Error(`the ${name} folder is a link; not saving there`);
5437
5520
  return dir;
5438
5521
  }
5439
5522
 
5440
5523
  // src/store/secrets.ts
5441
- import { execFile as execFile4 } from "node:child_process";
5442
- import fs17 from "node:fs";
5443
- import path17 from "node:path";
5444
- import { promisify as promisify4 } from "node:util";
5445
- var execFileP4 = promisify4(execFile4);
5524
+ import { execFile as execFile5 } from "node:child_process";
5525
+ import fs18 from "node:fs";
5526
+ import path18 from "node:path";
5527
+ import { promisify as promisify5 } from "node:util";
5528
+ var execFileP4 = promisify5(execFile5);
5446
5529
  var SERVICE = "monoclaw-host";
5447
5530
  var FileStore = class {
5448
- constructor(file = path17.join(baseDir(), "secrets.json")) {
5531
+ constructor(file = path18.join(baseDir(), "secrets.json")) {
5449
5532
  this.file = file;
5450
5533
  }
5451
5534
  file;
5452
5535
  kind = "file";
5453
5536
  read() {
5454
5537
  try {
5455
- return JSON.parse(fs17.readFileSync(this.file, "utf8"));
5538
+ return JSON.parse(fs18.readFileSync(this.file, "utf8"));
5456
5539
  } catch {
5457
5540
  return {};
5458
5541
  }
5459
5542
  }
5460
5543
  write(all2) {
5461
- fs17.mkdirSync(path17.dirname(this.file), { recursive: true, mode: 448 });
5462
- fs17.writeFileSync(this.file, `${JSON.stringify(all2, null, 2)}
5544
+ fs18.mkdirSync(path18.dirname(this.file), { recursive: true, mode: 448 });
5545
+ fs18.writeFileSync(this.file, `${JSON.stringify(all2, null, 2)}
5463
5546
  `, { mode: 384 });
5464
5547
  try {
5465
- fs17.chmodSync(this.file, 384);
5548
+ fs18.chmodSync(this.file, 384);
5466
5549
  } catch {
5467
5550
  }
5468
5551
  if (process.platform === "win32") void execFileP4("icacls", [this.file, "/inheritance:r", "/grant:r", `${process.env.USERNAME ?? "%USERNAME%"}:F`]).catch(() => void 0);
@@ -5518,7 +5601,7 @@ var SecretService = class {
5518
5601
  }
5519
5602
  async set(id, secret) {
5520
5603
  await new Promise((resolve, reject) => {
5521
- const p = execFile4("secret-tool", ["store", "--label", `Monoclaw provider account ${id}`, "service", SERVICE, "account", id], (err) => err ? reject(err) : resolve());
5604
+ const p = execFile5("secret-tool", ["store", "--label", `Monoclaw provider account ${id}`, "service", SERVICE, "account", id], (err) => err ? reject(err) : resolve());
5522
5605
  p.stdin?.end(secret);
5523
5606
  });
5524
5607
  }
@@ -5535,7 +5618,7 @@ async function has(cmd2) {
5535
5618
  }
5536
5619
  }
5537
5620
  async function pickSecretStore(dir = baseDir()) {
5538
- const file = () => new FileStore(path17.join(dir, "secrets.json"));
5621
+ const file = () => new FileStore(path18.join(dir, "secrets.json"));
5539
5622
  if (process.env.MONOCLAW_SECRET_STORE === "file") return file();
5540
5623
  if (process.platform === "darwin" && await has("security")) return new DarwinKeychain();
5541
5624
  if (process.platform === "linux" && process.env.DBUS_SESSION_BUS_ADDRESS && await has("secret-tool")) return new SecretService();
@@ -5543,12 +5626,12 @@ async function pickSecretStore(dir = baseDir()) {
5543
5626
  }
5544
5627
 
5545
5628
  // src/transfer.ts
5546
- import fs18 from "node:fs";
5547
- import path18 from "node:path";
5629
+ import fs19 from "node:fs";
5630
+ import path19 from "node:path";
5548
5631
  var MAX_DOWNLOAD = 50 * 1024 * 1024;
5549
5632
  var MAX_UPLOAD = 20 * 1024 * 1024;
5550
5633
  function safeName(name) {
5551
- const base = path18.basename(name).replace(/[^\w.() -]/g, "_").slice(0, 100) || "file";
5634
+ const base = path19.basename(name).replace(/[^\w.() -]/g, "_").slice(0, 100) || "file";
5552
5635
  return `${(/* @__PURE__ */ new Date()).toISOString().slice(0, 19).replace(/[:T]/g, "-")}-${base}`;
5553
5636
  }
5554
5637
  function assertRouterTarget(url, routerOrigin2, what) {
@@ -5583,12 +5666,12 @@ async function readCapped2(res, cap) {
5583
5666
  async function downloadAttachment(att2, dir, credential, routerOrigin2) {
5584
5667
  assertRouterTarget(att2.url, routerOrigin2, "attachment");
5585
5668
  if (att2.size > MAX_DOWNLOAD) throw new Error("attachment too large");
5586
- fs18.mkdirSync(dir, { recursive: true });
5669
+ fs19.mkdirSync(dir, { recursive: true });
5587
5670
  const res = await fetch(att2.url, { headers: { Authorization: `Bearer ${credential}` }, signal: AbortSignal.timeout(6e4), redirect: "manual" });
5588
5671
  if (!res.ok) throw new Error(`download failed: ${res.status}`);
5589
5672
  const buf = await readCapped2(res, MAX_DOWNLOAD);
5590
- const full = path18.join(dir, safeName(att2.name));
5591
- fs18.writeFileSync(full, buf);
5673
+ const full = path19.join(dir, safeName(att2.name));
5674
+ fs19.writeFileSync(full, buf);
5592
5675
  return full;
5593
5676
  }
5594
5677
  async function fetchAttachmentBytes(url, credential, routerOrigin2, cap) {
@@ -5599,7 +5682,7 @@ async function fetchAttachmentBytes(url, credential, routerOrigin2, cap) {
5599
5682
  }
5600
5683
  async function uploadFile(uploadUrl, credential, routerOrigin2, input) {
5601
5684
  assertRouterTarget(uploadUrl, routerOrigin2, "upload");
5602
- const stat = fs18.statSync(input.filePath);
5685
+ const stat = fs19.statSync(input.filePath);
5603
5686
  if (!stat.isFile()) throw new Error("not a file");
5604
5687
  if (stat.size > MAX_UPLOAD) throw new Error("file is larger than 20 MB, which Telegram bots cannot send");
5605
5688
  const form = new FormData();
@@ -5608,7 +5691,7 @@ async function uploadFile(uploadUrl, credential, routerOrigin2, input) {
5608
5691
  if (input.mime) form.set("mime", input.mime);
5609
5692
  if (input.caption) form.set("caption", input.caption);
5610
5693
  if (input.toolInput) form.set("toolInput", "1");
5611
- form.set("file", new Blob([fs18.readFileSync(input.filePath)], { type: input.mime || "application/octet-stream" }), input.name);
5694
+ form.set("file", new Blob([fs19.readFileSync(input.filePath)], { type: input.mime || "application/octet-stream" }), input.name);
5612
5695
  const res = await fetch(uploadUrl, { method: "POST", headers: { Authorization: `Bearer ${credential}` }, body: form, signal: AbortSignal.timeout(12e4), redirect: "manual" });
5613
5696
  if (!res.ok) throw new Error(`upload failed: ${res.status} ${(await res.text()).slice(0, 200)}`);
5614
5697
  return String((await res.json().catch(() => ({}))).id ?? "");
@@ -5627,7 +5710,7 @@ async function uploadJobOutput(uploadUrl, credential, routerOrigin2, input) {
5627
5710
  return a.id;
5628
5711
  }
5629
5712
  function guessMime(name) {
5630
- const ext = path18.extname(name).toLowerCase();
5713
+ const ext = path19.extname(name).toLowerCase();
5631
5714
  const map = {
5632
5715
  ".png": "image/png",
5633
5716
  ".jpg": "image/jpeg",
@@ -5658,7 +5741,7 @@ function guessMime(name) {
5658
5741
  }
5659
5742
 
5660
5743
  // src/version.ts
5661
- var APP_VERSION = true ? "1.1.0-rc.1" : fromPackage();
5744
+ var APP_VERSION = true ? "1.1.0-rc.2" : fromPackage();
5662
5745
 
5663
5746
  // src/diag.ts
5664
5747
  var MAX_HELD = 200;
@@ -5726,7 +5809,7 @@ var HostClient = class _HostClient {
5726
5809
  this.attachment = opts.attachment ?? attachmentFor(null);
5727
5810
  this.computerId = opts.computerId ?? null;
5728
5811
  this.config = new ConfigStore(cfg, this.attachment.dir);
5729
- this.accounts = opts.accounts ?? new Accounts(new FileStore(path19.join(this.attachment.dir, "secrets.json")), this.config);
5812
+ this.accounts = opts.accounts ?? new Accounts(new FileStore(path20.join(this.attachment.dir, "secrets.json")), this.config);
5730
5813
  this.registry = opts.registry ?? new ModuleRegistry({ config: this.config, accounts: this.accounts, providers: providers2, modules: opts.modules, fetch: opts.fetch, dir: this.attachment.dir, profile: this.attachment.profile });
5731
5814
  this.registry.onChange(() => this.scheduleModules());
5732
5815
  const accounts = this.accounts;
@@ -5870,7 +5953,7 @@ var HostClient = class _HostClient {
5870
5953
  watchConfig() {
5871
5954
  if (this.watching) return;
5872
5955
  this.watching = true;
5873
- fs19.watchFile(configPath(this.attachment.dir), { interval: 3e3 }, () => {
5956
+ fs20.watchFile(configPath(this.attachment.dir), { interval: 3e3 }, () => {
5874
5957
  void this.registry.refreshReadiness().catch(() => void 0);
5875
5958
  });
5876
5959
  }
@@ -5887,7 +5970,7 @@ var HostClient = class _HostClient {
5887
5970
  this.sessions.beginStop();
5888
5971
  if (this.heartbeat) clearInterval(this.heartbeat);
5889
5972
  if (this.modulesTimer) clearTimeout(this.modulesTimer);
5890
- if (this.watching) fs19.unwatchFile(configPath(this.attachment.dir));
5973
+ if (this.watching) fs20.unwatchFile(configPath(this.attachment.dir));
5891
5974
  this.watching = false;
5892
5975
  this.clearTimers();
5893
5976
  await Promise.allSettled([...this.inFlight]);
@@ -6015,10 +6098,10 @@ var HostClient = class _HostClient {
6015
6098
  }
6016
6099
  if ((event.kind === "tool.call" || event.kind === "tool.use") && event.file) {
6017
6100
  const { file, ...call } = event;
6018
- void uploadFile(this.uploadUrl, this.cfg.credential ?? "", routerOrigin(this.cfg.routerUrl), { groupId, filePath: file, name: path19.basename(file), mime: guessMime(file), toolInput: true }).then((attachmentId) => {
6101
+ void uploadFile(this.uploadUrl, this.cfg.credential ?? "", routerOrigin(this.cfg.routerUrl), { groupId, filePath: file, name: path20.basename(file), mime: guessMime(file), toolInput: true }).then((attachmentId) => {
6019
6102
  if (!attachmentId) throw new Error("the server kept no file");
6020
6103
  this.emit(groupId, { ...call, attachmentId });
6021
- }).catch((e) => void this.sessions.toolResult(groupId, event.id, { error: `Could not upload ${path19.basename(file)}: ${e.message}`, files: [] }));
6104
+ }).catch((e) => void this.sessions.toolResult(groupId, event.id, { error: `Could not upload ${path20.basename(file)}: ${e.message}`, files: [] }));
6022
6105
  return;
6023
6106
  }
6024
6107
  const frame = { t: "event", id: newId(), groupId, event, at: nowIso() };
@@ -6287,8 +6370,8 @@ var HostClient = class _HostClient {
6287
6370
  let job;
6288
6371
  if (frame.input.capability === "stt") {
6289
6372
  phase = "download";
6290
- audioFile = await downloadAttachment({ id: frame.jobId, name: `${frame.jobId}.audio`, mime: frame.input.mime, size: 0, url: frame.input.url, kind: "voice" }, path19.join(this.attachment.dir, "jobs"), credential, origin);
6291
- job = { capability: "stt", audio: fs19.readFileSync(audioFile), mime: frame.input.mime, options: frame.options };
6373
+ audioFile = await downloadAttachment({ id: frame.jobId, name: `${frame.jobId}.audio`, mime: frame.input.mime, size: 0, url: frame.input.url, kind: "voice" }, path20.join(this.attachment.dir, "jobs"), credential, origin);
6374
+ job = { capability: "stt", audio: fs20.readFileSync(audioFile), mime: frame.input.mime, options: frame.options };
6292
6375
  facts.bytes = job.audio.length;
6293
6376
  phase = "run";
6294
6377
  } else if (frame.input.capability === "tts") job = { capability: "tts", text: frame.input.text, options: frame.options };
@@ -6301,9 +6384,9 @@ var HostClient = class _HostClient {
6301
6384
  const rule = declared.files.find((d) => d.field === f.field);
6302
6385
  if (!rule) throw new Error(`${declared.name} takes no file in "${f.field}".`);
6303
6386
  if (!rule.accept.some((a) => mimeMatches(a, f.mime))) throw new Error(`${f.name || f.field} is ${f.mime}; ${declared.name} takes ${rule.accept.join(", ")}.`);
6304
- const saved = await downloadAttachment({ id: `${frame.jobId}-${f.field}`, name: `${frame.jobId}.${f.field}`, mime: f.mime, size: 0, url: f.url, kind: "image" }, path19.join(this.attachment.dir, "jobs"), credential, origin);
6387
+ const saved = await downloadAttachment({ id: `${frame.jobId}-${f.field}`, name: `${frame.jobId}.${f.field}`, mime: f.mime, size: 0, url: f.url, kind: "image" }, path20.join(this.attachment.dir, "jobs"), credential, origin);
6305
6388
  jobFiles.push(saved);
6306
- const bytes = fs19.readFileSync(saved);
6389
+ const bytes = fs20.readFileSync(saved);
6307
6390
  if (bytes.length > rule.maxMb * 1024 * 1024) throw new Error(`${f.name || f.field} is ${(bytes.length / 1024 / 1024).toFixed(1)} MB; ${declared.name} takes up to ${rule.maxMb} MB.`);
6308
6391
  files.push({ field: f.field, bytes, mime: f.mime, name: f.name });
6309
6392
  }
@@ -6311,8 +6394,8 @@ var HostClient = class _HostClient {
6311
6394
  } else {
6312
6395
  job = { capability: "image", prompt: frame.input.prompt, args: frame.input.args, options: frame.options };
6313
6396
  if (frame.input.reference) {
6314
- audioFile = await downloadAttachment({ id: frame.jobId, name: `${frame.jobId}.image`, mime: frame.input.reference.mime, size: 0, url: frame.input.reference.url, kind: "image" }, path19.join(this.attachment.dir, "jobs"), credential, origin);
6315
- job.reference = { bytes: fs19.readFileSync(audioFile), mime: frame.input.reference.mime };
6397
+ audioFile = await downloadAttachment({ id: frame.jobId, name: `${frame.jobId}.image`, mime: frame.input.reference.mime, size: 0, url: frame.input.reference.url, kind: "image" }, path20.join(this.attachment.dir, "jobs"), credential, origin);
6398
+ job.reference = { bytes: fs20.readFileSync(audioFile), mime: frame.input.reference.mime };
6316
6399
  }
6317
6400
  }
6318
6401
  phase = "run";
@@ -6341,14 +6424,14 @@ var HostClient = class _HostClient {
6341
6424
  this.send(result);
6342
6425
  } finally {
6343
6426
  clearTimeout(hung);
6344
- if (audioFile) fs19.rmSync(audioFile, { force: true });
6345
- for (const f of jobFiles) fs19.rmSync(f, { force: true });
6427
+ if (audioFile) fs20.rmSync(audioFile, { force: true });
6428
+ for (const f of jobFiles) fs20.rmSync(f, { force: true });
6346
6429
  }
6347
6430
  this.scheduleModules();
6348
6431
  }
6349
6432
  };
6350
6433
  function describeMachine() {
6351
- return { name: os6.hostname(), platform: process.platform, arch: process.arch, appVersion: APP_VERSION, nodeVersion: process.version };
6434
+ return { name: os7.hostname(), platform: process.platform, arch: process.arch, appVersion: APP_VERSION, nodeVersion: process.version };
6352
6435
  }
6353
6436
  function mimeMatches(pattern2, mime) {
6354
6437
  const m = mime.split(";")[0].trim().toLowerCase();
@@ -6357,24 +6440,24 @@ function mimeMatches(pattern2, mime) {
6357
6440
  }
6358
6441
 
6359
6442
  // src/held.ts
6360
- import fs20 from "node:fs";
6361
- import path20 from "node:path";
6362
- var heldFile = (dir = baseDir()) => path20.join(dir, "held-messages.json");
6443
+ import fs21 from "node:fs";
6444
+ import path21 from "node:path";
6445
+ var heldFile = (dir = baseDir()) => path21.join(dir, "held-messages.json");
6363
6446
  function saveHeld(records, dir = baseDir()) {
6364
6447
  if (!records.length) return;
6365
- fs20.mkdirSync(dir, { recursive: true });
6448
+ fs21.mkdirSync(dir, { recursive: true });
6366
6449
  const f = heldFile(dir);
6367
6450
  const tmp = `${f}.${process.pid}.part`;
6368
- fs20.writeFileSync(tmp, JSON.stringify({ savedAt: (/* @__PURE__ */ new Date()).toISOString(), records }), { mode: 384 });
6369
- fs20.chmodSync(tmp, 384);
6370
- fs20.renameSync(tmp, f);
6451
+ fs21.writeFileSync(tmp, JSON.stringify({ savedAt: (/* @__PURE__ */ new Date()).toISOString(), records }), { mode: 384 });
6452
+ fs21.chmodSync(tmp, 384);
6453
+ fs21.renameSync(tmp, f);
6371
6454
  log("info", `kept ${records.length} held message${records.length === 1 ? "" : "s"} for after the restart`);
6372
6455
  }
6373
6456
  function loadHeld(dir = baseDir()) {
6374
6457
  const f = heldFile(dir);
6375
- if (!fs20.existsSync(f)) return { records: [], problem: null };
6458
+ if (!fs21.existsSync(f)) return { records: [], problem: null };
6376
6459
  try {
6377
- const parsed = JSON.parse(fs20.readFileSync(f, "utf8"));
6460
+ const parsed = JSON.parse(fs21.readFileSync(f, "utf8"));
6378
6461
  const records = Array.isArray(parsed.records) ? parsed.records : null;
6379
6462
  if (!records) return { records: [], problem: "the held-messages file had no list of messages" };
6380
6463
  const good = records.filter((r) => !!r && typeof r === "object" && typeof r.groupId === "string" && !!r.message && typeof r.message.id === "string");
@@ -6382,7 +6465,7 @@ function loadHeld(dir = baseDir()) {
6382
6465
  } catch (e) {
6383
6466
  return { records: [], problem: `the held-messages file could not be read: ${e.message}` };
6384
6467
  } finally {
6385
- fs20.rmSync(f, { force: true });
6468
+ fs21.rmSync(f, { force: true });
6386
6469
  }
6387
6470
  }
6388
6471
 
@@ -6516,13 +6599,13 @@ var Fleet = class {
6516
6599
  };
6517
6600
 
6518
6601
  // src/control.ts
6519
- import fs21 from "node:fs";
6602
+ import fs22 from "node:fs";
6520
6603
  import net from "node:net";
6521
- import path21 from "node:path";
6604
+ import path22 from "node:path";
6522
6605
  var WINDOWS_CONTROL_NOTE = "The control channel on Windows (a named pipe) is not yet verified: `monoclaw status` reads what is on disk and cannot ask the running program.";
6523
6606
  function controlPath(base = baseDir(), platform = process.platform) {
6524
6607
  if (platform === "win32") return `\\\\.\\pipe\\monoclaw-${Buffer.from(base).toString("hex").slice(0, 32)}`;
6525
- return path21.join(base, "control.sock");
6608
+ return path22.join(base, "control.sock");
6526
6609
  }
6527
6610
  function serveControl(handlers, opts = {}) {
6528
6611
  const platform = opts.platform ?? process.platform;
@@ -6557,19 +6640,19 @@ function serveControl(handlers, opts = {}) {
6557
6640
  return new Promise((resolve, reject) => {
6558
6641
  if (platform !== "win32") {
6559
6642
  try {
6560
- fs21.rmSync(file, { force: true });
6643
+ fs22.rmSync(file, { force: true });
6561
6644
  } catch {
6562
6645
  }
6563
6646
  }
6564
6647
  server.once("error", reject);
6565
6648
  server.listen(file, () => {
6566
6649
  server.off("error", reject);
6567
- if (platform !== "win32") fs21.chmodSync(file, 384);
6650
+ if (platform !== "win32") fs22.chmodSync(file, 384);
6568
6651
  resolve({
6569
6652
  path: file,
6570
6653
  close: () => new Promise((done) => {
6571
6654
  server.close(() => {
6572
- if (platform !== "win32") fs21.rmSync(file, { force: true });
6655
+ if (platform !== "win32") fs22.rmSync(file, { force: true });
6573
6656
  done();
6574
6657
  });
6575
6658
  })
@@ -6610,8 +6693,8 @@ function askControl(req, opts = {}) {
6610
6693
  }
6611
6694
 
6612
6695
  // src/status.ts
6613
- import fs22 from "node:fs";
6614
- import path22 from "node:path";
6696
+ import fs23 from "node:fs";
6697
+ import path23 from "node:path";
6615
6698
  var label = (a) => a.organisation.name ? `${a.organisation.name}${a.organisation.handle ? ` (@${a.organisation.handle})` : ""}` : a.profile ? `profile "${a.profile}"` : "the default enrolment";
6616
6699
  var nameFor = (a) => a.organisation.handle ? `--organisation ${a.organisation.handle}` : a.profile ? `--profile ${a.profile}` : "";
6617
6700
  async function buildStatus(deps) {
@@ -6624,7 +6707,7 @@ async function buildStatus(deps) {
6624
6707
  if (control) running = { pid: Number(control.pid), version: control.version, startedAt: control.startedAt };
6625
6708
  else {
6626
6709
  try {
6627
- const pid = Number(fs22.readFileSync(path22.join(baseDir(), "host.pid"), "utf8").trim());
6710
+ const pid = Number(fs23.readFileSync(path23.join(baseDir(), "host.pid"), "utf8").trim());
6628
6711
  if (pid && processAlive(pid)) {
6629
6712
  running = { pid, version: "unknown", startedAt: "" };
6630
6713
  notes.push(`A program runs (pid ${pid}) but did not answer on the control channel: an older version, or still starting.`);
@@ -6642,11 +6725,11 @@ async function buildStatus(deps) {
6642
6725
  problems.push({ where: "computer", what: e.message, fix: null });
6643
6726
  }
6644
6727
  for (const u of unitsLeft) problems.push({ where: `profile "${u.profile}"`, what: `an old background service unit is still there: ${u.unit} (${u.error})`, fix: "monoclaw service uninstall removes it, then monoclaw service install" });
6645
- const serviceInstalled = fs22.existsSync(profileUnitFile(null, platform, deps.home) ?? "");
6728
+ const serviceInstalled = fs23.existsSync(profileUnitFile(null, platform, deps.home) ?? "");
6646
6729
  if (!running && serviceInstalled) problems.push({ where: "program", what: "the background service is installed but the program is not running", fix: "monoclaw service install starts it again; monoclaw logs shows why it stopped" });
6647
6730
  const claude = await deps.claude();
6648
6731
  if (claude.loggedIn === false) problems.push({ where: "Claude", what: "not logged in to Claude on this computer", fix: "monoclaw claude auth login" });
6649
- const modelsDir = path22.join(sharedDir(), "voice-models");
6732
+ const modelsDir = path23.join(sharedDir(), "voice-models");
6650
6733
  const models = { bytes: folderBytes(modelsDir), dir: modelsDir };
6651
6734
  const live = /* @__PURE__ */ new Map();
6652
6735
  for (const a of control?.fleet.attachments ?? []) live.set(a.profile, a);
@@ -6717,16 +6800,16 @@ function folderBytes(dir) {
6717
6800
  const walk = (d) => {
6718
6801
  let entries;
6719
6802
  try {
6720
- entries = fs22.readdirSync(d, { withFileTypes: true });
6803
+ entries = fs23.readdirSync(d, { withFileTypes: true });
6721
6804
  } catch {
6722
6805
  return;
6723
6806
  }
6724
6807
  for (const e of entries) {
6725
- const f = path22.join(d, e.name);
6808
+ const f = path23.join(d, e.name);
6726
6809
  if (e.isDirectory()) walk(f);
6727
6810
  else if (e.isFile()) {
6728
6811
  try {
6729
- total += fs22.statSync(f).size;
6812
+ total += fs23.statSync(f).size;
6730
6813
  } catch {
6731
6814
  }
6732
6815
  }
@@ -6754,9 +6837,68 @@ async function detachSelf(routerUrl, credential, opts, fetchFn = fetch) {
6754
6837
  }
6755
6838
 
6756
6839
  // src/uninstall.ts
6757
- import fs23 from "node:fs";
6758
- import os7 from "node:os";
6759
- import path23 from "node:path";
6840
+ import fs25 from "node:fs";
6841
+ import os9 from "node:os";
6842
+ import path25 from "node:path";
6843
+
6844
+ // src/shell-profile.ts
6845
+ import fs24 from "node:fs";
6846
+ import os8 from "node:os";
6847
+ import path24 from "node:path";
6848
+ var PROFILE_MARK = "# added by monoclaw: the monoclaw command";
6849
+ function profileTarget(binDir, shell = process.env.SHELL, platform = process.platform, home = os8.homedir()) {
6850
+ const name = path24.basename(shell ?? "").toLowerCase();
6851
+ const shown = binDir.startsWith(home + path24.sep) || binDir === home ? `$HOME${binDir.slice(home.length)}` : binDir;
6852
+ if (name === "fish") return { shell: "fish", file: path24.join(home, ".config", "fish", "conf.d", "monoclaw.fish"), line: `fish_add_path "${shown}" ${PROFILE_MARK}` };
6853
+ const line = `export PATH="${shown}:$PATH" ${PROFILE_MARK}`;
6854
+ if (name === "zsh") return { shell: "zsh", file: path24.join(home, ".zshrc"), line };
6855
+ if (name === "bash") return { shell: "bash", file: path24.join(home, platform === "darwin" ? ".bash_profile" : ".bashrc"), line };
6856
+ return { shell: name || "unknown", file: path24.join(home, ".profile"), line };
6857
+ }
6858
+ function windowsPathNote(binDir) {
6859
+ return `To use the monoclaw command in new terminals, add this folder to your PATH: ${binDir}
6860
+ Settings \u2192 System \u2192 About \u2192 Advanced system settings \u2192 Environment Variables \u2192 Path (your user's), or in PowerShell:
6861
+ [Environment]::SetEnvironmentVariable("Path", "$env:Path;${binDir}", "User")`;
6862
+ }
6863
+ var exportForNow = (binDir) => `export PATH="${binDir}:$PATH"`;
6864
+ function addProfileLine(t) {
6865
+ const have = fs24.existsSync(t.file) ? fs24.readFileSync(t.file, "utf8") : null;
6866
+ if (have !== null && have.split(/\r?\n/).some((l) => l.trim() === t.line)) return false;
6867
+ fs24.mkdirSync(path24.dirname(t.file), { recursive: true });
6868
+ const sep = have === null || have === "" || have.endsWith("\n") ? "" : "\n";
6869
+ fs24.appendFileSync(t.file, `${sep}${t.line}
6870
+ `);
6871
+ return true;
6872
+ }
6873
+ function removeProfileLine(t) {
6874
+ if (!fs24.existsSync(t.file)) return false;
6875
+ const lines = fs24.readFileSync(t.file, "utf8").split("\n");
6876
+ const kept = lines.filter((l) => l.trim() !== t.line);
6877
+ if (kept.length === lines.length) return false;
6878
+ fs24.writeFileSync(t.file, kept.join("\n"));
6879
+ return true;
6880
+ }
6881
+
6882
+ // src/uninstall.ts
6883
+ var PACKAGE_NAME = "@monoclaw/machine";
6884
+ var PREFIX_ENTRIES = /* @__PURE__ */ new Set(["lib", "bin", "share", "etc", "include"]);
6885
+ var PREFIX_ENTRIES_WIN = /* @__PURE__ */ new Set(["node_modules", "monoclaw", "monoclaw.cmd", "monoclaw.ps1", "etc"]);
6886
+ function canRemoveOwnFolder(dir, platform = process.platform, home = os9.homedir(), readdir = (d) => fs25.readdirSync(d)) {
6887
+ const pth = platform === "win32" ? path25.win32 : path25.posix;
6888
+ const d = pth.resolve(dir);
6889
+ const h = pth.resolve(home);
6890
+ if (pth.parse(d).root === d) return { ok: false, why: "it is a filesystem root" };
6891
+ if (d === h || h.startsWith(d.endsWith(pth.sep) ? d : d + pth.sep)) return { ok: false, why: "it is your home folder, or holds it" };
6892
+ let entries;
6893
+ try {
6894
+ entries = readdir(d);
6895
+ } catch {
6896
+ return { ok: false, why: "it could not be read" };
6897
+ }
6898
+ const allowed = platform === "win32" ? PREFIX_ENTRIES_WIN : PREFIX_ENTRIES;
6899
+ if (entries.some((e) => !allowed.has(e))) return { ok: false, why: "it holds things the program did not put there" };
6900
+ return { ok: true, why: null };
6901
+ }
6760
6902
  var ITEM_ORDER = ["disconnect", "service", "models", "modules", "keys", "config", "files", "program"];
6761
6903
  var mb = (b) => b >= 1024 * 1024 ? `${Math.round(b / 1024 / 1024)} MB` : b >= 1024 ? `${Math.round(b / 1024)} kB` : `${b} B`;
6762
6904
  var modelName = (bundle) => /kokoro/i.test(bundle) ? "Kokoro" : /parakeet/i.test(bundle) ? "Parakeet" : bundle;
@@ -6771,9 +6913,9 @@ async function planUninstall(deps) {
6771
6913
  const a = await deps.affected(p.config).catch(() => ({ agents: [], known: false }));
6772
6914
  attachments.push({ att: att2, cfg: p.config, agents: a.agents, known: a.known });
6773
6915
  }
6774
- const modelsDir = path23.join(shared, "voice-models");
6775
- const models = fs23.existsSync(modelsDir) ? fs23.readdirSync(modelsDir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => ({ bundle: e.name, bytes: folderBytes(path23.join(modelsDir, e.name)) })) : [];
6776
- const modulesDir = path23.join(shared, "modules");
6916
+ const modelsDir = path25.join(shared, "voice-models");
6917
+ const models = fs25.existsSync(modelsDir) ? fs25.readdirSync(modelsDir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => ({ bundle: e.name, bytes: folderBytes(path25.join(modelsDir, e.name)) })) : [];
6918
+ const modulesDir = path25.join(shared, "modules");
6777
6919
  const modulesBytes = folderBytes(modulesDir);
6778
6920
  const byCwd = /* @__PURE__ */ new Map();
6779
6921
  for (const a of attachments) {
@@ -6782,8 +6924,8 @@ async function planUninstall(deps) {
6782
6924
  e.attachments.push(a.att.profile);
6783
6925
  for (const f of r.files) {
6784
6926
  try {
6785
- const st = fs23.statSync(f.path);
6786
- if (st.isFile() && st.size === f.bytes && path23.dirname(f.path).startsWith(cwd)) e.files.set(f.path, f.bytes);
6927
+ const st = fs25.statSync(f.path);
6928
+ if (st.isFile() && st.size === f.bytes && path25.dirname(f.path).startsWith(cwd)) e.files.set(f.path, f.bytes);
6787
6929
  } catch {
6788
6930
  }
6789
6931
  }
@@ -6797,8 +6939,9 @@ async function planUninstall(deps) {
6797
6939
  if (files.length || e.createdDirs.size) folders.push({ cwd, attachments: e.attachments, bytes: files.reduce((n, f) => n + f.bytes, 0), files, createdDirs: [...e.createdDirs] });
6798
6940
  }
6799
6941
  const keyCount = attachments.reduce((n, a) => n + a.cfg.providerAccounts.filter((c) => c.type === "api_key").length, 0);
6942
+ const copies = installedCopies(deps.npmPrefix, deps.program?.dir ?? programDir(), deps.platform).filter((c) => !c.own || c.prefix === deps.program?.dir);
6800
6943
  const platform = deps.platform ?? process.platform;
6801
- const units = [null, ...attachments.map((a) => a.att.profile).filter((p) => !!p)].map((p) => profileUnitFile(p, platform, deps.home)).filter((f) => !!f && fs23.existsSync(f));
6944
+ const units = [null, ...attachments.map((a) => a.att.profile).filter((p) => !!p)].map((p) => profileUnitFile(p, platform, deps.home)).filter((f) => !!f && fs25.existsSync(f));
6802
6945
  const serviceThere = platform === "win32" || units.length > 0;
6803
6946
  const configBytes = folderBytes(base) - folderBytes(modelsDir) - modulesBytes;
6804
6947
  const items = [
@@ -6810,10 +6953,10 @@ async function planUninstall(deps) {
6810
6953
  present: attachments.length > 0
6811
6954
  },
6812
6955
  { key: "service", title: "Remove the background service", lines: serviceThere ? [platform === "win32" ? "The scheduled task (not checked on Windows)" : `${units.length === 1 ? "The one service" : `${units.length} units: the one service and old per-profile ones`}: ${units.join(", ")}`] : [], bytes: null, present: serviceThere },
6813
- { key: "models", title: "Remove downloaded models", lines: models.map((m) => `${modelName(m.bundle)} (${mb(m.bytes)}) in ${path23.join(modelsDir, m.bundle)}`), bytes: models.reduce((n, m) => n + m.bytes, 0), present: models.length > 0 },
6956
+ { key: "models", title: "Remove downloaded models", lines: models.map((m) => `${modelName(m.bundle)} (${mb(m.bytes)}) in ${path25.join(modelsDir, m.bundle)}`), bytes: models.reduce((n, m) => n + m.bytes, 0), present: models.length > 0 },
6814
6957
  { key: "modules", title: "Remove the modules' own files and settings", lines: [...modulesBytes > 0 ? [`${modulesDir} (${mb(modulesBytes)}: the speech library)`] : [], ...attachments.filter((a) => a.cfg.modules.length).map((a) => `${who(a.cfg, a.att)}: ${a.cfg.modules.map((m) => m.id).join(", ")}`)], bytes: modulesBytes, present: modulesBytes > 0 || attachments.some((a) => a.cfg.modules.length > 0) },
6815
6958
  { key: "keys", title: "Remove the keys kept on this computer", lines: attachments.flatMap((a) => a.cfg.providerAccounts.filter((c) => c.type === "api_key").map((c) => `${who(a.cfg, a.att)}: ${c.name} [${c.module}] (from the keychain or the secrets file)`)), bytes: null, present: keyCount > 0 },
6816
- { key: "config", title: "Remove the program's configuration, logs and usage records", lines: [`${base} (${mb(Math.max(0, configBytes))}): configs, logs, usage records, the computer's record${attachments.length > 1 ? `, ${attachments.length} attachment folders` : ""}`], bytes: Math.max(0, configBytes), present: fs23.existsSync(base) },
6959
+ { key: "config", title: "Remove the program's configuration, logs and usage records", lines: [`${base} (${mb(Math.max(0, configBytes))}): configs, logs, usage records, the computer's record${attachments.length > 1 ? `, ${attachments.length} attachment folders` : ""}`], bytes: Math.max(0, configBytes), present: fs25.existsSync(base) },
6817
6960
  {
6818
6961
  key: "files",
6819
6962
  title: "Remove the files agents' tools saved (under images/, audio/ and files/ in each agent's folder)",
@@ -6824,14 +6967,25 @@ async function planUninstall(deps) {
6824
6967
  bytes: folders.reduce((n, f) => n + f.bytes, 0),
6825
6968
  present: folders.some((f) => f.files.length > 0)
6826
6969
  },
6827
- { key: "program", title: "Remove the program itself (npm uninstall -g @monoclaw/machine)", lines: [deps.installedWithNpm ? "Last, after everything else" : "Not installed with npm: remove it the way it was installed"], bytes: null, present: deps.installedWithNpm }
6970
+ {
6971
+ key: "program",
6972
+ title: "Remove the program itself (npm uninstall -g @monoclaw/machine)",
6973
+ lines: copies.length ? copies.map((c) => {
6974
+ if (!c.own) return `${c.version} in ${c.prefix}`;
6975
+ const whole = canRemoveOwnFolder(c.prefix, deps.platform, deps.home);
6976
+ const line = deps.program?.profileLine ? `; the one line in ${deps.program.profileLine.file} goes too` : "";
6977
+ return `${c.version} in ${c.prefix} (its own folder, made by the program: ${whole.ok ? "removed with the folder" : `the folder is left, ${whole.why}`}${line})`;
6978
+ }) : [deps.installedWithNpm ? "Last, after everything else" : "Not installed with npm: remove it the way it was installed"],
6979
+ bytes: null,
6980
+ present: copies.length > 0 || deps.installedWithNpm
6981
+ }
6828
6982
  ];
6829
6983
  const untouched = [
6830
6984
  "The folders agents work in and everything in them that the program did not write itself: never touched. A folder goes only if the program made it and it is empty after.",
6831
6985
  "Files saved before 1.1.0 are not known and are left; so is every folder the program never opened a session in.",
6832
- `Claude's own login and session history (${path23.join(deps.home ?? os7.homedir(), ".claude")}): not ours to delete; \`claude auth logout\` signs out.`
6986
+ `Claude's own login and session history (${path25.join(deps.home ?? os9.homedir(), ".claude")}): not ours to delete; \`claude auth logout\` signs out.`
6833
6987
  ];
6834
- return { items, untouched, attachments, folders, models };
6988
+ return { items, untouched, attachments, folders, models, copies, program: deps.program };
6835
6989
  }
6836
6990
  async function runUninstall(plan, chosen, deps, say = () => {
6837
6991
  }) {
@@ -6854,27 +7008,27 @@ async function runUninstall(plan, chosen, deps, say = () => {
6854
7008
  for (const a of plan.attachments) {
6855
7009
  if (a.known) await deps.detach(a.cfg);
6856
7010
  await deps.dropFromProgram(a.att.profile);
6857
- fs23.rmSync(path23.join(a.att.dir, "config.json"), { force: true });
7011
+ fs25.rmSync(path25.join(a.att.dir, "config.json"), { force: true });
6858
7012
  removed.push(`the enrolment for ${who(a.cfg, a.att)}`);
6859
7013
  }
6860
7014
  return removed;
6861
7015
  });
6862
7016
  await step("service", async () => deps.removeServices());
6863
7017
  await step("models", async () => {
6864
- const dir = path23.join(shared, "voice-models");
6865
- fs23.rmSync(dir, { recursive: true, force: true });
7018
+ const dir = path25.join(shared, "voice-models");
7019
+ fs25.rmSync(dir, { recursive: true, force: true });
6866
7020
  return plan.models.map((m) => `${modelName(m.bundle)} (${mb(m.bytes)})`);
6867
7021
  });
6868
7022
  await step("modules", async () => {
6869
- fs23.rmSync(path23.join(shared, "modules"), { recursive: true, force: true });
6870
- const removed = [`${path23.join(shared, "modules")}`];
7023
+ fs25.rmSync(path25.join(shared, "modules"), { recursive: true, force: true });
7024
+ const removed = [`${path25.join(shared, "modules")}`];
6871
7025
  for (const a of plan.attachments) {
6872
- const f = path23.join(a.att.dir, "config.json");
6873
- if (!fs23.existsSync(f)) continue;
6874
- const raw = JSON.parse(fs23.readFileSync(f, "utf8"));
7026
+ const f = path25.join(a.att.dir, "config.json");
7027
+ if (!fs25.existsSync(f)) continue;
7028
+ const raw = JSON.parse(fs25.readFileSync(f, "utf8"));
6875
7029
  if (Array.isArray(raw.modules) && raw.modules.length) {
6876
7030
  raw.modules = [];
6877
- fs23.writeFileSync(f, `${JSON.stringify(raw, null, 2)}
7031
+ fs25.writeFileSync(f, `${JSON.stringify(raw, null, 2)}
6878
7032
  `, { mode: 384 });
6879
7033
  removed.push(`the module settings of ${who(a.cfg, a.att)}`);
6880
7034
  }
@@ -6888,7 +7042,7 @@ async function runUninstall(plan, chosen, deps, say = () => {
6888
7042
  await deps.deleteSecret(a.att, c.id);
6889
7043
  removed.push(`the key of ${c.name} (${who(a.cfg, a.att)})`);
6890
7044
  }
6891
- fs23.rmSync(path23.join(a.att.dir, "secrets.json"), { force: true });
7045
+ fs25.rmSync(path25.join(a.att.dir, "secrets.json"), { force: true });
6892
7046
  }
6893
7047
  return removed;
6894
7048
  });
@@ -6897,19 +7051,19 @@ async function runUninstall(plan, chosen, deps, say = () => {
6897
7051
  for (const f of plan.folders) {
6898
7052
  for (const file of f.files) {
6899
7053
  try {
6900
- if (fs23.statSync(file.path).size !== file.bytes) continue;
7054
+ if (fs25.statSync(file.path).size !== file.bytes) continue;
6901
7055
  } catch {
6902
7056
  continue;
6903
7057
  }
6904
- fs23.rmSync(file.path, { force: true });
7058
+ fs25.rmSync(file.path, { force: true });
6905
7059
  removed.push(`${file.path} (${mb(file.bytes)})`);
6906
7060
  }
6907
7061
  for (const d of f.createdDirs) {
6908
- const dir = path23.join(f.cwd, d);
7062
+ const dir = path25.join(f.cwd, d);
6909
7063
  try {
6910
- if (fs23.existsSync(dir) && fs23.readdirSync(dir).length === 0) {
6911
- fs23.rmdirSync(dir);
6912
- removed.push(`${dir}${path23.sep} (made by the program, empty)`);
7064
+ if (fs25.existsSync(dir) && fs25.readdirSync(dir).length === 0) {
7065
+ fs25.rmdirSync(dir);
7066
+ removed.push(`${dir}${path25.sep} (made by the program, empty)`);
6913
7067
  }
6914
7068
  } catch {
6915
7069
  }
@@ -6920,22 +7074,40 @@ async function runUninstall(plan, chosen, deps, say = () => {
6920
7074
  await step("config", async () => {
6921
7075
  const keep = /* @__PURE__ */ new Set([...chosen.has("models") ? [] : ["voice-models"], ...chosen.has("modules") ? [] : ["modules"]]);
6922
7076
  const removed = [];
6923
- if (fs23.existsSync(base)) {
6924
- for (const e of fs23.readdirSync(base)) {
7077
+ if (fs25.existsSync(base)) {
7078
+ for (const e of fs25.readdirSync(base)) {
6925
7079
  if (keep.has(e)) continue;
6926
- fs23.rmSync(path23.join(base, e), { recursive: true, force: true });
6927
- removed.push(path23.join(base, e));
7080
+ fs25.rmSync(path25.join(base, e), { recursive: true, force: true });
7081
+ removed.push(path25.join(base, e));
6928
7082
  }
6929
- if (!fs23.readdirSync(base).length) fs23.rmSync(base, { recursive: true, force: true });
7083
+ if (!fs25.readdirSync(base).length) fs25.rmSync(base, { recursive: true, force: true });
6930
7084
  }
6931
7085
  if (shared !== base) {
6932
- for (const e of fs23.existsSync(shared) ? fs23.readdirSync(shared) : []) if (!keep.has(e) && e !== "voice-models" && e !== "modules") removed.push(path23.join(shared, e));
7086
+ for (const e of fs25.existsSync(shared) ? fs25.readdirSync(shared) : []) if (!keep.has(e) && e !== "voice-models" && e !== "modules") removed.push(path25.join(shared, e));
6933
7087
  }
6934
7088
  return removed;
6935
7089
  });
6936
7090
  await step("program", async () => {
6937
- await deps.npmUninstall();
6938
- return ["@monoclaw/machine (npm)"];
7091
+ const removed = [];
7092
+ for (const c of plan.copies) {
7093
+ await deps.npmUninstall(c.prefix);
7094
+ removed.push(`${PACKAGE_NAME} ${c.version} in ${c.prefix}`);
7095
+ if (c.own && plan.program && c.prefix === plan.program.dir) {
7096
+ const whole = canRemoveOwnFolder(plan.program.dir, deps.platform, deps.home);
7097
+ if (whole.ok) {
7098
+ fs25.rmSync(plan.program.dir, { recursive: true, force: true });
7099
+ removed.push(plan.program.dir);
7100
+ const parent = path25.dirname(plan.program.dir);
7101
+ if (path25.basename(parent) === ".monoclaw" && fs25.existsSync(parent) && fs25.readdirSync(parent).length === 0) fs25.rmdirSync(parent);
7102
+ } else say(`left ${plan.program.dir}: ${whole.why}`);
7103
+ if (plan.program.profileLine && removeProfileLine(plan.program.profileLine)) removed.push(`the line in ${plan.program.profileLine.file}`);
7104
+ }
7105
+ }
7106
+ if (!plan.copies.length) {
7107
+ if (deps.npmPrefix) await deps.npmUninstall(deps.npmPrefix);
7108
+ removed.push(`${PACKAGE_NAME} (npm)`);
7109
+ }
7110
+ return removed;
6939
7111
  });
6940
7112
  return out;
6941
7113
  }
@@ -7036,22 +7208,19 @@ async function enrol(token, routerUrl, opts) {
7036
7208
  }
7037
7209
 
7038
7210
  // src/connect.ts
7039
- import { execFile as execFile5, spawn as spawn4 } from "node:child_process";
7040
- import fs25 from "node:fs";
7041
- import os8 from "node:os";
7042
- import path25 from "node:path";
7043
- import { promisify as promisify5 } from "node:util";
7211
+ import { spawn as spawn4 } from "node:child_process";
7212
+ import fs27 from "node:fs";
7213
+ import os10 from "node:os";
7214
+ import path27 from "node:path";
7044
7215
 
7045
7216
  // src/update.ts
7046
7217
  import { spawn as spawn3 } from "node:child_process";
7047
- import fs24 from "node:fs";
7048
- import path24 from "node:path";
7218
+ import fs26 from "node:fs";
7219
+ import path26 from "node:path";
7049
7220
  import { z as z12 } from "zod";
7050
7221
  var PACKAGE = "@monoclaw/machine";
7051
- function nodeInstallHint(platform) {
7052
- if (platform === "darwin") return "Install Node 22 or newer: `brew install node`, or the LTS installer from https://nodejs.org";
7053
- if (platform === "win32") return "Install Node 22 or newer: `winget install OpenJS.NodeJS.LTS`, or the LTS installer from https://nodejs.org";
7054
- return "Install Node 22 or newer with nvm (no sudo): https://github.com/nvm-sh/nvm#installing-and-updating then `nvm install 22`";
7222
+ function nodeInstallHint(_platform) {
7223
+ return "Install Node.js 22 or newer from https://nodejs.org/en/download, then open a new terminal";
7055
7224
  }
7056
7225
  var CHECK_EVERY_MS = 6 * 60 * 6e4;
7057
7226
  var RETRY_WHEN_BUSY_MS = 10 * 6e4;
@@ -7069,7 +7238,7 @@ var VersionPolicy = z12.object({ package: z12.string(), latest: z12.string().nul
7069
7238
  function detectInstallMode(entry = process.argv[1] ?? "") {
7070
7239
  let real = entry;
7071
7240
  try {
7072
- real = fs24.realpathSync(entry);
7241
+ real = fs26.realpathSync(entry);
7073
7242
  } catch {
7074
7243
  }
7075
7244
  const p = real.replace(/\\/g, "/");
@@ -7080,13 +7249,13 @@ function detectInstallMode(entry = process.argv[1] ?? "") {
7080
7249
  function installedVersion(entry = process.argv[1] ?? "") {
7081
7250
  let real = entry;
7082
7251
  try {
7083
- real = fs24.realpathSync(entry);
7252
+ real = fs26.realpathSync(entry);
7084
7253
  } catch {
7085
7254
  }
7086
7255
  const m = /^(.*[\\/]node_modules[\\/]@monoclaw[\\/]machine)[\\/]/.exec(real);
7087
7256
  if (!m) return null;
7088
7257
  try {
7089
- return JSON.parse(fs24.readFileSync(path24.join(m[1], "package.json"), "utf8")).version ?? null;
7258
+ return JSON.parse(fs26.readFileSync(path26.join(m[1], "package.json"), "utf8")).version ?? null;
7090
7259
  } catch {
7091
7260
  return null;
7092
7261
  }
@@ -7094,23 +7263,23 @@ function installedVersion(entry = process.argv[1] ?? "") {
7094
7263
  var LOCK_STALE_MS = 15 * 6e4;
7095
7264
  async function withUpdateLock(fn, opts = {}) {
7096
7265
  const dir = opts.dir ?? sharedDir();
7097
- fs24.mkdirSync(dir, { recursive: true });
7098
- const file = path24.join(dir, "update.lock");
7266
+ fs26.mkdirSync(dir, { recursive: true });
7267
+ const file = path26.join(dir, "update.lock");
7099
7268
  const deadline = Date.now() + (opts.waitMs ?? INSTALL_TIMEOUT_MS);
7100
7269
  for (; ; ) {
7101
7270
  try {
7102
- fs24.writeFileSync(file, JSON.stringify({ pid: process.pid, at: (/* @__PURE__ */ new Date()).toISOString() }), { flag: "wx" });
7271
+ fs26.writeFileSync(file, JSON.stringify({ pid: process.pid, at: (/* @__PURE__ */ new Date()).toISOString() }), { flag: "wx" });
7103
7272
  break;
7104
7273
  } catch (e) {
7105
7274
  if (e.code !== "EEXIST") throw e;
7106
7275
  let stale = false;
7107
7276
  try {
7108
- stale = Date.now() - fs24.statSync(file).mtimeMs > LOCK_STALE_MS;
7277
+ stale = Date.now() - fs26.statSync(file).mtimeMs > LOCK_STALE_MS;
7109
7278
  } catch {
7110
7279
  continue;
7111
7280
  }
7112
7281
  if (stale) {
7113
- fs24.rmSync(file, { force: true });
7282
+ fs26.rmSync(file, { force: true });
7114
7283
  continue;
7115
7284
  }
7116
7285
  if (Date.now() > deadline) throw new Error("another MonoClaw host on this computer has been updating for too long; try again later");
@@ -7120,7 +7289,7 @@ async function withUpdateLock(fn, opts = {}) {
7120
7289
  try {
7121
7290
  return await fn();
7122
7291
  } finally {
7123
- fs24.rmSync(file, { force: true });
7292
+ fs26.rmSync(file, { force: true });
7124
7293
  }
7125
7294
  }
7126
7295
  function decideUpdate(current, policy, mode, opts) {
@@ -7166,13 +7335,13 @@ function installVersion(version, source = PACKAGE, routerUrl = "") {
7166
7335
  if (!spec) return Promise.reject(new Error(`refusing to install ${version} from "${source}"`));
7167
7336
  return npmInstallGlobal(spec);
7168
7337
  }
7169
- var npmInstallArgs2 = (spec) => ["install", "-g", spec, "--ignore-scripts", "--no-fund", "--no-audit", "--loglevel=error"];
7170
- function npmInstallGlobal(spec) {
7338
+ var npmInstallArgs2 = (spec, prefix) => ["install", "-g", ...prefix ? ["--prefix", prefix] : [], spec, "--ignore-scripts", "--no-fund", "--no-audit", "--loglevel=error"];
7339
+ function npmInstallGlobal(spec, prefix = ownPrefix()) {
7171
7340
  if (!/^@?[\w./-]+@[\w.-]+$/.test(spec) && !/^https?:\/\/[\w.:-]+\/downloads\/host\/monoclaw-machine-[\w.-]+\.tgz$/.test(spec)) return Promise.reject(new Error(`refusing to install "${spec}"`));
7172
- return runNpm(npmInstallArgs2(spec), "npm install");
7341
+ return runNpm(npmInstallArgs2(spec, prefix), "npm install");
7173
7342
  }
7174
- function npmUninstallGlobal(pkg = PACKAGE) {
7175
- return runNpm(["uninstall", "-g", pkg, "--no-fund", "--no-audit", "--loglevel=error"], "npm uninstall");
7343
+ function npmUninstallGlobal(pkg = PACKAGE, prefix = ownPrefix()) {
7344
+ return runNpm(["uninstall", "-g", ...prefix ? ["--prefix", prefix] : [], pkg, "--no-fund", "--no-audit", "--loglevel=error"], "npm uninstall");
7176
7345
  }
7177
7346
  function runNpm(args2, what) {
7178
7347
  const npm = process.platform === "win32" ? "npm.cmd" : "npm";
@@ -7207,7 +7376,7 @@ function settleReexec(env = process.env, running = APP_VERSION) {
7207
7376
  }
7208
7377
  function reexec() {
7209
7378
  const hops = Number(process.env[REEXEC_ENV] ?? "0");
7210
- if (hops >= 2) return Promise.reject(new Error(`updated twice but still running ${APP_VERSION}; check that \`npm prefix -g\` is the install this service runs from`));
7379
+ if (hops >= 2) return Promise.reject(new Error(`updated twice but still running ${APP_VERSION}; the update went to ${ownPrefix() ?? "npm's prefix"} but this service runs ${process.argv[1] ?? "another copy"}`));
7211
7380
  return new Promise(() => {
7212
7381
  const child = spawn3(process.execPath, process.argv.slice(1), { stdio: "inherit", env: { ...process.env, [REEXEC_ENV]: String(hops + 1), [REEXEC_FROM_ENV]: APP_VERSION } });
7213
7382
  child.on("exit", (code, signal) => process.exit(code ?? (signal ? 1 : 0)));
@@ -7338,24 +7507,19 @@ var DEFAULT_ROUTER = "https://command.monoclaw.ai";
7338
7507
  function ranFromNpx(entry = process.argv[1] ?? "") {
7339
7508
  let real = entry;
7340
7509
  try {
7341
- real = fs25.realpathSync(entry);
7510
+ real = fs27.realpathSync(entry);
7342
7511
  } catch {
7343
7512
  }
7344
7513
  return /[\\/]_npx[\\/]/.test(real);
7345
7514
  }
7346
- function globalInstall(prefix, platform = process.platform) {
7347
- const p = platform === "win32" ? path25.win32 : path25.posix;
7348
- const modules2 = platform === "win32" ? p.join(prefix, "node_modules") : p.join(prefix, "lib", "node_modules");
7349
- return { script: p.join(modules2, "@monoclaw", "machine", "bin", "monoclaw.js"), binDir: platform === "win32" ? prefix : p.join(prefix, "bin") };
7350
- }
7351
7515
  function shouldInstall(installed, mine, from) {
7352
7516
  if (from) return { install: true, why: null };
7353
7517
  if (installed && compareVersions(installed, mine) >= 0) return { install: false, why: compareVersions(installed, mine) > 0 ? `${PACKAGE} ${installed} is already installed on this computer, newer than this command's ${mine}; using it as it is` : `${PACKAGE} ${installed} is already installed on this computer; using it as it is` };
7354
7518
  return { install: true, why: null };
7355
7519
  }
7356
- function enrolArgs(o, hasEnrolment, home = os8.homedir()) {
7520
+ function enrolArgs(o, hasEnrolment, home = os10.homedir()) {
7357
7521
  const args2 = [...o.profile ? ["--profile", o.profile] : [], "enrol", o.token, "--router", o.router];
7358
- const roots2 = o.root?.length ? o.root : hasEnrolment ? [] : [path25.join(home, "command")];
7522
+ const roots2 = o.root?.length ? o.root : hasEnrolment ? [] : [path27.join(home, "command")];
7359
7523
  if (roots2.length) args2.push("--root", ...roots2);
7360
7524
  if (o.name) args2.push("--name", o.name);
7361
7525
  if (o.insecure) args2.push("--insecure");
@@ -7364,23 +7528,20 @@ function enrolArgs(o, hasEnrolment, home = os8.homedir()) {
7364
7528
  var profileArgs = (profile) => profile ? ["--profile", profile] : [];
7365
7529
  function enrolOutcome(file = connectResultPath()) {
7366
7530
  try {
7367
- const r = JSON.parse(fs25.readFileSync(file, "utf8"));
7531
+ const r = JSON.parse(fs27.readFileSync(file, "utf8"));
7368
7532
  return { profile: typeof r.profile === "string" && r.profile ? r.profile : null, attached: r.attached === true };
7369
7533
  } catch {
7370
7534
  return { profile: null, attached: false };
7371
7535
  } finally {
7372
- fs25.rmSync(file, { force: true });
7536
+ fs27.rmSync(file, { force: true });
7373
7537
  }
7374
7538
  }
7375
- function installFailure(message) {
7376
- if (/EACCES|permission denied/i.test(message)) return "npm isn't allowed to install here (permission denied). Don't use sudo: install Node with Homebrew or nvm, which keep it in your own folders, then run this again.";
7377
- return `npm could not install ${PACKAGE}: ${message.trim().split("\n").slice(-3).join(" ").slice(0, 300)}`;
7378
- }
7379
- async function npmPrefix() {
7380
- const npm = process.platform === "win32" ? "npm.cmd" : "npm";
7381
- const { stdout } = await promisify5(execFile5)(npm, ["prefix", "-g"], { shell: process.platform === "win32", timeout: 3e4 });
7382
- return stdout.trim();
7539
+ function installFailure(message, where = "") {
7540
+ const tail = message.trim().split("\n").slice(-3).join(" ").slice(0, 300);
7541
+ if (/EACCES|permission denied/i.test(message)) return `npm isn't allowed to write to ${where || "that folder"} (permission denied). Don't use sudo. ${tail}`;
7542
+ return `npm could not install ${PACKAGE}${where ? ` into ${where}` : ""}: ${tail}`;
7383
7543
  }
7544
+ var isPermissionDenied = (message) => /EACCES|EPERM|permission denied/i.test(message);
7384
7545
  function run2(node, script, args2) {
7385
7546
  return new Promise((resolve) => {
7386
7547
  const child = spawn4(node, [script, ...args2], { stdio: "inherit", env: { ...process.env, MONOCLAW_CONNECT: "1" } });
@@ -7388,57 +7549,105 @@ function run2(node, script, args2) {
7388
7549
  child.on("exit", (code) => resolve(code ?? 1));
7389
7550
  });
7390
7551
  }
7391
- async function connect(o, out = { say: (s) => console.log(s), fail: (s) => console.error(s) }) {
7552
+ async function connect(o, out = { say: (s) => console.log(s), fail: (s) => console.error(s) }, deps = {}) {
7392
7553
  out.say("MonoClaw: connecting this computer");
7393
7554
  const node = process.execPath;
7394
7555
  let script = process.argv[1] ?? "";
7556
+ const runStep = deps.run ?? run2;
7557
+ const platform = deps.platform ?? process.platform;
7395
7558
  const lasting = detectInstallMode() === "npm-global" && !ranFromNpx();
7396
7559
  if (!lasting && detectInstallMode() !== "checkout") {
7397
- let prefix = null;
7398
- let have = null;
7560
+ const own = deps.programDir ?? programDir();
7561
+ let npmPrefix = null;
7399
7562
  try {
7400
- prefix = await npmPrefix();
7401
- have = installedVersion(globalInstall(prefix).script);
7563
+ npmPrefix = await (deps.npmPrefix ?? npmPrefixDefault)();
7402
7564
  } catch {
7403
7565
  }
7404
- const decision = shouldInstall(have, APP_VERSION, o.from);
7405
- if (decision.why) out.say(decision.why);
7406
- if (process.platform !== "win32" && (await askControl({ cmd: "ping" }, { timeoutMs: 1500 }))?.ok) out.say("A MonoClaw program is running on this computer; it will serve the new connection itself.");
7566
+ const copies = installedCopies(npmPrefix, own, platform);
7567
+ const newest = copies[0] ?? null;
7568
+ const decision = shouldInstall(newest?.version ?? null, APP_VERSION, o.from);
7569
+ if (decision.why) out.say(`${decision.why} (${newest.prefix})`);
7570
+ const running = deps.running ?? (async () => platform !== "win32" && !!(await askControl({ cmd: "ping" }, { timeoutMs: 1500 }))?.ok);
7571
+ if (await running()) out.say("A MonoClaw program is running on this computer; it will serve the new connection itself.");
7407
7572
  const spec = o.from ?? `${PACKAGE}@${APP_VERSION}`;
7573
+ let target = newest?.prefix ?? null;
7408
7574
  if (decision.install) {
7409
- out.say(`Installing ${spec} with npm...`);
7575
+ const writable = npmPrefix ? (deps.writable ?? ((p) => prefixWritable(p, platform)))(npmPrefix) : false;
7576
+ target = newest?.prefix ?? (writable && npmPrefix ? npmPrefix : own);
7577
+ if (target === own && !newest) out.say(`npm's folder (${npmPrefix ?? "unknown"}) is not writable by you, so MonoClaw goes into its own folder, ${own}. No sudo is needed, and npm's own settings are not changed.`);
7578
+ const installInto = async (prefix) => {
7579
+ out.say(`Installing ${spec} into ${prefix} (about a minute; npm says nothing while it works)\u2026`);
7580
+ const began = Date.now();
7581
+ const ticker = setInterval(() => out.say(` still installing (${Math.round((Date.now() - began) / 1e3)} s)\u2026`), deps.tickMs ?? 15e3);
7582
+ try {
7583
+ await (deps.install ?? npmInstallGlobal)(spec, prefix);
7584
+ } finally {
7585
+ clearInterval(ticker);
7586
+ }
7587
+ };
7410
7588
  try {
7411
- await npmInstallGlobal(spec);
7589
+ await installInto(target);
7412
7590
  } catch (e) {
7413
- out.fail(installFailure(e.message));
7414
- return 1;
7591
+ const msg = e.message;
7592
+ if (target !== own && isPermissionDenied(msg)) {
7593
+ out.say(`npm was not allowed to write to ${target} after all; installing into ${own} instead.`);
7594
+ target = own;
7595
+ try {
7596
+ await installInto(own);
7597
+ } catch (e2) {
7598
+ out.fail(installFailure(e2.message, own));
7599
+ return 1;
7600
+ }
7601
+ } else {
7602
+ out.fail(installFailure(msg, target));
7603
+ return 1;
7604
+ }
7605
+ }
7606
+ if (target === own) {
7607
+ const binDir = layout(own, platform).binDir;
7608
+ let profileLine = null;
7609
+ if (platform === "win32") out.say(windowsPathNote(binDir));
7610
+ else {
7611
+ const t = profileTarget(binDir, deps.shell, platform, deps.home);
7612
+ try {
7613
+ addProfileLine(t);
7614
+ profileLine = { file: t.file, line: t.line };
7615
+ out.say(`Added one line to ${t.file} so new terminals find the monoclaw command (${t.shell === "unknown" ? "your shell is not one MonoClaw knows, so it went to ~/.profile; move it if your shell reads another file" : `for ${t.shell}`}).`);
7616
+ } catch (e) {
7617
+ out.say(`Could not write ${t.file} (${e.message}); add this line to your shell's profile yourself:
7618
+ ${t.line}`);
7619
+ }
7620
+ out.say(`Open a new terminal to use the monoclaw command, or for this one run:
7621
+ ${exportForNow(binDir)}`);
7622
+ }
7623
+ (deps.record ?? recordProgram)({ dir: own, createdAt: (deps.now ?? (() => /* @__PURE__ */ new Date()))().toISOString(), profileLine });
7415
7624
  }
7416
7625
  }
7417
7626
  try {
7418
- const g = globalInstall(prefix ?? await npmPrefix());
7419
- if (!fs25.existsSync(g.script)) throw new Error(`${g.script} is missing`);
7627
+ const g = layout(target ?? npmPrefix ?? own, platform);
7628
+ if (!fs27.existsSync(g.script)) throw new Error(`${g.script} is missing`);
7420
7629
  script = g.script;
7421
- if (!(process.env.PATH ?? "").split(path25.delimiter).some((d) => path25.resolve(d) === path25.resolve(g.binDir))) out.say(`Note: ${g.binDir} is not on your PATH, so the monoclaw command won't be found until it is added.`);
7630
+ if (target !== own && !(process.env.PATH ?? "").split(path27.delimiter).some((d) => path27.resolve(d) === path27.resolve(g.binDir))) out.say(`Note: ${g.binDir} is not on your PATH, so the monoclaw command won't be found until it is added.`);
7422
7631
  } catch (e) {
7423
7632
  out.fail(`Installed, but the program could not be found afterwards (${e.message}). Run: npm install -g ${PACKAGE}`);
7424
7633
  return 1;
7425
7634
  }
7426
7635
  }
7427
7636
  const hasEnrolment = listProfiles().some((p) => p.config);
7428
- fs25.rmSync(connectResultPath(), { force: true });
7429
- if (await run2(node, script, enrolArgs(o, hasEnrolment)) !== 0) {
7637
+ fs27.rmSync(connectResultPath(), { force: true });
7638
+ if (await runStep(node, script, enrolArgs(o, hasEnrolment)) !== 0) {
7430
7639
  out.fail("This computer was not connected. If the token has run out, copy a new command from Add a machine.");
7431
7640
  return 1;
7432
7641
  }
7433
7642
  const outcome = enrolOutcome();
7434
7643
  const profile = profileArgs(o.profile ?? outcome.profile);
7435
7644
  if (outcome.attached) out.say("The program already running on this computer serves it from now.");
7436
- else if (o.service && await run2(node, script, ["service", "install"]) !== 0) {
7645
+ else if (o.service && await runStep(node, script, ["service", "install"]) !== 0) {
7437
7646
  out.fail(`The background service could not be installed here. To run it in this terminal instead: monoclaw start --foreground (it stops when the terminal closes)`);
7438
7647
  return 1;
7439
7648
  }
7440
7649
  out.say("");
7441
- await run2(node, script, [...profile, "doctor"]);
7650
+ await runStep(node, script, [...profile, "doctor"]);
7442
7651
  out.say("");
7443
7652
  out.say(o.service ? "Connected. Go back to MonoClaw in your browser: it has moved on by itself." : `Connected, not started (--no-service). To run it in this terminal: monoclaw start --foreground (it stops when the terminal closes)`);
7444
7653
  return 0;
@@ -7727,18 +7936,18 @@ var echoProvider = {
7727
7936
 
7728
7937
  // src/providers/claude/index.ts
7729
7938
  import { execFile as execFile7 } from "node:child_process";
7730
- import fs27 from "node:fs";
7731
- import os9 from "node:os";
7732
- import path27 from "node:path";
7939
+ import fs29 from "node:fs";
7940
+ import os11 from "node:os";
7941
+ import path29 from "node:path";
7733
7942
  import { promisify as promisify7 } from "node:util";
7734
7943
  import { z as z13 } from "zod";
7735
7944
  import { createSdkMcpServer, listSessions, query, tool } from "@anthropic-ai/claude-agent-sdk";
7736
7945
 
7737
7946
  // src/providers/claude/cli.ts
7738
7947
  import { execFile as execFile6 } from "node:child_process";
7739
- import fs26 from "node:fs";
7948
+ import fs28 from "node:fs";
7740
7949
  import { createRequire as createRequire3 } from "node:module";
7741
- import path26 from "node:path";
7950
+ import path28 from "node:path";
7742
7951
  import { promisify as promisify6 } from "node:util";
7743
7952
  var execFileP5 = promisify6(execFile6);
7744
7953
  var SDK = "@anthropic-ai/claude-agent-sdk";
@@ -7750,7 +7959,7 @@ function isMusl() {
7750
7959
  if (header && "glibcVersionRuntime" in header) return !header.glibcVersionRuntime;
7751
7960
  } catch {
7752
7961
  }
7753
- return fs26.existsSync("/etc/alpine-release");
7962
+ return fs28.existsSync("/etc/alpine-release");
7754
7963
  }
7755
7964
  function platformPackages(platform = process.platform, arch = process.arch, musl = isMusl()) {
7756
7965
  const base = `${SDK}-`;
@@ -7760,24 +7969,24 @@ function platformPackages(platform = process.platform, arch = process.arch, musl
7760
7969
  }
7761
7970
  var exe = (platform = process.platform) => platform === "win32" ? "claude.exe" : "claude";
7762
7971
  function sdkRoot() {
7763
- let dir = path26.dirname(createRequire3(import.meta.url).resolve(SDK));
7972
+ let dir = path28.dirname(createRequire3(import.meta.url).resolve(SDK));
7764
7973
  for (let i = 0; i < 6; i++) {
7765
- const pkg = path26.join(dir, "package.json");
7974
+ const pkg = path28.join(dir, "package.json");
7766
7975
  try {
7767
- if (JSON.parse(fs26.readFileSync(pkg, "utf8")).name === SDK) return dir;
7976
+ if (JSON.parse(fs28.readFileSync(pkg, "utf8")).name === SDK) return dir;
7768
7977
  } catch {
7769
7978
  }
7770
- dir = path26.dirname(dir);
7979
+ dir = path28.dirname(dir);
7771
7980
  }
7772
7981
  throw new Error(`could not find where ${SDK} is installed`);
7773
7982
  }
7774
7983
  function sdkResolve() {
7775
- return createRequire3(path26.join(sdkRoot(), "package.json")).resolve;
7984
+ return createRequire3(path28.join(sdkRoot(), "package.json")).resolve;
7776
7985
  }
7777
7986
  function sdkVersion() {
7778
- return JSON.parse(fs26.readFileSync(path26.join(sdkRoot(), "package.json"), "utf8")).version;
7987
+ return JSON.parse(fs28.readFileSync(path28.join(sdkRoot(), "package.json"), "utf8")).version;
7779
7988
  }
7780
- function bundledCli(resolve = sdkResolve(), exists = fs26.existsSync, platform = process.platform, arch = process.arch) {
7989
+ function bundledCli(resolve = sdkResolve(), exists = fs28.existsSync, platform = process.platform, arch = process.arch) {
7781
7990
  for (const pkg of platformPackages(platform, arch)) {
7782
7991
  try {
7783
7992
  const p = resolve(`${pkg}/${exe(platform)}`);
@@ -7816,7 +8025,7 @@ function resolveCli(deps = {}) {
7816
8025
  }
7817
8026
  async function resolveUncached(deps) {
7818
8027
  const env = deps.env ?? process.env;
7819
- const exists = deps.exists ?? fs26.existsSync;
8028
+ const exists = deps.exists ?? fs28.existsSync;
7820
8029
  const version = deps.version ?? ((f) => cliVersion(f, env));
7821
8030
  const override = env[CLI_PATH_ENV]?.trim();
7822
8031
  if (override) {
@@ -7865,7 +8074,7 @@ async function repairBundledCli(deps = {}) {
7865
8074
  forgetCli();
7866
8075
  const ok = bundled();
7867
8076
  if (!ok) {
7868
- const detail = `installed ${spec} but the program is still not found; check \`npm prefix -g\` matches the host's install`;
8077
+ const detail = `installed ${spec} but the program is still not found; it went to ${ownPrefix() ?? "npm's prefix"}, which should be where this program runs from`;
7869
8078
  log("warn", detail);
7870
8079
  return { outcome: "failed", detail };
7871
8080
  }
@@ -7933,18 +8142,18 @@ function backgroundTasksOf(tasks) {
7933
8142
  function startedByBackground(origin) {
7934
8143
  return origin?.kind === "task-notification" && !origin.subkind;
7935
8144
  }
7936
- var backgroundFile = (groupId, dir) => path27.join(dir, "background", `${groupId.replace(/[^\w.-]/g, "_")}.json`);
8145
+ var backgroundFile = (groupId, dir) => path29.join(dir, "background", `${groupId.replace(/[^\w.-]/g, "_")}.json`);
7937
8146
  function recordBackground(groupId, tasks, now = /* @__PURE__ */ new Date(), dir = baseDir()) {
7938
8147
  const file = backgroundFile(groupId, dir);
7939
8148
  try {
7940
- if (!tasks.length) return fs27.rmSync(file, { force: true });
7941
- fs27.mkdirSync(path27.dirname(file), { recursive: true, mode: 448 });
8149
+ if (!tasks.length) return fs29.rmSync(file, { force: true });
8150
+ fs29.mkdirSync(path29.dirname(file), { recursive: true, mode: 448 });
7942
8151
  let since = now.toISOString();
7943
8152
  try {
7944
- since = JSON.parse(fs27.readFileSync(file, "utf8")).since ?? since;
8153
+ since = JSON.parse(fs29.readFileSync(file, "utf8")).since ?? since;
7945
8154
  } catch {
7946
8155
  }
7947
- fs27.writeFileSync(file, JSON.stringify({ since, descriptions: tasks.map((t) => t.description) }), { mode: 384 });
8156
+ fs29.writeFileSync(file, JSON.stringify({ since, descriptions: tasks.map((t) => t.description) }), { mode: 384 });
7948
8157
  } catch {
7949
8158
  }
7950
8159
  }
@@ -7952,8 +8161,8 @@ function takeCutOffBackground(groupId, dir = baseDir()) {
7952
8161
  if (liveBackground.has(groupId)) return null;
7953
8162
  const file = backgroundFile(groupId, dir);
7954
8163
  try {
7955
- const o = JSON.parse(fs27.readFileSync(file, "utf8"));
7956
- fs27.rmSync(file, { force: true });
8164
+ const o = JSON.parse(fs29.readFileSync(file, "utf8"));
8165
+ fs29.rmSync(file, { force: true });
7957
8166
  return Array.isArray(o.descriptions) && o.descriptions.length ? { since: o.since ?? "", descriptions: o.descriptions.slice(0, 10) } : null;
7958
8167
  } catch {
7959
8168
  return null;
@@ -8076,9 +8285,9 @@ var ClaudeSession = class {
8076
8285
  async (args2) => {
8077
8286
  const full = sendablePath(this.opts.cwd, args2.path);
8078
8287
  if (!full) return { content: [{ type: "text", text: `Only files inside the working folder (${this.opts.cwd}), outside dot-folders, can be sent.` }], isError: true };
8079
- if (!fs27.existsSync(full) || !fs27.statSync(full).isFile()) return { content: [{ type: "text", text: `No file at ${full}` }], isError: true };
8080
- this.q.push({ kind: "file", path: full, name: path27.basename(full), mime: guessMime(full), caption: args2.caption });
8081
- return { content: [{ type: "text", text: `Sent ${path27.basename(full)} to the chat.` }] };
8288
+ if (!fs29.existsSync(full) || !fs29.statSync(full).isFile()) return { content: [{ type: "text", text: `No file at ${full}` }], isError: true };
8289
+ this.q.push({ kind: "file", path: full, name: path29.basename(full), mime: guessMime(full), caption: args2.caption });
8290
+ return { content: [{ type: "text", text: `Sent ${path29.basename(full)} to the chat.` }] };
8082
8291
  }
8083
8292
  )
8084
8293
  );
@@ -8313,7 +8522,7 @@ ${files.map((a) => `- ${a.localPath} (${a.mime}, ${a.size} bytes)${a.note ? `: $
8313
8522
  content.push({ type: "text", text: text2 });
8314
8523
  for (const a of files) {
8315
8524
  if (IMAGE_MIMES.has(a.mime) && a.size <= 5 * 1024 * 1024 && a.localPath) {
8316
- content.push({ type: "image", source: { type: "base64", media_type: a.mime, data: fs27.readFileSync(a.localPath).toString("base64") } });
8525
+ content.push({ type: "image", source: { type: "base64", media_type: a.mime, data: fs29.readFileSync(a.localPath).toString("base64") } });
8317
8526
  }
8318
8527
  }
8319
8528
  const user = { type: "user", message: { role: "user", content }, parent_tool_use_id: null, priority: msg.delivery, origin: { kind: "human" } };
@@ -8431,17 +8640,17 @@ function monoclawToolNames(s) {
8431
8640
  function sendablePath(cwd, p) {
8432
8641
  const real = (x) => {
8433
8642
  try {
8434
- return fs27.realpathSync(x);
8643
+ return fs29.realpathSync(x);
8435
8644
  } catch {
8436
8645
  return null;
8437
8646
  }
8438
8647
  };
8439
8648
  const root = real(cwd);
8440
- const full = real(path27.resolve(cwd, p));
8649
+ const full = real(path29.resolve(cwd, p));
8441
8650
  if (!root || !full) return null;
8442
- if (full !== root && !full.startsWith(root + path27.sep)) return null;
8443
- const rel = path27.relative(root, full);
8444
- if (rel.split(path27.sep).some((seg) => seg.startsWith(".") && seg !== ".")) return null;
8651
+ if (full !== root && !full.startsWith(root + path29.sep)) return null;
8652
+ const rel = path29.relative(root, full);
8653
+ if (rel.split(path29.sep).some((seg) => seg.startsWith(".") && seg !== ".")) return null;
8445
8654
  return full;
8446
8655
  }
8447
8656
  function safeJson(v) {
@@ -8460,30 +8669,30 @@ function friendlyPath(p, cwd) {
8460
8669
  if (file === base) return ".";
8461
8670
  if (file.startsWith(`${base}/`)) return file.slice(base.length + 1);
8462
8671
  }
8463
- const home = norm(os9.homedir());
8672
+ const home = norm(os11.homedir());
8464
8673
  if (home && file.startsWith(`${home}/`)) return `~/${file.slice(home.length + 1)}`;
8465
8674
  return file;
8466
8675
  }
8467
8676
  var clip = (s, n) => s.length > n ? `${s.slice(0, n - 1)}\u2026` : s;
8468
8677
  function describeTool(name, input, cwd) {
8469
8678
  const s = (k) => typeof input[k] === "string" ? input[k] : void 0;
8470
- const path29 = (k) => friendlyPath(s(k), cwd);
8679
+ const path31 = (k) => friendlyPath(s(k), cwd);
8471
8680
  const firstString = () => Object.values(input).find((v) => typeof v === "string" && v.trim().length > 0);
8472
8681
  switch (name) {
8473
8682
  case "Bash":
8474
8683
  return clip(s("description") ?? s("command") ?? "run a command", 120);
8475
8684
  case "Read":
8476
- return `Read ${path29("file_path") || path29("path")}`.trim();
8685
+ return `Read ${path31("file_path") || path31("path")}`.trim();
8477
8686
  case "Edit":
8478
8687
  case "Write":
8479
8688
  case "MultiEdit":
8480
- return `${name} ${path29("file_path")}`.trim();
8689
+ return `${name} ${path31("file_path")}`.trim();
8481
8690
  case "NotebookEdit":
8482
- return `Edit notebook ${path29("notebook_path")}`.trim();
8691
+ return `Edit notebook ${path31("notebook_path")}`.trim();
8483
8692
  case "Grep":
8484
- return `Grep "${clip(s("pattern") ?? "", 60)}"${s("path") ? ` in ${path29("path")}` : ""}`;
8693
+ return `Grep "${clip(s("pattern") ?? "", 60)}"${s("path") ? ` in ${path31("path")}` : ""}`;
8485
8694
  case "Glob":
8486
- return `Find ${clip(s("pattern") ?? "", 60)}${s("path") ? ` in ${path29("path")}` : ""}`;
8695
+ return `Find ${clip(s("pattern") ?? "", 60)}${s("path") ? ` in ${path31("path")}` : ""}`;
8487
8696
  case "WebSearch":
8488
8697
  return `Search "${clip(s("query") ?? "", 80)}"`;
8489
8698
  case "WebFetch": {
@@ -8539,8 +8748,8 @@ ${instructions}`);
8539
8748
  return parts.join("\n\n");
8540
8749
  }
8541
8750
  async function summarise(input) {
8542
- const dir = path27.join(sharedDir(), "summaries");
8543
- fs27.mkdirSync(dir, { recursive: true, mode: 448 });
8751
+ const dir = path29.join(sharedDir(), "summaries");
8752
+ fs29.mkdirSync(dir, { recursive: true, mode: 448 });
8544
8753
  const model = input.model?.trim() || process.env.MONOCLAW_SUMMARY_MODEL || DEFAULT_SUMMARY_MODEL;
8545
8754
  const abortController = new AbortController();
8546
8755
  const timer = setTimeout(() => abortController.abort(), SUMMARY_TIMEOUT_MS);
@@ -8597,8 +8806,8 @@ ${input.reply.slice(0, 24e3)}`);
8597
8806
  }
8598
8807
  var TEXT_TIMEOUT_MS = 45e3;
8599
8808
  async function text(input, env) {
8600
- const dir = path27.join(sharedDir(), "summaries");
8601
- fs27.mkdirSync(dir, { recursive: true, mode: 448 });
8809
+ const dir = path29.join(sharedDir(), "summaries");
8810
+ fs29.mkdirSync(dir, { recursive: true, mode: 448 });
8602
8811
  const model = input.model?.trim() || process.env.MONOCLAW_SUMMARY_MODEL || DEFAULT_SUMMARY_MODEL;
8603
8812
  const abortController = new AbortController();
8604
8813
  const timer = setTimeout(() => abortController.abort(), TEXT_TIMEOUT_MS);
@@ -8680,7 +8889,7 @@ var providers = only.length ? Object.fromEntries(Object.entries(all).filter(([id
8680
8889
 
8681
8890
  // src/cli.ts
8682
8891
  import { spawn as spawn5 } from "node:child_process";
8683
- import os10 from "node:os";
8892
+ import os12 from "node:os";
8684
8893
  async function readTokenFromStdin() {
8685
8894
  let data = "";
8686
8895
  for await (const chunk of process.stdin) data += chunk;
@@ -8719,9 +8928,9 @@ program.command("enrol [token]").description("Connect this machine to your MonoC
8719
8928
  }
8720
8929
  const profiles = listProfiles();
8721
8930
  const preview = await previewToken(opts.router, token, profiles.map((p) => p.config?.hostId ?? "").filter(Boolean), opts.insecure);
8722
- const plan = planEnrol(preview, profiles, opts.router, { requestedProfile: att.profile, defaultName: os10.hostname() });
8931
+ const plan = planEnrol(preview, profiles, opts.router, { requestedProfile: att.profile, defaultName: os12.hostname() });
8723
8932
  const report = (profile, attached2 = false) => {
8724
- if (process.env.MONOCLAW_CONNECT) fs28.writeFileSync(connectResultPath(), JSON.stringify({ profile, attached: attached2, at: (/* @__PURE__ */ new Date()).toISOString() }), { mode: 384 });
8933
+ if (process.env.MONOCLAW_CONNECT) fs30.writeFileSync(connectResultPath(), JSON.stringify({ profile, attached: attached2, at: (/* @__PURE__ */ new Date()).toISOString() }), { mode: 384 });
8725
8934
  };
8726
8935
  if (plan.action === "already") {
8727
8936
  console.log(plan.message);
@@ -8738,16 +8947,16 @@ program.command("enrol [token]").description("Connect this machine to your MonoC
8738
8947
  }
8739
8948
  att = attachmentFor(plan.profile);
8740
8949
  const existing = loadConfig(att.dir);
8741
- const roots2 = opts.root?.map((r) => path28.resolve(r)) ?? existing?.roots ?? plan.copyRootsFrom ?? [];
8950
+ const roots2 = opts.root?.map((r) => path30.resolve(r)) ?? existing?.roots ?? plan.copyRootsFrom ?? [];
8742
8951
  const unsafe = roots2.filter((r) => rootExposesConfig(r, att.dir));
8743
8952
  if (unsafe.length) {
8744
8953
  console.error(`Not exposing ${unsafe.join(", ")}: it contains this host's config folder (${att.dir}), so agents could change the machine's MonoClaw settings or read its keys. Pass a folder inside it instead, such as --root ~/command.`);
8745
8954
  process.exit(2);
8746
8955
  }
8747
8956
  for (const r of opts.root ? roots2 : []) {
8748
- if (fs28.existsSync(r)) continue;
8957
+ if (fs30.existsSync(r)) continue;
8749
8958
  try {
8750
- fs28.mkdirSync(r, { recursive: true });
8959
+ fs30.mkdirSync(r, { recursive: true });
8751
8960
  console.log(`Created ${r} for your agents to work in.`);
8752
8961
  } catch (e) {
8753
8962
  console.error(`Could not create ${r}: ${e.message}. Create it yourself, or add another folder with: ${cmd("roots add <folder>")}`);
@@ -8765,6 +8974,17 @@ program.command("enrol [token]").description("Connect this machine to your MonoC
8765
8974
  Next, run it:
8766
8975
  monoclaw service install in the background: starts now, at every login, and survives restarts`);
8767
8976
  });
8977
+ async function whereInstalled() {
8978
+ const mode = detectInstallMode();
8979
+ const prefix = ownPrefix();
8980
+ let text2 = describeInstall(mode, prefix);
8981
+ if (mode === "npm-global" && prefix) {
8982
+ const npmPrefix = await npmPrefixDefault().catch(() => null);
8983
+ const other = installedCopies(npmPrefix).find((c) => c.prefix !== prefix);
8984
+ if (other) text2 += `; a second copy, ${other.version}, in ${other.prefix} (monoclaw uninstall removes both)`;
8985
+ }
8986
+ return text2;
8987
+ }
8768
8988
  async function makeContext(cfg, a = att, voice) {
8769
8989
  const store = await pickSecretStore(a.dir);
8770
8990
  const config2 = new ConfigStore(cfg, a.dir);
@@ -8841,7 +9061,7 @@ provider.command("add <name>").description("Add a Claude connection; an api_key
8841
9061
  const { registry, accounts } = await makeContext(requireConfig(att));
8842
9062
  const moduleId = opts.type === "api_key" ? "claude-api" : "claude-subscription";
8843
9063
  if (!registry.isInstalled(moduleId)) await registry.add(moduleId).install;
8844
- const folders = opts.folders?.map((f) => path28.resolve(f.replace(/^~(?=$|\/)/, process.env.HOME ?? "")));
9064
+ const folders = opts.folders?.map((f) => path30.resolve(f.replace(/^~(?=$|\/)/, process.env.HOME ?? "")));
8845
9065
  if (opts.type === "api_key") {
8846
9066
  const id = await connectModule(registry, accounts, moduleId, io, { name, id: opts.id });
8847
9067
  if (folders) accounts.upsert({ ...accounts.get(id), allowedFolders: folders });
@@ -8870,18 +9090,18 @@ var roots = program.command("roots").description("Folders this machine exposes t
8870
9090
  roots.command("list").action(() => {
8871
9091
  const cfg = requireConfig(att);
8872
9092
  if (!cfg.roots.length) console.log("(none) \u2014 add one with: monoclaw roots add <path>");
8873
- for (const r of cfg.roots) console.log(`${fs28.existsSync(r) ? "\u2713" : "\u2717 (missing)"} ${r}`);
9093
+ for (const r of cfg.roots) console.log(`${fs30.existsSync(r) ? "\u2713" : "\u2717 (missing)"} ${r}`);
8874
9094
  });
8875
9095
  roots.command("add <path...>").action((paths) => {
8876
9096
  const cfg = requireConfig(att);
8877
9097
  for (const p of paths) {
8878
- const full = path28.resolve(p.replace(/^~(?=$|\/)/, process.env.HOME ?? ""));
8879
- if (!fs28.existsSync(full) || !fs28.statSync(full).isDirectory()) {
9098
+ const full = path30.resolve(p.replace(/^~(?=$|\/)/, process.env.HOME ?? ""));
9099
+ if (!fs30.existsSync(full) || !fs30.statSync(full).isDirectory()) {
8880
9100
  console.error(`not a folder: ${full}`);
8881
9101
  continue;
8882
9102
  }
8883
9103
  if (rootExposesConfig(full, att.dir)) {
8884
- console.error(`not adding ${full}: it contains this host's config folder (${att.dir}), so agents could change the machine's MonoClaw settings or read its keys. Add a folder inside it, such as ${path28.join(full, "command")}.`);
9104
+ console.error(`not adding ${full}: it contains this host's config folder (${att.dir}), so agents could change the machine's MonoClaw settings or read its keys. Add a folder inside it, such as ${path30.join(full, "command")}.`);
8885
9105
  process.exitCode = 1;
8886
9106
  continue;
8887
9107
  }
@@ -8894,14 +9114,14 @@ Restart the host for the change to reach the app.`);
8894
9114
  });
8895
9115
  roots.command("remove <path>").action((p) => {
8896
9116
  const cfg = requireConfig(att);
8897
- const full = path28.resolve(p);
9117
+ const full = path30.resolve(p);
8898
9118
  cfg.roots = cfg.roots.filter((r) => r !== full);
8899
9119
  saveConfig(cfg, att.dir);
8900
9120
  console.log(`Exposed folders: ${cfg.roots.join(", ") || "(none)"}`);
8901
9121
  });
8902
9122
  program.command("status").description("Everything this computer does for MonoClaw: the program, each organisation and personal account it serves, their modules and keys, and what is wrong (exit code 1 when something is)").option("--json", "The report as JSON (its shape is in the docs, Commands)").action(async (o) => {
8903
9123
  const report = await buildStatus({
8904
- installedWith: detectInstallMode() === "npm-global" ? "installed with npm" : detectInstallMode() === "checkout" ? "from a checkout" : "installed in an unknown way",
9124
+ installedWith: await whereInstalled(),
8905
9125
  fromDisk: async (cfg, a) => {
8906
9126
  const { registry } = await makeContext(cfg, a);
8907
9127
  await registry.refreshReadiness();
@@ -8923,24 +9143,24 @@ program.command("status").description("Everything this computer does for MonoCla
8923
9143
  if (report.problems.length) process.exit(1);
8924
9144
  });
8925
9145
  program.command("logs [organisation]").description("The program's log, all of it or one organisation's lines ('default' for the first enrolment); -f follows it").option("-f, --follow", "Keep printing new lines").option("--since <when>", "Only lines from then: a time (2026-11-28T10:00:00Z) or how long ago (30m, 2h, 1d)").action(async (organisation, o) => {
8926
- const file = path28.join(baseDir(), "logs", "host.log");
9146
+ const file = path30.join(baseDir(), "logs", "host.log");
8927
9147
  const profile = organisation ? organisation === "default" ? "default" : resolveAttachment(null, { organisation }).profile ?? "default" : null;
8928
9148
  const since = o.since ? parseSince(o.since) : null;
8929
9149
  if (o.since && !since) throw new Error(`--since takes a time or a duration like 30m, 2h or 1d (got "${o.since}")`);
8930
9150
  for (const line of readLog(file, { profile, since })) console.log(line);
8931
9151
  if (!o.follow) return;
8932
- let offset = fs28.existsSync(file) ? fs28.statSync(file).size : 0;
9152
+ let offset = fs30.existsSync(file) ? fs30.statSync(file).size : 0;
8933
9153
  const field = profile ? `[${profile}]` : null;
8934
9154
  await new Promise(() => {
8935
9155
  setInterval(() => {
8936
- if (!fs28.existsSync(file)) return;
8937
- const size = fs28.statSync(file).size;
9156
+ if (!fs30.existsSync(file)) return;
9157
+ const size = fs30.statSync(file).size;
8938
9158
  if (size < offset) offset = 0;
8939
9159
  if (size === offset) return;
8940
- const fd = fs28.openSync(file, "r");
9160
+ const fd = fs30.openSync(file, "r");
8941
9161
  const buf = Buffer.alloc(size - offset);
8942
- fs28.readSync(fd, buf, 0, buf.length, offset);
8943
- fs28.closeSync(fd);
9162
+ fs30.readSync(fd, buf, 0, buf.length, offset);
9163
+ fs30.closeSync(fd);
8944
9164
  offset = size;
8945
9165
  for (const line of buf.toString("utf8").split("\n")) if (line && (!field || line.includes(` ${field} `))) console.log(line);
8946
9166
  }, 500);
@@ -8963,14 +9183,14 @@ program.command("disconnect <organisation>").description("Detach this computer f
8963
9183
  if (!o.yes && !await confirm("Disconnect?", false)) return console.log("Nothing changed.");
8964
9184
  if (known) await detachSelf(cfg.routerUrl, cfg.credential ?? "", { dryRun: false });
8965
9185
  const reply = process.platform === "win32" ? null : await askControl({ cmd: "detach", profile: a.profile });
8966
- fs28.rmSync(configPath(a.dir), { force: true });
8967
- fs28.rmSync(path28.join(a.dir, "held-messages.json"), { force: true });
9186
+ fs30.rmSync(configPath(a.dir), { force: true });
9187
+ fs30.rmSync(path30.join(a.dir, "held-messages.json"), { force: true });
8968
9188
  console.log(`Disconnected from ${who2}.${reply?.ok ? " The running program let it go." : " (The program was not running, so there was nothing to stop.)"}`);
8969
9189
  });
8970
9190
  program.command("start", { hidden: true }).description("Run the machine program in this terminal and stay connected (the background service runs this; checks for updates first; MONOCLAW_NO_UPDATE=1 skips optional ones)").option("--foreground", "Meant to run in this terminal (a container, or no service manager): no warning").action(async (o) => {
8971
9191
  if (startedByHand(o.foreground, process.env, !!process.stdout.isTTY)) console.error(`${FOREGROUND_WARNING} monoclaw service install
8972
9192
  `);
8973
- const oldUnit = att.profile && underServiceManager() && fs28.existsSync(profileUnitFile(att.profile) ?? "") ? att.profile : null;
9193
+ const oldUnit = att.profile && underServiceManager() && fs30.existsSync(profileUnitFile(att.profile) ?? "") ? att.profile : null;
8974
9194
  const lock = acquireRunLock(baseDir());
8975
9195
  if (!lock.ok) {
8976
9196
  if (oldUnit) {
@@ -8982,7 +9202,7 @@ program.command("start", { hidden: true }).description("Run the machine program
8982
9202
  process.exit(1);
8983
9203
  }
8984
9204
  process.on("exit", lock.release);
8985
- setLogDir(path28.join(baseDir(), "logs"));
9205
+ setLogDir(path30.join(baseDir(), "logs"));
8986
9206
  let merge;
8987
9207
  try {
8988
9208
  merge = mergeAttachments({ keep: oldUnit, say: (m) => log("info", `merge: ${m}`) });
@@ -8993,7 +9213,7 @@ program.command("start", { hidden: true }).description("Run the machine program
8993
9213
  if (merge.merged) log("info", `one program for this computer: ${merge.attachments.length} attachment(s)${merge.unitsRemoved.length ? `; old units retired: ${merge.unitsRemoved.join(", ")}` : ""}${merge.unitsLeft.length ? `; could not remove: ${merge.unitsLeft.map((u) => `${u.unit} (${u.error})`).join("; ")}` : ""} (${merge.ms} ms)`);
8994
9214
  if (oldUnit) {
8995
9215
  try {
8996
- if (!fs28.existsSync(profileUnitFile(null) ?? "")) {
9216
+ if (!fs30.existsSync(profileUnitFile(null) ?? "")) {
8997
9217
  installService(attachmentFor(null));
8998
9218
  log("info", `installed the one background service for every organisation on this computer`);
8999
9219
  }
@@ -9098,7 +9318,7 @@ program.command("doctor").description("Check and repair what a working host need
9098
9318
  const major = Number(process.versions.node.split(".")[0]);
9099
9319
  lines.push({ ok: major >= 22, what: `Node ${process.versions.node}`, fix: major >= 22 ? void 0 : nodeInstallHint(process.platform) });
9100
9320
  const mode = detectInstallMode();
9101
- lines.push({ ok: mode !== "unknown", what: `monoclaw ${APP_VERSION}, installed ${mode === "npm-global" ? "with npm" : mode === "checkout" ? "from a checkout" : "in an unknown way"}`, fix: mode === "unknown" ? `Reinstall with: npm install -g ${PACKAGE}` : void 0 });
9321
+ lines.push({ ok: mode !== "unknown", what: `monoclaw ${APP_VERSION}, ${await whereInstalled()}`, fix: mode === "unknown" ? `Reinstall with: npm install -g ${PACKAGE}` : void 0 });
9102
9322
  forgetCli();
9103
9323
  let bundled = bundledCli();
9104
9324
  let repairNote = "";
@@ -9126,14 +9346,14 @@ program.command("doctor").description("Check and repair what a working host need
9126
9346
  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>" });
9127
9347
  else {
9128
9348
  lines.push({ ok: true, what: `Enrolled as "${cfg.name}" with ${cfg.routerUrl}` });
9129
- const missing = cfg.roots.filter((r) => !fs28.existsSync(r));
9349
+ const missing = cfg.roots.filter((r) => !fs30.existsSync(r));
9130
9350
  const exposing = cfg.roots.filter((r) => rootExposesConfig(r, att.dir));
9131
9351
  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>` });
9132
9352
  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 });
9133
9353
  const names = serviceNames(null);
9134
- const unit = process.platform === "darwin" ? path28.join(os10.homedir(), "Library", "LaunchAgents", `${names.label}.plist`) : process.platform === "linux" ? path28.join(os10.homedir(), ".config", "systemd", "user", `${names.unit}.service`) : null;
9135
- if (unit) lines.push({ ok: fs28.existsSync(unit), info: true, what: fs28.existsSync(unit) ? `Background service installed (${unit})` : "Not running as a background service (fine for now)", fix: fs28.existsSync(unit) ? void 0 : `${cmd("service install")} to run at login` });
9136
- if (unit && fs28.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 });
9354
+ const unit = process.platform === "darwin" ? path30.join(os12.homedir(), "Library", "LaunchAgents", `${names.label}.plist`) : process.platform === "linux" ? path30.join(os12.homedir(), ".config", "systemd", "user", `${names.unit}.service`) : null;
9355
+ if (unit) lines.push({ ok: fs30.existsSync(unit), info: true, what: fs30.existsSync(unit) ? `Background service installed (${unit})` : "Not running as a background service (fine for now)", fix: fs30.existsSync(unit) ? void 0 : `${cmd("service install")} to run at login` });
9356
+ if (unit && fs30.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 });
9137
9357
  const { registry } = await makeContext(cfg);
9138
9358
  await registry.refreshReadiness();
9139
9359
  const reports = registry.reports();
@@ -9210,7 +9430,7 @@ var service = program.command("service").description("Run the host in the backgr
9210
9430
  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) => {
9211
9431
  const one = attachmentFor(null);
9212
9432
  if (!listProfiles().some((p) => p.config)) requireConfig(one);
9213
- fs28.rmSync(pendingServicePath(), { force: true });
9433
+ fs30.rmSync(pendingServicePath(), { force: true });
9214
9434
  if (o.print) {
9215
9435
  const r2 = serviceInstructions(one);
9216
9436
  console.log(`Service file written to ${r2.file}. Run these commands:
@@ -9251,8 +9471,10 @@ program.command("uninstall").description("Remove MonoClaw from this computer, by
9251
9471
  return removed;
9252
9472
  },
9253
9473
  deleteSecret: async (a, id) => (await pickSecretStore(a.dir)).delete(id),
9254
- npmUninstall: () => npmUninstallGlobal(),
9255
- installedWithNpm: detectInstallMode() === "npm-global"
9474
+ npmUninstall: (prefix) => npmUninstallGlobal(PACKAGE, prefix),
9475
+ installedWithNpm: detectInstallMode() === "npm-global",
9476
+ npmPrefix: await npmPrefixDefault().catch(() => null),
9477
+ program: loadComputer()?.program ?? null
9256
9478
  };
9257
9479
  const plan = await planUninstall(deps);
9258
9480
  for (const line of describePlan(plan)) console.log(line);