@monoclaw/machine 1.0.3 → 1.0.5
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 +597 -405
- 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
|
|
|
@@ -511,9 +511,24 @@ function ensureKeypair(cfg) {
|
|
|
511
511
|
}
|
|
512
512
|
function requireConfig() {
|
|
513
513
|
const c = loadConfig();
|
|
514
|
-
if (!c)
|
|
514
|
+
if (!c) {
|
|
515
|
+
const others = currentProfile() ? [] : enrolledProfiles();
|
|
516
|
+
if (others.length) throw new Error(`This computer's enrolments are under profiles: ${others.map((p) => `"${p.profile}"${p.config.spaceName ? ` (${p.config.spaceName})` : ""}`).join(", ")}. Name one: monoclaw --profile ${others[0].profile} <command>`);
|
|
517
|
+
throw new Error(`Not enrolled. Run: monoclaw enrol <token> --router <url>`);
|
|
518
|
+
}
|
|
515
519
|
return c;
|
|
516
520
|
}
|
|
521
|
+
function enrolledProfiles() {
|
|
522
|
+
return listProfiles().flatMap((p) => p.profile && p.config ? [{ profile: p.profile, config: p.config }] : []);
|
|
523
|
+
}
|
|
524
|
+
function impliedProfile() {
|
|
525
|
+
if (currentProfile() || fs2.existsSync(path2.join(baseDir(), "config.json"))) return null;
|
|
526
|
+
const named = enrolledProfiles();
|
|
527
|
+
return named.length === 1 ? named[0].profile : null;
|
|
528
|
+
}
|
|
529
|
+
function connectResultPath() {
|
|
530
|
+
return path2.join(baseDir(), "connect-result.json");
|
|
531
|
+
}
|
|
517
532
|
var LOOPBACK = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
|
|
518
533
|
function assertRouterUrl(routerUrl, allowInsecure = false) {
|
|
519
534
|
const u = new URL(routerUrl);
|
|
@@ -1185,12 +1200,12 @@ var isVersion = (v) => parseVersion(v) !== null;
|
|
|
1185
1200
|
import path11 from "node:path";
|
|
1186
1201
|
|
|
1187
1202
|
// src/modules/types.ts
|
|
1188
|
-
function resolveOptions(fields, options,
|
|
1203
|
+
function resolveOptions(fields, options, args2 = {}) {
|
|
1189
1204
|
const out = {};
|
|
1190
1205
|
for (const f of fields) if (f.default !== void 0) out[f.key] = f.default;
|
|
1191
1206
|
for (const [k, v] of Object.entries(options)) out[k] = v;
|
|
1192
1207
|
const settable = new Set(fields.filter((f) => f.agentSettable).map((f) => f.key));
|
|
1193
|
-
for (const [k, v] of Object.entries(
|
|
1208
|
+
for (const [k, v] of Object.entries(args2)) if (settable.has(k)) out[k] = v;
|
|
1194
1209
|
return out;
|
|
1195
1210
|
}
|
|
1196
1211
|
var str = (v, fallback) => typeof v === "string" && v ? v : fallback;
|
|
@@ -1240,7 +1255,7 @@ function claudeSubscriptionModule(probe) {
|
|
|
1240
1255
|
return {
|
|
1241
1256
|
id: "claude-subscription",
|
|
1242
1257
|
version: "1.0.0",
|
|
1243
|
-
catalogue: { id: "claude-subscription", name: "Claude (subscription)", description: "Agents run Claude Code with this machine's own Claude login
|
|
1258
|
+
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
1259
|
multipleConnections: false,
|
|
1245
1260
|
connectionType: "subscription",
|
|
1246
1261
|
providerId: "claude",
|
|
@@ -1442,11 +1457,11 @@ var busy = (e) => e.status === 429 && (e.code === "system_busy" || e.code === "t
|
|
|
1442
1457
|
function elevenlabsModule(deps = {}) {
|
|
1443
1458
|
const f = deps.fetch ?? ((...a) => fetch(...a));
|
|
1444
1459
|
const queue = new PerKeyQueue();
|
|
1445
|
-
const call = (key,
|
|
1460
|
+
const call = (key, path23, init = {}, timeoutMs = 12e4) => withRetries(
|
|
1446
1461
|
async () => {
|
|
1447
1462
|
let res;
|
|
1448
1463
|
try {
|
|
1449
|
-
res = await f(`${ELEVENLABS_BASE}${
|
|
1464
|
+
res = await f(`${ELEVENLABS_BASE}${path23}`, { ...init, headers: { ...init.headers, "xi-api-key": key }, signal: AbortSignal.timeout(timeoutMs), redirect: "error" });
|
|
1450
1465
|
} catch (e) {
|
|
1451
1466
|
throw new Error(`Could not reach ElevenLabs: ${e.message}`);
|
|
1452
1467
|
}
|
|
@@ -2535,9 +2550,9 @@ import { promisify as promisify3 } from "node:util";
|
|
|
2535
2550
|
var execFileP3 = promisify3(execFile3);
|
|
2536
2551
|
var DEFAULT_TIMEOUT_MS = 9e4;
|
|
2537
2552
|
var MAX_BUFFER = 64 * 1024 * 1024;
|
|
2538
|
-
function run(ctx,
|
|
2539
|
-
if (ctx.exec) return ctx.exec(ctx.ffmpegPath,
|
|
2540
|
-
return execFileP3(ctx.ffmpegPath,
|
|
2553
|
+
function run(ctx, args2) {
|
|
2554
|
+
if (ctx.exec) return ctx.exec(ctx.ffmpegPath, args2);
|
|
2555
|
+
return execFileP3(ctx.ffmpegPath, args2, { timeout: ctx.timeoutMs ?? DEFAULT_TIMEOUT_MS, maxBuffer: MAX_BUFFER, killSignal: "SIGKILL" });
|
|
2541
2556
|
}
|
|
2542
2557
|
var SILENCE_LUFS = -50;
|
|
2543
2558
|
var MAX_STATIC_GAIN_DB = 20;
|
|
@@ -2948,7 +2963,7 @@ function npmInstallInto(dir) {
|
|
|
2948
2963
|
}
|
|
2949
2964
|
function ffmpegHint(platform = process.platform) {
|
|
2950
2965
|
if (platform === "darwin") return "Install ffmpeg: brew install ffmpeg";
|
|
2951
|
-
if (platform === "win32") return "Install ffmpeg: winget install
|
|
2966
|
+
if (platform === "win32") return "Install ffmpeg: winget install --id Gyan.FFmpeg -e";
|
|
2952
2967
|
return "Install ffmpeg: sudo apt install ffmpeg (or your distribution's package)";
|
|
2953
2968
|
}
|
|
2954
2969
|
var LocalInstall = class {
|
|
@@ -3223,7 +3238,7 @@ function moduleSetup(m, platform = process.platform) {
|
|
|
3223
3238
|
}
|
|
3224
3239
|
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
3240
|
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." });
|
|
3241
|
+
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
3242
|
}
|
|
3228
3243
|
if (m.connectionType === "api_key") {
|
|
3229
3244
|
const page = KEY_PAGES[m.id];
|
|
@@ -3576,10 +3591,10 @@ function toolShape(params, capability = "image") {
|
|
|
3576
3591
|
}
|
|
3577
3592
|
return shape;
|
|
3578
3593
|
}
|
|
3579
|
-
function toolCallArgs(tool2,
|
|
3594
|
+
function toolCallArgs(tool2, args2) {
|
|
3580
3595
|
const keys = new Set(tool2.params.map((p) => p.key));
|
|
3581
3596
|
const out = {};
|
|
3582
|
-
for (const [k, v] of Object.entries(
|
|
3597
|
+
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
3598
|
return out;
|
|
3584
3599
|
}
|
|
3585
3600
|
function formatToolResult(tool2, r, cwd) {
|
|
@@ -3626,10 +3641,10 @@ var SessionToolRunner = class {
|
|
|
3626
3641
|
timeoutMs;
|
|
3627
3642
|
scope;
|
|
3628
3643
|
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,
|
|
3644
|
+
async call(t, args2) {
|
|
3645
|
+
if (t.capability === "stt") return this.transcribe(t, args2);
|
|
3646
|
+
const prompt = typeof args2.prompt === "string" ? args2.prompt.trim() : "";
|
|
3647
|
+
const callArgs = toolCallArgs(t, args2);
|
|
3633
3648
|
if (t.askBeforeUse) {
|
|
3634
3649
|
const ok = await this.approve(toolMcpName(t), { prompt, ...callArgs }, `${t.name}: ${prompt.slice(0, 120)}`);
|
|
3635
3650
|
if (!ok) return formatToolResult(t, { error: "The user declined this tool call.", files: [] });
|
|
@@ -3640,11 +3655,11 @@ var SessionToolRunner = class {
|
|
|
3640
3655
|
return formatToolResult(t, await wait, this.cwd);
|
|
3641
3656
|
}
|
|
3642
3657
|
/** 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
|
|
3658
|
+
async transcribe(t, args2) {
|
|
3659
|
+
const given = typeof args2.file === "string" ? args2.file.trim() : "";
|
|
3645
3660
|
const file = resolveToolFile(given, this.cwd, this.scope);
|
|
3646
3661
|
if ("error" in file) return formatToolResult(t, { error: file.error, files: [] });
|
|
3647
|
-
const callArgs = toolCallArgs(t,
|
|
3662
|
+
const callArgs = toolCallArgs(t, args2);
|
|
3648
3663
|
if (t.askBeforeUse) {
|
|
3649
3664
|
const ok = await this.approve(toolMcpName(t), { file: given, ...callArgs }, `${t.name}: ${path12.basename(file.path)}`);
|
|
3650
3665
|
if (!ok) return formatToolResult(t, { error: "The user declined this tool call.", files: [] });
|
|
@@ -4223,7 +4238,7 @@ function guessMime(name) {
|
|
|
4223
4238
|
}
|
|
4224
4239
|
|
|
4225
4240
|
// src/version.ts
|
|
4226
|
-
var APP_VERSION = true ? "1.0.
|
|
4241
|
+
var APP_VERSION = true ? "1.0.5" : fromPackage();
|
|
4227
4242
|
|
|
4228
4243
|
// src/client.ts
|
|
4229
4244
|
var HEARTBEAT_MS = 2e4;
|
|
@@ -4448,7 +4463,7 @@ var HostClient = class {
|
|
|
4448
4463
|
return;
|
|
4449
4464
|
}
|
|
4450
4465
|
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
|
|
4466
|
+
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
4467
|
this.stopped = true;
|
|
4453
4468
|
this.onReplaced();
|
|
4454
4469
|
return;
|
|
@@ -4872,13 +4887,13 @@ function planEnrol(preview, profiles, routerUrl, opts) {
|
|
|
4872
4887
|
machineName: same.config.name,
|
|
4873
4888
|
message: `This computer is already enrolled in ${preview.space.name} (@${preview.space.handle}) as "${same.config.name}"${where}. Nothing to do: the token was not used.
|
|
4874
4889
|
If the machine shows offline in the app, start it: ${same.profile ? `monoclaw --profile ${same.profile} start` : "monoclaw start"} (or \`${same.profile ? `monoclaw --profile ${same.profile} ` : "monoclaw "}service install\` to run it in the background).
|
|
4875
|
-
To
|
|
4890
|
+
To connect it afresh instead, remove this machine on its page in the app first, then run the command from Add a machine again.`
|
|
4876
4891
|
};
|
|
4877
4892
|
}
|
|
4878
4893
|
if (same && requested !== null && requested !== same.profile) {
|
|
4879
4894
|
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
4895
|
}
|
|
4881
|
-
const
|
|
4896
|
+
const first2 = here.find((p) => p.profile === null) ?? here[0];
|
|
4882
4897
|
const taken = new Set(profiles.map((p) => p.profile));
|
|
4883
4898
|
let name = requested ?? (preview.space.handle.toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/^-+|-+$/g, "").slice(0, 30) || "space");
|
|
4884
4899
|
if (requested === null && taken.has(name)) {
|
|
@@ -4886,13 +4901,13 @@ To enrol it again as itself after a reset, use Re-enrol on the machine's page in
|
|
|
4886
4901
|
while (taken.has(`${name}-${i}`)) i++;
|
|
4887
4902
|
name = `${name}-${i}`;
|
|
4888
4903
|
}
|
|
4889
|
-
const existingName =
|
|
4904
|
+
const existingName = first2.config.name;
|
|
4890
4905
|
return {
|
|
4891
4906
|
action: "enrol",
|
|
4892
4907
|
profile: name,
|
|
4893
4908
|
reason: "second-space",
|
|
4894
|
-
copyRootsFrom:
|
|
4895
|
-
confirm: `This computer is enrolled in ${
|
|
4909
|
+
copyRootsFrom: first2.config.roots,
|
|
4910
|
+
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
4911
|
nameHint: `${existingName || opts.defaultName} \xB7 ${preview.space.name}`.slice(0, 60)
|
|
4897
4912
|
};
|
|
4898
4913
|
}
|
|
@@ -4920,252 +4935,10 @@ async function enrol(token, routerUrl, opts) {
|
|
|
4920
4935
|
return cfg;
|
|
4921
4936
|
}
|
|
4922
4937
|
|
|
4923
|
-
// src/
|
|
4924
|
-
|
|
4925
|
-
items = [];
|
|
4926
|
-
waiters = [];
|
|
4927
|
-
closed = false;
|
|
4928
|
-
push(item) {
|
|
4929
|
-
if (this.closed) return;
|
|
4930
|
-
const w = this.waiters.shift();
|
|
4931
|
-
if (w) w({ value: item, done: false });
|
|
4932
|
-
else this.items.push(item);
|
|
4933
|
-
}
|
|
4934
|
-
close() {
|
|
4935
|
-
this.closed = true;
|
|
4936
|
-
for (const w of this.waiters.splice(0)) w({ value: void 0, done: true });
|
|
4937
|
-
}
|
|
4938
|
-
get isClosed() {
|
|
4939
|
-
return this.closed;
|
|
4940
|
-
}
|
|
4941
|
-
[Symbol.asyncIterator]() {
|
|
4942
|
-
return {
|
|
4943
|
-
next: () => {
|
|
4944
|
-
const item = this.items.shift();
|
|
4945
|
-
if (item !== void 0) return Promise.resolve({ value: item, done: false });
|
|
4946
|
-
if (this.closed) return Promise.resolve({ value: void 0, done: true });
|
|
4947
|
-
return new Promise((res) => this.waiters.push(res));
|
|
4948
|
-
},
|
|
4949
|
-
return: () => {
|
|
4950
|
-
this.close();
|
|
4951
|
-
return Promise.resolve({ value: void 0, done: true });
|
|
4952
|
-
}
|
|
4953
|
-
};
|
|
4954
|
-
}
|
|
4955
|
-
};
|
|
4956
|
-
|
|
4957
|
-
// src/providers/echo/index.ts
|
|
4958
|
-
var EchoSession = class {
|
|
4959
|
-
constructor(opts) {
|
|
4960
|
-
this.opts = opts;
|
|
4961
|
-
this.mode = opts.settings.permissionMode ?? "default";
|
|
4962
|
-
this.tools = new SessionToolRunner(
|
|
4963
|
-
(ev) => this.q.push(ev),
|
|
4964
|
-
(tool2, input, description) => {
|
|
4965
|
-
const id = newId();
|
|
4966
|
-
this.q.push({ kind: "approval.request", id, tool: tool2, input, description });
|
|
4967
|
-
return new Promise((res) => this.pending.set(id, res));
|
|
4968
|
-
},
|
|
4969
|
-
opts.cwd,
|
|
4970
|
-
void 0,
|
|
4971
|
-
opts.settings.scope ?? "full"
|
|
4972
|
-
);
|
|
4973
|
-
const forked = opts.forkFrom && !opts.resumeId ? `${opts.forkFrom}-fork-${newId().slice(0, 4)}` : void 0;
|
|
4974
|
-
this.q.push({ kind: "session", providerSessionId: opts.resumeId ?? forked ?? `echo-${newId().slice(0, 8)}`, model: this.model, permissionMode: this.mode, commands: [{ name: "echo-help", description: "Echo provider help", argumentHint: "" }], tools: opts.settings.scope === "chat" ? [] : opts.settings.scope === "read" ? ["read"] : ["echo"], version: "1" });
|
|
4975
|
-
}
|
|
4976
|
-
opts;
|
|
4977
|
-
q = new EventQueue();
|
|
4978
|
-
pending = /* @__PURE__ */ new Map();
|
|
4979
|
-
agentWaits = /* @__PURE__ */ new Map();
|
|
4980
|
-
tools;
|
|
4981
|
-
abort = null;
|
|
4982
|
-
model = "echo-1";
|
|
4983
|
-
mode;
|
|
4984
|
-
async send(msg) {
|
|
4985
|
-
const text = msg.text.trim();
|
|
4986
|
-
this.q.push({ kind: "status", state: "thinking" });
|
|
4987
|
-
if (text.startsWith("sleep:")) {
|
|
4988
|
-
const ms = Math.min(6e4, Number(text.slice(6)) || 1e3);
|
|
4989
|
-
this.abort = new AbortController();
|
|
4990
|
-
const signal = this.abort.signal;
|
|
4991
|
-
const slept = await new Promise((res) => {
|
|
4992
|
-
const t = setTimeout(() => res(true), ms);
|
|
4993
|
-
signal.addEventListener("abort", () => (clearTimeout(t), res(false)));
|
|
4994
|
-
});
|
|
4995
|
-
this.abort = null;
|
|
4996
|
-
this.q.push({ kind: "text", text: slept ? `slept ${ms}ms` : "interrupted", final: true });
|
|
4997
|
-
this.q.push({ kind: "done", interrupted: !slept });
|
|
4998
|
-
return;
|
|
4999
|
-
}
|
|
5000
|
-
if (text.startsWith("approve:")) {
|
|
5001
|
-
const id = newId();
|
|
5002
|
-
const tool2 = text.slice(8) || "Bash";
|
|
5003
|
-
this.q.push({ kind: "approval.request", id, tool: tool2, input: { command: `echo ${tool2}` }, description: `Run ${tool2}` });
|
|
5004
|
-
const allow = await new Promise((res) => this.pending.set(id, res));
|
|
5005
|
-
this.q.push({ kind: "text", text: allow ? `approved ${tool2}` : `denied ${tool2}`, final: true });
|
|
5006
|
-
this.q.push({ kind: "done", interrupted: false });
|
|
5007
|
-
return;
|
|
5008
|
-
}
|
|
5009
|
-
if (text.startsWith("msg:") || text.startsWith("ask:") || text.startsWith("send:")) {
|
|
5010
|
-
const [, to = "", ...rest] = text.split(":");
|
|
5011
|
-
const id = newId();
|
|
5012
|
-
const r = await new Promise((res) => {
|
|
5013
|
-
const t = setTimeout(() => res({ error: "no answer from the router" }), 5e3);
|
|
5014
|
-
this.agentWaits.set(id, (x) => (clearTimeout(t), res(x)));
|
|
5015
|
-
this.q.push({ kind: "agent.send", id, to: to.trim(), text: rest.join(":").trim() });
|
|
5016
|
-
});
|
|
5017
|
-
this.agentWaits.delete(id);
|
|
5018
|
-
this.q.push({ kind: "text", text: r.error ? `could not reach ${to}: ${r.error}` : `sent to ${to}: ${r.text}`, final: true });
|
|
5019
|
-
this.q.push({ kind: "done", interrupted: false });
|
|
5020
|
-
return;
|
|
5021
|
-
}
|
|
5022
|
-
if (text === "agents:" || text.startsWith("agents:")) {
|
|
5023
|
-
const id = newId();
|
|
5024
|
-
const r = await new Promise((res) => {
|
|
5025
|
-
const t = setTimeout(() => res({ error: "no answer from the router" }), 5e3);
|
|
5026
|
-
this.agentWaits.set(id, (x) => (clearTimeout(t), res(x)));
|
|
5027
|
-
this.q.push({ kind: "agents.list", id });
|
|
5028
|
-
});
|
|
5029
|
-
this.agentWaits.delete(id);
|
|
5030
|
-
this.q.push({ kind: "text", text: r.error ? `could not list agents: ${r.error}` : `agents:
|
|
5031
|
-
${r.text}`, final: true });
|
|
5032
|
-
this.q.push({ kind: "done", interrupted: false });
|
|
5033
|
-
return;
|
|
5034
|
-
}
|
|
5035
|
-
if (text.startsWith("tool:")) {
|
|
5036
|
-
const [, name = "", ...rest] = text.split(":");
|
|
5037
|
-
const [prompt = "", ...pairs] = rest.join(":").split("|");
|
|
5038
|
-
const t = (this.opts.settings.tools ?? []).find((x) => x.name === name.trim());
|
|
5039
|
-
const reply = async () => {
|
|
5040
|
-
if (!t) return { content: [{ type: "text", text: `no tool called ${name}` }], isError: true };
|
|
5041
|
-
const args = 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()]));
|
|
5042
|
-
return this.tools.call(t, t.capability === "stt" ? { ...args, file: prompt } : { ...args, prompt });
|
|
5043
|
-
};
|
|
5044
|
-
const callId = `tu-${newId().slice(0, 8)}`;
|
|
5045
|
-
this.q.push({ kind: "tool", id: callId, name: `mcp__monoclaw-tools__${name.trim()}`, summary: prompt, input: JSON.stringify({ prompt }) });
|
|
5046
|
-
const r = await reply();
|
|
5047
|
-
const out = r.content.map((c) => c.text).join("\n");
|
|
5048
|
-
this.q.push({ kind: "tool_result", id: callId, name: `mcp__monoclaw-tools__${name.trim()}`, output: out, isError: !!r.isError });
|
|
5049
|
-
this.q.push({ kind: "text", text: out, final: true });
|
|
5050
|
-
this.q.push({ kind: "done", interrupted: false });
|
|
5051
|
-
return;
|
|
5052
|
-
}
|
|
5053
|
-
if (text.startsWith("tools:")) {
|
|
5054
|
-
const n = Math.max(1, Math.min(20, Number(text.slice(6)) || 2));
|
|
5055
|
-
this.q.push({ kind: "thinking", text: "I should look at the files first, then run the tests." });
|
|
5056
|
-
this.q.push({ kind: "text", text: "Let me look at the files.", final: false });
|
|
5057
|
-
for (let i = 1; i <= n; i++) {
|
|
5058
|
-
const name = i % 2 ? "Read" : "Bash";
|
|
5059
|
-
const input = i % 2 ? { file_path: `src/file-${i}.ts` } : { command: `pnpm test --run ${i}`, description: `Run test ${i}` };
|
|
5060
|
-
this.q.push({ kind: "tool", id: `tu-${i}`, name, summary: i % 2 ? `Read src/file-${i}.ts` : `Run test ${i}`, input: JSON.stringify(input) });
|
|
5061
|
-
this.q.push({ kind: "status", state: "tool", detail: name });
|
|
5062
|
-
await new Promise((r) => setTimeout(r, 5));
|
|
5063
|
-
this.q.push({ kind: "tool_result", id: `tu-${i}`, name, output: i % 2 ? `export const x${i} = ${i};` : `${i} passed`, isError: false });
|
|
5064
|
-
}
|
|
5065
|
-
this.q.push({ kind: "text", text: `Done: looked at ${n} things and all is well.`, final: true });
|
|
5066
|
-
this.q.push({ kind: "usage", inputTokens: 10, outputTokens: 10, costUsd: 0, durationMs: 1, turns: 1 });
|
|
5067
|
-
this.q.push({ kind: "done", interrupted: false });
|
|
5068
|
-
return;
|
|
5069
|
-
}
|
|
5070
|
-
if (text.startsWith("file:")) {
|
|
5071
|
-
const p = text.slice(5).trim();
|
|
5072
|
-
this.q.push({ kind: "file", path: p, name: p.split(/[\\/]/).pop() ?? "file", caption: "here you go" });
|
|
5073
|
-
} else if (text.startsWith("error:")) {
|
|
5074
|
-
this.q.push({ kind: "error", message: text.slice(6).trim() || "echo error", fatal: false });
|
|
5075
|
-
} else if (text.startsWith("md:")) {
|
|
5076
|
-
this.q.push({ kind: "text", text: "## Echo\n\nHere is **bold**, `code` and a list:\n\n- one\n- two\n\n```js\nconsole.log('hi')\n```", final: true });
|
|
5077
|
-
} else {
|
|
5078
|
-
const ctx = msg.context ? ` (with ${msg.context.split("\n").length} context lines)` : "";
|
|
5079
|
-
const att = msg.attachments.length ? ` [${msg.attachments.map((a) => a.name).join(", ")}]` : "";
|
|
5080
|
-
const reply = `${msg.sender.name}: ${text}${ctx}${att}`;
|
|
5081
|
-
const step = Math.max(1, Math.ceil(reply.length / 3));
|
|
5082
|
-
for (let i = 0; i < reply.length; i += step) {
|
|
5083
|
-
this.q.push({ kind: "text.delta", text: reply.slice(i, i + step) });
|
|
5084
|
-
await new Promise((r) => setTimeout(r, 40));
|
|
5085
|
-
}
|
|
5086
|
-
this.q.push({ kind: "text", text: reply, final: true });
|
|
5087
|
-
}
|
|
5088
|
-
this.q.push({ kind: "usage", inputTokens: text.length, outputTokens: text.length, costUsd: 0, durationMs: 1, turns: 1 });
|
|
5089
|
-
this.q.push({ kind: "done", interrupted: false });
|
|
5090
|
-
}
|
|
5091
|
-
events() {
|
|
5092
|
-
return this.q;
|
|
5093
|
-
}
|
|
5094
|
-
answerApproval(id, allow) {
|
|
5095
|
-
this.pending.get(id)?.(allow);
|
|
5096
|
-
this.pending.delete(id);
|
|
5097
|
-
}
|
|
5098
|
-
agentResult(id, result) {
|
|
5099
|
-
this.agentWaits.get(id)?.(result);
|
|
5100
|
-
}
|
|
5101
|
-
toolResult(id, result) {
|
|
5102
|
-
this.tools.result(id, result);
|
|
5103
|
-
}
|
|
5104
|
-
async interrupt() {
|
|
5105
|
-
this.abort?.abort();
|
|
5106
|
-
}
|
|
5107
|
-
async setModel(id) {
|
|
5108
|
-
this.model = id ?? "echo-1";
|
|
5109
|
-
this.q.push({ kind: "session", model: this.model });
|
|
5110
|
-
}
|
|
5111
|
-
async setPermissionMode(mode) {
|
|
5112
|
-
this.mode = mode;
|
|
5113
|
-
this.q.push({ kind: "session", permissionMode: mode });
|
|
5114
|
-
}
|
|
5115
|
-
async listModels() {
|
|
5116
|
-
return [
|
|
5117
|
-
{ id: "echo-1", name: "Echo One", description: "Repeats quickly" },
|
|
5118
|
-
{ id: "echo-2", name: "Echo Two", description: "Repeats thoughtfully" }
|
|
5119
|
-
];
|
|
5120
|
-
}
|
|
5121
|
-
async listCommands() {
|
|
5122
|
-
return [{ name: "echo-help", description: "Echo provider help", argumentHint: "" }];
|
|
5123
|
-
}
|
|
5124
|
-
async close() {
|
|
5125
|
-
this.abort?.abort();
|
|
5126
|
-
this.tools.close();
|
|
5127
|
-
this.q.close();
|
|
5128
|
-
}
|
|
5129
|
-
};
|
|
5130
|
-
var echoProvider = {
|
|
5131
|
-
manifest: {
|
|
5132
|
-
id: "echo",
|
|
5133
|
-
name: "Echo (test)",
|
|
5134
|
-
version: "1.0.0",
|
|
5135
|
-
description: "Repeats what you say. For testing the plumbing without a model.",
|
|
5136
|
-
capabilities: { models: true, permissionModes: ["default", "auto"], interrupt: true, steering: true, sessions: false, passthroughCommands: false, approvals: true, files: true, streaming: false, summarise: true },
|
|
5137
|
-
defaultModel: "echo-1",
|
|
5138
|
-
defaultPermissionMode: "default"
|
|
5139
|
-
},
|
|
5140
|
-
async probe() {
|
|
5141
|
-
return { ready: true, summary: "Ready", details: {} };
|
|
5142
|
-
},
|
|
5143
|
-
openSession(opts) {
|
|
5144
|
-
return new EchoSession(opts);
|
|
5145
|
-
},
|
|
5146
|
-
/** First twenty words of the reply, or an error when the reply says `summary-fail`, so the router's fallback can be tested. */
|
|
5147
|
-
async summarise(input) {
|
|
5148
|
-
if (/summary-fail/.test(input.reply)) throw new Error("echo cannot summarise this");
|
|
5149
|
-
const words = input.reply.replace(/\s+/g, " ").trim().split(" ").slice(0, Math.min(20, input.style.maxWords ?? 120));
|
|
5150
|
-
const head = input.mode === "progress" ? "Progress" : "Summary";
|
|
5151
|
-
const extra = input.activity ? ` [${input.activity.split("\n").length} activity lines]` : "";
|
|
5152
|
-
return { text: `${head}: ${words.join(" ")}${extra}`, model: input.model || "echo-1", inputTokens: input.reply.length, outputTokens: words.length, costUsd: 0 };
|
|
5153
|
-
}
|
|
5154
|
-
};
|
|
5155
|
-
|
|
5156
|
-
// src/providers/claude/index.ts
|
|
5157
|
-
import { execFile as execFile6 } from "node:child_process";
|
|
5158
|
-
import fs19 from "node:fs";
|
|
5159
|
-
import os5 from "node:os";
|
|
5160
|
-
import path19 from "node:path";
|
|
5161
|
-
import { promisify as promisify6 } from "node:util";
|
|
5162
|
-
import { z as z9 } from "zod";
|
|
5163
|
-
import { createSdkMcpServer, listSessions, query, tool } from "@anthropic-ai/claude-agent-sdk";
|
|
5164
|
-
|
|
5165
|
-
// src/providers/claude/cli.ts
|
|
5166
|
-
import { execFile as execFile5 } from "node:child_process";
|
|
4938
|
+
// src/connect.ts
|
|
4939
|
+
import { execFile as execFile5, spawn as spawn4 } from "node:child_process";
|
|
5167
4940
|
import fs18 from "node:fs";
|
|
5168
|
-
import
|
|
4941
|
+
import os5 from "node:os";
|
|
5169
4942
|
import path18 from "node:path";
|
|
5170
4943
|
import { promisify as promisify5 } from "node:util";
|
|
5171
4944
|
|
|
@@ -5288,9 +5061,9 @@ var npmInstallArgs2 = (spec) => ["install", "-g", spec, "--ignore-scripts", "--n
|
|
|
5288
5061
|
function npmInstallGlobal(spec) {
|
|
5289
5062
|
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
5063
|
const npm = process.platform === "win32" ? "npm.cmd" : "npm";
|
|
5291
|
-
const
|
|
5064
|
+
const args2 = npmInstallArgs2(spec);
|
|
5292
5065
|
return new Promise((resolve, reject) => {
|
|
5293
|
-
const child = spawn3(npm,
|
|
5066
|
+
const child = spawn3(npm, args2, { stdio: ["ignore", "pipe", "pipe"], shell: process.platform === "win32", env: { ...process.env, npm_config_update_notifier: "false" } });
|
|
5294
5067
|
let out = "";
|
|
5295
5068
|
child.stdout.on("data", (d) => out += d);
|
|
5296
5069
|
child.stderr.on("data", (d) => out += d);
|
|
@@ -5393,18 +5166,357 @@ function startPeriodicChecks(routerUrl, hooks) {
|
|
|
5393
5166
|
};
|
|
5394
5167
|
}
|
|
5395
5168
|
|
|
5396
|
-
// src/
|
|
5397
|
-
var
|
|
5398
|
-
|
|
5399
|
-
|
|
5400
|
-
function isMusl() {
|
|
5401
|
-
if (process.platform !== "linux") return false;
|
|
5169
|
+
// src/connect.ts
|
|
5170
|
+
var DEFAULT_ROUTER = "https://command.monoclaw.ai";
|
|
5171
|
+
function ranFromNpx(entry = process.argv[1] ?? "") {
|
|
5172
|
+
let real = entry;
|
|
5402
5173
|
try {
|
|
5403
|
-
|
|
5174
|
+
real = fs18.realpathSync(entry);
|
|
5175
|
+
} catch {
|
|
5176
|
+
}
|
|
5177
|
+
return /[\\/]_npx[\\/]/.test(real);
|
|
5178
|
+
}
|
|
5179
|
+
function globalInstall(prefix, platform = process.platform) {
|
|
5180
|
+
const p = platform === "win32" ? path18.win32 : path18.posix;
|
|
5181
|
+
const modules2 = platform === "win32" ? p.join(prefix, "node_modules") : p.join(prefix, "lib", "node_modules");
|
|
5182
|
+
return { script: p.join(modules2, "@monoclaw", "machine", "bin", "monoclaw.js"), binDir: platform === "win32" ? prefix : p.join(prefix, "bin") };
|
|
5183
|
+
}
|
|
5184
|
+
function enrolArgs(o, hasEnrolment, home = os5.homedir()) {
|
|
5185
|
+
const args2 = [...o.profile ? ["--profile", o.profile] : [], "enrol", o.token, "--router", o.router];
|
|
5186
|
+
const roots2 = o.root?.length ? o.root : hasEnrolment ? [] : [path18.join(home, "command")];
|
|
5187
|
+
if (roots2.length) args2.push("--root", ...roots2);
|
|
5188
|
+
if (o.name) args2.push("--name", o.name);
|
|
5189
|
+
if (o.insecure) args2.push("--insecure");
|
|
5190
|
+
return args2;
|
|
5191
|
+
}
|
|
5192
|
+
var profileArgs = (profile) => profile ? ["--profile", profile] : [];
|
|
5193
|
+
function enrolledProfile(file = connectResultPath()) {
|
|
5194
|
+
try {
|
|
5195
|
+
const r = JSON.parse(fs18.readFileSync(file, "utf8"));
|
|
5196
|
+
return typeof r.profile === "string" && r.profile ? r.profile : null;
|
|
5197
|
+
} catch {
|
|
5198
|
+
return null;
|
|
5199
|
+
} finally {
|
|
5200
|
+
fs18.rmSync(file, { force: true });
|
|
5201
|
+
}
|
|
5202
|
+
}
|
|
5203
|
+
function installFailure(message) {
|
|
5204
|
+
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.";
|
|
5205
|
+
return `npm could not install ${PACKAGE}: ${message.trim().split("\n").slice(-3).join(" ").slice(0, 300)}`;
|
|
5206
|
+
}
|
|
5207
|
+
async function npmPrefix() {
|
|
5208
|
+
const npm = process.platform === "win32" ? "npm.cmd" : "npm";
|
|
5209
|
+
const { stdout } = await promisify5(execFile5)(npm, ["prefix", "-g"], { shell: process.platform === "win32", timeout: 3e4 });
|
|
5210
|
+
return stdout.trim();
|
|
5211
|
+
}
|
|
5212
|
+
function run2(node, script, args2) {
|
|
5213
|
+
return new Promise((resolve) => {
|
|
5214
|
+
const child = spawn4(node, [script, ...args2], { stdio: "inherit", env: { ...process.env, MONOCLAW_CONNECT: "1" } });
|
|
5215
|
+
child.on("error", () => resolve(1));
|
|
5216
|
+
child.on("exit", (code) => resolve(code ?? 1));
|
|
5217
|
+
});
|
|
5218
|
+
}
|
|
5219
|
+
async function connect(o, out = { say: (s) => console.log(s), fail: (s) => console.error(s) }) {
|
|
5220
|
+
out.say("MonoClaw: connecting this computer");
|
|
5221
|
+
const node = process.execPath;
|
|
5222
|
+
let script = process.argv[1] ?? "";
|
|
5223
|
+
const lasting = detectInstallMode() === "npm-global" && !ranFromNpx();
|
|
5224
|
+
if (!lasting && detectInstallMode() !== "checkout") {
|
|
5225
|
+
const spec = o.from ?? `${PACKAGE}@${APP_VERSION}`;
|
|
5226
|
+
out.say(`Installing ${spec} with npm...`);
|
|
5227
|
+
try {
|
|
5228
|
+
await npmInstallGlobal(spec);
|
|
5229
|
+
} catch (e) {
|
|
5230
|
+
out.fail(installFailure(e.message));
|
|
5231
|
+
return 1;
|
|
5232
|
+
}
|
|
5233
|
+
try {
|
|
5234
|
+
const g = globalInstall(await npmPrefix());
|
|
5235
|
+
if (!fs18.existsSync(g.script)) throw new Error(`${g.script} is missing`);
|
|
5236
|
+
script = g.script;
|
|
5237
|
+
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.`);
|
|
5238
|
+
} catch (e) {
|
|
5239
|
+
out.fail(`Installed, but the program could not be found afterwards (${e.message}). Run: npm install -g ${PACKAGE}`);
|
|
5240
|
+
return 1;
|
|
5241
|
+
}
|
|
5242
|
+
}
|
|
5243
|
+
const hasEnrolment = listProfiles().some((p) => p.config);
|
|
5244
|
+
fs18.rmSync(connectResultPath(), { force: true });
|
|
5245
|
+
if (await run2(node, script, enrolArgs(o, hasEnrolment)) !== 0) {
|
|
5246
|
+
out.fail("This computer was not connected. If the token has run out, copy a new command from Add a machine.");
|
|
5247
|
+
return 1;
|
|
5248
|
+
}
|
|
5249
|
+
const profile = profileArgs(o.profile ?? enrolledProfile());
|
|
5250
|
+
if (o.service && await run2(node, script, [...profile, "service", "install"]) !== 0) {
|
|
5251
|
+
out.fail(`The background service could not be installed here. Run it in this terminal instead: monoclaw ${[...profile, "start"].join(" ")}`);
|
|
5252
|
+
return 1;
|
|
5253
|
+
}
|
|
5254
|
+
out.say("");
|
|
5255
|
+
await run2(node, script, [...profile, "doctor"]);
|
|
5256
|
+
out.say("");
|
|
5257
|
+
out.say(o.service ? "Connected. Go back to MonoClaw in your browser: it has moved on by itself." : `Connected. Now run it: monoclaw ${[...profile, "start"].join(" ")}`);
|
|
5258
|
+
return 0;
|
|
5259
|
+
}
|
|
5260
|
+
|
|
5261
|
+
// src/providers/queue.ts
|
|
5262
|
+
var EventQueue = class {
|
|
5263
|
+
items = [];
|
|
5264
|
+
waiters = [];
|
|
5265
|
+
closed = false;
|
|
5266
|
+
push(item) {
|
|
5267
|
+
if (this.closed) return;
|
|
5268
|
+
const w = this.waiters.shift();
|
|
5269
|
+
if (w) w({ value: item, done: false });
|
|
5270
|
+
else this.items.push(item);
|
|
5271
|
+
}
|
|
5272
|
+
close() {
|
|
5273
|
+
this.closed = true;
|
|
5274
|
+
for (const w of this.waiters.splice(0)) w({ value: void 0, done: true });
|
|
5275
|
+
}
|
|
5276
|
+
get isClosed() {
|
|
5277
|
+
return this.closed;
|
|
5278
|
+
}
|
|
5279
|
+
[Symbol.asyncIterator]() {
|
|
5280
|
+
return {
|
|
5281
|
+
next: () => {
|
|
5282
|
+
const item = this.items.shift();
|
|
5283
|
+
if (item !== void 0) return Promise.resolve({ value: item, done: false });
|
|
5284
|
+
if (this.closed) return Promise.resolve({ value: void 0, done: true });
|
|
5285
|
+
return new Promise((res) => this.waiters.push(res));
|
|
5286
|
+
},
|
|
5287
|
+
return: () => {
|
|
5288
|
+
this.close();
|
|
5289
|
+
return Promise.resolve({ value: void 0, done: true });
|
|
5290
|
+
}
|
|
5291
|
+
};
|
|
5292
|
+
}
|
|
5293
|
+
};
|
|
5294
|
+
|
|
5295
|
+
// src/providers/echo/index.ts
|
|
5296
|
+
var EchoSession = class {
|
|
5297
|
+
constructor(opts) {
|
|
5298
|
+
this.opts = opts;
|
|
5299
|
+
this.mode = opts.settings.permissionMode ?? "default";
|
|
5300
|
+
this.tools = new SessionToolRunner(
|
|
5301
|
+
(ev) => this.q.push(ev),
|
|
5302
|
+
(tool2, input, description) => {
|
|
5303
|
+
const id = newId();
|
|
5304
|
+
this.q.push({ kind: "approval.request", id, tool: tool2, input, description });
|
|
5305
|
+
return new Promise((res) => this.pending.set(id, res));
|
|
5306
|
+
},
|
|
5307
|
+
opts.cwd,
|
|
5308
|
+
void 0,
|
|
5309
|
+
opts.settings.scope ?? "full"
|
|
5310
|
+
);
|
|
5311
|
+
const forked = opts.forkFrom && !opts.resumeId ? `${opts.forkFrom}-fork-${newId().slice(0, 4)}` : void 0;
|
|
5312
|
+
this.q.push({ kind: "session", providerSessionId: opts.resumeId ?? forked ?? `echo-${newId().slice(0, 8)}`, model: this.model, permissionMode: this.mode, commands: [{ name: "echo-help", description: "Echo provider help", argumentHint: "" }], tools: opts.settings.scope === "chat" ? [] : opts.settings.scope === "read" ? ["read"] : ["echo"], version: "1" });
|
|
5313
|
+
}
|
|
5314
|
+
opts;
|
|
5315
|
+
q = new EventQueue();
|
|
5316
|
+
pending = /* @__PURE__ */ new Map();
|
|
5317
|
+
agentWaits = /* @__PURE__ */ new Map();
|
|
5318
|
+
tools;
|
|
5319
|
+
abort = null;
|
|
5320
|
+
model = "echo-1";
|
|
5321
|
+
mode;
|
|
5322
|
+
async send(msg) {
|
|
5323
|
+
const text = msg.text.trim();
|
|
5324
|
+
this.q.push({ kind: "status", state: "thinking" });
|
|
5325
|
+
if (text.startsWith("sleep:")) {
|
|
5326
|
+
const ms = Math.min(6e4, Number(text.slice(6)) || 1e3);
|
|
5327
|
+
this.abort = new AbortController();
|
|
5328
|
+
const signal = this.abort.signal;
|
|
5329
|
+
const slept = await new Promise((res) => {
|
|
5330
|
+
const t = setTimeout(() => res(true), ms);
|
|
5331
|
+
signal.addEventListener("abort", () => (clearTimeout(t), res(false)));
|
|
5332
|
+
});
|
|
5333
|
+
this.abort = null;
|
|
5334
|
+
this.q.push({ kind: "text", text: slept ? `slept ${ms}ms` : "interrupted", final: true });
|
|
5335
|
+
this.q.push({ kind: "done", interrupted: !slept });
|
|
5336
|
+
return;
|
|
5337
|
+
}
|
|
5338
|
+
if (text.startsWith("approve:")) {
|
|
5339
|
+
const id = newId();
|
|
5340
|
+
const tool2 = text.slice(8) || "Bash";
|
|
5341
|
+
this.q.push({ kind: "approval.request", id, tool: tool2, input: { command: `echo ${tool2}` }, description: `Run ${tool2}` });
|
|
5342
|
+
const allow = await new Promise((res) => this.pending.set(id, res));
|
|
5343
|
+
this.q.push({ kind: "text", text: allow ? `approved ${tool2}` : `denied ${tool2}`, final: true });
|
|
5344
|
+
this.q.push({ kind: "done", interrupted: false });
|
|
5345
|
+
return;
|
|
5346
|
+
}
|
|
5347
|
+
if (text.startsWith("msg:") || text.startsWith("ask:") || text.startsWith("send:")) {
|
|
5348
|
+
const [, to = "", ...rest] = text.split(":");
|
|
5349
|
+
const id = newId();
|
|
5350
|
+
const r = await new Promise((res) => {
|
|
5351
|
+
const t = setTimeout(() => res({ error: "no answer from the router" }), 5e3);
|
|
5352
|
+
this.agentWaits.set(id, (x) => (clearTimeout(t), res(x)));
|
|
5353
|
+
this.q.push({ kind: "agent.send", id, to: to.trim(), text: rest.join(":").trim() });
|
|
5354
|
+
});
|
|
5355
|
+
this.agentWaits.delete(id);
|
|
5356
|
+
this.q.push({ kind: "text", text: r.error ? `could not reach ${to}: ${r.error}` : `sent to ${to}: ${r.text}`, final: true });
|
|
5357
|
+
this.q.push({ kind: "done", interrupted: false });
|
|
5358
|
+
return;
|
|
5359
|
+
}
|
|
5360
|
+
if (text === "agents:" || text.startsWith("agents:")) {
|
|
5361
|
+
const id = newId();
|
|
5362
|
+
const r = await new Promise((res) => {
|
|
5363
|
+
const t = setTimeout(() => res({ error: "no answer from the router" }), 5e3);
|
|
5364
|
+
this.agentWaits.set(id, (x) => (clearTimeout(t), res(x)));
|
|
5365
|
+
this.q.push({ kind: "agents.list", id });
|
|
5366
|
+
});
|
|
5367
|
+
this.agentWaits.delete(id);
|
|
5368
|
+
this.q.push({ kind: "text", text: r.error ? `could not list agents: ${r.error}` : `agents:
|
|
5369
|
+
${r.text}`, final: true });
|
|
5370
|
+
this.q.push({ kind: "done", interrupted: false });
|
|
5371
|
+
return;
|
|
5372
|
+
}
|
|
5373
|
+
if (text.startsWith("tool:")) {
|
|
5374
|
+
const [, name = "", ...rest] = text.split(":");
|
|
5375
|
+
const [prompt = "", ...pairs] = rest.join(":").split("|");
|
|
5376
|
+
const t = (this.opts.settings.tools ?? []).find((x) => x.name === name.trim());
|
|
5377
|
+
const reply = async () => {
|
|
5378
|
+
if (!t) return { content: [{ type: "text", text: `no tool called ${name}` }], isError: true };
|
|
5379
|
+
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()]));
|
|
5380
|
+
return this.tools.call(t, t.capability === "stt" ? { ...args2, file: prompt } : { ...args2, prompt });
|
|
5381
|
+
};
|
|
5382
|
+
const callId = `tu-${newId().slice(0, 8)}`;
|
|
5383
|
+
this.q.push({ kind: "tool", id: callId, name: `mcp__monoclaw-tools__${name.trim()}`, summary: prompt, input: JSON.stringify({ prompt }) });
|
|
5384
|
+
const r = await reply();
|
|
5385
|
+
const out = r.content.map((c) => c.text).join("\n");
|
|
5386
|
+
this.q.push({ kind: "tool_result", id: callId, name: `mcp__monoclaw-tools__${name.trim()}`, output: out, isError: !!r.isError });
|
|
5387
|
+
this.q.push({ kind: "text", text: out, final: true });
|
|
5388
|
+
this.q.push({ kind: "done", interrupted: false });
|
|
5389
|
+
return;
|
|
5390
|
+
}
|
|
5391
|
+
if (text.startsWith("tools:")) {
|
|
5392
|
+
const n = Math.max(1, Math.min(20, Number(text.slice(6)) || 2));
|
|
5393
|
+
this.q.push({ kind: "thinking", text: "I should look at the files first, then run the tests." });
|
|
5394
|
+
this.q.push({ kind: "text", text: "Let me look at the files.", final: false });
|
|
5395
|
+
for (let i = 1; i <= n; i++) {
|
|
5396
|
+
const name = i % 2 ? "Read" : "Bash";
|
|
5397
|
+
const input = i % 2 ? { file_path: `src/file-${i}.ts` } : { command: `pnpm test --run ${i}`, description: `Run test ${i}` };
|
|
5398
|
+
this.q.push({ kind: "tool", id: `tu-${i}`, name, summary: i % 2 ? `Read src/file-${i}.ts` : `Run test ${i}`, input: JSON.stringify(input) });
|
|
5399
|
+
this.q.push({ kind: "status", state: "tool", detail: name });
|
|
5400
|
+
await new Promise((r) => setTimeout(r, 5));
|
|
5401
|
+
this.q.push({ kind: "tool_result", id: `tu-${i}`, name, output: i % 2 ? `export const x${i} = ${i};` : `${i} passed`, isError: false });
|
|
5402
|
+
}
|
|
5403
|
+
this.q.push({ kind: "text", text: `Done: looked at ${n} things and all is well.`, final: true });
|
|
5404
|
+
this.q.push({ kind: "usage", inputTokens: 10, outputTokens: 10, costUsd: 0, durationMs: 1, turns: 1 });
|
|
5405
|
+
this.q.push({ kind: "done", interrupted: false });
|
|
5406
|
+
return;
|
|
5407
|
+
}
|
|
5408
|
+
if (text.startsWith("file:")) {
|
|
5409
|
+
const p = text.slice(5).trim();
|
|
5410
|
+
this.q.push({ kind: "file", path: p, name: p.split(/[\\/]/).pop() ?? "file", caption: "here you go" });
|
|
5411
|
+
} else if (text.startsWith("error:")) {
|
|
5412
|
+
this.q.push({ kind: "error", message: text.slice(6).trim() || "echo error", fatal: false });
|
|
5413
|
+
} else if (text.startsWith("md:")) {
|
|
5414
|
+
this.q.push({ kind: "text", text: "## Echo\n\nHere is **bold**, `code` and a list:\n\n- one\n- two\n\n```js\nconsole.log('hi')\n```", final: true });
|
|
5415
|
+
} else {
|
|
5416
|
+
const ctx = msg.context ? ` (with ${msg.context.split("\n").length} context lines)` : "";
|
|
5417
|
+
const att = msg.attachments.length ? ` [${msg.attachments.map((a) => a.name).join(", ")}]` : "";
|
|
5418
|
+
const reply = `${msg.sender.name}: ${text}${ctx}${att}`;
|
|
5419
|
+
const step = Math.max(1, Math.ceil(reply.length / 3));
|
|
5420
|
+
for (let i = 0; i < reply.length; i += step) {
|
|
5421
|
+
this.q.push({ kind: "text.delta", text: reply.slice(i, i + step) });
|
|
5422
|
+
await new Promise((r) => setTimeout(r, 40));
|
|
5423
|
+
}
|
|
5424
|
+
this.q.push({ kind: "text", text: reply, final: true });
|
|
5425
|
+
}
|
|
5426
|
+
this.q.push({ kind: "usage", inputTokens: text.length, outputTokens: text.length, costUsd: 0, durationMs: 1, turns: 1 });
|
|
5427
|
+
this.q.push({ kind: "done", interrupted: false });
|
|
5428
|
+
}
|
|
5429
|
+
events() {
|
|
5430
|
+
return this.q;
|
|
5431
|
+
}
|
|
5432
|
+
answerApproval(id, allow) {
|
|
5433
|
+
this.pending.get(id)?.(allow);
|
|
5434
|
+
this.pending.delete(id);
|
|
5435
|
+
}
|
|
5436
|
+
agentResult(id, result) {
|
|
5437
|
+
this.agentWaits.get(id)?.(result);
|
|
5438
|
+
}
|
|
5439
|
+
toolResult(id, result) {
|
|
5440
|
+
this.tools.result(id, result);
|
|
5441
|
+
}
|
|
5442
|
+
async interrupt() {
|
|
5443
|
+
this.abort?.abort();
|
|
5444
|
+
}
|
|
5445
|
+
async setModel(id) {
|
|
5446
|
+
this.model = id ?? "echo-1";
|
|
5447
|
+
this.q.push({ kind: "session", model: this.model });
|
|
5448
|
+
}
|
|
5449
|
+
async setPermissionMode(mode) {
|
|
5450
|
+
this.mode = mode;
|
|
5451
|
+
this.q.push({ kind: "session", permissionMode: mode });
|
|
5452
|
+
}
|
|
5453
|
+
async listModels() {
|
|
5454
|
+
return [
|
|
5455
|
+
{ id: "echo-1", name: "Echo One", description: "Repeats quickly" },
|
|
5456
|
+
{ id: "echo-2", name: "Echo Two", description: "Repeats thoughtfully" }
|
|
5457
|
+
];
|
|
5458
|
+
}
|
|
5459
|
+
async listCommands() {
|
|
5460
|
+
return [{ name: "echo-help", description: "Echo provider help", argumentHint: "" }];
|
|
5461
|
+
}
|
|
5462
|
+
async close() {
|
|
5463
|
+
this.abort?.abort();
|
|
5464
|
+
this.tools.close();
|
|
5465
|
+
this.q.close();
|
|
5466
|
+
}
|
|
5467
|
+
};
|
|
5468
|
+
var echoProvider = {
|
|
5469
|
+
manifest: {
|
|
5470
|
+
id: "echo",
|
|
5471
|
+
name: "Echo (test)",
|
|
5472
|
+
version: "1.0.0",
|
|
5473
|
+
description: "Repeats what you say. For testing the plumbing without a model.",
|
|
5474
|
+
capabilities: { models: true, permissionModes: ["default", "auto"], interrupt: true, steering: true, sessions: false, passthroughCommands: false, approvals: true, files: true, streaming: false, summarise: true },
|
|
5475
|
+
defaultModel: "echo-1",
|
|
5476
|
+
defaultPermissionMode: "default"
|
|
5477
|
+
},
|
|
5478
|
+
async probe() {
|
|
5479
|
+
return { ready: true, summary: "Ready", details: {} };
|
|
5480
|
+
},
|
|
5481
|
+
openSession(opts) {
|
|
5482
|
+
return new EchoSession(opts);
|
|
5483
|
+
},
|
|
5484
|
+
/** First twenty words of the reply, or an error when the reply says `summary-fail`, so the router's fallback can be tested. */
|
|
5485
|
+
async summarise(input) {
|
|
5486
|
+
if (/summary-fail/.test(input.reply)) throw new Error("echo cannot summarise this");
|
|
5487
|
+
const words = input.reply.replace(/\s+/g, " ").trim().split(" ").slice(0, Math.min(20, input.style.maxWords ?? 120));
|
|
5488
|
+
const head = input.mode === "progress" ? "Progress" : "Summary";
|
|
5489
|
+
const extra = input.activity ? ` [${input.activity.split("\n").length} activity lines]` : "";
|
|
5490
|
+
return { text: `${head}: ${words.join(" ")}${extra}`, model: input.model || "echo-1", inputTokens: input.reply.length, outputTokens: words.length, costUsd: 0 };
|
|
5491
|
+
}
|
|
5492
|
+
};
|
|
5493
|
+
|
|
5494
|
+
// src/providers/claude/index.ts
|
|
5495
|
+
import { execFile as execFile7 } from "node:child_process";
|
|
5496
|
+
import fs20 from "node:fs";
|
|
5497
|
+
import os6 from "node:os";
|
|
5498
|
+
import path20 from "node:path";
|
|
5499
|
+
import { promisify as promisify7 } from "node:util";
|
|
5500
|
+
import { z as z9 } from "zod";
|
|
5501
|
+
import { createSdkMcpServer, listSessions, query, tool } from "@anthropic-ai/claude-agent-sdk";
|
|
5502
|
+
|
|
5503
|
+
// src/providers/claude/cli.ts
|
|
5504
|
+
import { execFile as execFile6 } from "node:child_process";
|
|
5505
|
+
import fs19 from "node:fs";
|
|
5506
|
+
import { createRequire as createRequire3 } from "node:module";
|
|
5507
|
+
import path19 from "node:path";
|
|
5508
|
+
import { promisify as promisify6 } from "node:util";
|
|
5509
|
+
var execFileP5 = promisify6(execFile6);
|
|
5510
|
+
var SDK = "@anthropic-ai/claude-agent-sdk";
|
|
5511
|
+
var CLI_PATH_ENV = "MONOCLAW_CLAUDE_PATH";
|
|
5512
|
+
function isMusl() {
|
|
5513
|
+
if (process.platform !== "linux") return false;
|
|
5514
|
+
try {
|
|
5515
|
+
const header = process.report?.getReport()?.header;
|
|
5404
5516
|
if (header && "glibcVersionRuntime" in header) return !header.glibcVersionRuntime;
|
|
5405
5517
|
} catch {
|
|
5406
5518
|
}
|
|
5407
|
-
return
|
|
5519
|
+
return fs19.existsSync("/etc/alpine-release");
|
|
5408
5520
|
}
|
|
5409
5521
|
function platformPackages(platform = process.platform, arch = process.arch, musl = isMusl()) {
|
|
5410
5522
|
const base = `${SDK}-`;
|
|
@@ -5414,24 +5526,24 @@ function platformPackages(platform = process.platform, arch = process.arch, musl
|
|
|
5414
5526
|
}
|
|
5415
5527
|
var exe = (platform = process.platform) => platform === "win32" ? "claude.exe" : "claude";
|
|
5416
5528
|
function sdkRoot() {
|
|
5417
|
-
let dir =
|
|
5529
|
+
let dir = path19.dirname(createRequire3(import.meta.url).resolve(SDK));
|
|
5418
5530
|
for (let i = 0; i < 6; i++) {
|
|
5419
|
-
const pkg =
|
|
5531
|
+
const pkg = path19.join(dir, "package.json");
|
|
5420
5532
|
try {
|
|
5421
|
-
if (JSON.parse(
|
|
5533
|
+
if (JSON.parse(fs19.readFileSync(pkg, "utf8")).name === SDK) return dir;
|
|
5422
5534
|
} catch {
|
|
5423
5535
|
}
|
|
5424
|
-
dir =
|
|
5536
|
+
dir = path19.dirname(dir);
|
|
5425
5537
|
}
|
|
5426
5538
|
throw new Error(`could not find where ${SDK} is installed`);
|
|
5427
5539
|
}
|
|
5428
5540
|
function sdkResolve() {
|
|
5429
|
-
return createRequire3(
|
|
5541
|
+
return createRequire3(path19.join(sdkRoot(), "package.json")).resolve;
|
|
5430
5542
|
}
|
|
5431
5543
|
function sdkVersion() {
|
|
5432
|
-
return JSON.parse(
|
|
5544
|
+
return JSON.parse(fs19.readFileSync(path19.join(sdkRoot(), "package.json"), "utf8")).version;
|
|
5433
5545
|
}
|
|
5434
|
-
function bundledCli(resolve = sdkResolve(), exists =
|
|
5546
|
+
function bundledCli(resolve = sdkResolve(), exists = fs19.existsSync, platform = process.platform, arch = process.arch) {
|
|
5435
5547
|
for (const pkg of platformPackages(platform, arch)) {
|
|
5436
5548
|
try {
|
|
5437
5549
|
const p = resolve(`${pkg}/${exe(platform)}`);
|
|
@@ -5453,8 +5565,8 @@ async function cliOnPath(env = process.env) {
|
|
|
5453
5565
|
const which = process.platform === "win32" ? "where" : "which";
|
|
5454
5566
|
try {
|
|
5455
5567
|
const { stdout } = await execFileP5(which, ["claude"], { env, timeout: 1e4 });
|
|
5456
|
-
const
|
|
5457
|
-
return
|
|
5568
|
+
const first2 = stdout.split(/\r?\n/).map((l) => l.trim()).find(Boolean);
|
|
5569
|
+
return first2 ?? null;
|
|
5458
5570
|
} catch {
|
|
5459
5571
|
return null;
|
|
5460
5572
|
}
|
|
@@ -5470,7 +5582,7 @@ function resolveCli(deps = {}) {
|
|
|
5470
5582
|
}
|
|
5471
5583
|
async function resolveUncached(deps) {
|
|
5472
5584
|
const env = deps.env ?? process.env;
|
|
5473
|
-
const exists = deps.exists ??
|
|
5585
|
+
const exists = deps.exists ?? fs19.existsSync;
|
|
5474
5586
|
const version = deps.version ?? ((f) => cliVersion(f, env));
|
|
5475
5587
|
const override = env[CLI_PATH_ENV]?.trim();
|
|
5476
5588
|
if (override) {
|
|
@@ -5487,7 +5599,20 @@ function describeCli(c) {
|
|
|
5487
5599
|
const v = c.version ?? "version unknown";
|
|
5488
5600
|
return c.kind === "bundled" ? `bundled ${v}` : c.kind === "path" ? `PATH ${v} (${c.path})` : `${CLI_PATH_ENV} ${v} (${c.path})`;
|
|
5489
5601
|
}
|
|
5490
|
-
var NO_CLI_ACTION = "Run `monoclaw doctor` on this machine
|
|
5602
|
+
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`.";
|
|
5603
|
+
var SIGN_IN_ACTION = "Sign in on this machine: `monoclaw claude auth login`.";
|
|
5604
|
+
async function authStatus(cliPath, env) {
|
|
5605
|
+
let stdout;
|
|
5606
|
+
try {
|
|
5607
|
+
({ stdout } = await execFileP5(cliPath, ["auth", "status"], { env, timeout: 15e3 }));
|
|
5608
|
+
} catch (e) {
|
|
5609
|
+
const out = e.stdout;
|
|
5610
|
+
if (typeof out !== "string" || !out.trim().startsWith("{")) throw e;
|
|
5611
|
+
stdout = out;
|
|
5612
|
+
}
|
|
5613
|
+
const j = JSON.parse(stdout);
|
|
5614
|
+
return { loggedIn: !!j.loggedIn, authMethod: j.authMethod, apiProvider: j.apiProvider };
|
|
5615
|
+
}
|
|
5491
5616
|
async function repairBundledCli(deps = {}) {
|
|
5492
5617
|
const bundled = deps.bundled ?? (() => bundledCli());
|
|
5493
5618
|
if (bundled()) return { outcome: "present", detail: "the host's copy of Claude Code is installed" };
|
|
@@ -5515,7 +5640,7 @@ async function repairBundledCli(deps = {}) {
|
|
|
5515
5640
|
}
|
|
5516
5641
|
|
|
5517
5642
|
// src/providers/claude/index.ts
|
|
5518
|
-
var execFileP6 =
|
|
5643
|
+
var execFileP6 = promisify7(execFile7);
|
|
5519
5644
|
var PERMISSION_MODES = ["auto", "acceptEdits", "default", "plan", "bypassPermissions"];
|
|
5520
5645
|
var SESSION_SETTING_SOURCES = ["user", "project", "local"];
|
|
5521
5646
|
var APPROVAL_TIMEOUT_MS = 10 * 6e4;
|
|
@@ -5551,9 +5676,9 @@ function withOverrides(base, over) {
|
|
|
5551
5676
|
return out;
|
|
5552
5677
|
}
|
|
5553
5678
|
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(
|
|
5679
|
+
function sendToolResult(args2, r) {
|
|
5555
5680
|
if (r.error) return { content: [{ type: "text", text: r.error }], isError: true };
|
|
5556
|
-
return { content: [{ type: "text", text: r.text ?? `Sent to ${
|
|
5681
|
+
return { content: [{ type: "text", text: r.text ?? `Sent to ${args2.to}.` }] };
|
|
5557
5682
|
}
|
|
5558
5683
|
function frameInbound(text, sender, settings) {
|
|
5559
5684
|
if (settings.multiHuman && sender.kind === "human") return `[${sender.name}${sender.isAdmin ? " (admin)" : ""}] ${text}`;
|
|
@@ -5634,12 +5759,12 @@ var ClaudeSession = class {
|
|
|
5634
5759
|
"send_file",
|
|
5635
5760
|
"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
5761
|
{ 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,
|
|
5762
|
+
async (args2) => {
|
|
5763
|
+
const full = sendablePath(this.opts.cwd, args2.path);
|
|
5639
5764
|
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 ${
|
|
5765
|
+
if (!fs20.existsSync(full) || !fs20.statSync(full).isFile()) return { content: [{ type: "text", text: `No file at ${full}` }], isError: true };
|
|
5766
|
+
this.q.push({ kind: "file", path: full, name: path20.basename(full), mime: guessMime(full), caption: args2.caption });
|
|
5767
|
+
return { content: [{ type: "text", text: `Sent ${path20.basename(full)} to the chat.` }] };
|
|
5643
5768
|
}
|
|
5644
5769
|
)
|
|
5645
5770
|
);
|
|
@@ -5670,7 +5795,7 @@ var ClaudeSession = class {
|
|
|
5670
5795
|
"send",
|
|
5671
5796
|
SEND_TOOL_DESCRIPTION,
|
|
5672
5797
|
{ to: z9.string().min(1).describe("One agent's name from list_agents"), text: z9.string().describe("The message") },
|
|
5673
|
-
async (
|
|
5798
|
+
async (args2) => {
|
|
5674
5799
|
const id = newId();
|
|
5675
5800
|
const result = new Promise((resolve) => {
|
|
5676
5801
|
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 +5806,8 @@ var ClaudeSession = class {
|
|
|
5681
5806
|
};
|
|
5682
5807
|
this.agentWaits.set(id, finish);
|
|
5683
5808
|
});
|
|
5684
|
-
this.q.push({ kind: "agent.send", id, to:
|
|
5685
|
-
return sendToolResult(
|
|
5809
|
+
this.q.push({ kind: "agent.send", id, to: args2.to, text: args2.text });
|
|
5810
|
+
return sendToolResult(args2, await result);
|
|
5686
5811
|
}
|
|
5687
5812
|
)
|
|
5688
5813
|
);
|
|
@@ -5847,7 +5972,7 @@ ${files.map((a) => `- ${a.localPath} (${a.mime}, ${a.size} bytes)${a.note ? `: $
|
|
|
5847
5972
|
content.push({ type: "text", text });
|
|
5848
5973
|
for (const a of files) {
|
|
5849
5974
|
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:
|
|
5975
|
+
content.push({ type: "image", source: { type: "base64", media_type: a.mime, data: fs20.readFileSync(a.localPath).toString("base64") } });
|
|
5851
5976
|
}
|
|
5852
5977
|
}
|
|
5853
5978
|
const user = { type: "user", message: { role: "user", content }, parent_tool_use_id: null, priority: msg.delivery, origin: { kind: "human" } };
|
|
@@ -5912,7 +6037,7 @@ function sessionToolsServer(list, runner) {
|
|
|
5912
6037
|
const server = createSdkMcpServer({
|
|
5913
6038
|
name: TOOLS_SERVER,
|
|
5914
6039
|
version: "1.0.0",
|
|
5915
|
-
tools: list.map((t) => tool(t.name, t.description, toolShape(t.params, t.capability), async (
|
|
6040
|
+
tools: list.map((t) => tool(t.name, t.description, toolShape(t.params, t.capability), async (args2) => runner.call(t, args2)))
|
|
5916
6041
|
});
|
|
5917
6042
|
return { servers: { [TOOLS_SERVER]: server }, allowed: list.map((t) => toolMcpName(t)) };
|
|
5918
6043
|
}
|
|
@@ -5932,17 +6057,17 @@ function monoclawToolNames(s) {
|
|
|
5932
6057
|
function sendablePath(cwd, p) {
|
|
5933
6058
|
const real = (x) => {
|
|
5934
6059
|
try {
|
|
5935
|
-
return
|
|
6060
|
+
return fs20.realpathSync(x);
|
|
5936
6061
|
} catch {
|
|
5937
6062
|
return null;
|
|
5938
6063
|
}
|
|
5939
6064
|
};
|
|
5940
6065
|
const root = real(cwd);
|
|
5941
|
-
const full = real(
|
|
6066
|
+
const full = real(path20.resolve(cwd, p));
|
|
5942
6067
|
if (!root || !full) return null;
|
|
5943
|
-
if (full !== root && !full.startsWith(root +
|
|
5944
|
-
const rel =
|
|
5945
|
-
if (rel.split(
|
|
6068
|
+
if (full !== root && !full.startsWith(root + path20.sep)) return null;
|
|
6069
|
+
const rel = path20.relative(root, full);
|
|
6070
|
+
if (rel.split(path20.sep).some((seg) => seg.startsWith(".") && seg !== ".")) return null;
|
|
5946
6071
|
return full;
|
|
5947
6072
|
}
|
|
5948
6073
|
function safeJson(v) {
|
|
@@ -5961,30 +6086,30 @@ function friendlyPath(p, cwd) {
|
|
|
5961
6086
|
if (file === base) return ".";
|
|
5962
6087
|
if (file.startsWith(`${base}/`)) return file.slice(base.length + 1);
|
|
5963
6088
|
}
|
|
5964
|
-
const home = norm(
|
|
6089
|
+
const home = norm(os6.homedir());
|
|
5965
6090
|
if (home && file.startsWith(`${home}/`)) return `~/${file.slice(home.length + 1)}`;
|
|
5966
6091
|
return file;
|
|
5967
6092
|
}
|
|
5968
6093
|
var clip = (s, n) => s.length > n ? `${s.slice(0, n - 1)}\u2026` : s;
|
|
5969
6094
|
function describeTool(name, input, cwd) {
|
|
5970
6095
|
const s = (k) => typeof input[k] === "string" ? input[k] : void 0;
|
|
5971
|
-
const
|
|
6096
|
+
const path23 = (k) => friendlyPath(s(k), cwd);
|
|
5972
6097
|
const firstString = () => Object.values(input).find((v) => typeof v === "string" && v.trim().length > 0);
|
|
5973
6098
|
switch (name) {
|
|
5974
6099
|
case "Bash":
|
|
5975
6100
|
return clip(s("description") ?? s("command") ?? "run a command", 120);
|
|
5976
6101
|
case "Read":
|
|
5977
|
-
return `Read ${
|
|
6102
|
+
return `Read ${path23("file_path") || path23("path")}`.trim();
|
|
5978
6103
|
case "Edit":
|
|
5979
6104
|
case "Write":
|
|
5980
6105
|
case "MultiEdit":
|
|
5981
|
-
return `${name} ${
|
|
6106
|
+
return `${name} ${path23("file_path")}`.trim();
|
|
5982
6107
|
case "NotebookEdit":
|
|
5983
|
-
return `Edit notebook ${
|
|
6108
|
+
return `Edit notebook ${path23("notebook_path")}`.trim();
|
|
5984
6109
|
case "Grep":
|
|
5985
|
-
return `Grep "${clip(s("pattern") ?? "", 60)}"${s("path") ? ` in ${
|
|
6110
|
+
return `Grep "${clip(s("pattern") ?? "", 60)}"${s("path") ? ` in ${path23("path")}` : ""}`;
|
|
5986
6111
|
case "Glob":
|
|
5987
|
-
return `Find ${clip(s("pattern") ?? "", 60)}${s("path") ? ` in ${
|
|
6112
|
+
return `Find ${clip(s("pattern") ?? "", 60)}${s("path") ? ` in ${path23("path")}` : ""}`;
|
|
5988
6113
|
case "WebSearch":
|
|
5989
6114
|
return `Search "${clip(s("query") ?? "", 80)}"`;
|
|
5990
6115
|
case "WebFetch": {
|
|
@@ -6040,8 +6165,8 @@ ${instructions}`);
|
|
|
6040
6165
|
return parts.join("\n\n");
|
|
6041
6166
|
}
|
|
6042
6167
|
async function summarise(input) {
|
|
6043
|
-
const dir =
|
|
6044
|
-
|
|
6168
|
+
const dir = path20.join(configDir(), "summaries");
|
|
6169
|
+
fs20.mkdirSync(dir, { recursive: true, mode: 448 });
|
|
6045
6170
|
const model = input.model?.trim() || process.env.MONOCLAW_SUMMARY_MODEL || DEFAULT_SUMMARY_MODEL;
|
|
6046
6171
|
const abortController = new AbortController();
|
|
6047
6172
|
const timer = setTimeout(() => abortController.abort(), SUMMARY_TIMEOUT_MS);
|
|
@@ -6122,12 +6247,11 @@ var claudeProvider = {
|
|
|
6122
6247
|
const fallback = cli.kind === "path" ? " \xB7 using the Claude Code on this machine (the host's copy is missing; `monoclaw doctor` repairs it)" : "";
|
|
6123
6248
|
if (env?.ANTHROPIC_API_KEY) return { ready: true, summary: "API key", details: { version, cli: where, authMethod: "api_key" } };
|
|
6124
6249
|
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`)." };
|
|
6250
|
+
const j = await authStatus(cli.path, withOverrides(cleanEnv(), env));
|
|
6251
|
+
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
6252
|
return { ready: true, summary: `Logged in (${j.authMethod ?? "ok"})${fallback}`, details: { version, cli: where, authMethod: j.authMethod ?? "", apiProvider: j.apiProvider ?? "" } };
|
|
6129
6253
|
} 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." };
|
|
6254
|
+
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
6255
|
}
|
|
6132
6256
|
},
|
|
6133
6257
|
openSession(opts) {
|
|
@@ -6150,9 +6274,9 @@ var providers = only.length ? Object.fromEntries(Object.entries(all).filter(([id
|
|
|
6150
6274
|
|
|
6151
6275
|
// src/service.ts
|
|
6152
6276
|
import { spawnSync } from "node:child_process";
|
|
6153
|
-
import
|
|
6154
|
-
import
|
|
6155
|
-
import
|
|
6277
|
+
import fs21 from "node:fs";
|
|
6278
|
+
import os7 from "node:os";
|
|
6279
|
+
import path21 from "node:path";
|
|
6156
6280
|
function serviceNames(profile = currentProfile()) {
|
|
6157
6281
|
return { unit: profile ? `monoclaw-${profile}` : "monoclaw", label: profile ? `ai.monoclaw.host.${profile}` : "ai.monoclaw.host", task: profile ? `MonoClaw host (${profile})` : "MonoClaw host" };
|
|
6158
6282
|
}
|
|
@@ -6163,26 +6287,26 @@ function profileEnv() {
|
|
|
6163
6287
|
function selfCommand() {
|
|
6164
6288
|
let script = process.argv[1] ?? "";
|
|
6165
6289
|
try {
|
|
6166
|
-
script =
|
|
6290
|
+
script = fs21.realpathSync(script);
|
|
6167
6291
|
} catch {
|
|
6168
6292
|
}
|
|
6169
6293
|
return { node: process.execPath, script };
|
|
6170
6294
|
}
|
|
6171
6295
|
function servicePath(node) {
|
|
6172
|
-
const dirs = process.platform === "win32" ? [
|
|
6173
|
-
return [...new Set(dirs)].join(
|
|
6296
|
+
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"];
|
|
6297
|
+
return [...new Set(dirs)].join(path21.delimiter);
|
|
6174
6298
|
}
|
|
6175
6299
|
function serviceInstructions() {
|
|
6176
6300
|
const dir = configDir();
|
|
6177
|
-
const home =
|
|
6301
|
+
const home = os7.homedir();
|
|
6178
6302
|
const { node, script } = selfCommand();
|
|
6179
|
-
const logs =
|
|
6180
|
-
|
|
6303
|
+
const logs = path21.join(dir, "logs");
|
|
6304
|
+
fs21.mkdirSync(logs, { recursive: true });
|
|
6181
6305
|
const names = serviceNames();
|
|
6182
6306
|
const env = profileEnv();
|
|
6183
6307
|
if (process.platform === "linux") {
|
|
6184
6308
|
const unit = `[Unit]
|
|
6185
|
-
Description=
|
|
6309
|
+
Description=MonoClaw machine${currentProfile() ? ` (${currentProfile()})` : ""}
|
|
6186
6310
|
After=network-online.target
|
|
6187
6311
|
|
|
6188
6312
|
[Service]
|
|
@@ -6195,13 +6319,13 @@ Environment="PATH=${servicePath(node)}"
|
|
|
6195
6319
|
[Install]
|
|
6196
6320
|
WantedBy=default.target
|
|
6197
6321
|
`;
|
|
6198
|
-
const file2 =
|
|
6199
|
-
|
|
6200
|
-
const target =
|
|
6322
|
+
const file2 = path21.join(dir, `${names.unit}.service`);
|
|
6323
|
+
fs21.writeFileSync(file2, unit);
|
|
6324
|
+
const target = path21.join(home, ".config", "systemd", "user", `${names.unit}.service`);
|
|
6201
6325
|
return {
|
|
6202
6326
|
file: file2,
|
|
6203
6327
|
steps: [
|
|
6204
|
-
`mkdir -p ${
|
|
6328
|
+
`mkdir -p ${path21.dirname(target)} && cp ${file2} ${target}`,
|
|
6205
6329
|
`systemctl --user daemon-reload && systemctl --user enable --now ${names.unit}`,
|
|
6206
6330
|
"loginctl enable-linger $USER # keeps it running when you are logged out",
|
|
6207
6331
|
`journalctl --user -u ${names.unit} -f # logs`
|
|
@@ -6221,17 +6345,17 @@ WantedBy=default.target
|
|
|
6221
6345
|
<key>${env.name}</key><string>${xml(env.value)}</string>
|
|
6222
6346
|
<key>PATH</key><string>${xml(servicePath(node))}</string>
|
|
6223
6347
|
</dict>
|
|
6224
|
-
<key>StandardOutPath</key><string>${xml(
|
|
6225
|
-
<key>StandardErrorPath</key><string>${xml(
|
|
6348
|
+
<key>StandardOutPath</key><string>${xml(path21.join(logs, "launchd.log"))}</string>
|
|
6349
|
+
<key>StandardErrorPath</key><string>${xml(path21.join(logs, "launchd.err"))}</string>
|
|
6226
6350
|
</dict></plist>
|
|
6227
6351
|
`;
|
|
6228
|
-
const file2 =
|
|
6229
|
-
|
|
6230
|
-
const target =
|
|
6231
|
-
return { file: file2, steps: [`cp ${file2} ${target}`, `launchctl bootstrap gui/$(id -u) ${target}`, `tail -f ${
|
|
6352
|
+
const file2 = path21.join(dir, `${names.label}.plist`);
|
|
6353
|
+
fs21.writeFileSync(file2, plist);
|
|
6354
|
+
const target = path21.join(home, "Library", "LaunchAgents", `${names.label}.plist`);
|
|
6355
|
+
return { file: file2, steps: [`cp ${file2} ${target}`, `launchctl bootstrap gui/$(id -u) ${target}`, `tail -f ${path21.join(logs, "launchd.log")}`] };
|
|
6232
6356
|
}
|
|
6233
|
-
const file =
|
|
6234
|
-
|
|
6357
|
+
const file = path21.join(dir, "monoclaw-host-task.ps1");
|
|
6358
|
+
fs21.writeFileSync(
|
|
6235
6359
|
file,
|
|
6236
6360
|
`$action = New-ScheduledTaskAction -Execute "${node}" -Argument '"${script}" start'
|
|
6237
6361
|
$trigger = New-ScheduledTaskTrigger -AtLogOn
|
|
@@ -6243,72 +6367,93 @@ Start-ScheduledTask -TaskName "${names.task}"
|
|
|
6243
6367
|
);
|
|
6244
6368
|
return { file, steps: [`powershell -ExecutionPolicy Bypass -File "${file}"`, `Get-ScheduledTask -TaskName "${names.task}"`] };
|
|
6245
6369
|
}
|
|
6246
|
-
var runSync = (cmd2,
|
|
6247
|
-
const r = spawnSync(cmd2,
|
|
6370
|
+
var runSync = (cmd2, args2) => {
|
|
6371
|
+
const r = spawnSync(cmd2, args2, { encoding: "utf8" });
|
|
6248
6372
|
return { status: r.status, stderr: String(r.stderr ?? "") };
|
|
6249
6373
|
};
|
|
6250
|
-
function installService(
|
|
6374
|
+
function installService(run3 = runSync) {
|
|
6251
6375
|
const r = serviceInstructions();
|
|
6252
|
-
const home =
|
|
6253
|
-
const must = (cmd2,
|
|
6254
|
-
const x =
|
|
6255
|
-
if (x.status !== 0) throw new Error(`${cmd2} ${
|
|
6376
|
+
const home = os7.homedir();
|
|
6377
|
+
const must = (cmd2, args2) => {
|
|
6378
|
+
const x = run3(cmd2, args2);
|
|
6379
|
+
if (x.status !== 0) throw new Error(`${cmd2} ${args2.join(" ")} failed: ${x.stderr.trim() || `exit ${x.status}`}`);
|
|
6256
6380
|
};
|
|
6257
6381
|
const names = serviceNames();
|
|
6258
6382
|
if (process.platform === "darwin") {
|
|
6259
|
-
const target =
|
|
6260
|
-
|
|
6261
|
-
|
|
6383
|
+
const target = path21.join(home, "Library", "LaunchAgents", `${names.label}.plist`);
|
|
6384
|
+
fs21.mkdirSync(path21.dirname(target), { recursive: true });
|
|
6385
|
+
fs21.copyFileSync(r.file, target);
|
|
6262
6386
|
const uid = String(process.getuid?.() ?? "");
|
|
6263
|
-
|
|
6387
|
+
run3("launchctl", ["bootout", `gui/${uid}/${names.label}`]);
|
|
6264
6388
|
must("launchctl", ["bootstrap", `gui/${uid}`, target]);
|
|
6265
|
-
return { file: r.file, target, notes: [`Logs: tail -f ${
|
|
6389
|
+
return { file: r.file, target, notes: [`Logs: tail -f ${path21.join(configDir(), "logs", "launchd.log")}`] };
|
|
6266
6390
|
}
|
|
6267
6391
|
if (process.platform === "linux") {
|
|
6268
|
-
const target =
|
|
6269
|
-
|
|
6270
|
-
|
|
6392
|
+
const target = path21.join(home, ".config", "systemd", "user", `${names.unit}.service`);
|
|
6393
|
+
fs21.mkdirSync(path21.dirname(target), { recursive: true });
|
|
6394
|
+
fs21.copyFileSync(r.file, target);
|
|
6271
6395
|
must("systemctl", ["--user", "daemon-reload"]);
|
|
6272
6396
|
must("systemctl", ["--user", "enable", "--now", names.unit]);
|
|
6273
6397
|
must("systemctl", ["--user", "restart", names.unit]);
|
|
6274
|
-
return { file: r.file, target, notes: [
|
|
6398
|
+
return { file: r.file, target, notes: [lingerNote(run3), `Logs: journalctl --user -u ${names.unit} -f`].filter((n) => !!n) };
|
|
6275
6399
|
}
|
|
6276
6400
|
must("powershell", ["-ExecutionPolicy", "Bypass", "-File", r.file]);
|
|
6277
6401
|
return { file: r.file, target: `Task Scheduler: ${names.task}`, notes: [`Check: Get-ScheduledTask -TaskName "${names.task}"`] };
|
|
6278
6402
|
}
|
|
6279
|
-
function uninstallService(
|
|
6280
|
-
const home =
|
|
6403
|
+
function uninstallService(run3 = runSync) {
|
|
6404
|
+
const home = os7.homedir();
|
|
6281
6405
|
const names = serviceNames();
|
|
6282
6406
|
if (process.platform === "darwin") {
|
|
6283
|
-
const target =
|
|
6284
|
-
|
|
6285
|
-
|
|
6407
|
+
const target = path21.join(home, "Library", "LaunchAgents", `${names.label}.plist`);
|
|
6408
|
+
run3("launchctl", ["bootout", `gui/${String(process.getuid?.() ?? "")}/${names.label}`]);
|
|
6409
|
+
fs21.rmSync(target, { force: true });
|
|
6286
6410
|
return target;
|
|
6287
6411
|
}
|
|
6288
6412
|
if (process.platform === "linux") {
|
|
6289
|
-
const target =
|
|
6290
|
-
|
|
6291
|
-
|
|
6292
|
-
|
|
6413
|
+
const target = path21.join(home, ".config", "systemd", "user", `${names.unit}.service`);
|
|
6414
|
+
run3("systemctl", ["--user", "disable", "--now", names.unit]);
|
|
6415
|
+
fs21.rmSync(target, { force: true });
|
|
6416
|
+
run3("systemctl", ["--user", "daemon-reload"]);
|
|
6293
6417
|
return target;
|
|
6294
6418
|
}
|
|
6295
|
-
|
|
6419
|
+
run3("powershell", ["-Command", `Unregister-ScheduledTask -TaskName "${names.task}" -Confirm:$false`]);
|
|
6296
6420
|
return `Task Scheduler: ${names.task}`;
|
|
6297
6421
|
}
|
|
6422
|
+
function lingerEnabled() {
|
|
6423
|
+
if (process.platform !== "linux") return null;
|
|
6424
|
+
const r = spawnSync("loginctl", ["show-user", os7.userInfo().username, "--property=Linger", "--value"], { encoding: "utf8" });
|
|
6425
|
+
if (r.status !== 0) return null;
|
|
6426
|
+
const v = String(r.stdout ?? "").trim();
|
|
6427
|
+
return v === "yes" ? true : v === "no" ? false : null;
|
|
6428
|
+
}
|
|
6429
|
+
var LINGER_FIX = "loginctl enable-linger $USER";
|
|
6430
|
+
function lingerNote(run3) {
|
|
6431
|
+
const on = lingerEnabled();
|
|
6432
|
+
if (on !== false) return null;
|
|
6433
|
+
const r = run3("loginctl", ["enable-linger", os7.userInfo().username]);
|
|
6434
|
+
if (r.status === 0 && lingerEnabled() === true) return "Set to keep running when you log out (linger is on for your user).";
|
|
6435
|
+
return `IMPORTANT: this machine will go offline when you log out of this computer. To keep it running, run: ${LINGER_FIX} (it may ask for your password, or need sudo)`;
|
|
6436
|
+
}
|
|
6298
6437
|
|
|
6299
6438
|
// src/cli.ts
|
|
6300
|
-
import {
|
|
6301
|
-
import
|
|
6302
|
-
import os7 from "node:os";
|
|
6439
|
+
import { spawn as spawn5 } from "node:child_process";
|
|
6440
|
+
import os8 from "node:os";
|
|
6303
6441
|
async function readTokenFromStdin() {
|
|
6304
6442
|
let data = "";
|
|
6305
6443
|
for await (const chunk of process.stdin) data += chunk;
|
|
6306
6444
|
return data.split(/\r?\n/).map((l) => l.trim()).find((l) => l.length > 0) ?? "";
|
|
6307
6445
|
}
|
|
6308
6446
|
var program = new Command();
|
|
6309
|
-
program.name("monoclaw").description("
|
|
6447
|
+
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", (_this, action) => {
|
|
6310
6448
|
const p = program.opts().profile;
|
|
6311
6449
|
if (p) process.env.MONOCLAW_PROFILE = assertProfileName(p);
|
|
6450
|
+
else if (!["enrol", "connect"].includes(action.name())) {
|
|
6451
|
+
const only2 = impliedProfile();
|
|
6452
|
+
if (only2) {
|
|
6453
|
+
process.env.MONOCLAW_PROFILE = only2;
|
|
6454
|
+
console.error(`(Using the profile "${only2}", this computer's only enrolment.)`);
|
|
6455
|
+
}
|
|
6456
|
+
}
|
|
6312
6457
|
});
|
|
6313
6458
|
var cmd = (rest) => `monoclaw ${currentProfile() ? `--profile ${currentProfile()} ` : ""}${rest}`;
|
|
6314
6459
|
async function confirm(question, fallback) {
|
|
@@ -6319,7 +6464,14 @@ async function confirm(question, fallback) {
|
|
|
6319
6464
|
const a = answer.trim().toLowerCase();
|
|
6320
6465
|
return a === "" ? fallback : a === "y" || a === "yes";
|
|
6321
6466
|
}
|
|
6322
|
-
program.command("
|
|
6467
|
+
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) => {
|
|
6468
|
+
if (!token) {
|
|
6469
|
+
console.error("No token. Copy the whole command from Add a machine in MonoClaw: it ends with a one-time token.");
|
|
6470
|
+
process.exit(2);
|
|
6471
|
+
}
|
|
6472
|
+
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() }));
|
|
6473
|
+
});
|
|
6474
|
+
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
6475
|
const token = opts.tokenStdin || tokenArg === "-" ? await readTokenFromStdin() : tokenArg;
|
|
6324
6476
|
if (!token) {
|
|
6325
6477
|
console.error("No token. Pass it as an argument, or pipe it in with --token-stdin.");
|
|
@@ -6327,9 +6479,13 @@ program.command("enrol [token]").description("Connect this machine to your Monoc
|
|
|
6327
6479
|
}
|
|
6328
6480
|
const profiles = listProfiles();
|
|
6329
6481
|
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:
|
|
6482
|
+
const plan = planEnrol(preview, profiles, opts.router, { requestedProfile: currentProfile(), defaultName: os8.hostname() });
|
|
6483
|
+
const report = (profile) => {
|
|
6484
|
+
if (process.env.MONOCLAW_CONNECT) fs22.writeFileSync(connectResultPath(), JSON.stringify({ profile, at: (/* @__PURE__ */ new Date()).toISOString() }), { mode: 384 });
|
|
6485
|
+
};
|
|
6331
6486
|
if (plan.action === "already") {
|
|
6332
6487
|
console.log(plan.message);
|
|
6488
|
+
report(plan.profile);
|
|
6333
6489
|
return;
|
|
6334
6490
|
}
|
|
6335
6491
|
if (plan.confirm) {
|
|
@@ -6342,19 +6498,30 @@ program.command("enrol [token]").description("Connect this machine to your Monoc
|
|
|
6342
6498
|
}
|
|
6343
6499
|
if (plan.profile) process.env.MONOCLAW_PROFILE = assertProfileName(plan.profile);
|
|
6344
6500
|
const existing = loadConfig();
|
|
6345
|
-
const roots2 = opts.root?.map((r) =>
|
|
6501
|
+
const roots2 = opts.root?.map((r) => path22.resolve(r)) ?? existing?.roots ?? plan.copyRootsFrom ?? [];
|
|
6346
6502
|
const unsafe = roots2.filter((r) => rootExposesConfig(r, configDir()));
|
|
6347
6503
|
if (unsafe.length) {
|
|
6348
6504
|
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
6505
|
process.exit(2);
|
|
6350
6506
|
}
|
|
6507
|
+
for (const r of opts.root ? roots2 : []) {
|
|
6508
|
+
if (fs22.existsSync(r)) continue;
|
|
6509
|
+
try {
|
|
6510
|
+
fs22.mkdirSync(r, { recursive: true });
|
|
6511
|
+
console.log(`Created ${r} for your agents to work in.`);
|
|
6512
|
+
} catch (e) {
|
|
6513
|
+
console.error(`Could not create ${r}: ${e.message}. Create it yourself, or add another folder with: ${cmd("roots add <folder>")}`);
|
|
6514
|
+
}
|
|
6515
|
+
}
|
|
6351
6516
|
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
6517
|
console.log(`Enrolled as "${cfg.name}"${cfg.spaceName ? ` in ${cfg.spaceName} (@${cfg.spaceHandle})` : ""}${currentProfile() ? ` under the profile "${currentProfile()}"` : ""}. Config saved to ${configPath()}.`);
|
|
6353
6518
|
if (plan.reason === "second-space") {
|
|
6354
|
-
|
|
6519
|
+
fs22.writeFileSync(pendingServicePath(), JSON.stringify({ profile: currentProfile(), at: (/* @__PURE__ */ new Date()).toISOString() }), { mode: 384 });
|
|
6355
6520
|
console.log(`This computer now runs one machine per space; its modules and Claude login are shared. The first enrolment is untouched.`);
|
|
6356
6521
|
}
|
|
6357
6522
|
if (!cfg.roots.length) console.log(`No folders exposed yet. Add one with: ${cmd("roots add ~/command")}`);
|
|
6523
|
+
report(currentProfile());
|
|
6524
|
+
if (process.env.MONOCLAW_CONNECT) return;
|
|
6358
6525
|
console.log(`
|
|
6359
6526
|
Next, run it (one of):
|
|
6360
6527
|
${cmd("service install")} in the background: starts now, at every login, and survives restarts
|
|
@@ -6436,7 +6603,7 @@ provider.command("add <name>").description("Add a Claude connection; an api_key
|
|
|
6436
6603
|
const { registry, accounts } = await makeContext(requireConfig());
|
|
6437
6604
|
const moduleId = opts.type === "api_key" ? "claude-api" : "claude-subscription";
|
|
6438
6605
|
if (!registry.isInstalled(moduleId)) await registry.add(moduleId).install;
|
|
6439
|
-
const folders = opts.folders?.map((f) =>
|
|
6606
|
+
const folders = opts.folders?.map((f) => path22.resolve(f.replace(/^~(?=$|\/)/, process.env.HOME ?? "")));
|
|
6440
6607
|
if (opts.type === "api_key") {
|
|
6441
6608
|
const id = await connectModule(registry, accounts, moduleId, io, { name, id: opts.id });
|
|
6442
6609
|
if (folders) accounts.upsert({ ...accounts.get(id), allowedFolders: folders });
|
|
@@ -6465,18 +6632,18 @@ var roots = program.command("roots").description("Folders this machine exposes t
|
|
|
6465
6632
|
roots.command("list").action(() => {
|
|
6466
6633
|
const cfg = requireConfig();
|
|
6467
6634
|
if (!cfg.roots.length) console.log("(none) \u2014 add one with: monoclaw roots add <path>");
|
|
6468
|
-
for (const r of cfg.roots) console.log(`${
|
|
6635
|
+
for (const r of cfg.roots) console.log(`${fs22.existsSync(r) ? "\u2713" : "\u2717 (missing)"} ${r}`);
|
|
6469
6636
|
});
|
|
6470
6637
|
roots.command("add <path...>").action((paths) => {
|
|
6471
6638
|
const cfg = requireConfig();
|
|
6472
6639
|
for (const p of paths) {
|
|
6473
|
-
const full =
|
|
6474
|
-
if (!
|
|
6640
|
+
const full = path22.resolve(p.replace(/^~(?=$|\/)/, process.env.HOME ?? ""));
|
|
6641
|
+
if (!fs22.existsSync(full) || !fs22.statSync(full).isDirectory()) {
|
|
6475
6642
|
console.error(`not a folder: ${full}`);
|
|
6476
6643
|
continue;
|
|
6477
6644
|
}
|
|
6478
6645
|
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 ${
|
|
6646
|
+
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
6647
|
process.exitCode = 1;
|
|
6481
6648
|
continue;
|
|
6482
6649
|
}
|
|
@@ -6489,7 +6656,7 @@ Restart the host for the change to reach the app.`);
|
|
|
6489
6656
|
});
|
|
6490
6657
|
roots.command("remove <path>").action((p) => {
|
|
6491
6658
|
const cfg = requireConfig();
|
|
6492
|
-
const full =
|
|
6659
|
+
const full = path22.resolve(p);
|
|
6493
6660
|
cfg.roots = cfg.roots.filter((r) => r !== full);
|
|
6494
6661
|
saveConfig(cfg);
|
|
6495
6662
|
console.log(`Exposed folders: ${cfg.roots.join(", ") || "(none)"}`);
|
|
@@ -6518,11 +6685,11 @@ program.command("start").description("Run the host and stay connected to the rou
|
|
|
6518
6685
|
assertRouterUrl(loaded.routerUrl, loaded.allowInsecure);
|
|
6519
6686
|
const lock = acquireRunLock(configDir());
|
|
6520
6687
|
if (!lock.ok) {
|
|
6521
|
-
console.error(`MonoClaw is already running for this machine (pid ${lock.pid}). Stop it first (\`monoclaw service
|
|
6688
|
+
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
6689
|
process.exit(1);
|
|
6523
6690
|
}
|
|
6524
6691
|
process.on("exit", lock.release);
|
|
6525
|
-
setLogDir(
|
|
6692
|
+
setLogDir(path22.join(configDir(), "logs"));
|
|
6526
6693
|
const unsafe = loaded.roots.filter((r) => rootExposesConfig(r, configDir()));
|
|
6527
6694
|
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
6695
|
const cfg = unsafe.length ? { ...loaded, roots: loaded.roots.filter((r) => !unsafe.includes(r)) } : loaded;
|
|
@@ -6531,7 +6698,7 @@ program.command("start").description("Run the host and stay connected to the rou
|
|
|
6531
6698
|
const repaired = await repairBundledCli();
|
|
6532
6699
|
if (repaired.outcome !== "present") log(repaired.outcome === "installed" ? "info" : "warn", `Claude Code copy: ${repaired.detail}`);
|
|
6533
6700
|
const cli = await resolveCli();
|
|
6534
|
-
log(cli ? "info" : "error", cli ? `Claude Code: ${describeCli(cli)}` : "Claude Code: not found; sessions will fail until `monoclaw doctor`
|
|
6701
|
+
log(cli ? "info" : "error", cli ? `Claude Code: ${describeCli(cli)}` : "Claude Code: not found; sessions will fail until `monoclaw doctor` fixes it");
|
|
6535
6702
|
const { accounts, registry } = await makeContext(cfg);
|
|
6536
6703
|
log("info", `modules: ${registry.installedIds().join(", ") || "(none)"}; ${accounts.list().length} connection(s) (secrets in the ${accounts.store.kind} store)`);
|
|
6537
6704
|
const client = new HostClient(cfg, providers, { accounts, registry });
|
|
@@ -6562,6 +6729,23 @@ program.command("start").description("Run the host and stay connected to the rou
|
|
|
6562
6729
|
process.on("SIGINT", shutdown);
|
|
6563
6730
|
process.on("SIGTERM", shutdown);
|
|
6564
6731
|
});
|
|
6732
|
+
async function runClaude(rest) {
|
|
6733
|
+
const cli = await resolveCli();
|
|
6734
|
+
if (!cli) {
|
|
6735
|
+
console.error("No Claude Code on this machine yet. Run `monoclaw doctor`: it installs the copy MonoClaw uses.");
|
|
6736
|
+
process.exit(1);
|
|
6737
|
+
}
|
|
6738
|
+
const code = await new Promise((resolve) => {
|
|
6739
|
+
const child = spawn5(cli.path, rest, { stdio: "inherit", env: cleanEnv() });
|
|
6740
|
+
child.on("error", (e) => {
|
|
6741
|
+
console.error(`Could not run ${cli.path}: ${e.message}`);
|
|
6742
|
+
resolve(1);
|
|
6743
|
+
});
|
|
6744
|
+
child.on("exit", (c) => resolve(c ?? 1));
|
|
6745
|
+
});
|
|
6746
|
+
process.exit(code);
|
|
6747
|
+
}
|
|
6748
|
+
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
6749
|
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
6750
|
const lines = [];
|
|
6567
6751
|
const major = Number(process.versions.node.split(".")[0]);
|
|
@@ -6579,27 +6763,30 @@ program.command("doctor").description("Check and repair what a working host need
|
|
|
6579
6763
|
const pkg = platformPackages()[0];
|
|
6580
6764
|
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
6765
|
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
|
|
6766
|
+
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
6767
|
const cli = await resolveCli();
|
|
6584
6768
|
if (cli) {
|
|
6585
6769
|
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`)" });
|
|
6770
|
+
const j = await authStatus(cli.path, cleanEnv());
|
|
6771
|
+
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
6772
|
} 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" });
|
|
6773
|
+
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
6774
|
}
|
|
6592
|
-
} else lines.push({ ok: false, what: "No Claude Code to run sessions with", fix: "
|
|
6775
|
+
} 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
6776
|
const cfg = loadConfig();
|
|
6594
|
-
|
|
6777
|
+
const named = currentProfile() ? [] : listProfiles().filter((p) => p.profile && p.config);
|
|
6778
|
+
if (!cfg && named.length) lines.push({ ok: false, info: true, what: `No default enrolment; this computer's enrolments are under profiles: ${named.map((p) => p.profile).join(", ")}`, fix: `monoclaw --profile ${named[0].profile} doctor checks that one` });
|
|
6779
|
+
else if (!cfg) lines.push({ ok: false, info: true, what: "Not enrolled yet", fix: "Copy the command from Add a machine in the app: npx -y @monoclaw/machine@latest connect <token>" });
|
|
6595
6780
|
else {
|
|
6596
6781
|
lines.push({ ok: true, what: `Enrolled as "${cfg.name}" with ${cfg.routerUrl}` });
|
|
6597
|
-
const missing = cfg.roots.filter((r) => !
|
|
6782
|
+
const missing = cfg.roots.filter((r) => !fs22.existsSync(r));
|
|
6598
6783
|
const exposing = cfg.roots.filter((r) => rootExposesConfig(r, configDir()));
|
|
6599
6784
|
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
6785
|
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
|
|
6602
|
-
|
|
6786
|
+
const names = serviceNames();
|
|
6787
|
+
const unit = process.platform === "darwin" ? path22.join(os8.homedir(), "Library", "LaunchAgents", `${names.label}.plist`) : process.platform === "linux" ? path22.join(os8.homedir(), ".config", "systemd", "user", `${names.unit}.service`) : null;
|
|
6788
|
+
if (unit) lines.push({ ok: fs22.existsSync(unit), info: true, what: fs22.existsSync(unit) ? `Background service installed (${unit})` : "Not running as a background service (fine for now)", fix: fs22.existsSync(unit) ? void 0 : `${cmd("service install")} to run at login` });
|
|
6789
|
+
if (unit && fs22.existsSync(unit) && lingerEnabled() === false) lines.push({ ok: false, what: "This machine goes offline when you log out of this computer (linger is off for your user)", fix: LINGER_FIX });
|
|
6603
6790
|
const { registry } = await makeContext(cfg);
|
|
6604
6791
|
await registry.refreshReadiness();
|
|
6605
6792
|
const reports = registry.reports();
|
|
@@ -6674,16 +6861,16 @@ config.command("set <key> <value>").description("Keys: allowedPermissionModes (c
|
|
|
6674
6861
|
});
|
|
6675
6862
|
var service = program.command("service").description("Run the host in the background at login");
|
|
6676
6863
|
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() &&
|
|
6864
|
+
if (!currentProfile() && fs22.existsSync(pendingServicePath())) {
|
|
6678
6865
|
try {
|
|
6679
|
-
const pending = JSON.parse(
|
|
6866
|
+
const pending = JSON.parse(fs22.readFileSync(pendingServicePath(), "utf8"));
|
|
6680
6867
|
if (pending.profile && Date.now() - Date.parse(pending.at ?? "") < 60 * 6e4) {
|
|
6681
6868
|
process.env.MONOCLAW_PROFILE = assertProfileName(pending.profile);
|
|
6682
6869
|
console.log(`Installing the service for the profile "${pending.profile}" (the enrolment just made). The first enrolment's service is untouched.`);
|
|
6683
6870
|
}
|
|
6684
6871
|
} catch {
|
|
6685
6872
|
}
|
|
6686
|
-
|
|
6873
|
+
fs22.rmSync(pendingServicePath(), { force: true });
|
|
6687
6874
|
}
|
|
6688
6875
|
requireConfig();
|
|
6689
6876
|
if (o.print) {
|
|
@@ -6699,7 +6886,12 @@ ${r2.steps.map((s) => ` ${s}`).join("\n")}
|
|
|
6699
6886
|
${r.notes.map((n) => ` ${n}`).join("\n")}` : ""}`);
|
|
6700
6887
|
});
|
|
6701
6888
|
service.command("uninstall").description("Stop and remove the background service").action(() => console.log(`Background service stopped and removed (${uninstallService()}).`));
|
|
6702
|
-
|
|
6889
|
+
var args = process.argv.slice(2);
|
|
6890
|
+
var first = args[0] === "--profile" ? 2 : 0;
|
|
6891
|
+
if (args[first] === "claude") {
|
|
6892
|
+
if (first) process.env.MONOCLAW_PROFILE = assertProfileName(args[1] ?? "");
|
|
6893
|
+
void runClaude(args.slice(first + 1));
|
|
6894
|
+
} else program.parseAsync(process.argv).catch((e) => {
|
|
6703
6895
|
console.error(e instanceof Error ? e.message : String(e));
|
|
6704
6896
|
process.exit(1);
|
|
6705
6897
|
});
|