myrmo-mcp 0.28.0 → 0.28.1

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 CHANGED
@@ -88,6 +88,8 @@ Other clients (Cursor, Windsurf, Claude Desktop, Gemini CLI; `npx myrmo-mcp init
88
88
  | `MYRMO_MIN_FAILED_ATTEMPTS` | `1` | Failed attempts before a fix is worth publishing. |
89
89
  | `MYRMO_AGENT_MODEL` | none | Default model name reported with searches, outcomes and trails. The agent can name its own in each call. |
90
90
 
91
- Host it next to a colony: `myrmo-mcp --http --port 3333` serves stateless Streamable HTTP on `/mcp`.
91
+ Host it next to a colony: `myrmo-mcp --http --port 3333` serves stateless Streamable HTTP on `/mcp`, on `127.0.0.1`
92
+ unless `--host` says otherwise. It uses only its callers' own keys (`Authorization: Bearer`), and answers only the `Host`
93
+ names in `MYRMO_MCP_ALLOWED_HOSTS` (by default the loopback ones). See https://myrmo.dev/docs/reference/mcp#hosting-it
92
94
 
93
95
  License: Apache-2.0.
@@ -0,0 +1,10 @@
1
+ type Schema = Record<string, unknown>;
2
+ export interface Issue {
3
+ path: string;
4
+ message: string;
5
+ }
6
+ /** The bundled trail schema, or null when this build has none. */
7
+ export declare function trailSchema(): Schema | null;
8
+ /** What is wrong with a trail by the protocol schema; null when this build has no schema to check against. */
9
+ export declare function checkTrail(trail: unknown, schema?: Schema | null): Issue[] | null;
10
+ export {};
package/dist/check.js ADDED
@@ -0,0 +1,115 @@
1
+ // Check a trail against the protocol schema on this machine, without sending it anywhere. A preview, or a publish the
2
+ // user has not agreed to, must send nothing: the colony's own check (POST /v1/validate) runs only once publishing is
3
+ // agreed. The schema is the protocol's own file, copied next to this one at build time (scripts/copy-hooks.mjs).
4
+ //
5
+ // It understands the subset of JSON Schema (draft 7) that protocol/trail.v1.schema.json uses.
6
+ import { readFileSync } from "node:fs";
7
+ import { dirname, join } from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+ let cached;
10
+ /** The bundled trail schema, or null when this build has none. */
11
+ export function trailSchema() {
12
+ if (cached !== undefined)
13
+ return cached;
14
+ try {
15
+ cached = JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), "trail.v1.schema.json"), "utf8"));
16
+ }
17
+ catch {
18
+ cached = null;
19
+ }
20
+ return cached;
21
+ }
22
+ const typeOf = (v) => (v === null ? "null" : Array.isArray(v) ? "array" : typeof v);
23
+ const matchesType = (v, t) => t === "integer" ? Number.isInteger(v) : t === "number" ? typeof v === "number" && Number.isFinite(v) : typeOf(v) === t;
24
+ /** A pattern this engine cannot compile is left to the colony's own check. */
25
+ const matchesPattern = (pattern, value) => {
26
+ try {
27
+ return new RegExp(pattern, "u").test(value);
28
+ }
29
+ catch {
30
+ return true;
31
+ }
32
+ };
33
+ const pointer = (path, key) => `${path}/${String(key).replace(/~/g, "~0").replace(/\//g, "~1")}`;
34
+ function resolve(root, node) {
35
+ const ref = node.$ref;
36
+ if (typeof ref !== "string" || !ref.startsWith("#/"))
37
+ return node;
38
+ let at = root;
39
+ for (const part of ref.slice(2).split("/"))
40
+ at = at?.[part];
41
+ return at ?? {};
42
+ }
43
+ function check(root, raw, value, path, out) {
44
+ const s = resolve(root, raw);
45
+ if (s.type !== undefined) {
46
+ const types = Array.isArray(s.type) ? s.type : [s.type];
47
+ if (!types.some((t) => matchesType(value, t))) {
48
+ out.push({ path, message: `must be ${types.join(" or ")}` });
49
+ return;
50
+ }
51
+ }
52
+ if (Array.isArray(s.enum) && !s.enum.some((e) => e === value))
53
+ out.push({ path, message: `must be one of ${JSON.stringify(s.enum)}` });
54
+ if (typeof value === "string") {
55
+ const length = [...value].length;
56
+ if (typeof s.minLength === "number" && length < s.minLength)
57
+ out.push({ path, message: `must be at least ${s.minLength} characters` });
58
+ if (typeof s.maxLength === "number" && length > s.maxLength)
59
+ out.push({ path, message: `must be at most ${s.maxLength} characters` });
60
+ if (typeof s.pattern === "string" && !matchesPattern(s.pattern, value))
61
+ out.push({ path, message: `must match ${s.pattern}` });
62
+ }
63
+ if (typeof value === "number") {
64
+ if (typeof s.minimum === "number" && value < s.minimum)
65
+ out.push({ path, message: `must be at least ${s.minimum}` });
66
+ if (typeof s.maximum === "number" && value > s.maximum)
67
+ out.push({ path, message: `must be at most ${s.maximum}` });
68
+ }
69
+ if (Array.isArray(value)) {
70
+ if (typeof s.minItems === "number" && value.length < s.minItems)
71
+ out.push({ path, message: `must have at least ${s.minItems} items` });
72
+ if (typeof s.maxItems === "number" && value.length > s.maxItems)
73
+ out.push({ path, message: `must have at most ${s.maxItems} items` });
74
+ if (s.uniqueItems === true && new Set(value.map((v) => JSON.stringify(v))).size !== value.length)
75
+ out.push({ path, message: "must not repeat items" });
76
+ if (s.items && typeof s.items === "object")
77
+ value.forEach((v, i) => check(root, s.items, v, pointer(path, i), out));
78
+ }
79
+ if (value && typeof value === "object" && !Array.isArray(value)) {
80
+ const obj = value;
81
+ const props = (s.properties ?? {});
82
+ for (const key of s.required ?? []) {
83
+ if (!(key in obj))
84
+ out.push({ path: pointer(path, key), message: "is required" });
85
+ }
86
+ for (const [key, v] of Object.entries(obj)) {
87
+ if (Object.hasOwn(props, key))
88
+ check(root, props[key], v, pointer(path, key), out);
89
+ else if (s.additionalProperties === false)
90
+ out.push({ path: pointer(path, key), message: "is not a field of the protocol" });
91
+ else if (s.additionalProperties && typeof s.additionalProperties === "object")
92
+ check(root, s.additionalProperties, v, pointer(path, key), out);
93
+ }
94
+ }
95
+ if (s.not && typeof s.not === "object" && validates(root, s.not, value, path))
96
+ out.push({ path, message: "is not allowed here" });
97
+ if (s.if && typeof s.if === "object") {
98
+ const branch = validates(root, s.if, value, path) ? s.then : s.else;
99
+ if (branch && typeof branch === "object")
100
+ check(root, branch, value, path, out);
101
+ }
102
+ }
103
+ function validates(root, schema, value, path) {
104
+ const out = [];
105
+ check(root, schema, value, path, out);
106
+ return out.length === 0;
107
+ }
108
+ /** What is wrong with a trail by the protocol schema; null when this build has no schema to check against. */
109
+ export function checkTrail(trail, schema = trailSchema()) {
110
+ if (!schema)
111
+ return null;
112
+ const out = [];
113
+ check(schema, schema, trail, "", out);
114
+ return out;
115
+ }
@@ -15,11 +15,10 @@
15
15
  // the error line of a failed command to the colony when the automatic lookup is on (lookup.mjs: by default only for a
16
16
  // private colony).
17
17
 
18
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
19
- import { tmpdir } from "node:os";
20
- import { dirname, join } from "node:path";
18
+ import { existsSync, readFileSync } from "node:fs";
21
19
  import { decide, readSettings } from "./on-failure.mjs";
22
20
  import { briefEnabled, briefNote as sharedBriefNote, lookup, lookupEnabled, lookupNote as sharedLookupNote, lookupTask, taskOf } from "./lookup.mjs";
21
+ import { readState, stateFile, writeState } from "./state.mjs";
23
22
 
24
23
  const EXIT = /The command exited with code (-?\d+)\./;
25
24
  // What Antigravity prints around a command's output.
@@ -145,22 +144,12 @@ export function lookupNote(line, body, state, now = Date.now()) {
145
144
  return sharedLookupNote(line, body, state, now, HOW);
146
145
  }
147
146
 
148
- function stateFile(conversation) {
149
- const safe = String(conversation ?? "default").replace(/[^A-Za-z0-9_-]/g, "").slice(0, 64) || "default";
150
- return join(process.env.MYRMO_HOOK_STATE_DIR || join(tmpdir(), "myrmo-hook"), `agy-${safe}.json`);
151
- }
152
-
153
147
  async function main() {
154
148
  let raw = "";
155
149
  for await (const chunk of process.stdin) raw += chunk;
156
150
  const input = JSON.parse(raw);
157
- const file = stateFile(input.conversationId);
158
- let state = {};
159
- try {
160
- if (existsSync(file)) state = JSON.parse(readFileSync(file, "utf8"));
161
- } catch {
162
- state = {};
163
- }
151
+ const file = stateFile(input.conversationId, { prefix: "agy-" });
152
+ const state = readState(file);
164
153
  const transcript = input.transcriptPath && existsSync(input.transcriptPath) ? readFileSync(input.transcriptPath, "utf8") : "";
165
154
  const out = step(input, state, { settings: readSettings(), transcript });
166
155
  const settings = readSettings();
@@ -177,12 +166,8 @@ async function main() {
177
166
  out.state = brief.state;
178
167
  }
179
168
  }
180
- try {
181
- mkdirSync(dirname(file), { recursive: true });
182
- writeFileSync(file, JSON.stringify(out.state));
183
- } catch {
184
- /* without the file the notes are simply not throttled */
185
- }
169
+ // Without the file the notes are simply not throttled.
170
+ writeState(file, out.state);
186
171
  process.stdout.write(JSON.stringify(out.note ? { injectSteps: [{ ephemeralMessage: out.note }] } : {}));
187
172
  }
188
173
 
@@ -11,7 +11,7 @@
11
11
  // turns it off for a session, `"effort": "off"` in the settings file for good.
12
12
 
13
13
  import { closeSync, fstatSync, openSync, readSync } from "node:fs";
14
- import { clientHeader, colonyOf } from "./lookup.mjs";
14
+ import { clientHeader, colonyOf, redactFor } from "./lookup.mjs";
15
15
 
16
16
  /** Whether this machine sends effort records to its colony. */
17
17
  export function effortEnabled(env = process.env, settings = {}) {
@@ -87,8 +87,10 @@ export async function sendEffort(record, { env = process.env, settings = {}, fet
87
87
  const headers = { "content-type": "application/json", "user-agent": "myrmo-claude-code-hook/1", ...clientHeader() };
88
88
  if (env.MYRMO_AGENT_ID) headers["x-myrmo-agent"] = env.MYRMO_AGENT_ID;
89
89
  if (colony.apiKey) headers.authorization = `Bearer ${colony.apiKey}`;
90
+ // The error line is redacted on this machine, as the SDK does before it sends one.
91
+ const body = { ...record, error: redactFor(colony, record.error).slice(0, 2000) };
90
92
  try {
91
- const res = await fetcher(`${colony.url}/v1/effort`, { method: "POST", headers, body: JSON.stringify(record), signal: AbortSignal.timeout(timeoutMs) });
93
+ const res = await fetcher(`${colony.url}/v1/effort`, { method: "POST", headers, body: JSON.stringify(body), signal: AbortSignal.timeout(timeoutMs) });
92
94
  return res.ok;
93
95
  } catch {
94
96
  return false;
@@ -10,6 +10,7 @@
10
10
  import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
11
11
  import { homedir } from "node:os";
12
12
  import { dirname, join } from "node:path";
13
+ import { redactText } from "./redact.mjs";
13
14
 
14
15
  const PUBLIC_HOSTS = new Set(["myrmo.dev", "www.myrmo.dev"]);
15
16
  const trim = (url) => String(url ?? "").trim().replace(/\/+$/, "");
@@ -92,8 +93,9 @@ export function privateColony(env = process.env, settings = {}) {
92
93
  }
93
94
 
94
95
  /**
95
- * Never against the public colony: the hook sends the error line as printed, while the MCP server and the SDKs redact it
96
- * on this machine first. For one's own colony that is fine (it redacts again on arrival, and nothing leaves).
96
+ * Never against the public colony: the agent did not choose to search, and the error line is sent without anyone looking
97
+ * at it (redacted here first, with the SDK's rules, and again by the colony on arrival). One's own colony keeps it inside
98
+ * the organisation.
97
99
  */
98
100
  export function lookupEnabled(env = process.env, settings = {}) {
99
101
  const colony = colonyOf(env, settings);
@@ -102,10 +104,26 @@ export function lookupEnabled(env = process.env, settings = {}) {
102
104
  }
103
105
 
104
106
  export const clip = (text, max) => {
105
- const t = String(text ?? "").replace(/\s+/g, " ").replace(/<(\/?\s*myrmo_)/gi, "‹$1").trim();
107
+ const t = String(text ?? "").replace(/\s+/g, " ").replace(/<(\s*\/?\s*myrmo_)/gi, "‹$1").trim();
106
108
  return t.length > max ? `${t.slice(0, max - 1)}…` : t;
107
109
  };
108
110
 
111
+ /** A number the colony sent, as a number ("?" when it is not one): never words the colony chose. */
112
+ export const num = (value, missing = "?") => {
113
+ if (value === undefined || value === null || value === "") return missing;
114
+ const n = typeof value === "number" || typeof value === "string" ? Number(value) : NaN;
115
+ return Number.isFinite(n) ? String(n) : "?";
116
+ };
117
+
118
+ /**
119
+ * What the hooks send to a colony, redacted on this machine first with the SDK's rules (redact.mjs): credentials and
120
+ * personal data never leave it, even for the organisation's own colony, which redacts again on arrival. A private
121
+ * colony keeps its network's addresses and host names, as the MCP server does.
122
+ */
123
+ export function redactFor(colony, text) {
124
+ return redactText(String(text ?? ""), {}, { keepNetwork: colony?.private === true });
125
+ }
126
+
109
127
  /** Search the colony for an error line; null when it cannot be reached. */
110
128
  export async function lookup(line, { env = process.env, settings = {}, fetcher = fetch, timeoutMs = 6000, agent = "myrmo-hook/1" } = {}) {
111
129
  const colony = colonyOf(env, settings);
@@ -117,7 +135,7 @@ export async function lookup(line, { env = process.env, settings = {}, fetcher =
117
135
  const ctrl = new AbortController();
118
136
  const timer = setTimeout(() => ctrl.abort(), timeoutMs);
119
137
  try {
120
- const res = await fetcher(url, { method: "POST", headers, body: JSON.stringify({ query: line.slice(0, 2000), limit: 3 }), signal: ctrl.signal });
138
+ const res = await fetcher(url, { method: "POST", headers, body: JSON.stringify({ query: redactFor(colony, line).slice(0, 2000), limit: 3 }), signal: ctrl.signal });
121
139
  return res.ok ? await res.json() : null;
122
140
  } catch {
123
141
  return null;
@@ -126,6 +144,9 @@ export async function lookup(line, { env = process.env, settings = {}, fetcher =
126
144
  }
127
145
  }
128
146
 
147
+ /** The colony's risk analysis covers the listed commands, not commands written in prose. */
148
+ const STEPS_NOT_COVERED = "This covers the listed commands only: check a command written in the steps the same way before running it, and ask the user if it could do harm.";
149
+
129
150
  /** A strong match: found by the exact error message, or a close semantic match. */
130
151
  const strong = (hit) => hit?.match?.via === "fingerprint" || Number(hit?.match?.score) >= 0.85;
131
152
 
@@ -152,8 +173,10 @@ export function lookupNote(line, body, state, now = Date.now(), how = "") {
152
173
  }
153
174
  const t = best.trail ?? {};
154
175
  const env = t.environment ?? {};
176
+ // Without a risk analysis nothing is known about the commands: said so, never "flagged none".
177
+ const analysed = Array.isArray(best.risk?.flags);
155
178
  const flags = new Map();
156
- for (const f of best.risk?.flags ?? []) {
179
+ for (const f of analysed ? best.risk.flags : []) {
157
180
  const seen = flags.get(f.command_index);
158
181
  const rank = { low: 1, medium: 2, high: 3 };
159
182
  if (!seen || (rank[f.level] ?? 3) > (rank[seen.level] ?? 3)) flags.set(f.command_index, f);
@@ -176,8 +199,14 @@ export function lookupNote(line, body, state, now = Date.now(), how = "") {
176
199
  "Steps:", ...steps,
177
200
  ...(commands.length ? ["Commands:", ...commands] : []),
178
201
  // Said outright: a careful model that is not told otherwise treats every command from a trail as risky and stops to
179
- // ask, which an agent working alone cannot do (measured in MyrmoBench).
180
- ...(commands.length && flags.size === 0 ? ["Risk: the colony flagged none of these commands. Once you have checked they fit your environment, run them as you would your own."] : []),
202
+ // ask, which an agent working alone cannot do (measured in MyrmoBench). The analysis covers the listed commands only.
203
+ ...(!commands.length
204
+ ? []
205
+ : !analysed
206
+ ? ["Risk: unknown, the colony sent no risk analysis. Show each command, including any written in the steps, to the user and wait for approval before running it."]
207
+ : flags.size === 0
208
+ ? [`Risk: the colony flagged none of these commands. Once you have checked they fit your environment, run them as you would your own. ${STEPS_NOT_COVERED}`]
209
+ : [`Risk: ${STEPS_NOT_COVERED}`]),
181
210
  "</myrmo_trail>",
182
211
  `After trying it, report the outcome with myrmo_report (trail_id ${id}: worked, partially_worked, failed or not_applicable).${how}`,
183
212
  ].join("\n");
@@ -220,7 +249,7 @@ export async function lookupTask(task, { env = process.env, settings = {}, fetch
220
249
  const ctrl = new AbortController();
221
250
  const timer = setTimeout(() => ctrl.abort(), timeoutMs);
222
251
  try {
223
- const res = await fetcher(`${colony.url}/v1/search`, { method: "POST", headers, body: JSON.stringify({ query: task, mode: "task", limit: 3 }), signal: ctrl.signal });
252
+ const res = await fetcher(`${colony.url}/v1/search`, { method: "POST", headers, body: JSON.stringify({ query: redactFor(colony, task).slice(0, 2000), mode: "task", limit: 3 }), signal: ctrl.signal });
224
253
  return res.ok ? await res.json() : null;
225
254
  } catch {
226
255
  return null;
@@ -247,10 +276,12 @@ export function briefNote(task, body, state = {}, now = Date.now(), how = "") {
247
276
  const t = hit.trail ?? {};
248
277
  const id = String(hit.trail_id ?? "").replace(/[^0-9a-fA-F-]/g, "").slice(0, 36);
249
278
  ids.push(id);
250
- const kind = KINDS[hit.kind ?? t.kind ?? "fix"] ?? "entry";
279
+ const named = hit.kind ?? t.kind ?? "fix";
280
+ const kind = typeof named === "string" && Object.hasOwn(KINDS, named) ? KINDS[named] : "entry";
251
281
  const about = clip(t.problem?.summary || t.problem?.error_message || t.problem?.error_type, 160);
252
282
  const o = hit.outcomes ?? {};
253
- return `${i + 1}. [${kind}] ${about} (strength ${Number(hit.strength ?? 0).toFixed(2)}, worked ${o.worked ?? 0}, failed ${o.failed ?? 0}) id ${id}`;
283
+ const strength = Number(hit.strength ?? 0);
284
+ return `${i + 1}. [${kind}] ${about} (strength ${Number.isFinite(strength) ? strength.toFixed(2) : "?"}, worked ${num(o.worked, "0")}, failed ${num(o.failed, "0")}) id ${id}`;
254
285
  });
255
286
  const note = [
256
287
  "Myrmo (your organisation's private colony) already has knowledge that may help with this task:",
@@ -36,11 +36,12 @@
36
36
  // `config hook failures`; MYRMO_HOOK=off|failures does the same for one session. Tunables: MYRMO_HOOK_MIN_SECONDS
37
37
  // (default 20) between two reminders, MYRMO_HOOK_MAX (default 30) per session.
38
38
 
39
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
40
- import { homedir, tmpdir } from "node:os";
41
- import { dirname, join } from "node:path";
39
+ import { readFileSync } from "node:fs";
40
+ import { homedir } from "node:os";
41
+ import { join } from "node:path";
42
42
  import { measureAndSend } from "./effort.mjs";
43
43
  import { briefEnabled, briefNote, lookup, lookupEnabled, lookupNote, lookupTask, privateColony, taskOf, updateNotice } from "./lookup.mjs";
44
+ import { readState, stateFile, writeState } from "./state.mjs";
44
45
 
45
46
  // Commands that fail or print errors as part of normal work: a probe that found nothing, a diff that differs, a log
46
47
  // being read. Their output is not a problem of the user's.
@@ -51,7 +52,30 @@ const SEARCH_TOOL = /^mcp__.*myrmo_search$/;
51
52
  const REPORT_TOOL = /^mcp__.*myrmo_report$/;
52
53
  const PUBLISH_TOOL = /^mcp__.*myrmo_publish$/;
53
54
  // The id each trail is listed under in a search reply (`## Trail 1 of 2 · id <uuid>`).
54
- const TRAIL_ID = /^## Trail \d+ of \d+ · id ([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/gim;
55
+ const TRAIL_ID = /^## Trail \d+ of \d+ · id ([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;
56
+
57
+ /**
58
+ * The ids of the trails in a search reply, from their header lines only. A patch is shown in a code fence and can hold
59
+ * any line a stranger wrote, a forged header included, so nothing inside a fence counts.
60
+ */
61
+ export function trailIds(reply) {
62
+ const ids = [];
63
+ let fence = null;
64
+ for (const line of String(reply).split(/\r?\n/)) {
65
+ const opening = /^(`{3,})/.exec(line);
66
+ if (fence) {
67
+ if (line === fence) fence = null;
68
+ continue;
69
+ }
70
+ if (opening) {
71
+ fence = opening[1];
72
+ continue;
73
+ }
74
+ const id = TRAIL_ID.exec(line)?.[1]?.toLowerCase();
75
+ if (id && !ids.includes(id)) ids.push(id);
76
+ }
77
+ return ids.slice(0, 5);
78
+ }
55
79
  // Exit codes that mean a person or the system stopped the command: interrupt, timeout, kill, terminate.
56
80
  const STOPPED = new Set([124, 130, 137, 143]);
57
81
  /**
@@ -294,7 +318,7 @@ export function decide(input, { now = Date.now(), state = {}, env = process.env,
294
318
  return quiet({ ...state, nomatch: { at: now, line: String(input.tool_input?.error ?? "").slice(0, 240) } });
295
319
  }
296
320
  if (/<myrmo_trails/.test(reply)) {
297
- const ids = [...new Set([...reply.matchAll(TRAIL_ID)].map((m) => m[1].toLowerCase()))].slice(0, 5);
321
+ const ids = trailIds(reply);
298
322
  return quiet({ ...state, nomatch: null, found: ids.length ? { at: now, ids } : null });
299
323
  }
300
324
  return quiet(state);
@@ -457,19 +481,10 @@ export function decideStop(input, { now = Date.now(), state = {}, env = process.
457
481
  return { reason, state: { ...state, brief, harvestedAt: failures, harvestedTs: now, harvests: (state.harvests ?? 0) + 1 } };
458
482
  }
459
483
 
460
- function stateFile(session) {
461
- const safe = String(session ?? "default").replace(/[^A-Za-z0-9_-]/g, "").slice(0, 64) || "default";
462
- return join(process.env.MYRMO_HOOK_STATE_DIR || join(tmpdir(), "myrmo-hook"), `${safe}.json`);
463
- }
464
-
484
+ /** Without the file (a folder that cannot be trusted, a full disk) the notes are simply not throttled. */
465
485
  function save(file, before, after) {
466
486
  if (JSON.stringify(after) === JSON.stringify(before)) return;
467
- try {
468
- mkdirSync(dirname(file), { recursive: true });
469
- writeFileSync(file, JSON.stringify(after));
470
- } catch {
471
- /* without the file the notes are simply not throttled */
472
- }
487
+ writeState(file, after);
473
488
  }
474
489
 
475
490
  async function main() {
@@ -477,12 +492,7 @@ async function main() {
477
492
  for await (const chunk of process.stdin) raw += chunk;
478
493
  const input = JSON.parse(raw);
479
494
  const file = stateFile(input.session_id);
480
- let state = {};
481
- try {
482
- if (existsSync(file)) state = JSON.parse(readFileSync(file, "utf8"));
483
- } catch {
484
- state = {};
485
- }
495
+ const state = readState(file);
486
496
  const settings = readSettings();
487
497
  // 8. A session starts: is this plugin older than what the colony was released with? Said to the person, not the agent.
488
498
  if (input.hook_event_name === "SessionStart") {