@monoclaw/machine 1.0.0 → 1.0.4
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/README.md +5 -6
- package/bin/monoclaw.js +12 -1
- package/dist/cli.js +522 -383
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
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
|
|
44
|
-
import
|
|
43
|
+
import fs22 from "node:fs";
|
|
44
|
+
import path22 from "node:path";
|
|
45
45
|
import { Command } from "commander";
|
|
46
46
|
import readline from "node:readline";
|
|
47
47
|
|
|
@@ -1185,12 +1185,12 @@ var isVersion = (v) => parseVersion(v) !== null;
|
|
|
1185
1185
|
import path11 from "node:path";
|
|
1186
1186
|
|
|
1187
1187
|
// src/modules/types.ts
|
|
1188
|
-
function resolveOptions(fields, options,
|
|
1188
|
+
function resolveOptions(fields, options, args2 = {}) {
|
|
1189
1189
|
const out = {};
|
|
1190
1190
|
for (const f of fields) if (f.default !== void 0) out[f.key] = f.default;
|
|
1191
1191
|
for (const [k, v] of Object.entries(options)) out[k] = v;
|
|
1192
1192
|
const settable = new Set(fields.filter((f) => f.agentSettable).map((f) => f.key));
|
|
1193
|
-
for (const [k, v] of Object.entries(
|
|
1193
|
+
for (const [k, v] of Object.entries(args2)) if (settable.has(k)) out[k] = v;
|
|
1194
1194
|
return out;
|
|
1195
1195
|
}
|
|
1196
1196
|
var str = (v, fallback) => typeof v === "string" && v ? v : fallback;
|
|
@@ -1240,7 +1240,7 @@ function claudeSubscriptionModule(probe) {
|
|
|
1240
1240
|
return {
|
|
1241
1241
|
id: "claude-subscription",
|
|
1242
1242
|
version: "1.0.0",
|
|
1243
|
-
catalogue: { id: "claude-subscription", name: "Claude (subscription)", description: "Agents run Claude Code with this machine's own Claude login
|
|
1243
|
+
catalogue: { id: "claude-subscription", name: "Claude (subscription)", description: "Agents run Claude Code with this machine's own Claude login, on your Claude subscription.", capabilities: ["agent"], kind: "local", needsSecret: false, downloadMb: null },
|
|
1244
1244
|
multipleConnections: false,
|
|
1245
1245
|
connectionType: "subscription",
|
|
1246
1246
|
providerId: "claude",
|
|
@@ -1442,11 +1442,11 @@ var busy = (e) => e.status === 429 && (e.code === "system_busy" || e.code === "t
|
|
|
1442
1442
|
function elevenlabsModule(deps = {}) {
|
|
1443
1443
|
const f = deps.fetch ?? ((...a) => fetch(...a));
|
|
1444
1444
|
const queue = new PerKeyQueue();
|
|
1445
|
-
const call = (key,
|
|
1445
|
+
const call = (key, path23, init = {}, timeoutMs = 12e4) => withRetries(
|
|
1446
1446
|
async () => {
|
|
1447
1447
|
let res;
|
|
1448
1448
|
try {
|
|
1449
|
-
res = await f(`${ELEVENLABS_BASE}${
|
|
1449
|
+
res = await f(`${ELEVENLABS_BASE}${path23}`, { ...init, headers: { ...init.headers, "xi-api-key": key }, signal: AbortSignal.timeout(timeoutMs), redirect: "error" });
|
|
1450
1450
|
} catch (e) {
|
|
1451
1451
|
throw new Error(`Could not reach ElevenLabs: ${e.message}`);
|
|
1452
1452
|
}
|
|
@@ -2535,9 +2535,9 @@ import { promisify as promisify3 } from "node:util";
|
|
|
2535
2535
|
var execFileP3 = promisify3(execFile3);
|
|
2536
2536
|
var DEFAULT_TIMEOUT_MS = 9e4;
|
|
2537
2537
|
var MAX_BUFFER = 64 * 1024 * 1024;
|
|
2538
|
-
function run(ctx,
|
|
2539
|
-
if (ctx.exec) return ctx.exec(ctx.ffmpegPath,
|
|
2540
|
-
return execFileP3(ctx.ffmpegPath,
|
|
2538
|
+
function run(ctx, args2) {
|
|
2539
|
+
if (ctx.exec) return ctx.exec(ctx.ffmpegPath, args2);
|
|
2540
|
+
return execFileP3(ctx.ffmpegPath, args2, { timeout: ctx.timeoutMs ?? DEFAULT_TIMEOUT_MS, maxBuffer: MAX_BUFFER, killSignal: "SIGKILL" });
|
|
2541
2541
|
}
|
|
2542
2542
|
var SILENCE_LUFS = -50;
|
|
2543
2543
|
var MAX_STATIC_GAIN_DB = 20;
|
|
@@ -2948,7 +2948,7 @@ function npmInstallInto(dir) {
|
|
|
2948
2948
|
}
|
|
2949
2949
|
function ffmpegHint(platform = process.platform) {
|
|
2950
2950
|
if (platform === "darwin") return "Install ffmpeg: brew install ffmpeg";
|
|
2951
|
-
if (platform === "win32") return "Install ffmpeg: winget install
|
|
2951
|
+
if (platform === "win32") return "Install ffmpeg: winget install --id Gyan.FFmpeg -e";
|
|
2952
2952
|
return "Install ffmpeg: sudo apt install ffmpeg (or your distribution's package)";
|
|
2953
2953
|
}
|
|
2954
2954
|
var LocalInstall = class {
|
|
@@ -3223,7 +3223,7 @@ function moduleSetup(m, platform = process.platform) {
|
|
|
3223
3223
|
}
|
|
3224
3224
|
steps.push({ title: `Add ${name}`, command: `monoclaw modules add ${m.id}`, detail: m.catalogue.downloadMb ? `Downloads about ${m.catalogue.downloadMb} MB (models and a speech library) the first time.` : void 0 });
|
|
3225
3225
|
if (m.id === "claude-subscription") {
|
|
3226
|
-
steps.push({ title: "Sign in to Claude on this machine", command: "claude login", detail: "Agents use this login (a Pro, Max, Team or Enterprise plan). Skip it if `monoclaw doctor` already shows you signed in." });
|
|
3226
|
+
steps.push({ title: "Sign in to Claude on this machine", command: "monoclaw claude auth login", detail: "Agents use this login (a Pro, Max, Team or Enterprise plan). Skip it if `monoclaw doctor` already shows you signed in." });
|
|
3227
3227
|
}
|
|
3228
3228
|
if (m.connectionType === "api_key") {
|
|
3229
3229
|
const page = KEY_PAGES[m.id];
|
|
@@ -3576,10 +3576,10 @@ function toolShape(params, capability = "image") {
|
|
|
3576
3576
|
}
|
|
3577
3577
|
return shape;
|
|
3578
3578
|
}
|
|
3579
|
-
function toolCallArgs(tool2,
|
|
3579
|
+
function toolCallArgs(tool2, args2) {
|
|
3580
3580
|
const keys = new Set(tool2.params.map((p) => p.key));
|
|
3581
3581
|
const out = {};
|
|
3582
|
-
for (const [k, v] of Object.entries(
|
|
3582
|
+
for (const [k, v] of Object.entries(args2)) if (k !== "prompt" && k !== "file" && keys.has(k) && (typeof v === "string" || typeof v === "number" || typeof v === "boolean")) out[k] = v;
|
|
3583
3583
|
return out;
|
|
3584
3584
|
}
|
|
3585
3585
|
function formatToolResult(tool2, r, cwd) {
|
|
@@ -3626,10 +3626,10 @@ var SessionToolRunner = class {
|
|
|
3626
3626
|
timeoutMs;
|
|
3627
3627
|
scope;
|
|
3628
3628
|
waits = new ToolWaits();
|
|
3629
|
-
async call(t,
|
|
3630
|
-
if (t.capability === "stt") return this.transcribe(t,
|
|
3631
|
-
const prompt = typeof
|
|
3632
|
-
const callArgs = toolCallArgs(t,
|
|
3629
|
+
async call(t, args2) {
|
|
3630
|
+
if (t.capability === "stt") return this.transcribe(t, args2);
|
|
3631
|
+
const prompt = typeof args2.prompt === "string" ? args2.prompt.trim() : "";
|
|
3632
|
+
const callArgs = toolCallArgs(t, args2);
|
|
3633
3633
|
if (t.askBeforeUse) {
|
|
3634
3634
|
const ok = await this.approve(toolMcpName(t), { prompt, ...callArgs }, `${t.name}: ${prompt.slice(0, 120)}`);
|
|
3635
3635
|
if (!ok) return formatToolResult(t, { error: "The user declined this tool call.", files: [] });
|
|
@@ -3640,11 +3640,11 @@ var SessionToolRunner = class {
|
|
|
3640
3640
|
return formatToolResult(t, await wait, this.cwd);
|
|
3641
3641
|
}
|
|
3642
3642
|
/** A transcription tool: the file must exist (inside the folder unless the agent is Full); the client uploads it. */
|
|
3643
|
-
async transcribe(t,
|
|
3644
|
-
const given = typeof
|
|
3643
|
+
async transcribe(t, args2) {
|
|
3644
|
+
const given = typeof args2.file === "string" ? args2.file.trim() : "";
|
|
3645
3645
|
const file = resolveToolFile(given, this.cwd, this.scope);
|
|
3646
3646
|
if ("error" in file) return formatToolResult(t, { error: file.error, files: [] });
|
|
3647
|
-
const callArgs = toolCallArgs(t,
|
|
3647
|
+
const callArgs = toolCallArgs(t, args2);
|
|
3648
3648
|
if (t.askBeforeUse) {
|
|
3649
3649
|
const ok = await this.approve(toolMcpName(t), { file: given, ...callArgs }, `${t.name}: ${path12.basename(file.path)}`);
|
|
3650
3650
|
if (!ok) return formatToolResult(t, { error: "The user declined this tool call.", files: [] });
|
|
@@ -4223,7 +4223,7 @@ function guessMime(name) {
|
|
|
4223
4223
|
}
|
|
4224
4224
|
|
|
4225
4225
|
// src/version.ts
|
|
4226
|
-
var APP_VERSION = true ? "1.0.
|
|
4226
|
+
var APP_VERSION = true ? "1.0.4" : fromPackage();
|
|
4227
4227
|
|
|
4228
4228
|
// src/client.ts
|
|
4229
4229
|
var HEARTBEAT_MS = 2e4;
|
|
@@ -4448,7 +4448,7 @@ var HostClient = class {
|
|
|
4448
4448
|
return;
|
|
4449
4449
|
}
|
|
4450
4450
|
if (code === 4002) {
|
|
4451
|
-
log("error", "another MonoClaw host connected with this machine's enrolment (a second `monoclaw start`, or the same config on another computer); this one has stopped. Run only one per machine: `monoclaw service
|
|
4451
|
+
log("error", "another MonoClaw host connected with this machine's enrolment (a second `monoclaw start`, or the same config on another computer); this one has stopped. Run only one per machine: stop the other with `monoclaw service uninstall`, or close the terminal it runs in.");
|
|
4452
4452
|
this.stopped = true;
|
|
4453
4453
|
this.onReplaced();
|
|
4454
4454
|
return;
|
|
@@ -4878,7 +4878,7 @@ To enrol it again as itself after a reset, use Re-enrol on the machine's page in
|
|
|
4878
4878
|
if (same && requested !== null && requested !== same.profile) {
|
|
4879
4879
|
return { action: "enrol", profile: requested, reason: "explicit", copyRootsFrom: same.config.roots, confirm: `This computer is already in ${preview.space.name} as "${same.config.name}". Enrol it a second time there as profile "${requested}"?`, nameHint: null };
|
|
4880
4880
|
}
|
|
4881
|
-
const
|
|
4881
|
+
const first2 = here.find((p) => p.profile === null) ?? here[0];
|
|
4882
4882
|
const taken = new Set(profiles.map((p) => p.profile));
|
|
4883
4883
|
let name = requested ?? (preview.space.handle.toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/^-+|-+$/g, "").slice(0, 30) || "space");
|
|
4884
4884
|
if (requested === null && taken.has(name)) {
|
|
@@ -4886,13 +4886,13 @@ To enrol it again as itself after a reset, use Re-enrol on the machine's page in
|
|
|
4886
4886
|
while (taken.has(`${name}-${i}`)) i++;
|
|
4887
4887
|
name = `${name}-${i}`;
|
|
4888
4888
|
}
|
|
4889
|
-
const existingName =
|
|
4889
|
+
const existingName = first2.config.name;
|
|
4890
4890
|
return {
|
|
4891
4891
|
action: "enrol",
|
|
4892
4892
|
profile: name,
|
|
4893
4893
|
reason: "second-space",
|
|
4894
|
-
copyRootsFrom:
|
|
4895
|
-
confirm: `This computer is enrolled in ${
|
|
4894
|
+
copyRootsFrom: first2.config.roots,
|
|
4895
|
+
confirm: `This computer is enrolled in ${first2.config.spaceName ? `${first2.config.spaceName} (@${first2.config.spaceHandle})` : "another space"} as "${existingName}". Enrol it for ${preview.space.name} (@${preview.space.handle}) too, as a second machine under the profile "${name}"?`,
|
|
4896
4896
|
nameHint: `${existingName || opts.defaultName} \xB7 ${preview.space.name}`.slice(0, 60)
|
|
4897
4897
|
};
|
|
4898
4898
|
}
|
|
@@ -4920,6 +4920,317 @@ async function enrol(token, routerUrl, opts) {
|
|
|
4920
4920
|
return cfg;
|
|
4921
4921
|
}
|
|
4922
4922
|
|
|
4923
|
+
// src/connect.ts
|
|
4924
|
+
import { execFile as execFile5, spawn as spawn4 } from "node:child_process";
|
|
4925
|
+
import fs18 from "node:fs";
|
|
4926
|
+
import os5 from "node:os";
|
|
4927
|
+
import path18 from "node:path";
|
|
4928
|
+
import { promisify as promisify5 } from "node:util";
|
|
4929
|
+
|
|
4930
|
+
// src/update.ts
|
|
4931
|
+
import { spawn as spawn3 } from "node:child_process";
|
|
4932
|
+
import fs17 from "node:fs";
|
|
4933
|
+
import path17 from "node:path";
|
|
4934
|
+
import { z as z8 } from "zod";
|
|
4935
|
+
var PACKAGE = "@monoclaw/machine";
|
|
4936
|
+
function nodeInstallHint(platform) {
|
|
4937
|
+
if (platform === "darwin") return "Install Node 22 or newer: `brew install node`, or the LTS installer from https://nodejs.org";
|
|
4938
|
+
if (platform === "win32") return "Install Node 22 or newer: `winget install OpenJS.NodeJS.LTS`, or the LTS installer from https://nodejs.org";
|
|
4939
|
+
return "Install Node 22 or newer with nvm (no sudo): https://github.com/nvm-sh/nvm#installing-and-updating then `nvm install 22`";
|
|
4940
|
+
}
|
|
4941
|
+
var CHECK_EVERY_MS = 6 * 60 * 6e4;
|
|
4942
|
+
var RETRY_WHEN_BUSY_MS = 10 * 6e4;
|
|
4943
|
+
var INSTALL_TIMEOUT_MS = 5 * 6e4;
|
|
4944
|
+
var VersionPolicy = z8.object({ package: z8.string(), latest: z8.string().nullable(), minimum: z8.string().nullable() });
|
|
4945
|
+
function detectInstallMode(entry = process.argv[1] ?? "") {
|
|
4946
|
+
let real = entry;
|
|
4947
|
+
try {
|
|
4948
|
+
real = fs17.realpathSync(entry);
|
|
4949
|
+
} catch {
|
|
4950
|
+
}
|
|
4951
|
+
const p = real.replace(/\\/g, "/");
|
|
4952
|
+
if (/[\\/]node_modules[\\/]@monoclaw[\\/]machine[\\/]/.test(p)) return "npm-global";
|
|
4953
|
+
if (p.endsWith(".ts") || /\/apps\/host\//.test(p)) return "checkout";
|
|
4954
|
+
return "unknown";
|
|
4955
|
+
}
|
|
4956
|
+
function installedVersion(entry = process.argv[1] ?? "") {
|
|
4957
|
+
let real = entry;
|
|
4958
|
+
try {
|
|
4959
|
+
real = fs17.realpathSync(entry);
|
|
4960
|
+
} catch {
|
|
4961
|
+
}
|
|
4962
|
+
const m = /^(.*[\\/]node_modules[\\/]@monoclaw[\\/]machine)[\\/]/.exec(real);
|
|
4963
|
+
if (!m) return null;
|
|
4964
|
+
try {
|
|
4965
|
+
return JSON.parse(fs17.readFileSync(path17.join(m[1], "package.json"), "utf8")).version ?? null;
|
|
4966
|
+
} catch {
|
|
4967
|
+
return null;
|
|
4968
|
+
}
|
|
4969
|
+
}
|
|
4970
|
+
var LOCK_STALE_MS = 15 * 6e4;
|
|
4971
|
+
async function withUpdateLock(fn, opts = {}) {
|
|
4972
|
+
const dir = opts.dir ?? sharedDir();
|
|
4973
|
+
fs17.mkdirSync(dir, { recursive: true });
|
|
4974
|
+
const file = path17.join(dir, "update.lock");
|
|
4975
|
+
const deadline = Date.now() + (opts.waitMs ?? INSTALL_TIMEOUT_MS);
|
|
4976
|
+
for (; ; ) {
|
|
4977
|
+
try {
|
|
4978
|
+
fs17.writeFileSync(file, JSON.stringify({ pid: process.pid, at: (/* @__PURE__ */ new Date()).toISOString() }), { flag: "wx" });
|
|
4979
|
+
break;
|
|
4980
|
+
} catch (e) {
|
|
4981
|
+
if (e.code !== "EEXIST") throw e;
|
|
4982
|
+
let stale = false;
|
|
4983
|
+
try {
|
|
4984
|
+
stale = Date.now() - fs17.statSync(file).mtimeMs > LOCK_STALE_MS;
|
|
4985
|
+
} catch {
|
|
4986
|
+
continue;
|
|
4987
|
+
}
|
|
4988
|
+
if (stale) {
|
|
4989
|
+
fs17.rmSync(file, { force: true });
|
|
4990
|
+
continue;
|
|
4991
|
+
}
|
|
4992
|
+
if (Date.now() > deadline) throw new Error("another MonoClaw host on this computer has been updating for too long; try again later");
|
|
4993
|
+
await new Promise((r) => setTimeout(r, opts.pollMs ?? 2e3));
|
|
4994
|
+
}
|
|
4995
|
+
}
|
|
4996
|
+
try {
|
|
4997
|
+
return await fn();
|
|
4998
|
+
} finally {
|
|
4999
|
+
fs17.rmSync(file, { force: true });
|
|
5000
|
+
}
|
|
5001
|
+
}
|
|
5002
|
+
function decideUpdate(current, policy, mode, opts) {
|
|
5003
|
+
const min = policy.minimum && isVersion(policy.minimum) ? policy.minimum : null;
|
|
5004
|
+
const latest = policy.latest && isVersion(policy.latest) ? policy.latest : null;
|
|
5005
|
+
const belowMin = !!min && compareVersions(current, min) < 0;
|
|
5006
|
+
const belowLatest = !!latest && compareVersions(current, latest) < 0;
|
|
5007
|
+
if (belowMin) {
|
|
5008
|
+
const to = latest && compareVersions(latest, min) > 0 ? latest : min;
|
|
5009
|
+
if (mode !== "npm-global") return { action: "block", reason: `monoclaw ${current} is older than the minimum this router accepts (${min}) and was not installed with npm, so it cannot update itself. Install the current version: npm install -g ${PACKAGE}@${to}` };
|
|
5010
|
+
return { action: "update", to, required: true };
|
|
5011
|
+
}
|
|
5012
|
+
if (belowLatest && !opts.disabled && mode === "npm-global") return { action: "update", to: latest, required: false };
|
|
5013
|
+
return { action: "none" };
|
|
5014
|
+
}
|
|
5015
|
+
async function fetchPolicy(routerUrl) {
|
|
5016
|
+
try {
|
|
5017
|
+
const res = await fetch(`${routerUrl.replace(/\/+$/, "")}/v1/host/version`, { signal: AbortSignal.timeout(1e4) });
|
|
5018
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
5019
|
+
const json = await res.json();
|
|
5020
|
+
return VersionPolicy.parse(json.data ?? json);
|
|
5021
|
+
} catch (e) {
|
|
5022
|
+
log("warn", `could not read the router's host version policy: ${e.message}`);
|
|
5023
|
+
return null;
|
|
5024
|
+
}
|
|
5025
|
+
}
|
|
5026
|
+
function installSpec(version, source, routerUrl) {
|
|
5027
|
+
if (!isVersion(version)) return null;
|
|
5028
|
+
if (!/^https?:\/\//.test(source)) return source === PACKAGE ? `${PACKAGE}@${version}` : null;
|
|
5029
|
+
let router;
|
|
5030
|
+
let src;
|
|
5031
|
+
try {
|
|
5032
|
+
router = new URL(routerUrl);
|
|
5033
|
+
src = new URL(source);
|
|
5034
|
+
} catch {
|
|
5035
|
+
return null;
|
|
5036
|
+
}
|
|
5037
|
+
if (src.origin !== router.origin || src.pathname.replace(/\/+$/, "") !== "/downloads/host") return null;
|
|
5038
|
+
return `${src.origin}/downloads/host/monoclaw-machine-${version}.tgz`;
|
|
5039
|
+
}
|
|
5040
|
+
function installVersion(version, source = PACKAGE, routerUrl = "") {
|
|
5041
|
+
const spec = installSpec(version, source, routerUrl);
|
|
5042
|
+
if (!spec) return Promise.reject(new Error(`refusing to install ${version} from "${source}"`));
|
|
5043
|
+
return npmInstallGlobal(spec);
|
|
5044
|
+
}
|
|
5045
|
+
var npmInstallArgs2 = (spec) => ["install", "-g", spec, "--ignore-scripts", "--no-fund", "--no-audit", "--loglevel=error"];
|
|
5046
|
+
function npmInstallGlobal(spec) {
|
|
5047
|
+
if (!/^@?[\w./-]+@[\w.-]+$/.test(spec) && !/^https?:\/\/[\w.:-]+\/downloads\/host\/monoclaw-machine-[\w.-]+\.tgz$/.test(spec)) return Promise.reject(new Error(`refusing to install "${spec}"`));
|
|
5048
|
+
const npm = process.platform === "win32" ? "npm.cmd" : "npm";
|
|
5049
|
+
const args2 = npmInstallArgs2(spec);
|
|
5050
|
+
return new Promise((resolve, reject) => {
|
|
5051
|
+
const child = spawn3(npm, args2, { stdio: ["ignore", "pipe", "pipe"], shell: process.platform === "win32", env: { ...process.env, npm_config_update_notifier: "false" } });
|
|
5052
|
+
let out = "";
|
|
5053
|
+
child.stdout.on("data", (d) => out += d);
|
|
5054
|
+
child.stderr.on("data", (d) => out += d);
|
|
5055
|
+
const timer = setTimeout(() => {
|
|
5056
|
+
child.kill();
|
|
5057
|
+
reject(new Error("npm install timed out after 5 minutes"));
|
|
5058
|
+
}, INSTALL_TIMEOUT_MS);
|
|
5059
|
+
child.on("error", (e) => {
|
|
5060
|
+
clearTimeout(timer);
|
|
5061
|
+
reject(new Error(`could not run npm: ${e.message}`));
|
|
5062
|
+
});
|
|
5063
|
+
child.on("exit", (code) => {
|
|
5064
|
+
clearTimeout(timer);
|
|
5065
|
+
if (code === 0) resolve();
|
|
5066
|
+
else reject(new Error(`npm install exited with ${code}: ${out.trim().slice(-600)}`));
|
|
5067
|
+
});
|
|
5068
|
+
});
|
|
5069
|
+
}
|
|
5070
|
+
var REEXEC_ENV = "MONOCLAW_REEXEC";
|
|
5071
|
+
var REEXEC_FROM_ENV = "MONOCLAW_REEXEC_FROM";
|
|
5072
|
+
function settleReexec(env = process.env, running = APP_VERSION) {
|
|
5073
|
+
const from = env[REEXEC_FROM_ENV];
|
|
5074
|
+
if (from && from !== running) {
|
|
5075
|
+
delete env[REEXEC_ENV];
|
|
5076
|
+
delete env[REEXEC_FROM_ENV];
|
|
5077
|
+
}
|
|
5078
|
+
}
|
|
5079
|
+
function reexec() {
|
|
5080
|
+
const hops = Number(process.env[REEXEC_ENV] ?? "0");
|
|
5081
|
+
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`));
|
|
5082
|
+
return new Promise(() => {
|
|
5083
|
+
const child = spawn3(process.execPath, process.argv.slice(1), { stdio: "inherit", env: { ...process.env, [REEXEC_ENV]: String(hops + 1), [REEXEC_FROM_ENV]: APP_VERSION } });
|
|
5084
|
+
child.on("exit", (code, signal) => process.exit(code ?? (signal ? 1 : 0)));
|
|
5085
|
+
child.on("error", (e) => {
|
|
5086
|
+
log("error", `could not restart after update: ${e.message}`);
|
|
5087
|
+
process.exit(1);
|
|
5088
|
+
});
|
|
5089
|
+
});
|
|
5090
|
+
}
|
|
5091
|
+
var updatesDisabled = () => process.env.MONOCLAW_NO_UPDATE === "1";
|
|
5092
|
+
async function ensureUpToDate(routerUrl, opts) {
|
|
5093
|
+
settleReexec();
|
|
5094
|
+
const policy = await fetchPolicy(routerUrl);
|
|
5095
|
+
if (!policy) return "ok";
|
|
5096
|
+
const d = decideUpdate(APP_VERSION, policy, opts.mode ?? detectInstallMode(), { disabled: updatesDisabled() });
|
|
5097
|
+
if (d.action === "none") return "ok";
|
|
5098
|
+
if (d.action === "block") throw new Error(d.reason);
|
|
5099
|
+
log("info", `${d.required ? "update required" : "update available"} (${opts.reason}): ${APP_VERSION} \u2192 ${d.to}; installing`);
|
|
5100
|
+
try {
|
|
5101
|
+
await withUpdateLock(async () => {
|
|
5102
|
+
if (installedVersion() === d.to) {
|
|
5103
|
+
log("info", `${PACKAGE} ${d.to} is already installed on this computer (by another profile); restarting onto it`);
|
|
5104
|
+
return;
|
|
5105
|
+
}
|
|
5106
|
+
await (opts.install ?? installVersion)(d.to, policy.package, routerUrl);
|
|
5107
|
+
});
|
|
5108
|
+
} catch (e) {
|
|
5109
|
+
if (d.required) throw e;
|
|
5110
|
+
log("warn", `update to ${d.to} failed, carrying on with ${APP_VERSION}: ${e.message}`);
|
|
5111
|
+
return "ok";
|
|
5112
|
+
}
|
|
5113
|
+
log("info", `installed ${PACKAGE} ${d.to}`);
|
|
5114
|
+
await opts.afterInstall?.();
|
|
5115
|
+
log("info", "restarting");
|
|
5116
|
+
await opts.onBeforeRestart?.();
|
|
5117
|
+
await reexec();
|
|
5118
|
+
return "ok";
|
|
5119
|
+
}
|
|
5120
|
+
function startPeriodicChecks(routerUrl, hooks) {
|
|
5121
|
+
let timer = null;
|
|
5122
|
+
const schedule = (ms) => {
|
|
5123
|
+
if (timer) clearTimeout(timer);
|
|
5124
|
+
timer = setTimeout(tick, ms);
|
|
5125
|
+
timer.unref();
|
|
5126
|
+
};
|
|
5127
|
+
const tick = async () => {
|
|
5128
|
+
try {
|
|
5129
|
+
const policy = await fetchPolicy(routerUrl);
|
|
5130
|
+
const d = policy ? decideUpdate(APP_VERSION, policy, detectInstallMode(), { disabled: updatesDisabled() }) : { action: "none" };
|
|
5131
|
+
if (d.action === "update") {
|
|
5132
|
+
if (hooks.isBusy()) {
|
|
5133
|
+
log("info", `update to ${d.to} is waiting for the current turn to finish`);
|
|
5134
|
+
return schedule(RETRY_WHEN_BUSY_MS);
|
|
5135
|
+
}
|
|
5136
|
+
await ensureUpToDate(routerUrl, { reason: "periodic check", onBeforeRestart: hooks.onBeforeRestart, afterInstall: hooks.afterInstall });
|
|
5137
|
+
return;
|
|
5138
|
+
}
|
|
5139
|
+
if (d.action === "block") hooks.onError(new Error(d.reason));
|
|
5140
|
+
} catch (e) {
|
|
5141
|
+
hooks.onError(e);
|
|
5142
|
+
}
|
|
5143
|
+
schedule(CHECK_EVERY_MS);
|
|
5144
|
+
};
|
|
5145
|
+
schedule(CHECK_EVERY_MS);
|
|
5146
|
+
return {
|
|
5147
|
+
stop: () => {
|
|
5148
|
+
if (timer) clearTimeout(timer);
|
|
5149
|
+
},
|
|
5150
|
+
checkSoon: () => schedule(5e3 + Math.floor(Math.random() * 25e3))
|
|
5151
|
+
};
|
|
5152
|
+
}
|
|
5153
|
+
|
|
5154
|
+
// src/connect.ts
|
|
5155
|
+
var DEFAULT_ROUTER = "https://command.monoclaw.ai";
|
|
5156
|
+
function ranFromNpx(entry = process.argv[1] ?? "") {
|
|
5157
|
+
let real = entry;
|
|
5158
|
+
try {
|
|
5159
|
+
real = fs18.realpathSync(entry);
|
|
5160
|
+
} catch {
|
|
5161
|
+
}
|
|
5162
|
+
return /[\\/]_npx[\\/]/.test(real);
|
|
5163
|
+
}
|
|
5164
|
+
function globalInstall(prefix, platform = process.platform) {
|
|
5165
|
+
const p = platform === "win32" ? path18.win32 : path18.posix;
|
|
5166
|
+
const modules2 = platform === "win32" ? p.join(prefix, "node_modules") : p.join(prefix, "lib", "node_modules");
|
|
5167
|
+
return { script: p.join(modules2, "@monoclaw", "machine", "bin", "monoclaw.js"), binDir: platform === "win32" ? prefix : p.join(prefix, "bin") };
|
|
5168
|
+
}
|
|
5169
|
+
function enrolArgs(o, hasEnrolment, home = os5.homedir()) {
|
|
5170
|
+
const args2 = [...o.profile ? ["--profile", o.profile] : [], "enrol", o.token, "--router", o.router];
|
|
5171
|
+
const roots2 = o.root?.length ? o.root : hasEnrolment ? [] : [path18.join(home, "command")];
|
|
5172
|
+
if (roots2.length) args2.push("--root", ...roots2);
|
|
5173
|
+
if (o.name) args2.push("--name", o.name);
|
|
5174
|
+
if (o.insecure) args2.push("--insecure");
|
|
5175
|
+
return args2;
|
|
5176
|
+
}
|
|
5177
|
+
function installFailure(message) {
|
|
5178
|
+
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.";
|
|
5179
|
+
return `npm could not install ${PACKAGE}: ${message.trim().split("\n").slice(-3).join(" ").slice(0, 300)}`;
|
|
5180
|
+
}
|
|
5181
|
+
async function npmPrefix() {
|
|
5182
|
+
const npm = process.platform === "win32" ? "npm.cmd" : "npm";
|
|
5183
|
+
const { stdout } = await promisify5(execFile5)(npm, ["prefix", "-g"], { shell: process.platform === "win32", timeout: 3e4 });
|
|
5184
|
+
return stdout.trim();
|
|
5185
|
+
}
|
|
5186
|
+
function run2(node, script, args2) {
|
|
5187
|
+
return new Promise((resolve) => {
|
|
5188
|
+
const child = spawn4(node, [script, ...args2], { stdio: "inherit", env: { ...process.env, MONOCLAW_CONNECT: "1" } });
|
|
5189
|
+
child.on("error", () => resolve(1));
|
|
5190
|
+
child.on("exit", (code) => resolve(code ?? 1));
|
|
5191
|
+
});
|
|
5192
|
+
}
|
|
5193
|
+
async function connect(o, out = { say: (s) => console.log(s), fail: (s) => console.error(s) }) {
|
|
5194
|
+
out.say("MonoClaw: connecting this computer");
|
|
5195
|
+
const node = process.execPath;
|
|
5196
|
+
let script = process.argv[1] ?? "";
|
|
5197
|
+
const lasting = detectInstallMode() === "npm-global" && !ranFromNpx();
|
|
5198
|
+
if (!lasting && detectInstallMode() !== "checkout") {
|
|
5199
|
+
const spec = o.from ?? `${PACKAGE}@${APP_VERSION}`;
|
|
5200
|
+
out.say(`Installing ${spec} with npm...`);
|
|
5201
|
+
try {
|
|
5202
|
+
await npmInstallGlobal(spec);
|
|
5203
|
+
} catch (e) {
|
|
5204
|
+
out.fail(installFailure(e.message));
|
|
5205
|
+
return 1;
|
|
5206
|
+
}
|
|
5207
|
+
try {
|
|
5208
|
+
const g = globalInstall(await npmPrefix());
|
|
5209
|
+
if (!fs18.existsSync(g.script)) throw new Error(`${g.script} is missing`);
|
|
5210
|
+
script = g.script;
|
|
5211
|
+
if (!(process.env.PATH ?? "").split(path18.delimiter).some((d) => path18.resolve(d) === path18.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.`);
|
|
5212
|
+
} catch (e) {
|
|
5213
|
+
out.fail(`Installed, but the program could not be found afterwards (${e.message}). Run: npm install -g ${PACKAGE}`);
|
|
5214
|
+
return 1;
|
|
5215
|
+
}
|
|
5216
|
+
}
|
|
5217
|
+
const hasEnrolment = fs18.existsSync(configPath());
|
|
5218
|
+
if (await run2(node, script, enrolArgs(o, hasEnrolment)) !== 0) {
|
|
5219
|
+
out.fail("This computer was not connected. If the token has run out, copy a new command from Add a machine.");
|
|
5220
|
+
return 1;
|
|
5221
|
+
}
|
|
5222
|
+
const profile = o.profile ? ["--profile", o.profile] : [];
|
|
5223
|
+
if (o.service && await run2(node, script, [...profile, "service", "install"]) !== 0) {
|
|
5224
|
+
out.fail("The background service could not be installed here. Run it in this terminal instead: monoclaw start");
|
|
5225
|
+
return 1;
|
|
5226
|
+
}
|
|
5227
|
+
out.say("");
|
|
5228
|
+
await run2(node, script, [...profile, "doctor"]);
|
|
5229
|
+
out.say("");
|
|
5230
|
+
out.say(o.service ? "Connected. Go back to MonoClaw in your browser: it has moved on by itself." : "Connected. Now run it: monoclaw start");
|
|
5231
|
+
return 0;
|
|
5232
|
+
}
|
|
5233
|
+
|
|
4923
5234
|
// src/providers/queue.ts
|
|
4924
5235
|
var EventQueue = class {
|
|
4925
5236
|
items = [];
|
|
@@ -5038,8 +5349,8 @@ ${r.text}`, final: true });
|
|
|
5038
5349
|
const t = (this.opts.settings.tools ?? []).find((x) => x.name === name.trim());
|
|
5039
5350
|
const reply = async () => {
|
|
5040
5351
|
if (!t) return { content: [{ type: "text", text: `no tool called ${name}` }], isError: true };
|
|
5041
|
-
const
|
|
5042
|
-
return this.tools.call(t, t.capability === "stt" ? { ...
|
|
5352
|
+
const args2 = Object.fromEntries(pairs.map((p) => p.split("=")).map(([k = "", v = ""]) => [k.trim(), /^-?\d+(\.\d+)?$/.test(v.trim()) ? Number(v) : v.trim() === "true" ? true : v.trim() === "false" ? false : v.trim()]));
|
|
5353
|
+
return this.tools.call(t, t.capability === "stt" ? { ...args2, file: prompt } : { ...args2, prompt });
|
|
5043
5354
|
};
|
|
5044
5355
|
const callId = `tu-${newId().slice(0, 8)}`;
|
|
5045
5356
|
this.q.push({ kind: "tool", id: callId, name: `mcp__monoclaw-tools__${name.trim()}`, summary: prompt, input: JSON.stringify({ prompt }) });
|
|
@@ -5154,242 +5465,21 @@ var echoProvider = {
|
|
|
5154
5465
|
};
|
|
5155
5466
|
|
|
5156
5467
|
// src/providers/claude/index.ts
|
|
5157
|
-
import { execFile as
|
|
5158
|
-
import
|
|
5159
|
-
import
|
|
5160
|
-
import
|
|
5161
|
-
import { promisify as
|
|
5162
|
-
import { z as z9 } from "zod";
|
|
5163
|
-
import { createSdkMcpServer, listSessions, query, tool } from "@anthropic-ai/claude-agent-sdk";
|
|
5468
|
+
import { execFile as execFile7 } from "node:child_process";
|
|
5469
|
+
import fs20 from "node:fs";
|
|
5470
|
+
import os6 from "node:os";
|
|
5471
|
+
import path20 from "node:path";
|
|
5472
|
+
import { promisify as promisify7 } from "node:util";
|
|
5473
|
+
import { z as z9 } from "zod";
|
|
5474
|
+
import { createSdkMcpServer, listSessions, query, tool } from "@anthropic-ai/claude-agent-sdk";
|
|
5164
5475
|
|
|
5165
5476
|
// src/providers/claude/cli.ts
|
|
5166
|
-
import { execFile as
|
|
5167
|
-
import
|
|
5477
|
+
import { execFile as execFile6 } from "node:child_process";
|
|
5478
|
+
import fs19 from "node:fs";
|
|
5168
5479
|
import { createRequire as createRequire3 } from "node:module";
|
|
5169
|
-
import
|
|
5170
|
-
import { promisify as
|
|
5171
|
-
|
|
5172
|
-
// src/update.ts
|
|
5173
|
-
import { spawn as spawn3 } from "node:child_process";
|
|
5174
|
-
import fs17 from "node:fs";
|
|
5175
|
-
import path17 from "node:path";
|
|
5176
|
-
import { z as z8 } from "zod";
|
|
5177
|
-
var PACKAGE = "@monoclaw/machine";
|
|
5178
|
-
var CHECK_EVERY_MS = 6 * 60 * 6e4;
|
|
5179
|
-
var RETRY_WHEN_BUSY_MS = 10 * 6e4;
|
|
5180
|
-
var INSTALL_TIMEOUT_MS = 5 * 6e4;
|
|
5181
|
-
var VersionPolicy = z8.object({ package: z8.string(), latest: z8.string().nullable(), minimum: z8.string().nullable() });
|
|
5182
|
-
function detectInstallMode(entry = process.argv[1] ?? "") {
|
|
5183
|
-
let real = entry;
|
|
5184
|
-
try {
|
|
5185
|
-
real = fs17.realpathSync(entry);
|
|
5186
|
-
} catch {
|
|
5187
|
-
}
|
|
5188
|
-
const p = real.replace(/\\/g, "/");
|
|
5189
|
-
if (/[\\/]node_modules[\\/]@monoclaw[\\/]machine[\\/]/.test(p)) return "npm-global";
|
|
5190
|
-
if (p.endsWith(".ts") || /\/apps\/host\//.test(p)) return "checkout";
|
|
5191
|
-
return "unknown";
|
|
5192
|
-
}
|
|
5193
|
-
function installedVersion(entry = process.argv[1] ?? "") {
|
|
5194
|
-
let real = entry;
|
|
5195
|
-
try {
|
|
5196
|
-
real = fs17.realpathSync(entry);
|
|
5197
|
-
} catch {
|
|
5198
|
-
}
|
|
5199
|
-
const m = /^(.*[\\/]node_modules[\\/]@monoclaw[\\/]machine)[\\/]/.exec(real);
|
|
5200
|
-
if (!m) return null;
|
|
5201
|
-
try {
|
|
5202
|
-
return JSON.parse(fs17.readFileSync(path17.join(m[1], "package.json"), "utf8")).version ?? null;
|
|
5203
|
-
} catch {
|
|
5204
|
-
return null;
|
|
5205
|
-
}
|
|
5206
|
-
}
|
|
5207
|
-
var LOCK_STALE_MS = 15 * 6e4;
|
|
5208
|
-
async function withUpdateLock(fn, opts = {}) {
|
|
5209
|
-
const dir = opts.dir ?? sharedDir();
|
|
5210
|
-
fs17.mkdirSync(dir, { recursive: true });
|
|
5211
|
-
const file = path17.join(dir, "update.lock");
|
|
5212
|
-
const deadline = Date.now() + (opts.waitMs ?? INSTALL_TIMEOUT_MS);
|
|
5213
|
-
for (; ; ) {
|
|
5214
|
-
try {
|
|
5215
|
-
fs17.writeFileSync(file, JSON.stringify({ pid: process.pid, at: (/* @__PURE__ */ new Date()).toISOString() }), { flag: "wx" });
|
|
5216
|
-
break;
|
|
5217
|
-
} catch (e) {
|
|
5218
|
-
if (e.code !== "EEXIST") throw e;
|
|
5219
|
-
let stale = false;
|
|
5220
|
-
try {
|
|
5221
|
-
stale = Date.now() - fs17.statSync(file).mtimeMs > LOCK_STALE_MS;
|
|
5222
|
-
} catch {
|
|
5223
|
-
continue;
|
|
5224
|
-
}
|
|
5225
|
-
if (stale) {
|
|
5226
|
-
fs17.rmSync(file, { force: true });
|
|
5227
|
-
continue;
|
|
5228
|
-
}
|
|
5229
|
-
if (Date.now() > deadline) throw new Error("another MonoClaw host on this computer has been updating for too long; try again later");
|
|
5230
|
-
await new Promise((r) => setTimeout(r, opts.pollMs ?? 2e3));
|
|
5231
|
-
}
|
|
5232
|
-
}
|
|
5233
|
-
try {
|
|
5234
|
-
return await fn();
|
|
5235
|
-
} finally {
|
|
5236
|
-
fs17.rmSync(file, { force: true });
|
|
5237
|
-
}
|
|
5238
|
-
}
|
|
5239
|
-
function decideUpdate(current, policy, mode, opts) {
|
|
5240
|
-
const min = policy.minimum && isVersion(policy.minimum) ? policy.minimum : null;
|
|
5241
|
-
const latest = policy.latest && isVersion(policy.latest) ? policy.latest : null;
|
|
5242
|
-
const belowMin = !!min && compareVersions(current, min) < 0;
|
|
5243
|
-
const belowLatest = !!latest && compareVersions(current, latest) < 0;
|
|
5244
|
-
if (belowMin) {
|
|
5245
|
-
const to = latest && compareVersions(latest, min) > 0 ? latest : min;
|
|
5246
|
-
if (mode !== "npm-global") return { action: "block", reason: `monoclaw ${current} is older than the minimum this router accepts (${min}) and was not installed with npm, so it cannot update itself. Install the current version: npm install -g ${PACKAGE}@${to}` };
|
|
5247
|
-
return { action: "update", to, required: true };
|
|
5248
|
-
}
|
|
5249
|
-
if (belowLatest && !opts.disabled && mode === "npm-global") return { action: "update", to: latest, required: false };
|
|
5250
|
-
return { action: "none" };
|
|
5251
|
-
}
|
|
5252
|
-
async function fetchPolicy(routerUrl) {
|
|
5253
|
-
try {
|
|
5254
|
-
const res = await fetch(`${routerUrl.replace(/\/+$/, "")}/v1/host/version`, { signal: AbortSignal.timeout(1e4) });
|
|
5255
|
-
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
5256
|
-
const json = await res.json();
|
|
5257
|
-
return VersionPolicy.parse(json.data ?? json);
|
|
5258
|
-
} catch (e) {
|
|
5259
|
-
log("warn", `could not read the router's host version policy: ${e.message}`);
|
|
5260
|
-
return null;
|
|
5261
|
-
}
|
|
5262
|
-
}
|
|
5263
|
-
function installSpec(version, source, routerUrl) {
|
|
5264
|
-
if (!isVersion(version)) return null;
|
|
5265
|
-
if (!/^https?:\/\//.test(source)) return source === PACKAGE ? `${PACKAGE}@${version}` : null;
|
|
5266
|
-
let router;
|
|
5267
|
-
let src;
|
|
5268
|
-
try {
|
|
5269
|
-
router = new URL(routerUrl);
|
|
5270
|
-
src = new URL(source);
|
|
5271
|
-
} catch {
|
|
5272
|
-
return null;
|
|
5273
|
-
}
|
|
5274
|
-
if (src.origin !== router.origin || src.pathname.replace(/\/+$/, "") !== "/downloads/host") return null;
|
|
5275
|
-
return `${src.origin}/downloads/host/monoclaw-machine-${version}.tgz`;
|
|
5276
|
-
}
|
|
5277
|
-
function installVersion(version, source = PACKAGE, routerUrl = "") {
|
|
5278
|
-
const spec = installSpec(version, source, routerUrl);
|
|
5279
|
-
if (!spec) return Promise.reject(new Error(`refusing to install ${version} from "${source}"`));
|
|
5280
|
-
return npmInstallGlobal(spec);
|
|
5281
|
-
}
|
|
5282
|
-
var npmInstallArgs2 = (spec) => ["install", "-g", spec, "--ignore-scripts", "--no-fund", "--no-audit", "--loglevel=error"];
|
|
5283
|
-
function npmInstallGlobal(spec) {
|
|
5284
|
-
if (!/^@?[\w./-]+@[\w.-]+$/.test(spec) && !/^https?:\/\/[\w.:-]+\/downloads\/host\/monoclaw-machine-[\w.-]+\.tgz$/.test(spec)) return Promise.reject(new Error(`refusing to install "${spec}"`));
|
|
5285
|
-
const npm = process.platform === "win32" ? "npm.cmd" : "npm";
|
|
5286
|
-
const args = npmInstallArgs2(spec);
|
|
5287
|
-
return new Promise((resolve, reject) => {
|
|
5288
|
-
const child = spawn3(npm, args, { stdio: ["ignore", "pipe", "pipe"], shell: process.platform === "win32", env: { ...process.env, npm_config_update_notifier: "false" } });
|
|
5289
|
-
let out = "";
|
|
5290
|
-
child.stdout.on("data", (d) => out += d);
|
|
5291
|
-
child.stderr.on("data", (d) => out += d);
|
|
5292
|
-
const timer = setTimeout(() => {
|
|
5293
|
-
child.kill();
|
|
5294
|
-
reject(new Error("npm install timed out after 5 minutes"));
|
|
5295
|
-
}, INSTALL_TIMEOUT_MS);
|
|
5296
|
-
child.on("error", (e) => {
|
|
5297
|
-
clearTimeout(timer);
|
|
5298
|
-
reject(new Error(`could not run npm: ${e.message}`));
|
|
5299
|
-
});
|
|
5300
|
-
child.on("exit", (code) => {
|
|
5301
|
-
clearTimeout(timer);
|
|
5302
|
-
if (code === 0) resolve();
|
|
5303
|
-
else reject(new Error(`npm install exited with ${code}: ${out.trim().slice(-600)}`));
|
|
5304
|
-
});
|
|
5305
|
-
});
|
|
5306
|
-
}
|
|
5307
|
-
var REEXEC_ENV = "MONOCLAW_REEXEC";
|
|
5308
|
-
var REEXEC_FROM_ENV = "MONOCLAW_REEXEC_FROM";
|
|
5309
|
-
function settleReexec(env = process.env, running = APP_VERSION) {
|
|
5310
|
-
const from = env[REEXEC_FROM_ENV];
|
|
5311
|
-
if (from && from !== running) {
|
|
5312
|
-
delete env[REEXEC_ENV];
|
|
5313
|
-
delete env[REEXEC_FROM_ENV];
|
|
5314
|
-
}
|
|
5315
|
-
}
|
|
5316
|
-
function reexec() {
|
|
5317
|
-
const hops = Number(process.env[REEXEC_ENV] ?? "0");
|
|
5318
|
-
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`));
|
|
5319
|
-
return new Promise(() => {
|
|
5320
|
-
const child = spawn3(process.execPath, process.argv.slice(1), { stdio: "inherit", env: { ...process.env, [REEXEC_ENV]: String(hops + 1), [REEXEC_FROM_ENV]: APP_VERSION } });
|
|
5321
|
-
child.on("exit", (code, signal) => process.exit(code ?? (signal ? 1 : 0)));
|
|
5322
|
-
child.on("error", (e) => {
|
|
5323
|
-
log("error", `could not restart after update: ${e.message}`);
|
|
5324
|
-
process.exit(1);
|
|
5325
|
-
});
|
|
5326
|
-
});
|
|
5327
|
-
}
|
|
5328
|
-
var updatesDisabled = () => process.env.MONOCLAW_NO_UPDATE === "1";
|
|
5329
|
-
async function ensureUpToDate(routerUrl, opts) {
|
|
5330
|
-
settleReexec();
|
|
5331
|
-
const policy = await fetchPolicy(routerUrl);
|
|
5332
|
-
if (!policy) return "ok";
|
|
5333
|
-
const d = decideUpdate(APP_VERSION, policy, opts.mode ?? detectInstallMode(), { disabled: updatesDisabled() });
|
|
5334
|
-
if (d.action === "none") return "ok";
|
|
5335
|
-
if (d.action === "block") throw new Error(d.reason);
|
|
5336
|
-
log("info", `${d.required ? "update required" : "update available"} (${opts.reason}): ${APP_VERSION} \u2192 ${d.to}; installing`);
|
|
5337
|
-
try {
|
|
5338
|
-
await withUpdateLock(async () => {
|
|
5339
|
-
if (installedVersion() === d.to) {
|
|
5340
|
-
log("info", `${PACKAGE} ${d.to} is already installed on this computer (by another profile); restarting onto it`);
|
|
5341
|
-
return;
|
|
5342
|
-
}
|
|
5343
|
-
await (opts.install ?? installVersion)(d.to, policy.package, routerUrl);
|
|
5344
|
-
});
|
|
5345
|
-
} catch (e) {
|
|
5346
|
-
if (d.required) throw e;
|
|
5347
|
-
log("warn", `update to ${d.to} failed, carrying on with ${APP_VERSION}: ${e.message}`);
|
|
5348
|
-
return "ok";
|
|
5349
|
-
}
|
|
5350
|
-
log("info", `installed ${PACKAGE} ${d.to}`);
|
|
5351
|
-
await opts.afterInstall?.();
|
|
5352
|
-
log("info", "restarting");
|
|
5353
|
-
await opts.onBeforeRestart?.();
|
|
5354
|
-
await reexec();
|
|
5355
|
-
return "ok";
|
|
5356
|
-
}
|
|
5357
|
-
function startPeriodicChecks(routerUrl, hooks) {
|
|
5358
|
-
let timer = null;
|
|
5359
|
-
const schedule = (ms) => {
|
|
5360
|
-
if (timer) clearTimeout(timer);
|
|
5361
|
-
timer = setTimeout(tick, ms);
|
|
5362
|
-
timer.unref();
|
|
5363
|
-
};
|
|
5364
|
-
const tick = async () => {
|
|
5365
|
-
try {
|
|
5366
|
-
const policy = await fetchPolicy(routerUrl);
|
|
5367
|
-
const d = policy ? decideUpdate(APP_VERSION, policy, detectInstallMode(), { disabled: updatesDisabled() }) : { action: "none" };
|
|
5368
|
-
if (d.action === "update") {
|
|
5369
|
-
if (hooks.isBusy()) {
|
|
5370
|
-
log("info", `update to ${d.to} is waiting for the current turn to finish`);
|
|
5371
|
-
return schedule(RETRY_WHEN_BUSY_MS);
|
|
5372
|
-
}
|
|
5373
|
-
await ensureUpToDate(routerUrl, { reason: "periodic check", onBeforeRestart: hooks.onBeforeRestart, afterInstall: hooks.afterInstall });
|
|
5374
|
-
return;
|
|
5375
|
-
}
|
|
5376
|
-
if (d.action === "block") hooks.onError(new Error(d.reason));
|
|
5377
|
-
} catch (e) {
|
|
5378
|
-
hooks.onError(e);
|
|
5379
|
-
}
|
|
5380
|
-
schedule(CHECK_EVERY_MS);
|
|
5381
|
-
};
|
|
5382
|
-
schedule(CHECK_EVERY_MS);
|
|
5383
|
-
return {
|
|
5384
|
-
stop: () => {
|
|
5385
|
-
if (timer) clearTimeout(timer);
|
|
5386
|
-
},
|
|
5387
|
-
checkSoon: () => schedule(5e3 + Math.floor(Math.random() * 25e3))
|
|
5388
|
-
};
|
|
5389
|
-
}
|
|
5390
|
-
|
|
5391
|
-
// src/providers/claude/cli.ts
|
|
5392
|
-
var execFileP5 = promisify5(execFile5);
|
|
5480
|
+
import path19 from "node:path";
|
|
5481
|
+
import { promisify as promisify6 } from "node:util";
|
|
5482
|
+
var execFileP5 = promisify6(execFile6);
|
|
5393
5483
|
var SDK = "@anthropic-ai/claude-agent-sdk";
|
|
5394
5484
|
var CLI_PATH_ENV = "MONOCLAW_CLAUDE_PATH";
|
|
5395
5485
|
function isMusl() {
|
|
@@ -5399,7 +5489,7 @@ function isMusl() {
|
|
|
5399
5489
|
if (header && "glibcVersionRuntime" in header) return !header.glibcVersionRuntime;
|
|
5400
5490
|
} catch {
|
|
5401
5491
|
}
|
|
5402
|
-
return
|
|
5492
|
+
return fs19.existsSync("/etc/alpine-release");
|
|
5403
5493
|
}
|
|
5404
5494
|
function platformPackages(platform = process.platform, arch = process.arch, musl = isMusl()) {
|
|
5405
5495
|
const base = `${SDK}-`;
|
|
@@ -5409,24 +5499,24 @@ function platformPackages(platform = process.platform, arch = process.arch, musl
|
|
|
5409
5499
|
}
|
|
5410
5500
|
var exe = (platform = process.platform) => platform === "win32" ? "claude.exe" : "claude";
|
|
5411
5501
|
function sdkRoot() {
|
|
5412
|
-
let dir =
|
|
5502
|
+
let dir = path19.dirname(createRequire3(import.meta.url).resolve(SDK));
|
|
5413
5503
|
for (let i = 0; i < 6; i++) {
|
|
5414
|
-
const pkg =
|
|
5504
|
+
const pkg = path19.join(dir, "package.json");
|
|
5415
5505
|
try {
|
|
5416
|
-
if (JSON.parse(
|
|
5506
|
+
if (JSON.parse(fs19.readFileSync(pkg, "utf8")).name === SDK) return dir;
|
|
5417
5507
|
} catch {
|
|
5418
5508
|
}
|
|
5419
|
-
dir =
|
|
5509
|
+
dir = path19.dirname(dir);
|
|
5420
5510
|
}
|
|
5421
5511
|
throw new Error(`could not find where ${SDK} is installed`);
|
|
5422
5512
|
}
|
|
5423
5513
|
function sdkResolve() {
|
|
5424
|
-
return createRequire3(
|
|
5514
|
+
return createRequire3(path19.join(sdkRoot(), "package.json")).resolve;
|
|
5425
5515
|
}
|
|
5426
5516
|
function sdkVersion() {
|
|
5427
|
-
return JSON.parse(
|
|
5517
|
+
return JSON.parse(fs19.readFileSync(path19.join(sdkRoot(), "package.json"), "utf8")).version;
|
|
5428
5518
|
}
|
|
5429
|
-
function bundledCli(resolve = sdkResolve(), exists =
|
|
5519
|
+
function bundledCli(resolve = sdkResolve(), exists = fs19.existsSync, platform = process.platform, arch = process.arch) {
|
|
5430
5520
|
for (const pkg of platformPackages(platform, arch)) {
|
|
5431
5521
|
try {
|
|
5432
5522
|
const p = resolve(`${pkg}/${exe(platform)}`);
|
|
@@ -5448,8 +5538,8 @@ async function cliOnPath(env = process.env) {
|
|
|
5448
5538
|
const which = process.platform === "win32" ? "where" : "which";
|
|
5449
5539
|
try {
|
|
5450
5540
|
const { stdout } = await execFileP5(which, ["claude"], { env, timeout: 1e4 });
|
|
5451
|
-
const
|
|
5452
|
-
return
|
|
5541
|
+
const first2 = stdout.split(/\r?\n/).map((l) => l.trim()).find(Boolean);
|
|
5542
|
+
return first2 ?? null;
|
|
5453
5543
|
} catch {
|
|
5454
5544
|
return null;
|
|
5455
5545
|
}
|
|
@@ -5465,7 +5555,7 @@ function resolveCli(deps = {}) {
|
|
|
5465
5555
|
}
|
|
5466
5556
|
async function resolveUncached(deps) {
|
|
5467
5557
|
const env = deps.env ?? process.env;
|
|
5468
|
-
const exists = deps.exists ??
|
|
5558
|
+
const exists = deps.exists ?? fs19.existsSync;
|
|
5469
5559
|
const version = deps.version ?? ((f) => cliVersion(f, env));
|
|
5470
5560
|
const override = env[CLI_PATH_ENV]?.trim();
|
|
5471
5561
|
if (override) {
|
|
@@ -5482,7 +5572,20 @@ function describeCli(c) {
|
|
|
5482
5572
|
const v = c.version ?? "version unknown";
|
|
5483
5573
|
return c.kind === "bundled" ? `bundled ${v}` : c.kind === "path" ? `PATH ${v} (${c.path})` : `${CLI_PATH_ENV} ${v} (${c.path})`;
|
|
5484
5574
|
}
|
|
5485
|
-
var NO_CLI_ACTION = "Run `monoclaw doctor` on this machine
|
|
5575
|
+
var NO_CLI_ACTION = "Run `monoclaw doctor` on this machine: it installs the copy of Claude Code that MonoClaw uses. Then sign in with `monoclaw claude auth login`.";
|
|
5576
|
+
var SIGN_IN_ACTION = "Sign in on this machine: `monoclaw claude auth login`.";
|
|
5577
|
+
async function authStatus(cliPath, env) {
|
|
5578
|
+
let stdout;
|
|
5579
|
+
try {
|
|
5580
|
+
({ stdout } = await execFileP5(cliPath, ["auth", "status"], { env, timeout: 15e3 }));
|
|
5581
|
+
} catch (e) {
|
|
5582
|
+
const out = e.stdout;
|
|
5583
|
+
if (typeof out !== "string" || !out.trim().startsWith("{")) throw e;
|
|
5584
|
+
stdout = out;
|
|
5585
|
+
}
|
|
5586
|
+
const j = JSON.parse(stdout);
|
|
5587
|
+
return { loggedIn: !!j.loggedIn, authMethod: j.authMethod, apiProvider: j.apiProvider };
|
|
5588
|
+
}
|
|
5486
5589
|
async function repairBundledCli(deps = {}) {
|
|
5487
5590
|
const bundled = deps.bundled ?? (() => bundledCli());
|
|
5488
5591
|
if (bundled()) return { outcome: "present", detail: "the host's copy of Claude Code is installed" };
|
|
@@ -5510,7 +5613,7 @@ async function repairBundledCli(deps = {}) {
|
|
|
5510
5613
|
}
|
|
5511
5614
|
|
|
5512
5615
|
// src/providers/claude/index.ts
|
|
5513
|
-
var execFileP6 =
|
|
5616
|
+
var execFileP6 = promisify7(execFile7);
|
|
5514
5617
|
var PERMISSION_MODES = ["auto", "acceptEdits", "default", "plan", "bypassPermissions"];
|
|
5515
5618
|
var SESSION_SETTING_SOURCES = ["user", "project", "local"];
|
|
5516
5619
|
var APPROVAL_TIMEOUT_MS = 10 * 6e4;
|
|
@@ -5546,9 +5649,9 @@ function withOverrides(base, over) {
|
|
|
5546
5649
|
return out;
|
|
5547
5650
|
}
|
|
5548
5651
|
var SEND_TOOL_DESCRIPTION = "Send a message to one other agent. `to` is one agent's name from list_agents; to message several agents, call send once for each. Only agents receive sends: people read your response in the project. Returns at once with whether it was delivered or queued; no reply is required, and any answer arrives later as a message.";
|
|
5549
|
-
function sendToolResult(
|
|
5652
|
+
function sendToolResult(args2, r) {
|
|
5550
5653
|
if (r.error) return { content: [{ type: "text", text: r.error }], isError: true };
|
|
5551
|
-
return { content: [{ type: "text", text: r.text ?? `Sent to ${
|
|
5654
|
+
return { content: [{ type: "text", text: r.text ?? `Sent to ${args2.to}.` }] };
|
|
5552
5655
|
}
|
|
5553
5656
|
function frameInbound(text, sender, settings) {
|
|
5554
5657
|
if (settings.multiHuman && sender.kind === "human") return `[${sender.name}${sender.isAdmin ? " (admin)" : ""}] ${text}`;
|
|
@@ -5629,12 +5732,12 @@ var ClaudeSession = class {
|
|
|
5629
5732
|
"send_file",
|
|
5630
5733
|
"Send a file from the working folder to the user in the chat. Use for screenshots, exports, documents, audio. Paths are relative to the working folder; files outside it, or inside dot-folders, cannot be sent.",
|
|
5631
5734
|
{ path: z9.string().describe("Path of the file to send, inside the working folder"), caption: z9.string().optional().describe("Short caption shown with the file") },
|
|
5632
|
-
async (
|
|
5633
|
-
const full = sendablePath(this.opts.cwd,
|
|
5735
|
+
async (args2) => {
|
|
5736
|
+
const full = sendablePath(this.opts.cwd, args2.path);
|
|
5634
5737
|
if (!full) return { content: [{ type: "text", text: `Only files inside the working folder (${this.opts.cwd}), outside dot-folders, can be sent.` }], isError: true };
|
|
5635
|
-
if (!
|
|
5636
|
-
this.q.push({ kind: "file", path: full, name:
|
|
5637
|
-
return { content: [{ type: "text", text: `Sent ${
|
|
5738
|
+
if (!fs20.existsSync(full) || !fs20.statSync(full).isFile()) return { content: [{ type: "text", text: `No file at ${full}` }], isError: true };
|
|
5739
|
+
this.q.push({ kind: "file", path: full, name: path20.basename(full), mime: guessMime(full), caption: args2.caption });
|
|
5740
|
+
return { content: [{ type: "text", text: `Sent ${path20.basename(full)} to the chat.` }] };
|
|
5638
5741
|
}
|
|
5639
5742
|
)
|
|
5640
5743
|
);
|
|
@@ -5665,7 +5768,7 @@ var ClaudeSession = class {
|
|
|
5665
5768
|
"send",
|
|
5666
5769
|
SEND_TOOL_DESCRIPTION,
|
|
5667
5770
|
{ to: z9.string().min(1).describe("One agent's name from list_agents"), text: z9.string().describe("The message") },
|
|
5668
|
-
async (
|
|
5771
|
+
async (args2) => {
|
|
5669
5772
|
const id = newId();
|
|
5670
5773
|
const result = new Promise((resolve) => {
|
|
5671
5774
|
const timer = setTimeout(() => finish({ error: "No answer from the router within 30 seconds; the message may not have been sent." }), AGENT_SEND_TIMEOUT_MS);
|
|
@@ -5676,8 +5779,8 @@ var ClaudeSession = class {
|
|
|
5676
5779
|
};
|
|
5677
5780
|
this.agentWaits.set(id, finish);
|
|
5678
5781
|
});
|
|
5679
|
-
this.q.push({ kind: "agent.send", id, to:
|
|
5680
|
-
return sendToolResult(
|
|
5782
|
+
this.q.push({ kind: "agent.send", id, to: args2.to, text: args2.text });
|
|
5783
|
+
return sendToolResult(args2, await result);
|
|
5681
5784
|
}
|
|
5682
5785
|
)
|
|
5683
5786
|
);
|
|
@@ -5842,7 +5945,7 @@ ${files.map((a) => `- ${a.localPath} (${a.mime}, ${a.size} bytes)${a.note ? `: $
|
|
|
5842
5945
|
content.push({ type: "text", text });
|
|
5843
5946
|
for (const a of files) {
|
|
5844
5947
|
if (IMAGE_MIMES.has(a.mime) && a.size <= 5 * 1024 * 1024 && a.localPath) {
|
|
5845
|
-
content.push({ type: "image", source: { type: "base64", media_type: a.mime, data:
|
|
5948
|
+
content.push({ type: "image", source: { type: "base64", media_type: a.mime, data: fs20.readFileSync(a.localPath).toString("base64") } });
|
|
5846
5949
|
}
|
|
5847
5950
|
}
|
|
5848
5951
|
const user = { type: "user", message: { role: "user", content }, parent_tool_use_id: null, priority: msg.delivery, origin: { kind: "human" } };
|
|
@@ -5907,7 +6010,7 @@ function sessionToolsServer(list, runner) {
|
|
|
5907
6010
|
const server = createSdkMcpServer({
|
|
5908
6011
|
name: TOOLS_SERVER,
|
|
5909
6012
|
version: "1.0.0",
|
|
5910
|
-
tools: list.map((t) => tool(t.name, t.description, toolShape(t.params, t.capability), async (
|
|
6013
|
+
tools: list.map((t) => tool(t.name, t.description, toolShape(t.params, t.capability), async (args2) => runner.call(t, args2)))
|
|
5911
6014
|
});
|
|
5912
6015
|
return { servers: { [TOOLS_SERVER]: server }, allowed: list.map((t) => toolMcpName(t)) };
|
|
5913
6016
|
}
|
|
@@ -5927,17 +6030,17 @@ function monoclawToolNames(s) {
|
|
|
5927
6030
|
function sendablePath(cwd, p) {
|
|
5928
6031
|
const real = (x) => {
|
|
5929
6032
|
try {
|
|
5930
|
-
return
|
|
6033
|
+
return fs20.realpathSync(x);
|
|
5931
6034
|
} catch {
|
|
5932
6035
|
return null;
|
|
5933
6036
|
}
|
|
5934
6037
|
};
|
|
5935
6038
|
const root = real(cwd);
|
|
5936
|
-
const full = real(
|
|
6039
|
+
const full = real(path20.resolve(cwd, p));
|
|
5937
6040
|
if (!root || !full) return null;
|
|
5938
|
-
if (full !== root && !full.startsWith(root +
|
|
5939
|
-
const rel =
|
|
5940
|
-
if (rel.split(
|
|
6041
|
+
if (full !== root && !full.startsWith(root + path20.sep)) return null;
|
|
6042
|
+
const rel = path20.relative(root, full);
|
|
6043
|
+
if (rel.split(path20.sep).some((seg) => seg.startsWith(".") && seg !== ".")) return null;
|
|
5941
6044
|
return full;
|
|
5942
6045
|
}
|
|
5943
6046
|
function safeJson(v) {
|
|
@@ -5956,30 +6059,30 @@ function friendlyPath(p, cwd) {
|
|
|
5956
6059
|
if (file === base) return ".";
|
|
5957
6060
|
if (file.startsWith(`${base}/`)) return file.slice(base.length + 1);
|
|
5958
6061
|
}
|
|
5959
|
-
const home = norm(
|
|
6062
|
+
const home = norm(os6.homedir());
|
|
5960
6063
|
if (home && file.startsWith(`${home}/`)) return `~/${file.slice(home.length + 1)}`;
|
|
5961
6064
|
return file;
|
|
5962
6065
|
}
|
|
5963
6066
|
var clip = (s, n) => s.length > n ? `${s.slice(0, n - 1)}\u2026` : s;
|
|
5964
6067
|
function describeTool(name, input, cwd) {
|
|
5965
6068
|
const s = (k) => typeof input[k] === "string" ? input[k] : void 0;
|
|
5966
|
-
const
|
|
6069
|
+
const path23 = (k) => friendlyPath(s(k), cwd);
|
|
5967
6070
|
const firstString = () => Object.values(input).find((v) => typeof v === "string" && v.trim().length > 0);
|
|
5968
6071
|
switch (name) {
|
|
5969
6072
|
case "Bash":
|
|
5970
6073
|
return clip(s("description") ?? s("command") ?? "run a command", 120);
|
|
5971
6074
|
case "Read":
|
|
5972
|
-
return `Read ${
|
|
6075
|
+
return `Read ${path23("file_path") || path23("path")}`.trim();
|
|
5973
6076
|
case "Edit":
|
|
5974
6077
|
case "Write":
|
|
5975
6078
|
case "MultiEdit":
|
|
5976
|
-
return `${name} ${
|
|
6079
|
+
return `${name} ${path23("file_path")}`.trim();
|
|
5977
6080
|
case "NotebookEdit":
|
|
5978
|
-
return `Edit notebook ${
|
|
6081
|
+
return `Edit notebook ${path23("notebook_path")}`.trim();
|
|
5979
6082
|
case "Grep":
|
|
5980
|
-
return `Grep "${clip(s("pattern") ?? "", 60)}"${s("path") ? ` in ${
|
|
6083
|
+
return `Grep "${clip(s("pattern") ?? "", 60)}"${s("path") ? ` in ${path23("path")}` : ""}`;
|
|
5981
6084
|
case "Glob":
|
|
5982
|
-
return `Find ${clip(s("pattern") ?? "", 60)}${s("path") ? ` in ${
|
|
6085
|
+
return `Find ${clip(s("pattern") ?? "", 60)}${s("path") ? ` in ${path23("path")}` : ""}`;
|
|
5983
6086
|
case "WebSearch":
|
|
5984
6087
|
return `Search "${clip(s("query") ?? "", 80)}"`;
|
|
5985
6088
|
case "WebFetch": {
|
|
@@ -6035,8 +6138,8 @@ ${instructions}`);
|
|
|
6035
6138
|
return parts.join("\n\n");
|
|
6036
6139
|
}
|
|
6037
6140
|
async function summarise(input) {
|
|
6038
|
-
const dir =
|
|
6039
|
-
|
|
6141
|
+
const dir = path20.join(configDir(), "summaries");
|
|
6142
|
+
fs20.mkdirSync(dir, { recursive: true, mode: 448 });
|
|
6040
6143
|
const model = input.model?.trim() || process.env.MONOCLAW_SUMMARY_MODEL || DEFAULT_SUMMARY_MODEL;
|
|
6041
6144
|
const abortController = new AbortController();
|
|
6042
6145
|
const timer = setTimeout(() => abortController.abort(), SUMMARY_TIMEOUT_MS);
|
|
@@ -6117,12 +6220,11 @@ var claudeProvider = {
|
|
|
6117
6220
|
const fallback = cli.kind === "path" ? " \xB7 using the Claude Code on this machine (the host's copy is missing; `monoclaw doctor` repairs it)" : "";
|
|
6118
6221
|
if (env?.ANTHROPIC_API_KEY) return { ready: true, summary: "API key", details: { version, cli: where, authMethod: "api_key" } };
|
|
6119
6222
|
try {
|
|
6120
|
-
const
|
|
6121
|
-
|
|
6122
|
-
if (!j.loggedIn) return { ready: false, summary: `Claude Code is installed but not logged in${fallback}`, details: { version, cli: where }, action: "Run `claude login` on this machine (or set CLAUDE_CODE_OAUTH_TOKEN from `claude setup-token`)." };
|
|
6223
|
+
const j = await authStatus(cli.path, withOverrides(cleanEnv(), env));
|
|
6224
|
+
if (!j.loggedIn) return { ready: false, summary: `Claude Code is installed but not logged in${fallback}`, details: { version, cli: where }, action: SIGN_IN_ACTION };
|
|
6123
6225
|
return { ready: true, summary: `Logged in (${j.authMethod ?? "ok"})${fallback}`, details: { version, cli: where, authMethod: j.authMethod ?? "", apiProvider: j.apiProvider ?? "" } };
|
|
6124
6226
|
} catch (e) {
|
|
6125
|
-
return { ready: false, summary: "Could not check login state", details: { version, cli: where, error: e.message.slice(0, 200) }, action: "Run `claude auth status` on this machine to see what is wrong." };
|
|
6227
|
+
return { ready: false, summary: "Could not check login state", details: { version, cli: where, error: e.message.slice(0, 200) }, action: "Run `monoclaw claude auth status` on this machine to see what is wrong." };
|
|
6126
6228
|
}
|
|
6127
6229
|
},
|
|
6128
6230
|
openSession(opts) {
|
|
@@ -6145,9 +6247,9 @@ var providers = only.length ? Object.fromEntries(Object.entries(all).filter(([id
|
|
|
6145
6247
|
|
|
6146
6248
|
// src/service.ts
|
|
6147
6249
|
import { spawnSync } from "node:child_process";
|
|
6148
|
-
import
|
|
6149
|
-
import
|
|
6150
|
-
import
|
|
6250
|
+
import fs21 from "node:fs";
|
|
6251
|
+
import os7 from "node:os";
|
|
6252
|
+
import path21 from "node:path";
|
|
6151
6253
|
function serviceNames(profile = currentProfile()) {
|
|
6152
6254
|
return { unit: profile ? `monoclaw-${profile}` : "monoclaw", label: profile ? `ai.monoclaw.host.${profile}` : "ai.monoclaw.host", task: profile ? `MonoClaw host (${profile})` : "MonoClaw host" };
|
|
6153
6255
|
}
|
|
@@ -6158,26 +6260,26 @@ function profileEnv() {
|
|
|
6158
6260
|
function selfCommand() {
|
|
6159
6261
|
let script = process.argv[1] ?? "";
|
|
6160
6262
|
try {
|
|
6161
|
-
script =
|
|
6263
|
+
script = fs21.realpathSync(script);
|
|
6162
6264
|
} catch {
|
|
6163
6265
|
}
|
|
6164
6266
|
return { node: process.execPath, script };
|
|
6165
6267
|
}
|
|
6166
6268
|
function servicePath(node) {
|
|
6167
|
-
const dirs = process.platform === "win32" ? [
|
|
6168
|
-
return [...new Set(dirs)].join(
|
|
6269
|
+
const dirs = process.platform === "win32" ? [path21.dirname(node), "C:\\Windows\\System32", "C:\\Windows"] : [path21.dirname(node), "/usr/local/bin", "/usr/bin", "/bin", "/opt/homebrew/bin"];
|
|
6270
|
+
return [...new Set(dirs)].join(path21.delimiter);
|
|
6169
6271
|
}
|
|
6170
6272
|
function serviceInstructions() {
|
|
6171
6273
|
const dir = configDir();
|
|
6172
|
-
const home =
|
|
6274
|
+
const home = os7.homedir();
|
|
6173
6275
|
const { node, script } = selfCommand();
|
|
6174
|
-
const logs =
|
|
6175
|
-
|
|
6276
|
+
const logs = path21.join(dir, "logs");
|
|
6277
|
+
fs21.mkdirSync(logs, { recursive: true });
|
|
6176
6278
|
const names = serviceNames();
|
|
6177
6279
|
const env = profileEnv();
|
|
6178
6280
|
if (process.platform === "linux") {
|
|
6179
6281
|
const unit = `[Unit]
|
|
6180
|
-
Description=
|
|
6282
|
+
Description=MonoClaw machine${currentProfile() ? ` (${currentProfile()})` : ""}
|
|
6181
6283
|
After=network-online.target
|
|
6182
6284
|
|
|
6183
6285
|
[Service]
|
|
@@ -6190,13 +6292,13 @@ Environment="PATH=${servicePath(node)}"
|
|
|
6190
6292
|
[Install]
|
|
6191
6293
|
WantedBy=default.target
|
|
6192
6294
|
`;
|
|
6193
|
-
const file2 =
|
|
6194
|
-
|
|
6195
|
-
const target =
|
|
6295
|
+
const file2 = path21.join(dir, `${names.unit}.service`);
|
|
6296
|
+
fs21.writeFileSync(file2, unit);
|
|
6297
|
+
const target = path21.join(home, ".config", "systemd", "user", `${names.unit}.service`);
|
|
6196
6298
|
return {
|
|
6197
6299
|
file: file2,
|
|
6198
6300
|
steps: [
|
|
6199
|
-
`mkdir -p ${
|
|
6301
|
+
`mkdir -p ${path21.dirname(target)} && cp ${file2} ${target}`,
|
|
6200
6302
|
`systemctl --user daemon-reload && systemctl --user enable --now ${names.unit}`,
|
|
6201
6303
|
"loginctl enable-linger $USER # keeps it running when you are logged out",
|
|
6202
6304
|
`journalctl --user -u ${names.unit} -f # logs`
|
|
@@ -6216,17 +6318,17 @@ WantedBy=default.target
|
|
|
6216
6318
|
<key>${env.name}</key><string>${xml(env.value)}</string>
|
|
6217
6319
|
<key>PATH</key><string>${xml(servicePath(node))}</string>
|
|
6218
6320
|
</dict>
|
|
6219
|
-
<key>StandardOutPath</key><string>${xml(
|
|
6220
|
-
<key>StandardErrorPath</key><string>${xml(
|
|
6321
|
+
<key>StandardOutPath</key><string>${xml(path21.join(logs, "launchd.log"))}</string>
|
|
6322
|
+
<key>StandardErrorPath</key><string>${xml(path21.join(logs, "launchd.err"))}</string>
|
|
6221
6323
|
</dict></plist>
|
|
6222
6324
|
`;
|
|
6223
|
-
const file2 =
|
|
6224
|
-
|
|
6225
|
-
const target =
|
|
6226
|
-
return { file: file2, steps: [`cp ${file2} ${target}`, `launchctl bootstrap gui/$(id -u) ${target}`, `tail -f ${
|
|
6325
|
+
const file2 = path21.join(dir, `${names.label}.plist`);
|
|
6326
|
+
fs21.writeFileSync(file2, plist);
|
|
6327
|
+
const target = path21.join(home, "Library", "LaunchAgents", `${names.label}.plist`);
|
|
6328
|
+
return { file: file2, steps: [`cp ${file2} ${target}`, `launchctl bootstrap gui/$(id -u) ${target}`, `tail -f ${path21.join(logs, "launchd.log")}`] };
|
|
6227
6329
|
}
|
|
6228
|
-
const file =
|
|
6229
|
-
|
|
6330
|
+
const file = path21.join(dir, "monoclaw-host-task.ps1");
|
|
6331
|
+
fs21.writeFileSync(
|
|
6230
6332
|
file,
|
|
6231
6333
|
`$action = New-ScheduledTaskAction -Execute "${node}" -Argument '"${script}" start'
|
|
6232
6334
|
$trigger = New-ScheduledTaskTrigger -AtLogOn
|
|
@@ -6238,31 +6340,31 @@ Start-ScheduledTask -TaskName "${names.task}"
|
|
|
6238
6340
|
);
|
|
6239
6341
|
return { file, steps: [`powershell -ExecutionPolicy Bypass -File "${file}"`, `Get-ScheduledTask -TaskName "${names.task}"`] };
|
|
6240
6342
|
}
|
|
6241
|
-
var runSync = (cmd2,
|
|
6242
|
-
const r = spawnSync(cmd2,
|
|
6343
|
+
var runSync = (cmd2, args2) => {
|
|
6344
|
+
const r = spawnSync(cmd2, args2, { encoding: "utf8" });
|
|
6243
6345
|
return { status: r.status, stderr: String(r.stderr ?? "") };
|
|
6244
6346
|
};
|
|
6245
|
-
function installService(
|
|
6347
|
+
function installService(run3 = runSync) {
|
|
6246
6348
|
const r = serviceInstructions();
|
|
6247
|
-
const home =
|
|
6248
|
-
const must = (cmd2,
|
|
6249
|
-
const x =
|
|
6250
|
-
if (x.status !== 0) throw new Error(`${cmd2} ${
|
|
6349
|
+
const home = os7.homedir();
|
|
6350
|
+
const must = (cmd2, args2) => {
|
|
6351
|
+
const x = run3(cmd2, args2);
|
|
6352
|
+
if (x.status !== 0) throw new Error(`${cmd2} ${args2.join(" ")} failed: ${x.stderr.trim() || `exit ${x.status}`}`);
|
|
6251
6353
|
};
|
|
6252
6354
|
const names = serviceNames();
|
|
6253
6355
|
if (process.platform === "darwin") {
|
|
6254
|
-
const target =
|
|
6255
|
-
|
|
6256
|
-
|
|
6356
|
+
const target = path21.join(home, "Library", "LaunchAgents", `${names.label}.plist`);
|
|
6357
|
+
fs21.mkdirSync(path21.dirname(target), { recursive: true });
|
|
6358
|
+
fs21.copyFileSync(r.file, target);
|
|
6257
6359
|
const uid = String(process.getuid?.() ?? "");
|
|
6258
|
-
|
|
6360
|
+
run3("launchctl", ["bootout", `gui/${uid}/${names.label}`]);
|
|
6259
6361
|
must("launchctl", ["bootstrap", `gui/${uid}`, target]);
|
|
6260
|
-
return { file: r.file, target, notes: [`Logs: tail -f ${
|
|
6362
|
+
return { file: r.file, target, notes: [`Logs: tail -f ${path21.join(configDir(), "logs", "launchd.log")}`] };
|
|
6261
6363
|
}
|
|
6262
6364
|
if (process.platform === "linux") {
|
|
6263
|
-
const target =
|
|
6264
|
-
|
|
6265
|
-
|
|
6365
|
+
const target = path21.join(home, ".config", "systemd", "user", `${names.unit}.service`);
|
|
6366
|
+
fs21.mkdirSync(path21.dirname(target), { recursive: true });
|
|
6367
|
+
fs21.copyFileSync(r.file, target);
|
|
6266
6368
|
must("systemctl", ["--user", "daemon-reload"]);
|
|
6267
6369
|
must("systemctl", ["--user", "enable", "--now", names.unit]);
|
|
6268
6370
|
must("systemctl", ["--user", "restart", names.unit]);
|
|
@@ -6271,37 +6373,36 @@ function installService(run2 = runSync) {
|
|
|
6271
6373
|
must("powershell", ["-ExecutionPolicy", "Bypass", "-File", r.file]);
|
|
6272
6374
|
return { file: r.file, target: `Task Scheduler: ${names.task}`, notes: [`Check: Get-ScheduledTask -TaskName "${names.task}"`] };
|
|
6273
6375
|
}
|
|
6274
|
-
function uninstallService(
|
|
6275
|
-
const home =
|
|
6376
|
+
function uninstallService(run3 = runSync) {
|
|
6377
|
+
const home = os7.homedir();
|
|
6276
6378
|
const names = serviceNames();
|
|
6277
6379
|
if (process.platform === "darwin") {
|
|
6278
|
-
const target =
|
|
6279
|
-
|
|
6280
|
-
|
|
6380
|
+
const target = path21.join(home, "Library", "LaunchAgents", `${names.label}.plist`);
|
|
6381
|
+
run3("launchctl", ["bootout", `gui/${String(process.getuid?.() ?? "")}/${names.label}`]);
|
|
6382
|
+
fs21.rmSync(target, { force: true });
|
|
6281
6383
|
return target;
|
|
6282
6384
|
}
|
|
6283
6385
|
if (process.platform === "linux") {
|
|
6284
|
-
const target =
|
|
6285
|
-
|
|
6286
|
-
|
|
6287
|
-
|
|
6386
|
+
const target = path21.join(home, ".config", "systemd", "user", `${names.unit}.service`);
|
|
6387
|
+
run3("systemctl", ["--user", "disable", "--now", names.unit]);
|
|
6388
|
+
fs21.rmSync(target, { force: true });
|
|
6389
|
+
run3("systemctl", ["--user", "daemon-reload"]);
|
|
6288
6390
|
return target;
|
|
6289
6391
|
}
|
|
6290
|
-
|
|
6392
|
+
run3("powershell", ["-Command", `Unregister-ScheduledTask -TaskName "${names.task}" -Confirm:$false`]);
|
|
6291
6393
|
return `Task Scheduler: ${names.task}`;
|
|
6292
6394
|
}
|
|
6293
6395
|
|
|
6294
6396
|
// src/cli.ts
|
|
6295
|
-
import {
|
|
6296
|
-
import
|
|
6297
|
-
import os7 from "node:os";
|
|
6397
|
+
import { spawn as spawn5 } from "node:child_process";
|
|
6398
|
+
import os8 from "node:os";
|
|
6298
6399
|
async function readTokenFromStdin() {
|
|
6299
6400
|
let data = "";
|
|
6300
6401
|
for await (const chunk of process.stdin) data += chunk;
|
|
6301
6402
|
return data.split(/\r?\n/).map((l) => l.trim()).find((l) => l.length > 0) ?? "";
|
|
6302
6403
|
}
|
|
6303
6404
|
var program = new Command();
|
|
6304
|
-
program.name("monoclaw").description("
|
|
6405
|
+
program.name("monoclaw").description("MonoClaw machine: runs your agents, voices, transcription and images on this computer for your MonoClaw projects.").version(APP_VERSION).option("--profile <name>", "Which enrolment on this computer (one per space): `monoclaw --profile guestlab start`. Default: the first enrolment.").hook("preAction", () => {
|
|
6305
6406
|
const p = program.opts().profile;
|
|
6306
6407
|
if (p) process.env.MONOCLAW_PROFILE = assertProfileName(p);
|
|
6307
6408
|
});
|
|
@@ -6314,7 +6415,14 @@ async function confirm(question, fallback) {
|
|
|
6314
6415
|
const a = answer.trim().toLowerCase();
|
|
6315
6416
|
return a === "" ? fallback : a === "y" || a === "yes";
|
|
6316
6417
|
}
|
|
6317
|
-
program.command("
|
|
6418
|
+
program.command("connect [token]").description("Set this computer up in one go with the token from Add a machine in the app: install, connect, start in the background, check").option("--router <url>", "The MonoClaw server", DEFAULT_ROUTER).option("--no-service", "Don't start it in the background; run `monoclaw start` yourself afterwards").option("--root <path...>", "Folders agents may work in (default on a new computer: ~/command)").option("--name <name>", "Name shown in the app (default: this computer's name)").option("--from <package>", "Install this instead of the current version from npm").option("--insecure", "Allow an http:// server (development only)").action(async (token, opts) => {
|
|
6419
|
+
if (!token) {
|
|
6420
|
+
console.error("No token. Copy the whole command from Add a machine in MonoClaw: it ends with a one-time token.");
|
|
6421
|
+
process.exit(2);
|
|
6422
|
+
}
|
|
6423
|
+
process.exit(await connect({ token, router: opts.router, service: opts.service, root: opts.root, name: opts.name, from: opts.from, insecure: opts.insecure, profile: currentProfile() }));
|
|
6424
|
+
});
|
|
6425
|
+
program.command("enrol [token]").description("Connect this machine to your MonoClaw account with a token from Add a machine in the app").option("--router <url>", "The MonoClaw server", DEFAULT_ROUTER).option("--name <name>", "Name shown in the app (default: hostname)").option("--root <path...>", "Folders to expose (you can add more later with `roots add`)").option("--token-stdin", "Read the token from standard input instead of the command line (keeps it out of the process list)").option("--insecure", "Allow an http:// router (development only)").option("-y, --yes", "Don't ask: when this computer is already enrolled for another space, enrol it again under a new profile").action(async (tokenArg, opts) => {
|
|
6318
6426
|
const token = opts.tokenStdin || tokenArg === "-" ? await readTokenFromStdin() : tokenArg;
|
|
6319
6427
|
if (!token) {
|
|
6320
6428
|
console.error("No token. Pass it as an argument, or pipe it in with --token-stdin.");
|
|
@@ -6322,7 +6430,7 @@ program.command("enrol [token]").description("Connect this machine to your Monoc
|
|
|
6322
6430
|
}
|
|
6323
6431
|
const profiles = listProfiles();
|
|
6324
6432
|
const preview = await previewToken(opts.router, token, profiles.map((p) => p.config?.hostId ?? "").filter(Boolean), opts.insecure);
|
|
6325
|
-
const plan = planEnrol(preview, profiles, opts.router, { requestedProfile: currentProfile(), defaultName:
|
|
6433
|
+
const plan = planEnrol(preview, profiles, opts.router, { requestedProfile: currentProfile(), defaultName: os8.hostname() });
|
|
6326
6434
|
if (plan.action === "already") {
|
|
6327
6435
|
console.log(plan.message);
|
|
6328
6436
|
return;
|
|
@@ -6337,19 +6445,29 @@ program.command("enrol [token]").description("Connect this machine to your Monoc
|
|
|
6337
6445
|
}
|
|
6338
6446
|
if (plan.profile) process.env.MONOCLAW_PROFILE = assertProfileName(plan.profile);
|
|
6339
6447
|
const existing = loadConfig();
|
|
6340
|
-
const roots2 = opts.root?.map((r) =>
|
|
6448
|
+
const roots2 = opts.root?.map((r) => path22.resolve(r)) ?? existing?.roots ?? plan.copyRootsFrom ?? [];
|
|
6341
6449
|
const unsafe = roots2.filter((r) => rootExposesConfig(r, configDir()));
|
|
6342
6450
|
if (unsafe.length) {
|
|
6343
6451
|
console.error(`Not exposing ${unsafe.join(", ")}: it contains this host's config folder (${configDir()}), so agents could change the machine's MonoClaw settings or read its keys. Pass a folder inside it instead, such as --root ~/command.`);
|
|
6344
6452
|
process.exit(2);
|
|
6345
6453
|
}
|
|
6454
|
+
for (const r of opts.root ? roots2 : []) {
|
|
6455
|
+
if (fs22.existsSync(r)) continue;
|
|
6456
|
+
try {
|
|
6457
|
+
fs22.mkdirSync(r, { recursive: true });
|
|
6458
|
+
console.log(`Created ${r} for your agents to work in.`);
|
|
6459
|
+
} catch (e) {
|
|
6460
|
+
console.error(`Could not create ${r}: ${e.message}. Create it yourself, or add another folder with: ${cmd("roots add <folder>")}`);
|
|
6461
|
+
}
|
|
6462
|
+
}
|
|
6346
6463
|
const cfg = await enrol(token, opts.router, { name: opts.name ?? (plan.reason === "second-space" ? plan.nameHint ?? void 0 : void 0), roots: roots2, insecure: opts.insecure });
|
|
6347
6464
|
console.log(`Enrolled as "${cfg.name}"${cfg.spaceName ? ` in ${cfg.spaceName} (@${cfg.spaceHandle})` : ""}${currentProfile() ? ` under the profile "${currentProfile()}"` : ""}. Config saved to ${configPath()}.`);
|
|
6348
6465
|
if (plan.reason === "second-space") {
|
|
6349
|
-
|
|
6466
|
+
fs22.writeFileSync(pendingServicePath(), JSON.stringify({ profile: currentProfile(), at: (/* @__PURE__ */ new Date()).toISOString() }), { mode: 384 });
|
|
6350
6467
|
console.log(`This computer now runs one machine per space; its modules and Claude login are shared. The first enrolment is untouched.`);
|
|
6351
6468
|
}
|
|
6352
6469
|
if (!cfg.roots.length) console.log(`No folders exposed yet. Add one with: ${cmd("roots add ~/command")}`);
|
|
6470
|
+
if (process.env.MONOCLAW_CONNECT) return;
|
|
6353
6471
|
console.log(`
|
|
6354
6472
|
Next, run it (one of):
|
|
6355
6473
|
${cmd("service install")} in the background: starts now, at every login, and survives restarts
|
|
@@ -6431,7 +6549,7 @@ provider.command("add <name>").description("Add a Claude connection; an api_key
|
|
|
6431
6549
|
const { registry, accounts } = await makeContext(requireConfig());
|
|
6432
6550
|
const moduleId = opts.type === "api_key" ? "claude-api" : "claude-subscription";
|
|
6433
6551
|
if (!registry.isInstalled(moduleId)) await registry.add(moduleId).install;
|
|
6434
|
-
const folders = opts.folders?.map((f) =>
|
|
6552
|
+
const folders = opts.folders?.map((f) => path22.resolve(f.replace(/^~(?=$|\/)/, process.env.HOME ?? "")));
|
|
6435
6553
|
if (opts.type === "api_key") {
|
|
6436
6554
|
const id = await connectModule(registry, accounts, moduleId, io, { name, id: opts.id });
|
|
6437
6555
|
if (folders) accounts.upsert({ ...accounts.get(id), allowedFolders: folders });
|
|
@@ -6460,18 +6578,18 @@ var roots = program.command("roots").description("Folders this machine exposes t
|
|
|
6460
6578
|
roots.command("list").action(() => {
|
|
6461
6579
|
const cfg = requireConfig();
|
|
6462
6580
|
if (!cfg.roots.length) console.log("(none) \u2014 add one with: monoclaw roots add <path>");
|
|
6463
|
-
for (const r of cfg.roots) console.log(`${
|
|
6581
|
+
for (const r of cfg.roots) console.log(`${fs22.existsSync(r) ? "\u2713" : "\u2717 (missing)"} ${r}`);
|
|
6464
6582
|
});
|
|
6465
6583
|
roots.command("add <path...>").action((paths) => {
|
|
6466
6584
|
const cfg = requireConfig();
|
|
6467
6585
|
for (const p of paths) {
|
|
6468
|
-
const full =
|
|
6469
|
-
if (!
|
|
6586
|
+
const full = path22.resolve(p.replace(/^~(?=$|\/)/, process.env.HOME ?? ""));
|
|
6587
|
+
if (!fs22.existsSync(full) || !fs22.statSync(full).isDirectory()) {
|
|
6470
6588
|
console.error(`not a folder: ${full}`);
|
|
6471
6589
|
continue;
|
|
6472
6590
|
}
|
|
6473
6591
|
if (rootExposesConfig(full, configDir())) {
|
|
6474
|
-
console.error(`not adding ${full}: it contains this host's config folder (${configDir()}), so agents could change the machine's MonoClaw settings or read its keys. Add a folder inside it, such as ${
|
|
6592
|
+
console.error(`not adding ${full}: it contains this host's config folder (${configDir()}), so agents could change the machine's MonoClaw settings or read its keys. Add a folder inside it, such as ${path22.join(full, "command")}.`);
|
|
6475
6593
|
process.exitCode = 1;
|
|
6476
6594
|
continue;
|
|
6477
6595
|
}
|
|
@@ -6484,7 +6602,7 @@ Restart the host for the change to reach the app.`);
|
|
|
6484
6602
|
});
|
|
6485
6603
|
roots.command("remove <path>").action((p) => {
|
|
6486
6604
|
const cfg = requireConfig();
|
|
6487
|
-
const full =
|
|
6605
|
+
const full = path22.resolve(p);
|
|
6488
6606
|
cfg.roots = cfg.roots.filter((r) => r !== full);
|
|
6489
6607
|
saveConfig(cfg);
|
|
6490
6608
|
console.log(`Exposed folders: ${cfg.roots.join(", ") || "(none)"}`);
|
|
@@ -6513,11 +6631,11 @@ program.command("start").description("Run the host and stay connected to the rou
|
|
|
6513
6631
|
assertRouterUrl(loaded.routerUrl, loaded.allowInsecure);
|
|
6514
6632
|
const lock = acquireRunLock(configDir());
|
|
6515
6633
|
if (!lock.ok) {
|
|
6516
|
-
console.error(`MonoClaw is already running for this machine (pid ${lock.pid}). Stop it first (\`monoclaw service
|
|
6634
|
+
console.error(`MonoClaw is already running for this machine (pid ${lock.pid}). Stop it first (\`monoclaw service uninstall\` for the background service, or close the terminal it runs in), or use another --profile. If no host is running, delete ${lock.file}.`);
|
|
6517
6635
|
process.exit(1);
|
|
6518
6636
|
}
|
|
6519
6637
|
process.on("exit", lock.release);
|
|
6520
|
-
setLogDir(
|
|
6638
|
+
setLogDir(path22.join(configDir(), "logs"));
|
|
6521
6639
|
const unsafe = loaded.roots.filter((r) => rootExposesConfig(r, configDir()));
|
|
6522
6640
|
for (const r of unsafe) log("error", `not exposing ${r}: it contains this host's config folder (${configDir()}). Expose a folder inside it instead (\`monoclaw roots remove ${r}\`, then \`monoclaw roots add <folder>\`).`);
|
|
6523
6641
|
const cfg = unsafe.length ? { ...loaded, roots: loaded.roots.filter((r) => !unsafe.includes(r)) } : loaded;
|
|
@@ -6526,7 +6644,7 @@ program.command("start").description("Run the host and stay connected to the rou
|
|
|
6526
6644
|
const repaired = await repairBundledCli();
|
|
6527
6645
|
if (repaired.outcome !== "present") log(repaired.outcome === "installed" ? "info" : "warn", `Claude Code copy: ${repaired.detail}`);
|
|
6528
6646
|
const cli = await resolveCli();
|
|
6529
|
-
log(cli ? "info" : "error", cli ? `Claude Code: ${describeCli(cli)}` : "Claude Code: not found; sessions will fail until `monoclaw doctor`
|
|
6647
|
+
log(cli ? "info" : "error", cli ? `Claude Code: ${describeCli(cli)}` : "Claude Code: not found; sessions will fail until `monoclaw doctor` fixes it");
|
|
6530
6648
|
const { accounts, registry } = await makeContext(cfg);
|
|
6531
6649
|
log("info", `modules: ${registry.installedIds().join(", ") || "(none)"}; ${accounts.list().length} connection(s) (secrets in the ${accounts.store.kind} store)`);
|
|
6532
6650
|
const client = new HostClient(cfg, providers, { accounts, registry });
|
|
@@ -6557,10 +6675,27 @@ program.command("start").description("Run the host and stay connected to the rou
|
|
|
6557
6675
|
process.on("SIGINT", shutdown);
|
|
6558
6676
|
process.on("SIGTERM", shutdown);
|
|
6559
6677
|
});
|
|
6678
|
+
async function runClaude(rest) {
|
|
6679
|
+
const cli = await resolveCli();
|
|
6680
|
+
if (!cli) {
|
|
6681
|
+
console.error("No Claude Code on this machine yet. Run `monoclaw doctor`: it installs the copy MonoClaw uses.");
|
|
6682
|
+
process.exit(1);
|
|
6683
|
+
}
|
|
6684
|
+
const code = await new Promise((resolve) => {
|
|
6685
|
+
const child = spawn5(cli.path, rest, { stdio: "inherit", env: cleanEnv() });
|
|
6686
|
+
child.on("error", (e) => {
|
|
6687
|
+
console.error(`Could not run ${cli.path}: ${e.message}`);
|
|
6688
|
+
resolve(1);
|
|
6689
|
+
});
|
|
6690
|
+
child.on("exit", (c) => resolve(c ?? 1));
|
|
6691
|
+
});
|
|
6692
|
+
process.exit(code);
|
|
6693
|
+
}
|
|
6694
|
+
program.command("claude").description("Run the Claude Code this machine uses, with whatever follows: `monoclaw claude auth login` signs it in, `monoclaw claude auth status` shows who is signed in").allowUnknownOption(true).allowExcessArguments(true).helpOption(false).action(() => runClaude(process.argv.slice(process.argv.indexOf("claude", 2) + 1)));
|
|
6560
6695
|
program.command("doctor").description("Check and repair what a working host needs: Node, the host's copy of Claude Code, your Claude login, folders, the service").option("--no-repair", "Only report; do not install anything").action(async (opts) => {
|
|
6561
6696
|
const lines = [];
|
|
6562
6697
|
const major = Number(process.versions.node.split(".")[0]);
|
|
6563
|
-
lines.push({ ok: major >= 22, what: `Node ${process.versions.node}`, fix: major >= 22 ? void 0 :
|
|
6698
|
+
lines.push({ ok: major >= 22, what: `Node ${process.versions.node}`, fix: major >= 22 ? void 0 : nodeInstallHint(process.platform) });
|
|
6564
6699
|
const mode = detectInstallMode();
|
|
6565
6700
|
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 });
|
|
6566
6701
|
forgetCli();
|
|
@@ -6574,27 +6709,26 @@ program.command("doctor").description("Check and repair what a working host need
|
|
|
6574
6709
|
const pkg = platformPackages()[0];
|
|
6575
6710
|
lines.push({ ok: !!bundled, what: bundled ? `Host's copy of Claude Code: ${bundled} (${await cliVersion(bundled, cleanEnv()) ?? "version unknown"})${repairNote}` : `Host's copy of Claude Code is missing (${pkg}@${sdkVersion()})${repairNote}`, fix: bundled ? void 0 : `npm install -g ${pkg}@${sdkVersion()} (or set ${CLI_PATH_ENV} to a Claude Code executable)` });
|
|
6576
6711
|
const onPath2 = await cliOnPath();
|
|
6577
|
-
lines.push({ ok: !!onPath2, what: onPath2 ? `Claude Code on the PATH: ${onPath2} (${await cliVersion(onPath2, cleanEnv()) ?? "version unknown"})` : "Claude Code is not
|
|
6712
|
+
lines.push({ ok: !!onPath2, info: true, what: onPath2 ? `Claude Code on the PATH: ${onPath2} (${await cliVersion(onPath2, cleanEnv()) ?? "version unknown"})` : "Claude Code is not installed separately (fine: MonoClaw uses its own copy)" });
|
|
6578
6713
|
const cli = await resolveCli();
|
|
6579
6714
|
if (cli) {
|
|
6580
6715
|
try {
|
|
6581
|
-
const
|
|
6582
|
-
|
|
6583
|
-
lines.push({ ok: !!j.loggedIn, what: j.loggedIn ? `Logged in to Claude (${j.authMethod ?? "ok"}) via ${describeCli(cli)}` : "Not logged in to Claude", fix: j.loggedIn ? void 0 : "Run `claude login` on this machine (or set CLAUDE_CODE_OAUTH_TOKEN from `claude setup-token`)" });
|
|
6716
|
+
const j = await authStatus(cli.path, cleanEnv());
|
|
6717
|
+
lines.push({ ok: j.loggedIn, what: j.loggedIn ? `Logged in to Claude (${j.authMethod ?? "ok"}) via ${describeCli(cli)}` : "Not logged in to Claude", fix: j.loggedIn ? void 0 : SIGN_IN_ACTION });
|
|
6584
6718
|
} catch (e) {
|
|
6585
|
-
lines.push({ ok: false, what: `Could not check the Claude login: ${e.message.slice(0, 120)}`, fix: "Run `claude auth status` on this machine" });
|
|
6719
|
+
lines.push({ ok: false, what: `Could not check the Claude login: ${e.message.slice(0, 120)}`, fix: "Run `monoclaw claude auth status` on this machine" });
|
|
6586
6720
|
}
|
|
6587
|
-
} else lines.push({ ok: false, what: "No Claude Code to run sessions with", fix: "
|
|
6721
|
+
} else lines.push({ ok: false, what: "No Claude Code to run sessions with", fix: "Run `monoclaw doctor` again; if the copy still can't be installed, install Claude Code from https://claude.com/claude-code" });
|
|
6588
6722
|
const cfg = loadConfig();
|
|
6589
6723
|
if (!cfg) lines.push({ ok: false, info: true, what: "Not enrolled yet", fix: "monoclaw enrol <token> --router <url> --root ~/command (the token comes from Add a machine in the app)" });
|
|
6590
6724
|
else {
|
|
6591
6725
|
lines.push({ ok: true, what: `Enrolled as "${cfg.name}" with ${cfg.routerUrl}` });
|
|
6592
|
-
const missing = cfg.roots.filter((r) => !
|
|
6726
|
+
const missing = cfg.roots.filter((r) => !fs22.existsSync(r));
|
|
6593
6727
|
const exposing = cfg.roots.filter((r) => rootExposesConfig(r, configDir()));
|
|
6594
6728
|
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>` });
|
|
6595
6729
|
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 });
|
|
6596
|
-
const unit = process.platform === "darwin" ?
|
|
6597
|
-
if (unit) lines.push({ ok:
|
|
6730
|
+
const unit = process.platform === "darwin" ? path22.join(os8.homedir(), "Library", "LaunchAgents", "ai.monoclaw.host.plist") : process.platform === "linux" ? path22.join(os8.homedir(), ".config", "systemd", "user", "monoclaw.service") : null;
|
|
6731
|
+
if (unit) lines.push({ ok: fs22.existsSync(unit), info: true, what: fs22.existsSync(unit) ? `Background service installed (${unit})` : "Not running as a background service (fine for now)", fix: fs22.existsSync(unit) ? void 0 : "monoclaw service install to run at login" });
|
|
6598
6732
|
const { registry } = await makeContext(cfg);
|
|
6599
6733
|
await registry.refreshReadiness();
|
|
6600
6734
|
const reports = registry.reports();
|
|
@@ -6669,16 +6803,16 @@ config.command("set <key> <value>").description("Keys: allowedPermissionModes (c
|
|
|
6669
6803
|
});
|
|
6670
6804
|
var service = program.command("service").description("Run the host in the background at login");
|
|
6671
6805
|
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) => {
|
|
6672
|
-
if (!currentProfile() &&
|
|
6806
|
+
if (!currentProfile() && fs22.existsSync(pendingServicePath())) {
|
|
6673
6807
|
try {
|
|
6674
|
-
const pending = JSON.parse(
|
|
6808
|
+
const pending = JSON.parse(fs22.readFileSync(pendingServicePath(), "utf8"));
|
|
6675
6809
|
if (pending.profile && Date.now() - Date.parse(pending.at ?? "") < 60 * 6e4) {
|
|
6676
6810
|
process.env.MONOCLAW_PROFILE = assertProfileName(pending.profile);
|
|
6677
6811
|
console.log(`Installing the service for the profile "${pending.profile}" (the enrolment just made). The first enrolment's service is untouched.`);
|
|
6678
6812
|
}
|
|
6679
6813
|
} catch {
|
|
6680
6814
|
}
|
|
6681
|
-
|
|
6815
|
+
fs22.rmSync(pendingServicePath(), { force: true });
|
|
6682
6816
|
}
|
|
6683
6817
|
requireConfig();
|
|
6684
6818
|
if (o.print) {
|
|
@@ -6694,7 +6828,12 @@ ${r2.steps.map((s) => ` ${s}`).join("\n")}
|
|
|
6694
6828
|
${r.notes.map((n) => ` ${n}`).join("\n")}` : ""}`);
|
|
6695
6829
|
});
|
|
6696
6830
|
service.command("uninstall").description("Stop and remove the background service").action(() => console.log(`Background service stopped and removed (${uninstallService()}).`));
|
|
6697
|
-
|
|
6831
|
+
var args = process.argv.slice(2);
|
|
6832
|
+
var first = args[0] === "--profile" ? 2 : 0;
|
|
6833
|
+
if (args[first] === "claude") {
|
|
6834
|
+
if (first) process.env.MONOCLAW_PROFILE = assertProfileName(args[1] ?? "");
|
|
6835
|
+
void runClaude(args.slice(first + 1));
|
|
6836
|
+
} else program.parseAsync(process.argv).catch((e) => {
|
|
6698
6837
|
console.error(e instanceof Error ? e.message : String(e));
|
|
6699
6838
|
process.exit(1);
|
|
6700
6839
|
});
|