@leonidstern/labit 0.6.1 → 0.6.3-edge.3.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.
@@ -1,3 +1,12 @@
1
+ import {
2
+ WAIT_SAID,
3
+ findLab,
4
+ labCall
5
+ } from "./chunk-QTMKKULT.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,15 +29,16 @@ 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
- const forTools = (t) => t.replace(/^Answer each: .*$/m, "Answer each with the `reply` tool (id, text, resolve: true when done), then call `wait` again.");
41
+ const forTools = (t) => t.replace(/^Answer each: .*$/m, "Answer each with the `reply` tool (id, text, intent: done when it is done, question when you need the person), then call `wait` again.");
32
42
  const text = (t, isError = false) => ({ content: [{ type: "text", text: forTools(t).trim() || "(nothing)" }], ...isError ? { isError } : {} });
33
43
  const tools = [
34
44
  {
@@ -41,12 +51,13 @@ async function runMcp({ HERE, ME, CMD, VERSION, WRITE_SHORT, AGENTS, agentKind,
41
51
  {
42
52
  name: "reply",
43
53
  title: "Answer on a pin",
44
- description: `Answer on a pin in the local lab, by the id \`comments\` shows. resolve: true closes the thread. ${WRITE_SHORT}`,
54
+ description: `Answer on a pin in the local lab, by the id \`comments\` shows. intent says what the answer is: done (the thread closes), working (you're on it) or question (you need the person). resolve: true closes the thread. ${WRITE_SHORT}`,
45
55
  inputSchema: {
46
56
  type: "object",
47
57
  properties: {
48
58
  id: { type: "string", description: "The comment id" },
49
- text: { type: "string", description: 'What you did, e.g. "Done: the title is red"' },
59
+ text: { type: "string", description: 'What you did, e.g. "The title is red"' },
60
+ intent: { type: "string", enum: ["done", "working", "question"], description: "done: the ask is done; working: you are on it; question: you need the person" },
50
61
  resolve: { type: "boolean", description: "Close the thread" },
51
62
  dir: { type: "string", description: "The project folder, if the server started somewhere else (default: the client's root or the folder it started in)" }
52
63
  },
@@ -105,20 +116,33 @@ async function runMcp({ HERE, ME, CMD, VERSION, WRITE_SHORT, AGENTS, agentKind,
105
116
  if (typeof a.id !== "string" || !a.id.trim()) return text("`id` is required: the comment id that `comments` shows.", true);
106
117
  if (typeof a.text !== "string" || !a.text.trim()) return text("`text` is required: what you did.", true);
107
118
  if (a.resolve !== void 0 && typeof a.resolve !== "boolean") return text("`resolve` must be true or false.", true);
119
+ const flag = { done: "--done", working: "--on-it", question: "--question" }[a.intent];
120
+ if (a.intent !== void 0 && !flag) return text("`intent` must be done, working or question.", true);
108
121
  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);
122
+ const r = await run(["reply", a.id, a.text, ...flag ? [flag] : [], ...a.resolve ? ["--resolve"] : []], 3e4, project(a));
123
+ return text(r.text, !r.ok);
111
124
  }
112
125
  if (a.seconds !== void 0 && (typeof a.seconds !== "number" || !Number.isFinite(a.seconds))) return text("`seconds` must be a number.", true);
126
+ if (a.dir !== void 0 && typeof a.dir !== "string") return text("`dir` must be a folder path.", true);
127
+ if (a.model !== void 0 && typeof a.model !== "string") return text("`model` must be a name, e.g. Sonnet 5.5.", true);
113
128
  const s = Math.min(Math.max(Math.round(a.seconds ?? 50), 5), 1500);
114
129
  const token = m.params?._meta?.progressToken;
115
130
  let n = 0;
116
131
  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);
132
+ const lab = findLab(project(a));
133
+ if (!lab) return text(`No lab in ${project(a)}. Start one there: ${CMD} (or pass \`dir\`, the project folder)`, true);
134
+ const stop = new AbortController();
135
+ running.set(m.id, stop);
136
+ try {
137
+ nameAgent();
138
+ const out = await labCall(lab.server, "/_lab/wait", { timeout: s, pages: null }, mySession(void 0, a.model), stop.signal);
139
+ return text(WAIT_SAID[out.status] ?? out.text, out.status >= 300 && !WAIT_SAID[out.status]);
140
+ } catch {
141
+ return text(stop.signal.aborted ? "Stopped." : `The lab server for ${lab.dir} isn't running. Start it: ${CMD}`, true);
142
+ } finally {
143
+ running.delete(m.id);
144
+ if (tick) clearInterval(tick);
145
+ }
122
146
  };
123
147
  const handle = async (m) => {
124
148
  const version = m.params?._meta?.[`${META}protocolVersion`];
@@ -132,7 +156,7 @@ async function runMcp({ HERE, ME, CMD, VERSION, WRITE_SHORT, AGENTS, agentKind,
132
156
  return done({ supportedVersions: [...MODERN, ...LEGACY], capabilities: { tools: {} }, _meta: { [`${META}serverInfo`]: info }, instructions: INSTRUCTIONS });
133
157
  if (m.method === "initialize") {
134
158
  const asked = m.params?.protocolVersion;
135
- if (m.params?.capabilities?.roots) setTimeout(() => send({ id: "labit-roots", method: "roots/list" }), 0);
159
+ askRoots = Boolean(m.params?.capabilities?.roots);
136
160
  return { protocolVersion: LEGACY.includes(asked) ? asked : LEGACY[0], capabilities: { tools: {} }, serverInfo: info, instructions: INSTRUCTIONS };
137
161
  }
138
162
  if (m.method === "ping") return done({});
@@ -140,7 +164,9 @@ async function runMcp({ HERE, ME, CMD, VERSION, WRITE_SHORT, AGENTS, agentKind,
140
164
  if (m.method === "tools/call") return done(await call(m));
141
165
  throw fail(-32601, `Method not found: ${m.method}`);
142
166
  };
167
+ const pending = /* @__PURE__ */ new Set();
143
168
  const cancelled = /* @__PURE__ */ new Set();
169
+ let askRoots = false;
144
170
  let buf = "";
145
171
  process.stdin.setEncoding("utf8");
146
172
  process.stdin.on("data", (chunk) => {
@@ -164,26 +190,47 @@ async function runMcp({ HERE, ME, CMD, VERSION, WRITE_SHORT, AGENTS, agentKind,
164
190
  }
165
191
  continue;
166
192
  }
167
- if (!m || typeof m !== "object" || Array.isArray(m) || typeof m.method !== "string") {
193
+ if (Array.isArray(m)) {
194
+ send({ id: null, error: { code: -32600, message: "Invalid request: send one message per line, not a batch" } });
195
+ continue;
196
+ }
197
+ if (!m || typeof m !== "object" || typeof m.method !== "string") {
168
198
  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
199
  continue;
170
200
  }
171
201
  if (m.id === void 0) {
172
202
  if (m.method === "notifications/cancelled") {
173
- const id = m.params?.requestId;
174
- running.get(id)?.kill();
175
- cancelled.add(id);
203
+ const id2 = m.params?.requestId;
204
+ if (pending.has(id2)) {
205
+ cancelled.add(id2);
206
+ running.get(id2)?.abort();
207
+ }
208
+ }
209
+ if (m.method === "notifications/initialized" && askRoots) {
210
+ askRoots = false;
211
+ send({ id: "labit-roots", method: "roots/list" });
176
212
  }
177
213
  continue;
178
214
  }
215
+ const id = m.id;
216
+ pending.add(id);
217
+ const answer = (msg) => {
218
+ pending.delete(id);
219
+ if (!cancelled.delete(id)) send({ id, ...msg });
220
+ };
179
221
  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 } : {} } })
222
+ (result) => answer({ result }),
223
+ (e) => answer({ error: { code: e.code || -32603, message: e.message, ...e.data ? { data: e.data } : {} } })
182
224
  );
183
225
  }
184
226
  });
185
- process.stdin.on("end", () => process.exit(0));
186
- process.on("SIGTERM", () => process.exit(0));
227
+ const quit = () => {
228
+ for (const stop of running.values()) stop.abort();
229
+ process.exit(0);
230
+ };
231
+ process.stdin.on("end", quit);
232
+ process.on("SIGTERM", quit);
233
+ process.on("SIGINT", quit);
187
234
  return new Promise(() => {
188
235
  });
189
236
  }
@@ -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.3-edge.3.1",
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": {