@monoclaw/machine 1.0.11 → 1.0.13

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
@@ -2402,7 +2402,55 @@ function encodeWavPcm16(samples, sampleRate) {
2402
2402
  }
2403
2403
 
2404
2404
  // ../../packages/voice-engine/src/stt.ts
2405
+ var STT_PIECE_SECONDS = 120;
2406
+ var CUT_SEARCH_SECONDS = 8;
2407
+ var CUT_WINDOW_SECONDS = 0.1;
2408
+ function cutPoints(samples, sampleRate, pieceSeconds = STT_PIECE_SECONDS) {
2409
+ const piece = Math.floor(pieceSeconds * sampleRate);
2410
+ const search = Math.floor(Math.min(CUT_SEARCH_SECONDS, pieceSeconds / 4) * sampleRate);
2411
+ const win = Math.max(1, Math.floor(CUT_WINDOW_SECONDS * sampleRate));
2412
+ const cuts = [];
2413
+ let start = 0;
2414
+ while (samples.length - start > piece) {
2415
+ const limit = start + piece;
2416
+ let best = limit;
2417
+ let bestEnergy = Infinity;
2418
+ for (let at = limit - search; at + win <= limit; at += win) {
2419
+ let e = 0;
2420
+ for (let i = at; i < at + win; i++) e += samples[i] * samples[i];
2421
+ if (e < bestEnergy) {
2422
+ bestEnergy = e;
2423
+ best = at + Math.floor(win / 2);
2424
+ }
2425
+ }
2426
+ cuts.push(best);
2427
+ start = best;
2428
+ }
2429
+ return cuts;
2430
+ }
2405
2431
  async function transcribe(mgr, modelId, samples, sampleRate, withTimestamps) {
2432
+ const cuts = cutPoints(samples, sampleRate);
2433
+ if (!cuts.length) return transcribeOne(mgr, modelId, samples, sampleRate, withTimestamps);
2434
+ const bounds = [0, ...cuts, samples.length];
2435
+ const texts = [];
2436
+ const words = [];
2437
+ let language = null;
2438
+ for (let i = 0; i < bounds.length - 1; i++) {
2439
+ const from = bounds[i];
2440
+ const part = await transcribeOne(mgr, modelId, samples.subarray(from, bounds[i + 1]), sampleRate, withTimestamps);
2441
+ if (part.text) texts.push(part.text);
2442
+ language ??= part.language;
2443
+ const offset = from / sampleRate;
2444
+ for (const w of part.words ?? []) words.push({ word: w.word, start: round(w.start + offset), end: round(w.end + offset) });
2445
+ }
2446
+ const out = { text: texts.join(" ").replace(/\s+/g, " ").trim(), durationSeconds: samples.length / sampleRate, language };
2447
+ if (withTimestamps) {
2448
+ out.words = words;
2449
+ out.segments = segmentsFromWords(words);
2450
+ }
2451
+ return out;
2452
+ }
2453
+ async function transcribeOne(mgr, modelId, samples, sampleRate, withTimestamps) {
2406
2454
  const rec = mgr.recognizer(modelId);
2407
2455
  if (!rec) throw new Error(`model ${modelId} is not loaded`);
2408
2456
  const stream = rec.createStream();
@@ -2882,7 +2930,7 @@ var Engine = class {
2882
2930
  rate = parsed.sampleRate;
2883
2931
  } else throw new EngineError("bad_audio", "audio or samples required");
2884
2932
  if (rate !== 16e3) samples = resampleLinear(samples, rate, 16e3);
2885
- if (samples.length / 16e3 > 600) throw new EngineError("too_long", "audio longer than 600 s; chunk it");
2933
+ if (samples.length / 16e3 > 1800) throw new EngineError("too_long", "audio longer than 30 minutes");
2886
2934
  try {
2887
2935
  const out = await this.queue.run(() => transcribe(this.manager, model, samples, 16e3, req.timestamps ?? false), req.queueTimeoutMs ?? 12e4, req.caller);
2888
2936
  return { ...out, model, latencyMs: Date.now() - t0 };
@@ -4322,7 +4370,53 @@ function guessMime(name) {
4322
4370
  }
4323
4371
 
4324
4372
  // src/version.ts
4325
- var APP_VERSION = true ? "1.0.11" : fromPackage();
4373
+ var APP_VERSION = true ? "1.0.13" : fromPackage();
4374
+
4375
+ // src/diag.ts
4376
+ var MAX_HELD = 200;
4377
+ var BATCH = 50;
4378
+ var MachineDiag = class {
4379
+ constructor(target, fetchFn = fetch) {
4380
+ this.target = target;
4381
+ this.fetchFn = fetchFn;
4382
+ }
4383
+ target;
4384
+ fetchFn;
4385
+ held = [];
4386
+ timer = null;
4387
+ report(e) {
4388
+ if (this.held.length >= MAX_HELD) this.held.shift();
4389
+ this.held.push({ ...e, message: e.message?.slice(0, 500), at: e.at ?? (/* @__PURE__ */ new Date()).toISOString() });
4390
+ this.schedule(e.level === "error" ? 3e3 : 3e4);
4391
+ }
4392
+ schedule(ms) {
4393
+ if (this.timer) return;
4394
+ this.timer = setTimeout(() => {
4395
+ this.timer = null;
4396
+ void this.flush();
4397
+ }, ms);
4398
+ this.timer.unref?.();
4399
+ }
4400
+ /** Send what is held (called on a timer, and when the machine comes online). Never throws. */
4401
+ async flush() {
4402
+ const t = this.target();
4403
+ if (!t || !this.held.length) return;
4404
+ const events = this.held.splice(0, BATCH);
4405
+ try {
4406
+ const url = `${t.origin}/v1/diagnostics/machine`;
4407
+ assertRouterTarget(url, t.origin, "diagnostics");
4408
+ 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" });
4409
+ if (!res.ok && res.status !== 404 && res.status !== 429) this.held.unshift(...events.slice(0, MAX_HELD - this.held.length));
4410
+ } catch {
4411
+ this.held.unshift(...events.slice(0, MAX_HELD - this.held.length));
4412
+ return;
4413
+ }
4414
+ if (this.held.length) this.schedule(2e3);
4415
+ }
4416
+ get waiting() {
4417
+ return this.held.length;
4418
+ }
4419
+ };
4326
4420
 
4327
4421
  // src/client.ts
4328
4422
  var HEARTBEAT_MS = 2e4;
@@ -4371,6 +4465,11 @@ var HostClient = class {
4371
4465
  cfg;
4372
4466
  ws = null;
4373
4467
  backoff = 1e3;
4468
+ /** When the connection last went, to say how long the machine was away. */
4469
+ downSince = null;
4470
+ lastCloseCode = 0;
4471
+ /** The development watch: this machine's own trouble, sent to the service (never what was said). */
4472
+ diag = new MachineDiag(() => this.cfg.credential ? { origin: routerOrigin(this.cfg.routerUrl), credential: this.cfg.credential } : null);
4374
4473
  connectWatchdog = null;
4375
4474
  liveness = null;
4376
4475
  lastHeard = 0;
@@ -4559,6 +4658,8 @@ var HostClient = class {
4559
4658
  return;
4560
4659
  }
4561
4660
  if (this.stopped) return;
4661
+ if (this.downSince === null) this.downSince = Date.now();
4662
+ this.lastCloseCode = code;
4562
4663
  log("warn", `disconnected (${code}); reconnecting in ${this.backoff / 1e3}s`);
4563
4664
  setTimeout(() => void this.connect(), Math.round(this.backoff * (0.8 + Math.random() * 0.4)));
4564
4665
  this.backoff = Math.min(this.backoff * 2, 3e4);
@@ -4627,6 +4728,13 @@ var HostClient = class {
4627
4728
  this.connectWatchdog = null;
4628
4729
  this.onState("online");
4629
4730
  log("info", `connected to router as ${frame.hostName} (${frame.hostId.slice(0, 8)})`);
4731
+ this.backoff = 1e3;
4732
+ if (this.downSince !== null) {
4733
+ const downMs = Date.now() - this.downSince;
4734
+ this.downSince = null;
4735
+ 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 } });
4736
+ }
4737
+ void this.diag.flush();
4630
4738
  return;
4631
4739
  case "error":
4632
4740
  log("error", `router: ${frame.code} ${frame.message}`);
@@ -4798,6 +4906,13 @@ var HostClient = class {
4798
4906
  const origin = routerOrigin(this.cfg.routerUrl);
4799
4907
  const credential = this.cfg.credential ?? "";
4800
4908
  let audioFile = "";
4909
+ log("info", `job ${frame.jobId.slice(0, 10)} ${frame.module} ${frame.input.capability}: received`);
4910
+ const facts = { module: frame.module, capability: frame.input.capability, jobId: frame.jobId.slice(0, 10) };
4911
+ const hung = setTimeout(() => {
4912
+ log("warn", `job ${frame.jobId.slice(0, 10)} ${frame.module} ${frame.input.capability}: still running after 60 s`);
4913
+ this.diag.report({ kind: "job.long", level: "warn", message: `${frame.module} ${frame.input.capability} still running after 60 s`, data: facts });
4914
+ }, 6e4);
4915
+ hung.unref?.();
4801
4916
  try {
4802
4917
  let job;
4803
4918
  if (frame.input.capability === "stt") {
@@ -4806,18 +4921,22 @@ var HostClient = class {
4806
4921
  } else if (frame.input.capability === "tts") job = { capability: "tts", text: frame.input.text, options: frame.options };
4807
4922
  else job = { capability: "image", prompt: frame.input.prompt, args: frame.input.args, options: frame.options };
4808
4923
  const out = await this.registry.runJob(frame.module, frame.connectionId, job);
4924
+ const made = Date.now();
4809
4925
  const outputs = [];
4810
4926
  for (const [index, f] of out.files.entries()) {
4811
4927
  const uploadId = await uploadJobOutput(this.uploadUrl, credential, origin, { jobId: frame.jobId, index, bytes: f.bytes, mime: f.mime, name: f.name });
4812
4928
  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 } : {} });
4813
4929
  }
4814
4930
  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 } : {} });
4815
- log("info", `job ${frame.jobId.slice(0, 10)} ${frame.module} ${frame.input.capability}: ${outputs.length} output(s) in ${Date.now() - started} ms`);
4931
+ 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})`);
4932
+ 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 } });
4816
4933
  } catch (e) {
4817
4934
  const message = e.message.split("\n")[0].slice(0, 300);
4818
4935
  log("warn", `job ${frame.jobId.slice(0, 10)} ${frame.module} ${frame.input.capability} failed: ${message}`);
4936
+ this.diag.report({ kind: "job.failed", level: "error", message, data: { ...facts, ms: Date.now() - started } });
4819
4937
  this.send({ t: "job.result", jobId: frame.jobId, outputs: [], error: message });
4820
4938
  } finally {
4939
+ clearTimeout(hung);
4821
4940
  if (audioFile) fs16.rmSync(audioFile, { force: true });
4822
4941
  }
4823
4942
  this.scheduleModules();
@@ -5522,10 +5641,19 @@ ${r.text}`, final: true });
5522
5641
  const ctx = msg.context ? ` (with ${msg.context.split("\n").length} context lines)` : "";
5523
5642
  const att = msg.attachments.length ? ` [${msg.attachments.map((a) => a.name).join(", ")}]` : "";
5524
5643
  const reply = `${msg.sender.name}: ${text2}${ctx}${att}`;
5525
- const step = Math.max(1, Math.ceil(reply.length / 3));
5526
- for (let i = 0; i < reply.length; i += step) {
5527
- this.q.push({ kind: "text.delta", text: reply.slice(i, i + step) });
5528
- await new Promise((r) => setTimeout(r, 40));
5644
+ const slow = /^slow:(\d+):/.exec(text2);
5645
+ if (slow) {
5646
+ const gap = Math.min(5e3, Number(slow[1]));
5647
+ for (const word of reply.match(/\S+\s*/g) ?? [reply]) {
5648
+ this.q.push({ kind: "text.delta", text: word });
5649
+ await new Promise((r) => setTimeout(r, gap));
5650
+ }
5651
+ } else {
5652
+ const step = Math.max(1, Math.ceil(reply.length / 3));
5653
+ for (let i = 0; i < reply.length; i += step) {
5654
+ this.q.push({ kind: "text.delta", text: reply.slice(i, i + step) });
5655
+ await new Promise((r) => setTimeout(r, 40));
5656
+ }
5529
5657
  }
5530
5658
  this.q.push({ kind: "text", text: reply, final: true });
5531
5659
  }
@@ -6979,6 +7107,17 @@ program.command("start", { hidden: true }).description("Run the host in this ter
6979
7107
  };
6980
7108
  process.on("SIGINT", shutdown);
6981
7109
  process.on("SIGTERM", shutdown);
7110
+ process.on("unhandledRejection", (reason) => {
7111
+ const e = reason instanceof Error ? reason : new Error(String(reason));
7112
+ log("error", `a promise failed with nobody handling it: ${e.stack ?? e.message}`);
7113
+ client.diag.report({ kind: "machine.unhandled_rejection", level: "error", message: `${e.name}: ${e.message}`.slice(0, 300) });
7114
+ });
7115
+ process.on("uncaughtException", (e) => {
7116
+ log("error", `an error nobody caught; stopping: ${e.stack ?? e.message}`);
7117
+ client.diag.report({ kind: "machine.crash", level: "error", message: `${e.name}: ${e.message}`.slice(0, 300) });
7118
+ void client.diag.flush().finally(() => process.exit(1));
7119
+ setTimeout(() => process.exit(1), 5e3).unref();
7120
+ });
6982
7121
  });
6983
7122
  async function runClaude(rest) {
6984
7123
  const cli = await resolveCli();
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@monoclaw/machine",
3
- "version": "1.0.11",
3
+ "version": "1.0.13",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@monoclaw/machine",
9
- "version": "1.0.11",
9
+ "version": "1.0.13",
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.11",
3
+ "version": "1.0.13",
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": {