@monoclaw/machine 1.0.3 → 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 +519 -385
- 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,247 +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
|
|
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";
|
|
5162
5473
|
import { z as z9 } from "zod";
|
|
5163
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
|
-
function nodeInstallHint(platform) {
|
|
5179
|
-
if (platform === "darwin") return "Install Node 22 or newer: `brew install node`, or the LTS installer from https://nodejs.org";
|
|
5180
|
-
if (platform === "win32") return "Install Node 22 or newer: `winget install OpenJS.NodeJS.LTS`, or the LTS installer from https://nodejs.org";
|
|
5181
|
-
return "Install Node 22 or newer with nvm (no sudo): https://github.com/nvm-sh/nvm#installing-and-updating then `nvm install 22`";
|
|
5182
|
-
}
|
|
5183
|
-
var CHECK_EVERY_MS = 6 * 60 * 6e4;
|
|
5184
|
-
var RETRY_WHEN_BUSY_MS = 10 * 6e4;
|
|
5185
|
-
var INSTALL_TIMEOUT_MS = 5 * 6e4;
|
|
5186
|
-
var VersionPolicy = z8.object({ package: z8.string(), latest: z8.string().nullable(), minimum: z8.string().nullable() });
|
|
5187
|
-
function detectInstallMode(entry = process.argv[1] ?? "") {
|
|
5188
|
-
let real = entry;
|
|
5189
|
-
try {
|
|
5190
|
-
real = fs17.realpathSync(entry);
|
|
5191
|
-
} catch {
|
|
5192
|
-
}
|
|
5193
|
-
const p = real.replace(/\\/g, "/");
|
|
5194
|
-
if (/[\\/]node_modules[\\/]@monoclaw[\\/]machine[\\/]/.test(p)) return "npm-global";
|
|
5195
|
-
if (p.endsWith(".ts") || /\/apps\/host\//.test(p)) return "checkout";
|
|
5196
|
-
return "unknown";
|
|
5197
|
-
}
|
|
5198
|
-
function installedVersion(entry = process.argv[1] ?? "") {
|
|
5199
|
-
let real = entry;
|
|
5200
|
-
try {
|
|
5201
|
-
real = fs17.realpathSync(entry);
|
|
5202
|
-
} catch {
|
|
5203
|
-
}
|
|
5204
|
-
const m = /^(.*[\\/]node_modules[\\/]@monoclaw[\\/]machine)[\\/]/.exec(real);
|
|
5205
|
-
if (!m) return null;
|
|
5206
|
-
try {
|
|
5207
|
-
return JSON.parse(fs17.readFileSync(path17.join(m[1], "package.json"), "utf8")).version ?? null;
|
|
5208
|
-
} catch {
|
|
5209
|
-
return null;
|
|
5210
|
-
}
|
|
5211
|
-
}
|
|
5212
|
-
var LOCK_STALE_MS = 15 * 6e4;
|
|
5213
|
-
async function withUpdateLock(fn, opts = {}) {
|
|
5214
|
-
const dir = opts.dir ?? sharedDir();
|
|
5215
|
-
fs17.mkdirSync(dir, { recursive: true });
|
|
5216
|
-
const file = path17.join(dir, "update.lock");
|
|
5217
|
-
const deadline = Date.now() + (opts.waitMs ?? INSTALL_TIMEOUT_MS);
|
|
5218
|
-
for (; ; ) {
|
|
5219
|
-
try {
|
|
5220
|
-
fs17.writeFileSync(file, JSON.stringify({ pid: process.pid, at: (/* @__PURE__ */ new Date()).toISOString() }), { flag: "wx" });
|
|
5221
|
-
break;
|
|
5222
|
-
} catch (e) {
|
|
5223
|
-
if (e.code !== "EEXIST") throw e;
|
|
5224
|
-
let stale = false;
|
|
5225
|
-
try {
|
|
5226
|
-
stale = Date.now() - fs17.statSync(file).mtimeMs > LOCK_STALE_MS;
|
|
5227
|
-
} catch {
|
|
5228
|
-
continue;
|
|
5229
|
-
}
|
|
5230
|
-
if (stale) {
|
|
5231
|
-
fs17.rmSync(file, { force: true });
|
|
5232
|
-
continue;
|
|
5233
|
-
}
|
|
5234
|
-
if (Date.now() > deadline) throw new Error("another MonoClaw host on this computer has been updating for too long; try again later");
|
|
5235
|
-
await new Promise((r) => setTimeout(r, opts.pollMs ?? 2e3));
|
|
5236
|
-
}
|
|
5237
|
-
}
|
|
5238
|
-
try {
|
|
5239
|
-
return await fn();
|
|
5240
|
-
} finally {
|
|
5241
|
-
fs17.rmSync(file, { force: true });
|
|
5242
|
-
}
|
|
5243
|
-
}
|
|
5244
|
-
function decideUpdate(current, policy, mode, opts) {
|
|
5245
|
-
const min = policy.minimum && isVersion(policy.minimum) ? policy.minimum : null;
|
|
5246
|
-
const latest = policy.latest && isVersion(policy.latest) ? policy.latest : null;
|
|
5247
|
-
const belowMin = !!min && compareVersions(current, min) < 0;
|
|
5248
|
-
const belowLatest = !!latest && compareVersions(current, latest) < 0;
|
|
5249
|
-
if (belowMin) {
|
|
5250
|
-
const to = latest && compareVersions(latest, min) > 0 ? latest : min;
|
|
5251
|
-
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}` };
|
|
5252
|
-
return { action: "update", to, required: true };
|
|
5253
|
-
}
|
|
5254
|
-
if (belowLatest && !opts.disabled && mode === "npm-global") return { action: "update", to: latest, required: false };
|
|
5255
|
-
return { action: "none" };
|
|
5256
|
-
}
|
|
5257
|
-
async function fetchPolicy(routerUrl) {
|
|
5258
|
-
try {
|
|
5259
|
-
const res = await fetch(`${routerUrl.replace(/\/+$/, "")}/v1/host/version`, { signal: AbortSignal.timeout(1e4) });
|
|
5260
|
-
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
5261
|
-
const json = await res.json();
|
|
5262
|
-
return VersionPolicy.parse(json.data ?? json);
|
|
5263
|
-
} catch (e) {
|
|
5264
|
-
log("warn", `could not read the router's host version policy: ${e.message}`);
|
|
5265
|
-
return null;
|
|
5266
|
-
}
|
|
5267
|
-
}
|
|
5268
|
-
function installSpec(version, source, routerUrl) {
|
|
5269
|
-
if (!isVersion(version)) return null;
|
|
5270
|
-
if (!/^https?:\/\//.test(source)) return source === PACKAGE ? `${PACKAGE}@${version}` : null;
|
|
5271
|
-
let router;
|
|
5272
|
-
let src;
|
|
5273
|
-
try {
|
|
5274
|
-
router = new URL(routerUrl);
|
|
5275
|
-
src = new URL(source);
|
|
5276
|
-
} catch {
|
|
5277
|
-
return null;
|
|
5278
|
-
}
|
|
5279
|
-
if (src.origin !== router.origin || src.pathname.replace(/\/+$/, "") !== "/downloads/host") return null;
|
|
5280
|
-
return `${src.origin}/downloads/host/monoclaw-machine-${version}.tgz`;
|
|
5281
|
-
}
|
|
5282
|
-
function installVersion(version, source = PACKAGE, routerUrl = "") {
|
|
5283
|
-
const spec = installSpec(version, source, routerUrl);
|
|
5284
|
-
if (!spec) return Promise.reject(new Error(`refusing to install ${version} from "${source}"`));
|
|
5285
|
-
return npmInstallGlobal(spec);
|
|
5286
|
-
}
|
|
5287
|
-
var npmInstallArgs2 = (spec) => ["install", "-g", spec, "--ignore-scripts", "--no-fund", "--no-audit", "--loglevel=error"];
|
|
5288
|
-
function npmInstallGlobal(spec) {
|
|
5289
|
-
if (!/^@?[\w./-]+@[\w.-]+$/.test(spec) && !/^https?:\/\/[\w.:-]+\/downloads\/host\/monoclaw-machine-[\w.-]+\.tgz$/.test(spec)) return Promise.reject(new Error(`refusing to install "${spec}"`));
|
|
5290
|
-
const npm = process.platform === "win32" ? "npm.cmd" : "npm";
|
|
5291
|
-
const args = npmInstallArgs2(spec);
|
|
5292
|
-
return new Promise((resolve, reject) => {
|
|
5293
|
-
const child = spawn3(npm, args, { stdio: ["ignore", "pipe", "pipe"], shell: process.platform === "win32", env: { ...process.env, npm_config_update_notifier: "false" } });
|
|
5294
|
-
let out = "";
|
|
5295
|
-
child.stdout.on("data", (d) => out += d);
|
|
5296
|
-
child.stderr.on("data", (d) => out += d);
|
|
5297
|
-
const timer = setTimeout(() => {
|
|
5298
|
-
child.kill();
|
|
5299
|
-
reject(new Error("npm install timed out after 5 minutes"));
|
|
5300
|
-
}, INSTALL_TIMEOUT_MS);
|
|
5301
|
-
child.on("error", (e) => {
|
|
5302
|
-
clearTimeout(timer);
|
|
5303
|
-
reject(new Error(`could not run npm: ${e.message}`));
|
|
5304
|
-
});
|
|
5305
|
-
child.on("exit", (code) => {
|
|
5306
|
-
clearTimeout(timer);
|
|
5307
|
-
if (code === 0) resolve();
|
|
5308
|
-
else reject(new Error(`npm install exited with ${code}: ${out.trim().slice(-600)}`));
|
|
5309
|
-
});
|
|
5310
|
-
});
|
|
5311
|
-
}
|
|
5312
|
-
var REEXEC_ENV = "MONOCLAW_REEXEC";
|
|
5313
|
-
var REEXEC_FROM_ENV = "MONOCLAW_REEXEC_FROM";
|
|
5314
|
-
function settleReexec(env = process.env, running = APP_VERSION) {
|
|
5315
|
-
const from = env[REEXEC_FROM_ENV];
|
|
5316
|
-
if (from && from !== running) {
|
|
5317
|
-
delete env[REEXEC_ENV];
|
|
5318
|
-
delete env[REEXEC_FROM_ENV];
|
|
5319
|
-
}
|
|
5320
|
-
}
|
|
5321
|
-
function reexec() {
|
|
5322
|
-
const hops = Number(process.env[REEXEC_ENV] ?? "0");
|
|
5323
|
-
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`));
|
|
5324
|
-
return new Promise(() => {
|
|
5325
|
-
const child = spawn3(process.execPath, process.argv.slice(1), { stdio: "inherit", env: { ...process.env, [REEXEC_ENV]: String(hops + 1), [REEXEC_FROM_ENV]: APP_VERSION } });
|
|
5326
|
-
child.on("exit", (code, signal) => process.exit(code ?? (signal ? 1 : 0)));
|
|
5327
|
-
child.on("error", (e) => {
|
|
5328
|
-
log("error", `could not restart after update: ${e.message}`);
|
|
5329
|
-
process.exit(1);
|
|
5330
|
-
});
|
|
5331
|
-
});
|
|
5332
|
-
}
|
|
5333
|
-
var updatesDisabled = () => process.env.MONOCLAW_NO_UPDATE === "1";
|
|
5334
|
-
async function ensureUpToDate(routerUrl, opts) {
|
|
5335
|
-
settleReexec();
|
|
5336
|
-
const policy = await fetchPolicy(routerUrl);
|
|
5337
|
-
if (!policy) return "ok";
|
|
5338
|
-
const d = decideUpdate(APP_VERSION, policy, opts.mode ?? detectInstallMode(), { disabled: updatesDisabled() });
|
|
5339
|
-
if (d.action === "none") return "ok";
|
|
5340
|
-
if (d.action === "block") throw new Error(d.reason);
|
|
5341
|
-
log("info", `${d.required ? "update required" : "update available"} (${opts.reason}): ${APP_VERSION} \u2192 ${d.to}; installing`);
|
|
5342
|
-
try {
|
|
5343
|
-
await withUpdateLock(async () => {
|
|
5344
|
-
if (installedVersion() === d.to) {
|
|
5345
|
-
log("info", `${PACKAGE} ${d.to} is already installed on this computer (by another profile); restarting onto it`);
|
|
5346
|
-
return;
|
|
5347
|
-
}
|
|
5348
|
-
await (opts.install ?? installVersion)(d.to, policy.package, routerUrl);
|
|
5349
|
-
});
|
|
5350
|
-
} catch (e) {
|
|
5351
|
-
if (d.required) throw e;
|
|
5352
|
-
log("warn", `update to ${d.to} failed, carrying on with ${APP_VERSION}: ${e.message}`);
|
|
5353
|
-
return "ok";
|
|
5354
|
-
}
|
|
5355
|
-
log("info", `installed ${PACKAGE} ${d.to}`);
|
|
5356
|
-
await opts.afterInstall?.();
|
|
5357
|
-
log("info", "restarting");
|
|
5358
|
-
await opts.onBeforeRestart?.();
|
|
5359
|
-
await reexec();
|
|
5360
|
-
return "ok";
|
|
5361
|
-
}
|
|
5362
|
-
function startPeriodicChecks(routerUrl, hooks) {
|
|
5363
|
-
let timer = null;
|
|
5364
|
-
const schedule = (ms) => {
|
|
5365
|
-
if (timer) clearTimeout(timer);
|
|
5366
|
-
timer = setTimeout(tick, ms);
|
|
5367
|
-
timer.unref();
|
|
5368
|
-
};
|
|
5369
|
-
const tick = async () => {
|
|
5370
|
-
try {
|
|
5371
|
-
const policy = await fetchPolicy(routerUrl);
|
|
5372
|
-
const d = policy ? decideUpdate(APP_VERSION, policy, detectInstallMode(), { disabled: updatesDisabled() }) : { action: "none" };
|
|
5373
|
-
if (d.action === "update") {
|
|
5374
|
-
if (hooks.isBusy()) {
|
|
5375
|
-
log("info", `update to ${d.to} is waiting for the current turn to finish`);
|
|
5376
|
-
return schedule(RETRY_WHEN_BUSY_MS);
|
|
5377
|
-
}
|
|
5378
|
-
await ensureUpToDate(routerUrl, { reason: "periodic check", onBeforeRestart: hooks.onBeforeRestart, afterInstall: hooks.afterInstall });
|
|
5379
|
-
return;
|
|
5380
|
-
}
|
|
5381
|
-
if (d.action === "block") hooks.onError(new Error(d.reason));
|
|
5382
|
-
} catch (e) {
|
|
5383
|
-
hooks.onError(e);
|
|
5384
|
-
}
|
|
5385
|
-
schedule(CHECK_EVERY_MS);
|
|
5386
|
-
};
|
|
5387
|
-
schedule(CHECK_EVERY_MS);
|
|
5388
|
-
return {
|
|
5389
|
-
stop: () => {
|
|
5390
|
-
if (timer) clearTimeout(timer);
|
|
5391
|
-
},
|
|
5392
|
-
checkSoon: () => schedule(5e3 + Math.floor(Math.random() * 25e3))
|
|
5393
|
-
};
|
|
5394
|
-
}
|
|
5395
|
-
|
|
5396
|
-
// src/providers/claude/cli.ts
|
|
5397
|
-
var execFileP5 = promisify5(execFile5);
|
|
5480
|
+
import path19 from "node:path";
|
|
5481
|
+
import { promisify as promisify6 } from "node:util";
|
|
5482
|
+
var execFileP5 = promisify6(execFile6);
|
|
5398
5483
|
var SDK = "@anthropic-ai/claude-agent-sdk";
|
|
5399
5484
|
var CLI_PATH_ENV = "MONOCLAW_CLAUDE_PATH";
|
|
5400
5485
|
function isMusl() {
|
|
@@ -5404,7 +5489,7 @@ function isMusl() {
|
|
|
5404
5489
|
if (header && "glibcVersionRuntime" in header) return !header.glibcVersionRuntime;
|
|
5405
5490
|
} catch {
|
|
5406
5491
|
}
|
|
5407
|
-
return
|
|
5492
|
+
return fs19.existsSync("/etc/alpine-release");
|
|
5408
5493
|
}
|
|
5409
5494
|
function platformPackages(platform = process.platform, arch = process.arch, musl = isMusl()) {
|
|
5410
5495
|
const base = `${SDK}-`;
|
|
@@ -5414,24 +5499,24 @@ function platformPackages(platform = process.platform, arch = process.arch, musl
|
|
|
5414
5499
|
}
|
|
5415
5500
|
var exe = (platform = process.platform) => platform === "win32" ? "claude.exe" : "claude";
|
|
5416
5501
|
function sdkRoot() {
|
|
5417
|
-
let dir =
|
|
5502
|
+
let dir = path19.dirname(createRequire3(import.meta.url).resolve(SDK));
|
|
5418
5503
|
for (let i = 0; i < 6; i++) {
|
|
5419
|
-
const pkg =
|
|
5504
|
+
const pkg = path19.join(dir, "package.json");
|
|
5420
5505
|
try {
|
|
5421
|
-
if (JSON.parse(
|
|
5506
|
+
if (JSON.parse(fs19.readFileSync(pkg, "utf8")).name === SDK) return dir;
|
|
5422
5507
|
} catch {
|
|
5423
5508
|
}
|
|
5424
|
-
dir =
|
|
5509
|
+
dir = path19.dirname(dir);
|
|
5425
5510
|
}
|
|
5426
5511
|
throw new Error(`could not find where ${SDK} is installed`);
|
|
5427
5512
|
}
|
|
5428
5513
|
function sdkResolve() {
|
|
5429
|
-
return createRequire3(
|
|
5514
|
+
return createRequire3(path19.join(sdkRoot(), "package.json")).resolve;
|
|
5430
5515
|
}
|
|
5431
5516
|
function sdkVersion() {
|
|
5432
|
-
return JSON.parse(
|
|
5517
|
+
return JSON.parse(fs19.readFileSync(path19.join(sdkRoot(), "package.json"), "utf8")).version;
|
|
5433
5518
|
}
|
|
5434
|
-
function bundledCli(resolve = sdkResolve(), exists =
|
|
5519
|
+
function bundledCli(resolve = sdkResolve(), exists = fs19.existsSync, platform = process.platform, arch = process.arch) {
|
|
5435
5520
|
for (const pkg of platformPackages(platform, arch)) {
|
|
5436
5521
|
try {
|
|
5437
5522
|
const p = resolve(`${pkg}/${exe(platform)}`);
|
|
@@ -5453,8 +5538,8 @@ async function cliOnPath(env = process.env) {
|
|
|
5453
5538
|
const which = process.platform === "win32" ? "where" : "which";
|
|
5454
5539
|
try {
|
|
5455
5540
|
const { stdout } = await execFileP5(which, ["claude"], { env, timeout: 1e4 });
|
|
5456
|
-
const
|
|
5457
|
-
return
|
|
5541
|
+
const first2 = stdout.split(/\r?\n/).map((l) => l.trim()).find(Boolean);
|
|
5542
|
+
return first2 ?? null;
|
|
5458
5543
|
} catch {
|
|
5459
5544
|
return null;
|
|
5460
5545
|
}
|
|
@@ -5470,7 +5555,7 @@ function resolveCli(deps = {}) {
|
|
|
5470
5555
|
}
|
|
5471
5556
|
async function resolveUncached(deps) {
|
|
5472
5557
|
const env = deps.env ?? process.env;
|
|
5473
|
-
const exists = deps.exists ??
|
|
5558
|
+
const exists = deps.exists ?? fs19.existsSync;
|
|
5474
5559
|
const version = deps.version ?? ((f) => cliVersion(f, env));
|
|
5475
5560
|
const override = env[CLI_PATH_ENV]?.trim();
|
|
5476
5561
|
if (override) {
|
|
@@ -5487,7 +5572,20 @@ function describeCli(c) {
|
|
|
5487
5572
|
const v = c.version ?? "version unknown";
|
|
5488
5573
|
return c.kind === "bundled" ? `bundled ${v}` : c.kind === "path" ? `PATH ${v} (${c.path})` : `${CLI_PATH_ENV} ${v} (${c.path})`;
|
|
5489
5574
|
}
|
|
5490
|
-
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
|
+
}
|
|
5491
5589
|
async function repairBundledCli(deps = {}) {
|
|
5492
5590
|
const bundled = deps.bundled ?? (() => bundledCli());
|
|
5493
5591
|
if (bundled()) return { outcome: "present", detail: "the host's copy of Claude Code is installed" };
|
|
@@ -5515,7 +5613,7 @@ async function repairBundledCli(deps = {}) {
|
|
|
5515
5613
|
}
|
|
5516
5614
|
|
|
5517
5615
|
// src/providers/claude/index.ts
|
|
5518
|
-
var execFileP6 =
|
|
5616
|
+
var execFileP6 = promisify7(execFile7);
|
|
5519
5617
|
var PERMISSION_MODES = ["auto", "acceptEdits", "default", "plan", "bypassPermissions"];
|
|
5520
5618
|
var SESSION_SETTING_SOURCES = ["user", "project", "local"];
|
|
5521
5619
|
var APPROVAL_TIMEOUT_MS = 10 * 6e4;
|
|
@@ -5551,9 +5649,9 @@ function withOverrides(base, over) {
|
|
|
5551
5649
|
return out;
|
|
5552
5650
|
}
|
|
5553
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.";
|
|
5554
|
-
function sendToolResult(
|
|
5652
|
+
function sendToolResult(args2, r) {
|
|
5555
5653
|
if (r.error) return { content: [{ type: "text", text: r.error }], isError: true };
|
|
5556
|
-
return { content: [{ type: "text", text: r.text ?? `Sent to ${
|
|
5654
|
+
return { content: [{ type: "text", text: r.text ?? `Sent to ${args2.to}.` }] };
|
|
5557
5655
|
}
|
|
5558
5656
|
function frameInbound(text, sender, settings) {
|
|
5559
5657
|
if (settings.multiHuman && sender.kind === "human") return `[${sender.name}${sender.isAdmin ? " (admin)" : ""}] ${text}`;
|
|
@@ -5634,12 +5732,12 @@ var ClaudeSession = class {
|
|
|
5634
5732
|
"send_file",
|
|
5635
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.",
|
|
5636
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") },
|
|
5637
|
-
async (
|
|
5638
|
-
const full = sendablePath(this.opts.cwd,
|
|
5735
|
+
async (args2) => {
|
|
5736
|
+
const full = sendablePath(this.opts.cwd, args2.path);
|
|
5639
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 };
|
|
5640
|
-
if (!
|
|
5641
|
-
this.q.push({ kind: "file", path: full, name:
|
|
5642
|
-
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.` }] };
|
|
5643
5741
|
}
|
|
5644
5742
|
)
|
|
5645
5743
|
);
|
|
@@ -5670,7 +5768,7 @@ var ClaudeSession = class {
|
|
|
5670
5768
|
"send",
|
|
5671
5769
|
SEND_TOOL_DESCRIPTION,
|
|
5672
5770
|
{ to: z9.string().min(1).describe("One agent's name from list_agents"), text: z9.string().describe("The message") },
|
|
5673
|
-
async (
|
|
5771
|
+
async (args2) => {
|
|
5674
5772
|
const id = newId();
|
|
5675
5773
|
const result = new Promise((resolve) => {
|
|
5676
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);
|
|
@@ -5681,8 +5779,8 @@ var ClaudeSession = class {
|
|
|
5681
5779
|
};
|
|
5682
5780
|
this.agentWaits.set(id, finish);
|
|
5683
5781
|
});
|
|
5684
|
-
this.q.push({ kind: "agent.send", id, to:
|
|
5685
|
-
return sendToolResult(
|
|
5782
|
+
this.q.push({ kind: "agent.send", id, to: args2.to, text: args2.text });
|
|
5783
|
+
return sendToolResult(args2, await result);
|
|
5686
5784
|
}
|
|
5687
5785
|
)
|
|
5688
5786
|
);
|
|
@@ -5847,7 +5945,7 @@ ${files.map((a) => `- ${a.localPath} (${a.mime}, ${a.size} bytes)${a.note ? `: $
|
|
|
5847
5945
|
content.push({ type: "text", text });
|
|
5848
5946
|
for (const a of files) {
|
|
5849
5947
|
if (IMAGE_MIMES.has(a.mime) && a.size <= 5 * 1024 * 1024 && a.localPath) {
|
|
5850
|
-
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") } });
|
|
5851
5949
|
}
|
|
5852
5950
|
}
|
|
5853
5951
|
const user = { type: "user", message: { role: "user", content }, parent_tool_use_id: null, priority: msg.delivery, origin: { kind: "human" } };
|
|
@@ -5912,7 +6010,7 @@ function sessionToolsServer(list, runner) {
|
|
|
5912
6010
|
const server = createSdkMcpServer({
|
|
5913
6011
|
name: TOOLS_SERVER,
|
|
5914
6012
|
version: "1.0.0",
|
|
5915
|
-
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)))
|
|
5916
6014
|
});
|
|
5917
6015
|
return { servers: { [TOOLS_SERVER]: server }, allowed: list.map((t) => toolMcpName(t)) };
|
|
5918
6016
|
}
|
|
@@ -5932,17 +6030,17 @@ function monoclawToolNames(s) {
|
|
|
5932
6030
|
function sendablePath(cwd, p) {
|
|
5933
6031
|
const real = (x) => {
|
|
5934
6032
|
try {
|
|
5935
|
-
return
|
|
6033
|
+
return fs20.realpathSync(x);
|
|
5936
6034
|
} catch {
|
|
5937
6035
|
return null;
|
|
5938
6036
|
}
|
|
5939
6037
|
};
|
|
5940
6038
|
const root = real(cwd);
|
|
5941
|
-
const full = real(
|
|
6039
|
+
const full = real(path20.resolve(cwd, p));
|
|
5942
6040
|
if (!root || !full) return null;
|
|
5943
|
-
if (full !== root && !full.startsWith(root +
|
|
5944
|
-
const rel =
|
|
5945
|
-
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;
|
|
5946
6044
|
return full;
|
|
5947
6045
|
}
|
|
5948
6046
|
function safeJson(v) {
|
|
@@ -5961,30 +6059,30 @@ function friendlyPath(p, cwd) {
|
|
|
5961
6059
|
if (file === base) return ".";
|
|
5962
6060
|
if (file.startsWith(`${base}/`)) return file.slice(base.length + 1);
|
|
5963
6061
|
}
|
|
5964
|
-
const home = norm(
|
|
6062
|
+
const home = norm(os6.homedir());
|
|
5965
6063
|
if (home && file.startsWith(`${home}/`)) return `~/${file.slice(home.length + 1)}`;
|
|
5966
6064
|
return file;
|
|
5967
6065
|
}
|
|
5968
6066
|
var clip = (s, n) => s.length > n ? `${s.slice(0, n - 1)}\u2026` : s;
|
|
5969
6067
|
function describeTool(name, input, cwd) {
|
|
5970
6068
|
const s = (k) => typeof input[k] === "string" ? input[k] : void 0;
|
|
5971
|
-
const
|
|
6069
|
+
const path23 = (k) => friendlyPath(s(k), cwd);
|
|
5972
6070
|
const firstString = () => Object.values(input).find((v) => typeof v === "string" && v.trim().length > 0);
|
|
5973
6071
|
switch (name) {
|
|
5974
6072
|
case "Bash":
|
|
5975
6073
|
return clip(s("description") ?? s("command") ?? "run a command", 120);
|
|
5976
6074
|
case "Read":
|
|
5977
|
-
return `Read ${
|
|
6075
|
+
return `Read ${path23("file_path") || path23("path")}`.trim();
|
|
5978
6076
|
case "Edit":
|
|
5979
6077
|
case "Write":
|
|
5980
6078
|
case "MultiEdit":
|
|
5981
|
-
return `${name} ${
|
|
6079
|
+
return `${name} ${path23("file_path")}`.trim();
|
|
5982
6080
|
case "NotebookEdit":
|
|
5983
|
-
return `Edit notebook ${
|
|
6081
|
+
return `Edit notebook ${path23("notebook_path")}`.trim();
|
|
5984
6082
|
case "Grep":
|
|
5985
|
-
return `Grep "${clip(s("pattern") ?? "", 60)}"${s("path") ? ` in ${
|
|
6083
|
+
return `Grep "${clip(s("pattern") ?? "", 60)}"${s("path") ? ` in ${path23("path")}` : ""}`;
|
|
5986
6084
|
case "Glob":
|
|
5987
|
-
return `Find ${clip(s("pattern") ?? "", 60)}${s("path") ? ` in ${
|
|
6085
|
+
return `Find ${clip(s("pattern") ?? "", 60)}${s("path") ? ` in ${path23("path")}` : ""}`;
|
|
5988
6086
|
case "WebSearch":
|
|
5989
6087
|
return `Search "${clip(s("query") ?? "", 80)}"`;
|
|
5990
6088
|
case "WebFetch": {
|
|
@@ -6040,8 +6138,8 @@ ${instructions}`);
|
|
|
6040
6138
|
return parts.join("\n\n");
|
|
6041
6139
|
}
|
|
6042
6140
|
async function summarise(input) {
|
|
6043
|
-
const dir =
|
|
6044
|
-
|
|
6141
|
+
const dir = path20.join(configDir(), "summaries");
|
|
6142
|
+
fs20.mkdirSync(dir, { recursive: true, mode: 448 });
|
|
6045
6143
|
const model = input.model?.trim() || process.env.MONOCLAW_SUMMARY_MODEL || DEFAULT_SUMMARY_MODEL;
|
|
6046
6144
|
const abortController = new AbortController();
|
|
6047
6145
|
const timer = setTimeout(() => abortController.abort(), SUMMARY_TIMEOUT_MS);
|
|
@@ -6122,12 +6220,11 @@ var claudeProvider = {
|
|
|
6122
6220
|
const fallback = cli.kind === "path" ? " \xB7 using the Claude Code on this machine (the host's copy is missing; `monoclaw doctor` repairs it)" : "";
|
|
6123
6221
|
if (env?.ANTHROPIC_API_KEY) return { ready: true, summary: "API key", details: { version, cli: where, authMethod: "api_key" } };
|
|
6124
6222
|
try {
|
|
6125
|
-
const
|
|
6126
|
-
|
|
6127
|
-
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 };
|
|
6128
6225
|
return { ready: true, summary: `Logged in (${j.authMethod ?? "ok"})${fallback}`, details: { version, cli: where, authMethod: j.authMethod ?? "", apiProvider: j.apiProvider ?? "" } };
|
|
6129
6226
|
} catch (e) {
|
|
6130
|
-
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." };
|
|
6131
6228
|
}
|
|
6132
6229
|
},
|
|
6133
6230
|
openSession(opts) {
|
|
@@ -6150,9 +6247,9 @@ var providers = only.length ? Object.fromEntries(Object.entries(all).filter(([id
|
|
|
6150
6247
|
|
|
6151
6248
|
// src/service.ts
|
|
6152
6249
|
import { spawnSync } from "node:child_process";
|
|
6153
|
-
import
|
|
6154
|
-
import
|
|
6155
|
-
import
|
|
6250
|
+
import fs21 from "node:fs";
|
|
6251
|
+
import os7 from "node:os";
|
|
6252
|
+
import path21 from "node:path";
|
|
6156
6253
|
function serviceNames(profile = currentProfile()) {
|
|
6157
6254
|
return { unit: profile ? `monoclaw-${profile}` : "monoclaw", label: profile ? `ai.monoclaw.host.${profile}` : "ai.monoclaw.host", task: profile ? `MonoClaw host (${profile})` : "MonoClaw host" };
|
|
6158
6255
|
}
|
|
@@ -6163,26 +6260,26 @@ function profileEnv() {
|
|
|
6163
6260
|
function selfCommand() {
|
|
6164
6261
|
let script = process.argv[1] ?? "";
|
|
6165
6262
|
try {
|
|
6166
|
-
script =
|
|
6263
|
+
script = fs21.realpathSync(script);
|
|
6167
6264
|
} catch {
|
|
6168
6265
|
}
|
|
6169
6266
|
return { node: process.execPath, script };
|
|
6170
6267
|
}
|
|
6171
6268
|
function servicePath(node) {
|
|
6172
|
-
const dirs = process.platform === "win32" ? [
|
|
6173
|
-
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);
|
|
6174
6271
|
}
|
|
6175
6272
|
function serviceInstructions() {
|
|
6176
6273
|
const dir = configDir();
|
|
6177
|
-
const home =
|
|
6274
|
+
const home = os7.homedir();
|
|
6178
6275
|
const { node, script } = selfCommand();
|
|
6179
|
-
const logs =
|
|
6180
|
-
|
|
6276
|
+
const logs = path21.join(dir, "logs");
|
|
6277
|
+
fs21.mkdirSync(logs, { recursive: true });
|
|
6181
6278
|
const names = serviceNames();
|
|
6182
6279
|
const env = profileEnv();
|
|
6183
6280
|
if (process.platform === "linux") {
|
|
6184
6281
|
const unit = `[Unit]
|
|
6185
|
-
Description=
|
|
6282
|
+
Description=MonoClaw machine${currentProfile() ? ` (${currentProfile()})` : ""}
|
|
6186
6283
|
After=network-online.target
|
|
6187
6284
|
|
|
6188
6285
|
[Service]
|
|
@@ -6195,13 +6292,13 @@ Environment="PATH=${servicePath(node)}"
|
|
|
6195
6292
|
[Install]
|
|
6196
6293
|
WantedBy=default.target
|
|
6197
6294
|
`;
|
|
6198
|
-
const file2 =
|
|
6199
|
-
|
|
6200
|
-
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`);
|
|
6201
6298
|
return {
|
|
6202
6299
|
file: file2,
|
|
6203
6300
|
steps: [
|
|
6204
|
-
`mkdir -p ${
|
|
6301
|
+
`mkdir -p ${path21.dirname(target)} && cp ${file2} ${target}`,
|
|
6205
6302
|
`systemctl --user daemon-reload && systemctl --user enable --now ${names.unit}`,
|
|
6206
6303
|
"loginctl enable-linger $USER # keeps it running when you are logged out",
|
|
6207
6304
|
`journalctl --user -u ${names.unit} -f # logs`
|
|
@@ -6221,17 +6318,17 @@ WantedBy=default.target
|
|
|
6221
6318
|
<key>${env.name}</key><string>${xml(env.value)}</string>
|
|
6222
6319
|
<key>PATH</key><string>${xml(servicePath(node))}</string>
|
|
6223
6320
|
</dict>
|
|
6224
|
-
<key>StandardOutPath</key><string>${xml(
|
|
6225
|
-
<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>
|
|
6226
6323
|
</dict></plist>
|
|
6227
6324
|
`;
|
|
6228
|
-
const file2 =
|
|
6229
|
-
|
|
6230
|
-
const target =
|
|
6231
|
-
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")}`] };
|
|
6232
6329
|
}
|
|
6233
|
-
const file =
|
|
6234
|
-
|
|
6330
|
+
const file = path21.join(dir, "monoclaw-host-task.ps1");
|
|
6331
|
+
fs21.writeFileSync(
|
|
6235
6332
|
file,
|
|
6236
6333
|
`$action = New-ScheduledTaskAction -Execute "${node}" -Argument '"${script}" start'
|
|
6237
6334
|
$trigger = New-ScheduledTaskTrigger -AtLogOn
|
|
@@ -6243,31 +6340,31 @@ Start-ScheduledTask -TaskName "${names.task}"
|
|
|
6243
6340
|
);
|
|
6244
6341
|
return { file, steps: [`powershell -ExecutionPolicy Bypass -File "${file}"`, `Get-ScheduledTask -TaskName "${names.task}"`] };
|
|
6245
6342
|
}
|
|
6246
|
-
var runSync = (cmd2,
|
|
6247
|
-
const r = spawnSync(cmd2,
|
|
6343
|
+
var runSync = (cmd2, args2) => {
|
|
6344
|
+
const r = spawnSync(cmd2, args2, { encoding: "utf8" });
|
|
6248
6345
|
return { status: r.status, stderr: String(r.stderr ?? "") };
|
|
6249
6346
|
};
|
|
6250
|
-
function installService(
|
|
6347
|
+
function installService(run3 = runSync) {
|
|
6251
6348
|
const r = serviceInstructions();
|
|
6252
|
-
const home =
|
|
6253
|
-
const must = (cmd2,
|
|
6254
|
-
const x =
|
|
6255
|
-
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}`}`);
|
|
6256
6353
|
};
|
|
6257
6354
|
const names = serviceNames();
|
|
6258
6355
|
if (process.platform === "darwin") {
|
|
6259
|
-
const target =
|
|
6260
|
-
|
|
6261
|
-
|
|
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);
|
|
6262
6359
|
const uid = String(process.getuid?.() ?? "");
|
|
6263
|
-
|
|
6360
|
+
run3("launchctl", ["bootout", `gui/${uid}/${names.label}`]);
|
|
6264
6361
|
must("launchctl", ["bootstrap", `gui/${uid}`, target]);
|
|
6265
|
-
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")}`] };
|
|
6266
6363
|
}
|
|
6267
6364
|
if (process.platform === "linux") {
|
|
6268
|
-
const target =
|
|
6269
|
-
|
|
6270
|
-
|
|
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);
|
|
6271
6368
|
must("systemctl", ["--user", "daemon-reload"]);
|
|
6272
6369
|
must("systemctl", ["--user", "enable", "--now", names.unit]);
|
|
6273
6370
|
must("systemctl", ["--user", "restart", names.unit]);
|
|
@@ -6276,37 +6373,36 @@ function installService(run2 = runSync) {
|
|
|
6276
6373
|
must("powershell", ["-ExecutionPolicy", "Bypass", "-File", r.file]);
|
|
6277
6374
|
return { file: r.file, target: `Task Scheduler: ${names.task}`, notes: [`Check: Get-ScheduledTask -TaskName "${names.task}"`] };
|
|
6278
6375
|
}
|
|
6279
|
-
function uninstallService(
|
|
6280
|
-
const home =
|
|
6376
|
+
function uninstallService(run3 = runSync) {
|
|
6377
|
+
const home = os7.homedir();
|
|
6281
6378
|
const names = serviceNames();
|
|
6282
6379
|
if (process.platform === "darwin") {
|
|
6283
|
-
const target =
|
|
6284
|
-
|
|
6285
|
-
|
|
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 });
|
|
6286
6383
|
return target;
|
|
6287
6384
|
}
|
|
6288
6385
|
if (process.platform === "linux") {
|
|
6289
|
-
const target =
|
|
6290
|
-
|
|
6291
|
-
|
|
6292
|
-
|
|
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"]);
|
|
6293
6390
|
return target;
|
|
6294
6391
|
}
|
|
6295
|
-
|
|
6392
|
+
run3("powershell", ["-Command", `Unregister-ScheduledTask -TaskName "${names.task}" -Confirm:$false`]);
|
|
6296
6393
|
return `Task Scheduler: ${names.task}`;
|
|
6297
6394
|
}
|
|
6298
6395
|
|
|
6299
6396
|
// src/cli.ts
|
|
6300
|
-
import {
|
|
6301
|
-
import
|
|
6302
|
-
import os7 from "node:os";
|
|
6397
|
+
import { spawn as spawn5 } from "node:child_process";
|
|
6398
|
+
import os8 from "node:os";
|
|
6303
6399
|
async function readTokenFromStdin() {
|
|
6304
6400
|
let data = "";
|
|
6305
6401
|
for await (const chunk of process.stdin) data += chunk;
|
|
6306
6402
|
return data.split(/\r?\n/).map((l) => l.trim()).find((l) => l.length > 0) ?? "";
|
|
6307
6403
|
}
|
|
6308
6404
|
var program = new Command();
|
|
6309
|
-
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", () => {
|
|
6310
6406
|
const p = program.opts().profile;
|
|
6311
6407
|
if (p) process.env.MONOCLAW_PROFILE = assertProfileName(p);
|
|
6312
6408
|
});
|
|
@@ -6319,7 +6415,14 @@ async function confirm(question, fallback) {
|
|
|
6319
6415
|
const a = answer.trim().toLowerCase();
|
|
6320
6416
|
return a === "" ? fallback : a === "y" || a === "yes";
|
|
6321
6417
|
}
|
|
6322
|
-
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) => {
|
|
6323
6426
|
const token = opts.tokenStdin || tokenArg === "-" ? await readTokenFromStdin() : tokenArg;
|
|
6324
6427
|
if (!token) {
|
|
6325
6428
|
console.error("No token. Pass it as an argument, or pipe it in with --token-stdin.");
|
|
@@ -6327,7 +6430,7 @@ program.command("enrol [token]").description("Connect this machine to your Monoc
|
|
|
6327
6430
|
}
|
|
6328
6431
|
const profiles = listProfiles();
|
|
6329
6432
|
const preview = await previewToken(opts.router, token, profiles.map((p) => p.config?.hostId ?? "").filter(Boolean), opts.insecure);
|
|
6330
|
-
const plan = planEnrol(preview, profiles, opts.router, { requestedProfile: currentProfile(), defaultName:
|
|
6433
|
+
const plan = planEnrol(preview, profiles, opts.router, { requestedProfile: currentProfile(), defaultName: os8.hostname() });
|
|
6331
6434
|
if (plan.action === "already") {
|
|
6332
6435
|
console.log(plan.message);
|
|
6333
6436
|
return;
|
|
@@ -6342,19 +6445,29 @@ program.command("enrol [token]").description("Connect this machine to your Monoc
|
|
|
6342
6445
|
}
|
|
6343
6446
|
if (plan.profile) process.env.MONOCLAW_PROFILE = assertProfileName(plan.profile);
|
|
6344
6447
|
const existing = loadConfig();
|
|
6345
|
-
const roots2 = opts.root?.map((r) =>
|
|
6448
|
+
const roots2 = opts.root?.map((r) => path22.resolve(r)) ?? existing?.roots ?? plan.copyRootsFrom ?? [];
|
|
6346
6449
|
const unsafe = roots2.filter((r) => rootExposesConfig(r, configDir()));
|
|
6347
6450
|
if (unsafe.length) {
|
|
6348
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.`);
|
|
6349
6452
|
process.exit(2);
|
|
6350
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
|
+
}
|
|
6351
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 });
|
|
6352
6464
|
console.log(`Enrolled as "${cfg.name}"${cfg.spaceName ? ` in ${cfg.spaceName} (@${cfg.spaceHandle})` : ""}${currentProfile() ? ` under the profile "${currentProfile()}"` : ""}. Config saved to ${configPath()}.`);
|
|
6353
6465
|
if (plan.reason === "second-space") {
|
|
6354
|
-
|
|
6466
|
+
fs22.writeFileSync(pendingServicePath(), JSON.stringify({ profile: currentProfile(), at: (/* @__PURE__ */ new Date()).toISOString() }), { mode: 384 });
|
|
6355
6467
|
console.log(`This computer now runs one machine per space; its modules and Claude login are shared. The first enrolment is untouched.`);
|
|
6356
6468
|
}
|
|
6357
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;
|
|
6358
6471
|
console.log(`
|
|
6359
6472
|
Next, run it (one of):
|
|
6360
6473
|
${cmd("service install")} in the background: starts now, at every login, and survives restarts
|
|
@@ -6436,7 +6549,7 @@ provider.command("add <name>").description("Add a Claude connection; an api_key
|
|
|
6436
6549
|
const { registry, accounts } = await makeContext(requireConfig());
|
|
6437
6550
|
const moduleId = opts.type === "api_key" ? "claude-api" : "claude-subscription";
|
|
6438
6551
|
if (!registry.isInstalled(moduleId)) await registry.add(moduleId).install;
|
|
6439
|
-
const folders = opts.folders?.map((f) =>
|
|
6552
|
+
const folders = opts.folders?.map((f) => path22.resolve(f.replace(/^~(?=$|\/)/, process.env.HOME ?? "")));
|
|
6440
6553
|
if (opts.type === "api_key") {
|
|
6441
6554
|
const id = await connectModule(registry, accounts, moduleId, io, { name, id: opts.id });
|
|
6442
6555
|
if (folders) accounts.upsert({ ...accounts.get(id), allowedFolders: folders });
|
|
@@ -6465,18 +6578,18 @@ var roots = program.command("roots").description("Folders this machine exposes t
|
|
|
6465
6578
|
roots.command("list").action(() => {
|
|
6466
6579
|
const cfg = requireConfig();
|
|
6467
6580
|
if (!cfg.roots.length) console.log("(none) \u2014 add one with: monoclaw roots add <path>");
|
|
6468
|
-
for (const r of cfg.roots) console.log(`${
|
|
6581
|
+
for (const r of cfg.roots) console.log(`${fs22.existsSync(r) ? "\u2713" : "\u2717 (missing)"} ${r}`);
|
|
6469
6582
|
});
|
|
6470
6583
|
roots.command("add <path...>").action((paths) => {
|
|
6471
6584
|
const cfg = requireConfig();
|
|
6472
6585
|
for (const p of paths) {
|
|
6473
|
-
const full =
|
|
6474
|
-
if (!
|
|
6586
|
+
const full = path22.resolve(p.replace(/^~(?=$|\/)/, process.env.HOME ?? ""));
|
|
6587
|
+
if (!fs22.existsSync(full) || !fs22.statSync(full).isDirectory()) {
|
|
6475
6588
|
console.error(`not a folder: ${full}`);
|
|
6476
6589
|
continue;
|
|
6477
6590
|
}
|
|
6478
6591
|
if (rootExposesConfig(full, configDir())) {
|
|
6479
|
-
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")}.`);
|
|
6480
6593
|
process.exitCode = 1;
|
|
6481
6594
|
continue;
|
|
6482
6595
|
}
|
|
@@ -6489,7 +6602,7 @@ Restart the host for the change to reach the app.`);
|
|
|
6489
6602
|
});
|
|
6490
6603
|
roots.command("remove <path>").action((p) => {
|
|
6491
6604
|
const cfg = requireConfig();
|
|
6492
|
-
const full =
|
|
6605
|
+
const full = path22.resolve(p);
|
|
6493
6606
|
cfg.roots = cfg.roots.filter((r) => r !== full);
|
|
6494
6607
|
saveConfig(cfg);
|
|
6495
6608
|
console.log(`Exposed folders: ${cfg.roots.join(", ") || "(none)"}`);
|
|
@@ -6518,11 +6631,11 @@ program.command("start").description("Run the host and stay connected to the rou
|
|
|
6518
6631
|
assertRouterUrl(loaded.routerUrl, loaded.allowInsecure);
|
|
6519
6632
|
const lock = acquireRunLock(configDir());
|
|
6520
6633
|
if (!lock.ok) {
|
|
6521
|
-
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}.`);
|
|
6522
6635
|
process.exit(1);
|
|
6523
6636
|
}
|
|
6524
6637
|
process.on("exit", lock.release);
|
|
6525
|
-
setLogDir(
|
|
6638
|
+
setLogDir(path22.join(configDir(), "logs"));
|
|
6526
6639
|
const unsafe = loaded.roots.filter((r) => rootExposesConfig(r, configDir()));
|
|
6527
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>\`).`);
|
|
6528
6641
|
const cfg = unsafe.length ? { ...loaded, roots: loaded.roots.filter((r) => !unsafe.includes(r)) } : loaded;
|
|
@@ -6531,7 +6644,7 @@ program.command("start").description("Run the host and stay connected to the rou
|
|
|
6531
6644
|
const repaired = await repairBundledCli();
|
|
6532
6645
|
if (repaired.outcome !== "present") log(repaired.outcome === "installed" ? "info" : "warn", `Claude Code copy: ${repaired.detail}`);
|
|
6533
6646
|
const cli = await resolveCli();
|
|
6534
|
-
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");
|
|
6535
6648
|
const { accounts, registry } = await makeContext(cfg);
|
|
6536
6649
|
log("info", `modules: ${registry.installedIds().join(", ") || "(none)"}; ${accounts.list().length} connection(s) (secrets in the ${accounts.store.kind} store)`);
|
|
6537
6650
|
const client = new HostClient(cfg, providers, { accounts, registry });
|
|
@@ -6562,6 +6675,23 @@ program.command("start").description("Run the host and stay connected to the rou
|
|
|
6562
6675
|
process.on("SIGINT", shutdown);
|
|
6563
6676
|
process.on("SIGTERM", shutdown);
|
|
6564
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)));
|
|
6565
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) => {
|
|
6566
6696
|
const lines = [];
|
|
6567
6697
|
const major = Number(process.versions.node.split(".")[0]);
|
|
@@ -6579,27 +6709,26 @@ program.command("doctor").description("Check and repair what a working host need
|
|
|
6579
6709
|
const pkg = platformPackages()[0];
|
|
6580
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)` });
|
|
6581
6711
|
const onPath2 = await cliOnPath();
|
|
6582
|
-
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)" });
|
|
6583
6713
|
const cli = await resolveCli();
|
|
6584
6714
|
if (cli) {
|
|
6585
6715
|
try {
|
|
6586
|
-
const
|
|
6587
|
-
|
|
6588
|
-
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 });
|
|
6589
6718
|
} catch (e) {
|
|
6590
|
-
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" });
|
|
6591
6720
|
}
|
|
6592
|
-
} 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" });
|
|
6593
6722
|
const cfg = loadConfig();
|
|
6594
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)" });
|
|
6595
6724
|
else {
|
|
6596
6725
|
lines.push({ ok: true, what: `Enrolled as "${cfg.name}" with ${cfg.routerUrl}` });
|
|
6597
|
-
const missing = cfg.roots.filter((r) => !
|
|
6726
|
+
const missing = cfg.roots.filter((r) => !fs22.existsSync(r));
|
|
6598
6727
|
const exposing = cfg.roots.filter((r) => rootExposesConfig(r, configDir()));
|
|
6599
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>` });
|
|
6600
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 });
|
|
6601
|
-
const unit = process.platform === "darwin" ?
|
|
6602
|
-
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" });
|
|
6603
6732
|
const { registry } = await makeContext(cfg);
|
|
6604
6733
|
await registry.refreshReadiness();
|
|
6605
6734
|
const reports = registry.reports();
|
|
@@ -6674,16 +6803,16 @@ config.command("set <key> <value>").description("Keys: allowedPermissionModes (c
|
|
|
6674
6803
|
});
|
|
6675
6804
|
var service = program.command("service").description("Run the host in the background at login");
|
|
6676
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) => {
|
|
6677
|
-
if (!currentProfile() &&
|
|
6806
|
+
if (!currentProfile() && fs22.existsSync(pendingServicePath())) {
|
|
6678
6807
|
try {
|
|
6679
|
-
const pending = JSON.parse(
|
|
6808
|
+
const pending = JSON.parse(fs22.readFileSync(pendingServicePath(), "utf8"));
|
|
6680
6809
|
if (pending.profile && Date.now() - Date.parse(pending.at ?? "") < 60 * 6e4) {
|
|
6681
6810
|
process.env.MONOCLAW_PROFILE = assertProfileName(pending.profile);
|
|
6682
6811
|
console.log(`Installing the service for the profile "${pending.profile}" (the enrolment just made). The first enrolment's service is untouched.`);
|
|
6683
6812
|
}
|
|
6684
6813
|
} catch {
|
|
6685
6814
|
}
|
|
6686
|
-
|
|
6815
|
+
fs22.rmSync(pendingServicePath(), { force: true });
|
|
6687
6816
|
}
|
|
6688
6817
|
requireConfig();
|
|
6689
6818
|
if (o.print) {
|
|
@@ -6699,7 +6828,12 @@ ${r2.steps.map((s) => ` ${s}`).join("\n")}
|
|
|
6699
6828
|
${r.notes.map((n) => ` ${n}`).join("\n")}` : ""}`);
|
|
6700
6829
|
});
|
|
6701
6830
|
service.command("uninstall").description("Stop and remove the background service").action(() => console.log(`Background service stopped and removed (${uninstallService()}).`));
|
|
6702
|
-
|
|
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) => {
|
|
6703
6837
|
console.error(e instanceof Error ? e.message : String(e));
|
|
6704
6838
|
process.exit(1);
|
|
6705
6839
|
});
|