@leonidstern/labit 0.6.1 → 0.6.2

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.
@@ -1,3 +1,12 @@
1
+ import {
2
+ WAIT_SAID,
3
+ findLab,
4
+ labCall
5
+ } from "./chunk-LNYMIFDQ.mjs";
6
+ import {
7
+ mySession
8
+ } from "./chunk-X4RYDWNI.mjs";
9
+
1
10
  // lib/mcp.ts
2
11
  import fs from "node:fs";
3
12
  import path from "node:path";
@@ -20,13 +29,14 @@ async function runMcp({ HERE, ME, CMD, VERSION, WRITE_SHORT, AGENTS, agentKind,
20
29
  if (typeof a.dir === "string" && a.dir.trim()) return path.resolve(HERE, a.dir);
21
30
  return rootDir || (labAbove(HERE) ? HERE : pwd && labAbove(pwd) ? pwd : HERE);
22
31
  };
23
- const run = (args, ms, id, cwd = HERE) => new Promise((done) => {
24
- const env = client && !agentNow().kind && !process.env.LAB_AGENT ? { ...process.env, LAB_AGENT: AGENTS[agentKind(client)]?.name || client } : process.env;
25
- const child = execFile(process.execPath, [ME, ...args], { cwd, timeout: ms, maxBuffer: 4 << 20, env }, (err, stdout, stderr) => {
26
- running.delete(id);
32
+ const nameAgent = () => {
33
+ if (client && !agentNow().kind && !process.env.LAB_AGENT) process.env.LAB_AGENT = AGENTS[agentKind(client)]?.name || client;
34
+ };
35
+ const run = (args, ms, cwd = HERE) => new Promise((done) => {
36
+ nameAgent();
37
+ execFile(process.execPath, [ME, ...args], { cwd, timeout: ms, maxBuffer: 4 << 20 }, (err, stdout, stderr) => {
27
38
  done({ ok: !err, text: (stdout || "") + (err && !stdout ? stderr || err.message : "") });
28
39
  });
29
- if (id !== void 0) running.set(id, child);
30
40
  });
31
41
  const forTools = (t) => t.replace(/^Answer each: .*$/m, "Answer each with the `reply` tool (id, text, resolve: true when done), then call `wait` again.");
32
42
  const text = (t, isError = false) => ({ content: [{ type: "text", text: forTools(t).trim() || "(nothing)" }], ...isError ? { isError } : {} });
@@ -106,19 +116,30 @@ async function runMcp({ HERE, ME, CMD, VERSION, WRITE_SHORT, AGENTS, agentKind,
106
116
  if (typeof a.text !== "string" || !a.text.trim()) return text("`text` is required: what you did.", true);
107
117
  if (a.resolve !== void 0 && typeof a.resolve !== "boolean") return text("`resolve` must be true or false.", true);
108
118
  if (a.dir !== void 0 && typeof a.dir !== "string") return text("`dir` must be a folder path.", true);
109
- const r2 = await run(["reply", a.id, a.text, ...a.resolve ? ["--resolve"] : []], 3e4, void 0, project(a));
110
- return text(r2.text, !r2.ok);
119
+ const r = await run(["reply", a.id, a.text, ...a.resolve ? ["--resolve"] : []], 3e4, project(a));
120
+ return text(r.text, !r.ok);
111
121
  }
112
122
  if (a.seconds !== void 0 && (typeof a.seconds !== "number" || !Number.isFinite(a.seconds))) return text("`seconds` must be a number.", true);
123
+ if (a.dir !== void 0 && typeof a.dir !== "string") return text("`dir` must be a folder path.", true);
124
+ if (a.model !== void 0 && typeof a.model !== "string") return text("`model` must be a name, e.g. Sonnet 5.5.", true);
113
125
  const s = Math.min(Math.max(Math.round(a.seconds ?? 50), 5), 1500);
114
126
  const token = m.params?._meta?.progressToken;
115
127
  let n = 0;
116
128
  const tick = token === void 0 ? null : setInterval(() => send({ method: "notifications/progress", params: { progressToken: token, progress: ++n * 20, total: s, message: "Waiting for the next pin" } }), 2e4);
117
- if (a.dir !== void 0 && typeof a.dir !== "string") return text("`dir` must be a folder path.", true);
118
- if (a.model !== void 0 && typeof a.model !== "string") return text("`model` must be a name, e.g. Sonnet 5.5.", true);
119
- const r = await run(["wait", "--timeout", String(s), ...a.model ? ["--model", a.model] : []], (s + 30) * 1e3, m.id, project(a));
120
- if (tick) clearInterval(tick);
121
- return text(r.text, !r.ok);
129
+ const lab = findLab(project(a));
130
+ if (!lab) return text(`No lab in ${project(a)}. Start one there: ${CMD} (or pass \`dir\`, the project folder)`, true);
131
+ const stop = new AbortController();
132
+ running.set(m.id, stop);
133
+ try {
134
+ nameAgent();
135
+ const out = await labCall(lab.server, "/_lab/wait", { timeout: s, pages: null }, mySession(void 0, a.model), stop.signal);
136
+ return text(WAIT_SAID[out.status] ?? out.text, out.status >= 300 && !WAIT_SAID[out.status]);
137
+ } catch {
138
+ return text(stop.signal.aborted ? "Stopped." : `The lab server for ${lab.dir} isn't running. Start it: ${CMD}`, true);
139
+ } finally {
140
+ running.delete(m.id);
141
+ if (tick) clearInterval(tick);
142
+ }
122
143
  };
123
144
  const handle = async (m) => {
124
145
  const version = m.params?._meta?.[`${META}protocolVersion`];
@@ -132,7 +153,7 @@ async function runMcp({ HERE, ME, CMD, VERSION, WRITE_SHORT, AGENTS, agentKind,
132
153
  return done({ supportedVersions: [...MODERN, ...LEGACY], capabilities: { tools: {} }, _meta: { [`${META}serverInfo`]: info }, instructions: INSTRUCTIONS });
133
154
  if (m.method === "initialize") {
134
155
  const asked = m.params?.protocolVersion;
135
- if (m.params?.capabilities?.roots) setTimeout(() => send({ id: "labit-roots", method: "roots/list" }), 0);
156
+ askRoots = Boolean(m.params?.capabilities?.roots);
136
157
  return { protocolVersion: LEGACY.includes(asked) ? asked : LEGACY[0], capabilities: { tools: {} }, serverInfo: info, instructions: INSTRUCTIONS };
137
158
  }
138
159
  if (m.method === "ping") return done({});
@@ -140,7 +161,9 @@ async function runMcp({ HERE, ME, CMD, VERSION, WRITE_SHORT, AGENTS, agentKind,
140
161
  if (m.method === "tools/call") return done(await call(m));
141
162
  throw fail(-32601, `Method not found: ${m.method}`);
142
163
  };
164
+ const pending = /* @__PURE__ */ new Set();
143
165
  const cancelled = /* @__PURE__ */ new Set();
166
+ let askRoots = false;
144
167
  let buf = "";
145
168
  process.stdin.setEncoding("utf8");
146
169
  process.stdin.on("data", (chunk) => {
@@ -164,26 +187,47 @@ async function runMcp({ HERE, ME, CMD, VERSION, WRITE_SHORT, AGENTS, agentKind,
164
187
  }
165
188
  continue;
166
189
  }
167
- if (!m || typeof m !== "object" || Array.isArray(m) || typeof m.method !== "string") {
190
+ if (Array.isArray(m)) {
191
+ send({ id: null, error: { code: -32600, message: "Invalid request: send one message per line, not a batch" } });
192
+ continue;
193
+ }
194
+ if (!m || typeof m !== "object" || typeof m.method !== "string") {
168
195
  if (m && m.id !== void 0 && typeof m.method !== "string" && !("result" in m) && !("error" in m)) send({ id: m.id, error: { code: -32600, message: "Invalid request" } });
169
196
  continue;
170
197
  }
171
198
  if (m.id === void 0) {
172
199
  if (m.method === "notifications/cancelled") {
173
- const id = m.params?.requestId;
174
- running.get(id)?.kill();
175
- cancelled.add(id);
200
+ const id2 = m.params?.requestId;
201
+ if (pending.has(id2)) {
202
+ cancelled.add(id2);
203
+ running.get(id2)?.abort();
204
+ }
205
+ }
206
+ if (m.method === "notifications/initialized" && askRoots) {
207
+ askRoots = false;
208
+ send({ id: "labit-roots", method: "roots/list" });
176
209
  }
177
210
  continue;
178
211
  }
212
+ const id = m.id;
213
+ pending.add(id);
214
+ const answer = (msg) => {
215
+ pending.delete(id);
216
+ if (!cancelled.delete(id)) send({ id, ...msg });
217
+ };
179
218
  handle(m).then(
180
- (result) => !cancelled.delete(m.id) && send({ id: m.id, result }),
181
- (e) => !cancelled.delete(m.id) && send({ id: m.id, error: { code: e.code || -32603, message: e.message, ...e.data ? { data: e.data } : {} } })
219
+ (result) => answer({ result }),
220
+ (e) => answer({ error: { code: e.code || -32603, message: e.message, ...e.data ? { data: e.data } : {} } })
182
221
  );
183
222
  }
184
223
  });
185
- process.stdin.on("end", () => process.exit(0));
186
- process.on("SIGTERM", () => process.exit(0));
224
+ const quit = () => {
225
+ for (const stop of running.values()) stop.abort();
226
+ process.exit(0);
227
+ };
228
+ process.stdin.on("end", quit);
229
+ process.on("SIGTERM", quit);
230
+ process.on("SIGINT", quit);
187
231
  return new Promise(() => {
188
232
  });
189
233
  }
@@ -0,0 +1,175 @@
1
+ import {
2
+ FLAGS,
3
+ flagDefaults
4
+ } from "./chunk-DIR2O7SK.mjs";
5
+
6
+ // lib/settings.ts
7
+ import fs from "node:fs";
8
+ import os from "node:os";
9
+ import path from "node:path";
10
+ var SHORTCUTS = { toggle: "m", comment: "1", go: "2", zoom: "3", pointer: "4", chat: "c", next: "w", pause: "p", done: "d", reply: "r", resolve: "e" };
11
+ var SPEC = {
12
+ port: { type: "number", def: 4400, min: 1 },
13
+ proxy: { type: "string", def: "", only: "project" },
14
+ folder: { type: "string", def: ".", only: "project" },
15
+ open: { type: "boolean", def: true },
16
+ wifi: { type: "boolean", def: false, only: "personal" },
17
+ batchSeconds: { type: "number", def: 2, min: 0 },
18
+ stopListeningAfterMinutes: { type: "number", def: 60, min: 0 },
19
+ remindAfterMinutes: { type: "number", def: 3, min: 0 },
20
+ archiveAfterDays: { type: "number", def: 30, min: 1 },
21
+ updateCheck: { type: "boolean", def: true },
22
+ name: { type: "string", def: "", only: "personal" },
23
+ model: { type: "string", def: "", only: "personal" },
24
+ shortcuts: { type: "shortcuts", def: SHORTCUTS },
25
+ zoom: { type: "zoom", def: { skill: "" }, only: "project" },
26
+ // What is being tried here (lib/flags.ts). Off unless a file or the ⋯ menu turns one on.
27
+ flags: { type: "flags", def: flagDefaults() }
28
+ };
29
+ var ENV = {
30
+ port: ["PORT", Number],
31
+ batchSeconds: ["LAB_SETTLE_MS", (v) => Number(v) / 1e3],
32
+ stopListeningAfterMinutes: ["LAB_CLOSE_GRACE", (v) => Number(v) / 60],
33
+ remindAfterMinutes: ["LAB_REMIND_MS", (v) => Number(v) / 6e4],
34
+ updateCheck: ["LABIT_NO_UPDATE_CHECK", () => false],
35
+ model: ["LAB_MODEL", String]
36
+ };
37
+ var personalFile = () => path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config"), "labit", "settings.json");
38
+ var projectFile = (from) => {
39
+ for (let dir = path.resolve(from); ; dir = path.dirname(dir)) {
40
+ if (fs.existsSync(path.join(dir, "labit.json"))) return path.join(dir, "labit.json");
41
+ if (path.dirname(dir) === dir) return null;
42
+ }
43
+ };
44
+ var read = (file, problems) => {
45
+ if (!file || !fs.existsSync(file)) return {};
46
+ try {
47
+ const v = JSON.parse(fs.readFileSync(file, "utf8"));
48
+ if (v && typeof v === "object" && !Array.isArray(v)) return v;
49
+ problems.push(`${file}: not an object of settings; ignored`);
50
+ } catch (e) {
51
+ problems.push(`${file}: not valid JSON (${e.message}); ignored`);
52
+ }
53
+ return {};
54
+ };
55
+ var check = (key, v, file, problems) => {
56
+ const s = SPEC[key];
57
+ const bad = (why) => void problems.push(`${file}: ${key} ${why}; ignored`);
58
+ if (s.type === "shortcuts") {
59
+ if (!v || typeof v !== "object" || Array.isArray(v)) return bad("must be an object of action \u2192 key");
60
+ const out = {};
61
+ for (const [action, key1] of Object.entries(v)) {
62
+ if (!(action in SHORTCUTS)) bad(`.${action} is not an action (${Object.keys(SHORTCUTS).join(", ")})`);
63
+ else if (typeof key1 !== "string" || !/^[a-z0-9]$/i.test(key1)) bad(`.${action} must be one letter or digit`);
64
+ else out[action] = key1.toLowerCase();
65
+ }
66
+ return out;
67
+ }
68
+ if (s.type === "flags") {
69
+ if (!v || typeof v !== "object" || Array.isArray(v)) return bad("must be an object of flag \u2192 true or false");
70
+ const out = {};
71
+ for (const [flag, on] of Object.entries(v)) {
72
+ if (!(flag in FLAGS)) bad(`.${flag} is not something being tried now (${Object.keys(FLAGS).join(", ") || "nothing at the moment"})`);
73
+ else if (typeof on !== "boolean") bad(`.${flag} must be true or false`);
74
+ else out[flag] = on;
75
+ }
76
+ return out;
77
+ }
78
+ if (s.type === "zoom") {
79
+ if (!v || typeof v !== "object" || typeof v.skill !== "string") return bad('must be { "skill": "<path to a .md file>" }');
80
+ const skill = path.resolve(path.dirname(file), v.skill);
81
+ if (!fs.existsSync(skill)) return bad(`.skill: no file ${skill}`);
82
+ return { skill };
83
+ }
84
+ if (typeof v !== s.type) return bad(`must be a ${s.type}`);
85
+ if (s.type === "number" && (!Number.isFinite(v) || v < (s.min ?? -Infinity))) return bad(`must be a number of at least ${s.min}`);
86
+ if (s.type === "string" && key === "folder") return path.resolve(path.dirname(file), v);
87
+ return s.type === "string" ? v.trim() : v;
88
+ };
89
+ function loadSettings(here, flags = {}, env = process.env) {
90
+ const problems = [];
91
+ const files = { project: projectFile(here), personal: personalFile() };
92
+ const layers = [
93
+ [files.project || "", read(files.project, problems), "project"],
94
+ [files.personal, read(files.personal, problems), "personal"]
95
+ ];
96
+ const values = {};
97
+ const from = {};
98
+ for (const [file, data] of layers)
99
+ for (const key of Object.keys(data)) if (!(key in SPEC) && key !== "$schema") problems.push(`${file}: ${key} is not a setting; ignored`);
100
+ for (const key of Object.keys(SPEC)) {
101
+ const s = SPEC[key];
102
+ if (flags[key] !== void 0) {
103
+ values[key] = flags[key];
104
+ from[key] = "flag";
105
+ continue;
106
+ }
107
+ const e = ENV[key];
108
+ if (e && env[e[0]] !== void 0 && env[e[0]] !== "") {
109
+ values[key] = e[1](env[e[0]]);
110
+ from[key] = `env ${e[0]}`;
111
+ continue;
112
+ }
113
+ for (const [file, data, where] of layers) {
114
+ if (!(key in data)) continue;
115
+ if (s.only && s.only !== where) {
116
+ problems.push(`${file}: ${key} can only be set in ${s.only === "personal" ? `your own settings (${files.personal})` : "the project's labit.json"}; ignored`);
117
+ continue;
118
+ }
119
+ const v = check(key, data[key], file, problems);
120
+ if (v === void 0) continue;
121
+ if (s.type === "shortcuts" || s.type === "flags") {
122
+ values[key] = { ...v, ...values[key] };
123
+ from[key] = from[key] ? `${from[key]} + ${file}` : file;
124
+ continue;
125
+ }
126
+ values[key] = v;
127
+ from[key] = file;
128
+ break;
129
+ }
130
+ if (s.type === "flags" && values[key]) values[key] = { ...flagDefaults(), ...values[key] };
131
+ if (s.type === "shortcuts" && values[key]) {
132
+ values[key] = { ...SHORTCUTS, ...values[key] };
133
+ const taken = Object.entries(values[key]).filter(([, k], i, all) => all.findIndex(([, k2]) => k2 === k) !== i);
134
+ for (const [action, k] of taken) problems.push(`shortcuts: "${k}" is used twice (${action} too); the first action keeps it`);
135
+ }
136
+ if (!(key in values)) {
137
+ values[key] = s.def;
138
+ from[key] = "default";
139
+ }
140
+ }
141
+ return { values, from, files, problems };
142
+ }
143
+ var changedShortcuts = (keys) => Object.fromEntries(Object.entries(keys).filter(([a, k]) => SHORTCUTS[a] !== k));
144
+ function saveFlag(here, flag, on) {
145
+ const file = projectFile(here) || path.join(path.resolve(here), "labit.json");
146
+ let data = {};
147
+ try {
148
+ data = JSON.parse(fs.readFileSync(file, "utf8"));
149
+ } catch {
150
+ }
151
+ const flags = data.flags && typeof data.flags === "object" && !Array.isArray(data.flags) ? data.flags : {};
152
+ if (on) flags[flag] = true;
153
+ else delete flags[flag];
154
+ if (Object.keys(flags).length) data.flags = flags;
155
+ else delete data.flags;
156
+ fs.writeFileSync(file, JSON.stringify(data, null, 2) + "\n");
157
+ return file;
158
+ }
159
+ function savePersonal(key, value) {
160
+ const file = personalFile();
161
+ let data = {};
162
+ try {
163
+ data = JSON.parse(fs.readFileSync(file, "utf8"));
164
+ } catch {
165
+ }
166
+ data[key] = value;
167
+ fs.mkdirSync(path.dirname(file), { recursive: true });
168
+ fs.writeFileSync(file, JSON.stringify(data, null, 2) + "\n");
169
+ }
170
+ export {
171
+ changedShortcuts,
172
+ loadSettings,
173
+ saveFlag,
174
+ savePersonal
175
+ };
package/package.json CHANGED
@@ -1,11 +1,10 @@
1
1
  {
2
2
  "name": "@leonidstern/labit",
3
- "version": "0.6.1",
3
+ "version": "0.6.2",
4
4
  "description": "Pin comments on pages, read by your agent as plain text. Local mode: comment on pages on your computer and Claude answers on the pins.",
5
5
  "type": "module",
6
6
  "bin": {
7
- "labit": "dist/local.mjs",
8
- "labfb": "dist/local.mjs"
7
+ "labit": "dist/local.mjs"
9
8
  },
10
9
  "files": [
11
10
  "dist/",
@@ -23,6 +22,7 @@
23
22
  "build:cli": "npx --yes esbuild@0.25.12 local.mjs --bundle --splitting --format=esm --platform=node --target=node22 --outdir=dist --out-extension:.js=.mjs --log-level=warning",
24
23
  "prepack": "npm run build:cli",
25
24
  "typecheck": "node ci/metrics.mjs types",
25
+ "deadcode": "npx --yes knip@5.66.0 --include files,exports,types --no-progress",
26
26
  "test": "node --import ./test/setup.mjs --test test/*.test.mjs"
27
27
  },
28
28
  "engines": {