@monoclaw/machine 1.0.10 → 1.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -3755,6 +3755,7 @@ function uniqueFileName(dir, name) {
3755
3755
  }
3756
3756
 
3757
3757
  // src/sessions.ts
3758
+ var BARE_SETTINGS = { persona: "", channelNotes: "", groupTitle: "", adminName: "", multiHuman: false, replyLength: "normal", tools: [], permissionMode: "default" };
3758
3759
  var SessionManager = class {
3759
3760
  constructor(providers2, emit, download, policy, accounts = { resolveCwd: (_id, cwd) => resolveInsideRoots(policy().roots, cwd), envFor: async () => ({}), providerOf: () => void 0 }, saveFile = async (f, dir) => {
3760
3761
  const tmp = await download({ id: f.attachmentId, name: f.name, mime: f.mime, size: 0, url: f.url, kind: "image" }, dir);
@@ -3807,7 +3808,25 @@ var SessionManager = class {
3807
3808
  get(groupId) {
3808
3809
  return this.live.get(groupId);
3809
3810
  }
3810
- async open(frame, known = /* @__PURE__ */ new Set()) {
3811
+ /**
3812
+ * One thing at a time per session (bug 084): frames arrive on the socket and are handled as they come, so an open
3813
+ * that was still starting could finish after the close and the fresh open that followed it, and a message that
3814
+ * arrived in between found no session and opened one with no settings at all. Opens, controls and messages for a
3815
+ * session now run in the order they arrived.
3816
+ */
3817
+ lanes = /* @__PURE__ */ new Map();
3818
+ inLane(groupId, fn) {
3819
+ const next = (this.lanes.get(groupId) ?? Promise.resolve()).catch(() => void 0).then(fn);
3820
+ this.lanes.set(groupId, next);
3821
+ void next.catch(() => void 0).finally(() => {
3822
+ if (this.lanes.get(groupId) === next) this.lanes.delete(groupId);
3823
+ });
3824
+ return next;
3825
+ }
3826
+ open(frame, known = /* @__PURE__ */ new Set()) {
3827
+ return this.inLane(frame.groupId, () => this.openNow(frame, known));
3828
+ }
3829
+ async openNow(frame, known = /* @__PURE__ */ new Set()) {
3811
3830
  const p = this.doOpen(frame, known);
3812
3831
  this.opening.set(frame.groupId, p);
3813
3832
  try {
@@ -3923,7 +3942,10 @@ var SessionManager = class {
3923
3942
  * `opts.cwd` is the v3 server's folder for this delivery (architecture §7). It is checked against the machine's roots
3924
3943
  * like `session.open`; when no session is open it opens one there (provider = the account's provider, default settings).
3925
3944
  */
3926
- async inbound(groupId, message, opts = {}) {
3945
+ inbound(groupId, message, opts = {}) {
3946
+ return this.inLane(groupId, () => this.inboundNow(groupId, message, opts));
3947
+ }
3948
+ async inboundNow(groupId, message, opts = {}) {
3927
3949
  if (!this.firstDelivery(groupId, message.id)) {
3928
3950
  log("info", `ignored a repeat of message ${message.id.slice(0, 8)} for ${groupId.slice(0, 8)}`);
3929
3951
  return;
@@ -3940,7 +3962,7 @@ var SessionManager = class {
3940
3962
  if (!open) {
3941
3963
  const byAccount = this.accounts.providerOf(opts.providerAccountId);
3942
3964
  const providerId = byAccount && this.providers[byAccount] ? byAccount : opts.providerAccountId && this.providers[opts.providerAccountId] ? opts.providerAccountId : Object.keys(this.providers)[0];
3943
- await this.open({ t: "session.open", groupId, provider: providerId, cwd: inside, providerAccountId: opts.providerAccountId, settings: { persona: "", channelNotes: "", groupTitle: "", adminName: "", multiHuman: false, replyLength: "normal", tools: [] } });
3965
+ await this.openNow({ t: "session.open", groupId, provider: providerId, cwd: inside, providerAccountId: opts.providerAccountId, settings: { ...BARE_SETTINGS } });
3944
3966
  } else if (open.cwd !== inside) {
3945
3967
  log("warn", `inbound for ${groupId.slice(0, 8)} names ${opts.cwd} but the session runs in ${open.cwd}; keeping the open session`);
3946
3968
  }
@@ -4014,7 +4036,11 @@ var SessionManager = class {
4014
4036
  log("info", `[${groupId.slice(0, 8)}] approval ${id.slice(0, 8)}: ${allow ? "ALLOW" : "deny"}${input ? " with edited input " + JSON.stringify(input).slice(0, 500) : ""}`);
4015
4037
  live.session.answerApproval(id, allow, input);
4016
4038
  }
4017
- async control(groupId, control) {
4039
+ control(groupId, control) {
4040
+ if (control.action === "stop") return this.controlNow(groupId, control);
4041
+ return this.inLane(groupId, () => this.controlNow(groupId, control));
4042
+ }
4043
+ async controlNow(groupId, control) {
4018
4044
  await this.awaitOpen(groupId);
4019
4045
  const live = this.live.get(groupId);
4020
4046
  switch (control.action) {
@@ -4030,7 +4056,7 @@ var SessionManager = class {
4030
4056
  const frame = { t: "session.open", groupId, provider: live.providerId, cwd: live.cwd, settings: live.settings, providerAccountId: live.accountId, resumeId: control.action === "resume" ? control.providerSessionId : void 0 };
4031
4057
  const known = live.knownSessionIds;
4032
4058
  await this.closeGroup(groupId);
4033
- await this.open(frame, known);
4059
+ await this.openNow(frame, known);
4034
4060
  this.emit(groupId, { kind: "notice", text: control.action === "new" ? "Started a fresh session." : "Resumed the session." });
4035
4061
  return;
4036
4062
  }
@@ -4296,7 +4322,53 @@ function guessMime(name) {
4296
4322
  }
4297
4323
 
4298
4324
  // src/version.ts
4299
- var APP_VERSION = true ? "1.0.10" : fromPackage();
4325
+ var APP_VERSION = true ? "1.0.12" : fromPackage();
4326
+
4327
+ // src/diag.ts
4328
+ var MAX_HELD = 200;
4329
+ var BATCH = 50;
4330
+ var MachineDiag = class {
4331
+ constructor(target, fetchFn = fetch) {
4332
+ this.target = target;
4333
+ this.fetchFn = fetchFn;
4334
+ }
4335
+ target;
4336
+ fetchFn;
4337
+ held = [];
4338
+ timer = null;
4339
+ report(e) {
4340
+ if (this.held.length >= MAX_HELD) this.held.shift();
4341
+ this.held.push({ ...e, message: e.message?.slice(0, 500), at: e.at ?? (/* @__PURE__ */ new Date()).toISOString() });
4342
+ this.schedule(e.level === "error" ? 3e3 : 3e4);
4343
+ }
4344
+ schedule(ms) {
4345
+ if (this.timer) return;
4346
+ this.timer = setTimeout(() => {
4347
+ this.timer = null;
4348
+ void this.flush();
4349
+ }, ms);
4350
+ this.timer.unref?.();
4351
+ }
4352
+ /** Send what is held (called on a timer, and when the machine comes online). Never throws. */
4353
+ async flush() {
4354
+ const t = this.target();
4355
+ if (!t || !this.held.length) return;
4356
+ const events = this.held.splice(0, BATCH);
4357
+ try {
4358
+ const url = `${t.origin}/v1/diagnostics/machine`;
4359
+ assertRouterTarget(url, t.origin, "diagnostics");
4360
+ const res = await this.fetchFn(url, { method: "POST", headers: { Authorization: `Bearer ${t.credential}`, "content-type": "application/json" }, body: JSON.stringify({ appVersion: APP_VERSION, events }), signal: AbortSignal.timeout(15e3), redirect: "manual" });
4361
+ if (!res.ok && res.status !== 404 && res.status !== 429) this.held.unshift(...events.slice(0, MAX_HELD - this.held.length));
4362
+ } catch {
4363
+ this.held.unshift(...events.slice(0, MAX_HELD - this.held.length));
4364
+ return;
4365
+ }
4366
+ if (this.held.length) this.schedule(2e3);
4367
+ }
4368
+ get waiting() {
4369
+ return this.held.length;
4370
+ }
4371
+ };
4300
4372
 
4301
4373
  // src/client.ts
4302
4374
  var HEARTBEAT_MS = 2e4;
@@ -4345,6 +4417,11 @@ var HostClient = class {
4345
4417
  cfg;
4346
4418
  ws = null;
4347
4419
  backoff = 1e3;
4420
+ /** When the connection last went, to say how long the machine was away. */
4421
+ downSince = null;
4422
+ lastCloseCode = 0;
4423
+ /** The development watch: this machine's own trouble, sent to the service (never what was said). */
4424
+ diag = new MachineDiag(() => this.cfg.credential ? { origin: routerOrigin(this.cfg.routerUrl), credential: this.cfg.credential } : null);
4348
4425
  connectWatchdog = null;
4349
4426
  liveness = null;
4350
4427
  lastHeard = 0;
@@ -4533,6 +4610,8 @@ var HostClient = class {
4533
4610
  return;
4534
4611
  }
4535
4612
  if (this.stopped) return;
4613
+ if (this.downSince === null) this.downSince = Date.now();
4614
+ this.lastCloseCode = code;
4536
4615
  log("warn", `disconnected (${code}); reconnecting in ${this.backoff / 1e3}s`);
4537
4616
  setTimeout(() => void this.connect(), Math.round(this.backoff * (0.8 + Math.random() * 0.4)));
4538
4617
  this.backoff = Math.min(this.backoff * 2, 3e4);
@@ -4601,6 +4680,13 @@ var HostClient = class {
4601
4680
  this.connectWatchdog = null;
4602
4681
  this.onState("online");
4603
4682
  log("info", `connected to router as ${frame.hostName} (${frame.hostId.slice(0, 8)})`);
4683
+ this.backoff = 1e3;
4684
+ if (this.downSince !== null) {
4685
+ const downMs = Date.now() - this.downSince;
4686
+ this.downSince = null;
4687
+ this.diag.report({ kind: "machine.reconnected", level: downMs > 6e4 ? "warn" : "info", message: `back after ${Math.round(downMs / 1e3)} s (closed with ${this.lastCloseCode})`, data: { downMs, code: this.lastCloseCode } });
4688
+ }
4689
+ void this.diag.flush();
4604
4690
  return;
4605
4691
  case "error":
4606
4692
  log("error", `router: ${frame.code} ${frame.message}`);
@@ -4772,6 +4858,13 @@ var HostClient = class {
4772
4858
  const origin = routerOrigin(this.cfg.routerUrl);
4773
4859
  const credential = this.cfg.credential ?? "";
4774
4860
  let audioFile = "";
4861
+ log("info", `job ${frame.jobId.slice(0, 10)} ${frame.module} ${frame.input.capability}: received`);
4862
+ const facts = { module: frame.module, capability: frame.input.capability, jobId: frame.jobId.slice(0, 10) };
4863
+ const hung = setTimeout(() => {
4864
+ log("warn", `job ${frame.jobId.slice(0, 10)} ${frame.module} ${frame.input.capability}: still running after 60 s`);
4865
+ this.diag.report({ kind: "job.long", level: "warn", message: `${frame.module} ${frame.input.capability} still running after 60 s`, data: facts });
4866
+ }, 6e4);
4867
+ hung.unref?.();
4775
4868
  try {
4776
4869
  let job;
4777
4870
  if (frame.input.capability === "stt") {
@@ -4780,18 +4873,22 @@ var HostClient = class {
4780
4873
  } else if (frame.input.capability === "tts") job = { capability: "tts", text: frame.input.text, options: frame.options };
4781
4874
  else job = { capability: "image", prompt: frame.input.prompt, args: frame.input.args, options: frame.options };
4782
4875
  const out = await this.registry.runJob(frame.module, frame.connectionId, job);
4876
+ const made = Date.now();
4783
4877
  const outputs = [];
4784
4878
  for (const [index, f] of out.files.entries()) {
4785
4879
  const uploadId = await uploadJobOutput(this.uploadUrl, credential, origin, { jobId: frame.jobId, index, bytes: f.bytes, mime: f.mime, name: f.name });
4786
4880
  outputs.push({ uploadId, mime: f.mime, name: f.name, ...f.durationMs !== void 0 ? { durationMs: f.durationMs } : {}, ...f.width ? { width: f.width } : {}, ...f.height ? { height: f.height } : {} });
4787
4881
  }
4788
4882
  this.send({ t: "job.result", jobId: frame.jobId, outputs, ...out.text !== void 0 ? { text: out.text } : {}, ...out.language ? { language: out.language } : {}, ...out.usage ? { usage: out.usage } : {} });
4789
- log("info", `job ${frame.jobId.slice(0, 10)} ${frame.module} ${frame.input.capability}: ${outputs.length} output(s) in ${Date.now() - started} ms`);
4883
+ log("info", `job ${frame.jobId.slice(0, 10)} ${frame.module} ${frame.input.capability}: ${outputs.length} output(s) in ${Date.now() - started} ms (made in ${made - started}, uploaded in ${Date.now() - made})`);
4884
+ if (Date.now() - started > 3e4) this.diag.report({ kind: "job.slow", level: "warn", message: `${frame.module} ${frame.input.capability} took ${Math.round((Date.now() - started) / 1e3)} s`, data: { ...facts, ms: Date.now() - started, madeMs: made - started, uploadMs: Date.now() - made } });
4790
4885
  } catch (e) {
4791
4886
  const message = e.message.split("\n")[0].slice(0, 300);
4792
4887
  log("warn", `job ${frame.jobId.slice(0, 10)} ${frame.module} ${frame.input.capability} failed: ${message}`);
4888
+ this.diag.report({ kind: "job.failed", level: "error", message, data: { ...facts, ms: Date.now() - started } });
4793
4889
  this.send({ t: "job.result", jobId: frame.jobId, outputs: [], error: message });
4794
4890
  } finally {
4891
+ clearTimeout(hung);
4795
4892
  if (audioFile) fs16.rmSync(audioFile, { force: true });
4796
4893
  }
4797
4894
  this.scheduleModules();
@@ -5496,10 +5593,19 @@ ${r.text}`, final: true });
5496
5593
  const ctx = msg.context ? ` (with ${msg.context.split("\n").length} context lines)` : "";
5497
5594
  const att = msg.attachments.length ? ` [${msg.attachments.map((a) => a.name).join(", ")}]` : "";
5498
5595
  const reply = `${msg.sender.name}: ${text2}${ctx}${att}`;
5499
- const step = Math.max(1, Math.ceil(reply.length / 3));
5500
- for (let i = 0; i < reply.length; i += step) {
5501
- this.q.push({ kind: "text.delta", text: reply.slice(i, i + step) });
5502
- await new Promise((r) => setTimeout(r, 40));
5596
+ const slow = /^slow:(\d+):/.exec(text2);
5597
+ if (slow) {
5598
+ const gap = Math.min(5e3, Number(slow[1]));
5599
+ for (const word of reply.match(/\S+\s*/g) ?? [reply]) {
5600
+ this.q.push({ kind: "text.delta", text: word });
5601
+ await new Promise((r) => setTimeout(r, gap));
5602
+ }
5603
+ } else {
5604
+ const step = Math.max(1, Math.ceil(reply.length / 3));
5605
+ for (let i = 0; i < reply.length; i += step) {
5606
+ this.q.push({ kind: "text.delta", text: reply.slice(i, i + step) });
5607
+ await new Promise((r) => setTimeout(r, 40));
5608
+ }
5503
5609
  }
5504
5610
  this.q.push({ kind: "text", text: reply, final: true });
5505
5611
  }
@@ -6953,6 +7059,17 @@ program.command("start", { hidden: true }).description("Run the host in this ter
6953
7059
  };
6954
7060
  process.on("SIGINT", shutdown);
6955
7061
  process.on("SIGTERM", shutdown);
7062
+ process.on("unhandledRejection", (reason) => {
7063
+ const e = reason instanceof Error ? reason : new Error(String(reason));
7064
+ log("error", `a promise failed with nobody handling it: ${e.stack ?? e.message}`);
7065
+ client.diag.report({ kind: "machine.unhandled_rejection", level: "error", message: `${e.name}: ${e.message}`.slice(0, 300) });
7066
+ });
7067
+ process.on("uncaughtException", (e) => {
7068
+ log("error", `an error nobody caught; stopping: ${e.stack ?? e.message}`);
7069
+ client.diag.report({ kind: "machine.crash", level: "error", message: `${e.name}: ${e.message}`.slice(0, 300) });
7070
+ void client.diag.flush().finally(() => process.exit(1));
7071
+ setTimeout(() => process.exit(1), 5e3).unref();
7072
+ });
6956
7073
  });
6957
7074
  async function runClaude(rest) {
6958
7075
  const cli = await resolveCli();
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@monoclaw/machine",
3
- "version": "1.0.10",
3
+ "version": "1.0.12",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@monoclaw/machine",
9
- "version": "1.0.10",
9
+ "version": "1.0.12",
10
10
  "license": "UNLICENSED",
11
11
  "dependencies": {
12
12
  "@anthropic-ai/claude-agent-sdk": "0.3.302",
@@ -789,9 +789,9 @@
789
789
  }
790
790
  },
791
791
  "node_modules/hono": {
792
- "version": "4.13.19",
793
- "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.19.tgz",
794
- "integrity": "sha512-KmXvQAXwcAHV+muzbIwoJ23niEB5nMoDVr9WcRkU8mvjUECm/1+7v4Jgp7P7a+H6MLFrh+vXrGonGrGS+RQfkA==",
792
+ "version": "4.13.20",
793
+ "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.20.tgz",
794
+ "integrity": "sha512-xo6gecEJQ+CjTtOUUbcLHE8CdRKMeF4qITe+DT+OhFnSUmZR/ZBa9XavAfiGh4HlukmlaHFdaK4dz5tkTYFNmA==",
795
795
  "license": "MIT",
796
796
  "engines": {
797
797
  "node": ">=16.9.0"
@@ -1072,9 +1072,9 @@
1072
1072
  }
1073
1073
  },
1074
1074
  "node_modules/pkce-challenge": {
1075
- "version": "5.0.1",
1076
- "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz",
1077
- "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==",
1075
+ "version": "5.0.2",
1076
+ "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.2.tgz",
1077
+ "integrity": "sha512-vCc54+qyIfKC5e2UN28AZKElwqjLINgiIV3RKI8pDu93TjaAJoB3QrgMzEBouy8yOKsXVXdAinO1QArJf9x5WA==",
1078
1078
  "license": "MIT",
1079
1079
  "engines": {
1080
1080
  "node": ">=16.20.0"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@monoclaw/machine",
3
- "version": "1.0.10",
3
+ "version": "1.0.12",
4
4
  "description": "Monoclaw host app: runs agents on your machine and connects them to your Monoclaw account (command.monoclaw.ai).",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {