@web-remarq/mcp 0.4.0 → 0.6.0
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/LICENSE +21 -0
- package/README.md +144 -15
- package/dist/server.js +798 -246
- package/dist/server.js.map +1 -1
- package/package.json +3 -3
package/dist/server.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// src/server.ts
|
|
2
|
-
import { dirname as
|
|
2
|
+
import { dirname as dirname3, join as join3 } from "path";
|
|
3
3
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
4
4
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
5
5
|
|
|
@@ -18,7 +18,34 @@ function require_(env, key) {
|
|
|
18
18
|
return v;
|
|
19
19
|
}
|
|
20
20
|
var DEFAULT_PORT = 1817;
|
|
21
|
+
function isPort(value) {
|
|
22
|
+
return Number.isInteger(value) && value >= 1 && value <= 65535;
|
|
23
|
+
}
|
|
24
|
+
function effectivePort(config, local) {
|
|
25
|
+
return config.port ?? local.port ?? DEFAULT_PORT;
|
|
26
|
+
}
|
|
21
27
|
var DEFAULT_DATA_FILE = ".remarq/annotations.json";
|
|
28
|
+
function parseMs(env, key, fallback, min) {
|
|
29
|
+
const raw = env[key];
|
|
30
|
+
if (raw === void 0 || raw.trim() === "") return fallback;
|
|
31
|
+
const n = Number(raw);
|
|
32
|
+
if (!Number.isInteger(n) || n < min) {
|
|
33
|
+
throw new ConfigError(`${key} must be an integer >= ${min} (milliseconds), got "${raw}"`);
|
|
34
|
+
}
|
|
35
|
+
return n;
|
|
36
|
+
}
|
|
37
|
+
function parseChannel(env) {
|
|
38
|
+
const mode = (env.REMARQ_CHANNEL ?? "on").trim().toLowerCase();
|
|
39
|
+
if (mode !== "on" && mode !== "off") {
|
|
40
|
+
throw new ConfigError(`REMARQ_CHANNEL must be "on" or "off", got "${env.REMARQ_CHANNEL}"`);
|
|
41
|
+
}
|
|
42
|
+
return {
|
|
43
|
+
enabled: mode === "on",
|
|
44
|
+
settleMs: parseMs(env, "REMARQ_CHANNEL_SETTLE_MS", 3e3, 0),
|
|
45
|
+
staleMs: parseMs(env, "REMARQ_CHANNEL_STALE_MS", 18e4, 1),
|
|
46
|
+
redeliverMs: parseMs(env, "REMARQ_CHANNEL_REDELIVER_MS", 2e3, 0)
|
|
47
|
+
};
|
|
48
|
+
}
|
|
22
49
|
function parseEnv(env) {
|
|
23
50
|
const cloudRequested = Boolean(
|
|
24
51
|
env.REMARQ_PROJECT_KEY || env.REMARQ_SUPABASE_URL || env.REMARQ_SUPABASE_ANON_KEY
|
|
@@ -35,12 +62,12 @@ function parseEnv(env) {
|
|
|
35
62
|
}
|
|
36
63
|
return { mode: "cloud", projectKey, supabaseUrl, supabaseAnonKey };
|
|
37
64
|
}
|
|
38
|
-
const rawPort = env.REMARQ_PORT
|
|
39
|
-
const port = Number(rawPort);
|
|
40
|
-
if (
|
|
65
|
+
const rawPort = env.REMARQ_PORT;
|
|
66
|
+
const port = rawPort === void 0 ? null : Number(rawPort);
|
|
67
|
+
if (port !== null && !isPort(port)) {
|
|
41
68
|
throw new ConfigError(`REMARQ_PORT must be an integer between 1 and 65535, got "${rawPort}"`);
|
|
42
69
|
}
|
|
43
|
-
return { mode: "local", port, dataFile: env.REMARQ_DATA_FILE ?? DEFAULT_DATA_FILE };
|
|
70
|
+
return { mode: "local", port, dataFile: env.REMARQ_DATA_FILE ?? DEFAULT_DATA_FILE, channel: parseChannel(env) };
|
|
44
71
|
}
|
|
45
72
|
|
|
46
73
|
// src/storage-factory.ts
|
|
@@ -56,58 +83,258 @@ function createStorage(config) {
|
|
|
56
83
|
|
|
57
84
|
// src/file-storage-adapter.ts
|
|
58
85
|
import { EventEmitter } from "events";
|
|
59
|
-
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "fs";
|
|
60
|
-
import {
|
|
86
|
+
import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, renameSync, writeFileSync as writeFileSync2 } from "fs";
|
|
87
|
+
import { dirname } from "path";
|
|
88
|
+
import { AnnotationNotFoundError } from "web-remarq/core";
|
|
89
|
+
|
|
90
|
+
// src/local-config.ts
|
|
91
|
+
import { randomBytes } from "crypto";
|
|
92
|
+
import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "fs";
|
|
93
|
+
import { basename, join } from "path";
|
|
94
|
+
var CONFIG_FILE = "config.json";
|
|
95
|
+
var LOCK_FILE = "server.lock";
|
|
96
|
+
var DEFAULT_ALLOWED_ORIGINS = ["http://localhost:*", "http://127.0.0.1:*", "http://[::1]:*"];
|
|
97
|
+
var LocalConfigError = class extends Error {
|
|
98
|
+
constructor(message) {
|
|
99
|
+
super(message);
|
|
100
|
+
this.name = "LocalConfigError";
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
function generateProjectId() {
|
|
104
|
+
return `prj_${randomBytes(8).toString("hex")}`;
|
|
105
|
+
}
|
|
106
|
+
function generateToken() {
|
|
107
|
+
return randomBytes(24).toString("hex");
|
|
108
|
+
}
|
|
109
|
+
function ensureSelfIgnored(dir) {
|
|
110
|
+
if (basename(dir) !== ".remarq") return;
|
|
111
|
+
const gitignore = join(dir, ".gitignore");
|
|
112
|
+
if (!existsSync(gitignore)) writeFileSync(gitignore, "*\n");
|
|
113
|
+
}
|
|
114
|
+
function validate(raw, path) {
|
|
115
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
|
116
|
+
throw new LocalConfigError(`${path} must contain a JSON object`);
|
|
117
|
+
}
|
|
118
|
+
const obj = raw;
|
|
119
|
+
if (typeof obj.projectId !== "string" || !/^[A-Za-z0-9_-]{4,64}$/.test(obj.projectId)) {
|
|
120
|
+
throw new LocalConfigError(`${path}: projectId must be a 4-64 character id (letters, digits, _ -)`);
|
|
121
|
+
}
|
|
122
|
+
if (typeof obj.token !== "string" || obj.token.length < 16 || /\s/.test(obj.token)) {
|
|
123
|
+
throw new LocalConfigError(`${path}: token must be at least 16 characters with no whitespace`);
|
|
124
|
+
}
|
|
125
|
+
const origins = obj.allowedOrigins ?? DEFAULT_ALLOWED_ORIGINS;
|
|
126
|
+
if (!Array.isArray(origins) || !origins.every((o) => typeof o === "string")) {
|
|
127
|
+
throw new LocalConfigError(`${path}: allowedOrigins must be an array of origin strings`);
|
|
128
|
+
}
|
|
129
|
+
if (obj.port !== void 0 && !isPort(obj.port)) {
|
|
130
|
+
throw new LocalConfigError(`${path}: port must be an integer between 1 and 65535`);
|
|
131
|
+
}
|
|
132
|
+
return { projectId: obj.projectId, token: obj.token, allowedOrigins: origins, ...obj.port !== void 0 ? { port: obj.port } : {} };
|
|
133
|
+
}
|
|
134
|
+
function readOrCreateLocalConfig(dir) {
|
|
135
|
+
const path = join(dir, CONFIG_FILE);
|
|
136
|
+
if (existsSync(path)) {
|
|
137
|
+
let parsed;
|
|
138
|
+
try {
|
|
139
|
+
parsed = JSON.parse(readFileSync(path, "utf8"));
|
|
140
|
+
} catch (err) {
|
|
141
|
+
throw new LocalConfigError(`${path} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`);
|
|
142
|
+
}
|
|
143
|
+
return validate(parsed, path);
|
|
144
|
+
}
|
|
145
|
+
const config = {
|
|
146
|
+
projectId: generateProjectId(),
|
|
147
|
+
token: generateToken(),
|
|
148
|
+
allowedOrigins: [...DEFAULT_ALLOWED_ORIGINS]
|
|
149
|
+
};
|
|
150
|
+
mkdirSync(dir, { recursive: true });
|
|
151
|
+
ensureSelfIgnored(dir);
|
|
152
|
+
writeFileSync(path, `${JSON.stringify(config, null, 2)}
|
|
153
|
+
`, { mode: 384 });
|
|
154
|
+
return config;
|
|
155
|
+
}
|
|
156
|
+
var StoreLockedError = class extends Error {
|
|
157
|
+
constructor(pid, port, path) {
|
|
158
|
+
super(
|
|
159
|
+
`another web-remarq MCP server (pid ${pid}, port ${port}) already serves this store - two processes on one store cannot guarantee atomic transitions. Stop it first, or remove ${path} if that process is gone.`
|
|
160
|
+
);
|
|
161
|
+
this.pid = pid;
|
|
162
|
+
this.port = port;
|
|
163
|
+
this.name = "StoreLockedError";
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
function pidAlive(pid) {
|
|
167
|
+
try {
|
|
168
|
+
process.kill(pid, 0);
|
|
169
|
+
return true;
|
|
170
|
+
} catch (err) {
|
|
171
|
+
return err.code === "EPERM";
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
function acquireStoreLock(dir, port) {
|
|
175
|
+
const path = join(dir, LOCK_FILE);
|
|
176
|
+
mkdirSync(dir, { recursive: true });
|
|
177
|
+
if (existsSync(path)) {
|
|
178
|
+
let owner = {};
|
|
179
|
+
try {
|
|
180
|
+
owner = JSON.parse(readFileSync(path, "utf8"));
|
|
181
|
+
} catch {
|
|
182
|
+
}
|
|
183
|
+
const pid = typeof owner.pid === "number" ? owner.pid : NaN;
|
|
184
|
+
if (Number.isInteger(pid) && pid !== process.pid && pidAlive(pid)) {
|
|
185
|
+
throw new StoreLockedError(pid, typeof owner.port === "number" ? owner.port : 0, path);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
writeFileSync(path, `${JSON.stringify({ pid: process.pid, port, startedAt: (/* @__PURE__ */ new Date()).toISOString() })}
|
|
189
|
+
`);
|
|
190
|
+
let released = false;
|
|
191
|
+
const release = () => {
|
|
192
|
+
if (released) return;
|
|
193
|
+
released = true;
|
|
194
|
+
try {
|
|
195
|
+
const owner = JSON.parse(readFileSync(path, "utf8"));
|
|
196
|
+
if (owner.pid === process.pid) unlinkSync(path);
|
|
197
|
+
} catch {
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
const onSignal = (signal) => {
|
|
201
|
+
release();
|
|
202
|
+
process.exit(signal === "SIGINT" ? 130 : 143);
|
|
203
|
+
};
|
|
204
|
+
process.once("exit", release);
|
|
205
|
+
process.once("SIGINT", onSignal);
|
|
206
|
+
process.once("SIGTERM", onSignal);
|
|
207
|
+
return () => {
|
|
208
|
+
process.off("exit", release);
|
|
209
|
+
process.off("SIGINT", onSignal);
|
|
210
|
+
process.off("SIGTERM", onSignal);
|
|
211
|
+
release();
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// src/file-storage-adapter.ts
|
|
61
216
|
var FileStorageAdapter = class {
|
|
62
217
|
constructor(filePath) {
|
|
63
218
|
this.filePath = filePath;
|
|
64
|
-
/** Monotonic revision
|
|
219
|
+
/** Monotonic store revision - bumps on every persisted mutation. Exposed via GET /store. */
|
|
65
220
|
this.rev = 0;
|
|
66
221
|
this.emitter = new EventEmitter();
|
|
67
|
-
/** Serializes
|
|
222
|
+
/** Serializes every read-check-write so concurrent ops observe each other's results. */
|
|
68
223
|
this.queue = Promise.resolve();
|
|
69
224
|
this.emitter.setMaxListeners(0);
|
|
70
225
|
}
|
|
71
226
|
async load() {
|
|
72
|
-
if (!
|
|
227
|
+
if (!existsSync2(this.filePath)) return null;
|
|
73
228
|
let parsed;
|
|
74
229
|
try {
|
|
75
|
-
parsed = JSON.parse(
|
|
230
|
+
parsed = JSON.parse(readFileSync2(this.filePath, "utf8"));
|
|
76
231
|
} catch (err) {
|
|
77
232
|
const message = err instanceof Error ? err.message : String(err);
|
|
78
233
|
throw new Error(`annotations store corrupted at ${this.filePath}: ${message}`);
|
|
79
234
|
}
|
|
80
235
|
const store = parsed;
|
|
236
|
+
const annotations = Array.isArray(store.annotations) ? store.annotations : [];
|
|
81
237
|
return {
|
|
82
238
|
version: 1,
|
|
83
|
-
annotations:
|
|
239
|
+
annotations: annotations.map((a) => Number.isInteger(a.rev) && a.rev > 0 ? a : { ...a, rev: 1 })
|
|
84
240
|
};
|
|
85
241
|
}
|
|
242
|
+
/** Unconditional upsert (StorageAdapter contract). Bumps the record's rev. */
|
|
86
243
|
async save(annotation) {
|
|
87
|
-
|
|
244
|
+
await this.enqueue(async () => {
|
|
88
245
|
const store = await this.load() ?? { version: 1, annotations: [] };
|
|
89
246
|
const idx = store.annotations.findIndex((a) => a.id === annotation.id);
|
|
90
|
-
|
|
91
|
-
|
|
247
|
+
const nextRev = idx === -1 ? 1 : (store.annotations[idx].rev ?? 0) + 1;
|
|
248
|
+
const saved = { ...annotation, rev: nextRev };
|
|
249
|
+
if (idx === -1) store.annotations.push(saved);
|
|
250
|
+
else store.annotations[idx] = saved;
|
|
251
|
+
this.persist(store);
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* Revision-checked upsert used by the HTTP endpoint. `expectedRev` is the
|
|
256
|
+
* revision the client last saw (`If-Match`); `null` means the client sent
|
|
257
|
+
* none. Creating a new record needs no expectation; updating an existing one
|
|
258
|
+
* requires a matching expectation, so a stale copy can never overwrite a
|
|
259
|
+
* newer status or history.
|
|
260
|
+
*/
|
|
261
|
+
saveIfMatch(annotation, expectedRev) {
|
|
262
|
+
return this.enqueueResult(async () => {
|
|
263
|
+
const store = await this.load() ?? { version: 1, annotations: [] };
|
|
264
|
+
const idx = store.annotations.findIndex((a) => a.id === annotation.id);
|
|
265
|
+
if (idx === -1) {
|
|
266
|
+
if (expectedRev !== null && expectedRev !== 0) {
|
|
267
|
+
return { ok: false, reason: "conflict", current: null, rev: this.rev };
|
|
268
|
+
}
|
|
269
|
+
const saved2 = { ...annotation, rev: 1 };
|
|
270
|
+
store.annotations.push(saved2);
|
|
271
|
+
this.persist(store);
|
|
272
|
+
return { ok: true, annotation: saved2, rev: this.rev };
|
|
273
|
+
}
|
|
274
|
+
const current = store.annotations[idx];
|
|
275
|
+
if (expectedRev === null) {
|
|
276
|
+
return { ok: false, reason: "precondition_required", current, rev: this.rev };
|
|
277
|
+
}
|
|
278
|
+
if (expectedRev !== current.rev) {
|
|
279
|
+
return { ok: false, reason: "conflict", current, rev: this.rev };
|
|
280
|
+
}
|
|
281
|
+
const saved = { ...annotation, rev: (current.rev ?? 0) + 1 };
|
|
282
|
+
store.annotations[idx] = saved;
|
|
92
283
|
this.persist(store);
|
|
284
|
+
return { ok: true, annotation: saved, rev: this.rev };
|
|
93
285
|
});
|
|
94
286
|
}
|
|
95
287
|
async remove(id) {
|
|
96
|
-
|
|
288
|
+
const result = await this.removeIfMatch(id, null);
|
|
289
|
+
if (!result.ok) throw new Error(`remove(${id}): unexpected ${result.reason}`);
|
|
290
|
+
}
|
|
291
|
+
/** Revision-checked delete; `expectedRev === null` skips the check. Deleting a missing id is a no-op success. */
|
|
292
|
+
removeIfMatch(id, expectedRev) {
|
|
293
|
+
return this.enqueueResult(async () => {
|
|
97
294
|
const store = await this.load() ?? { version: 1, annotations: [] };
|
|
295
|
+
const current = store.annotations.find((a) => a.id === id) ?? null;
|
|
296
|
+
if (current && expectedRev !== null && expectedRev !== current.rev) {
|
|
297
|
+
return { ok: false, reason: "conflict", current, rev: this.rev };
|
|
298
|
+
}
|
|
98
299
|
store.annotations = store.annotations.filter((a) => a.id !== id);
|
|
99
300
|
this.persist(store);
|
|
301
|
+
return { ok: true, annotation: current ?? { id }, rev: this.rev };
|
|
100
302
|
});
|
|
101
303
|
}
|
|
102
304
|
async clear() {
|
|
103
|
-
|
|
305
|
+
await this.enqueue(async () => {
|
|
104
306
|
this.persist({ version: 1, annotations: [] });
|
|
105
307
|
});
|
|
106
308
|
}
|
|
309
|
+
/**
|
|
310
|
+
* Atomic read-check-write: load, apply, persist inside one queue slot, so two
|
|
311
|
+
* concurrent transitions on the same record see each other. `apply` throwing
|
|
312
|
+
* aborts without persisting; returning the same object persists nothing.
|
|
313
|
+
*/
|
|
314
|
+
mutate(id, apply) {
|
|
315
|
+
return this.enqueueResult(async () => {
|
|
316
|
+
const store = await this.load() ?? { version: 1, annotations: [] };
|
|
317
|
+
const idx = store.annotations.findIndex((a) => a.id === id);
|
|
318
|
+
if (idx === -1) throw new AnnotationNotFoundError(id);
|
|
319
|
+
const current = store.annotations[idx];
|
|
320
|
+
const next = apply(current);
|
|
321
|
+
if (next === current) return current;
|
|
322
|
+
const saved = { ...next, id, rev: (current.rev ?? 0) + 1 };
|
|
323
|
+
store.annotations[idx] = saved;
|
|
324
|
+
this.persist(store);
|
|
325
|
+
return saved;
|
|
326
|
+
});
|
|
327
|
+
}
|
|
107
328
|
/** Chains `op` onto the mutation queue; a rejected op doesn't poison later ops. */
|
|
108
329
|
enqueue(op) {
|
|
330
|
+
return this.enqueueResult(op);
|
|
331
|
+
}
|
|
332
|
+
enqueueResult(op) {
|
|
109
333
|
const result = this.queue.then(op);
|
|
110
|
-
this.queue = result.
|
|
334
|
+
this.queue = result.then(
|
|
335
|
+
() => void 0,
|
|
336
|
+
() => void 0
|
|
337
|
+
);
|
|
111
338
|
return result;
|
|
112
339
|
}
|
|
113
340
|
/** Resolves true on the next mutation, false after timeoutMs. */
|
|
@@ -124,19 +351,16 @@ var FileStorageAdapter = class {
|
|
|
124
351
|
this.emitter.once("change", onChange);
|
|
125
352
|
});
|
|
126
353
|
}
|
|
127
|
-
/** Persistent listener for every mutation (save/remove/clear). */
|
|
354
|
+
/** Persistent listener for every persisted mutation (save/remove/clear/mutate). Conflicts and no-ops never fire it. */
|
|
128
355
|
onChange(listener) {
|
|
129
356
|
this.emitter.on("change", listener);
|
|
130
357
|
}
|
|
131
358
|
persist(store) {
|
|
132
359
|
const dir = dirname(this.filePath);
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
const gitignore = join(dir, ".gitignore");
|
|
136
|
-
if (!existsSync(gitignore)) writeFileSync(gitignore, "*\n");
|
|
137
|
-
}
|
|
360
|
+
mkdirSync2(dir, { recursive: true });
|
|
361
|
+
ensureSelfIgnored(dir);
|
|
138
362
|
const tmp = `${this.filePath}.tmp`;
|
|
139
|
-
|
|
363
|
+
writeFileSync2(tmp, JSON.stringify(store, null, 2));
|
|
140
364
|
renameSync(tmp, this.filePath);
|
|
141
365
|
this.rev++;
|
|
142
366
|
this.emitter.emit("change");
|
|
@@ -145,19 +369,433 @@ var FileStorageAdapter = class {
|
|
|
145
369
|
|
|
146
370
|
// src/http-server.ts
|
|
147
371
|
import * as http from "http";
|
|
372
|
+
import { timingSafeEqual } from "crypto";
|
|
373
|
+
import { isSafeAnnotationId, validateAnnotation } from "web-remarq/core";
|
|
374
|
+
var PROTOCOL_VERSION = 2;
|
|
375
|
+
var MAX_BODY_BYTES = 512 * 1024;
|
|
376
|
+
var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "[::1]"]);
|
|
377
|
+
function send(res, status, body, cors) {
|
|
378
|
+
res.writeHead(status, { ...cors, "content-type": "application/json", "cache-control": "no-store" });
|
|
379
|
+
res.end(JSON.stringify(body));
|
|
380
|
+
}
|
|
381
|
+
function fail(res, status, code, error, cors, details) {
|
|
382
|
+
const body = { error, code };
|
|
383
|
+
if (details !== void 0) body.details = details;
|
|
384
|
+
send(res, status, body, cors);
|
|
385
|
+
}
|
|
386
|
+
function originAllowed(origin, allowed) {
|
|
387
|
+
let parsed;
|
|
388
|
+
try {
|
|
389
|
+
parsed = new URL(origin);
|
|
390
|
+
} catch {
|
|
391
|
+
return false;
|
|
392
|
+
}
|
|
393
|
+
if (parsed.username || parsed.password || parsed.pathname !== "/" && parsed.pathname !== "" || parsed.search || parsed.hash) {
|
|
394
|
+
return false;
|
|
395
|
+
}
|
|
396
|
+
const defaultPort = parsed.protocol === "https:" ? "443" : "80";
|
|
397
|
+
const originPort = parsed.port || defaultPort;
|
|
398
|
+
return allowed.some((pattern) => {
|
|
399
|
+
const m = pattern.match(/^(https?):\/\/(\[[0-9a-fA-F:]+\]|[A-Za-z0-9.-]+)(?::(\d{1,5}|\*))?$/);
|
|
400
|
+
if (!m) return false;
|
|
401
|
+
const [, scheme, host, port] = m;
|
|
402
|
+
if (parsed.protocol !== `${scheme}:`) return false;
|
|
403
|
+
if (parsed.hostname.toLowerCase() !== host.toLowerCase()) return false;
|
|
404
|
+
if (port === "*") return true;
|
|
405
|
+
return originPort === (port ?? (scheme === "https" ? "443" : "80"));
|
|
406
|
+
});
|
|
407
|
+
}
|
|
408
|
+
function hostAllowed(host, port) {
|
|
409
|
+
if (!host) return false;
|
|
410
|
+
let parsed;
|
|
411
|
+
try {
|
|
412
|
+
parsed = new URL(`http://${host}`);
|
|
413
|
+
} catch {
|
|
414
|
+
return false;
|
|
415
|
+
}
|
|
416
|
+
if (!LOOPBACK_HOSTS.has(parsed.hostname.toLowerCase())) return false;
|
|
417
|
+
return parsed.port === "" || parsed.port === String(port);
|
|
418
|
+
}
|
|
419
|
+
function tokenMatches(header, token) {
|
|
420
|
+
if (!header) return false;
|
|
421
|
+
const m = header.match(/^Bearer\s+(\S+)$/i);
|
|
422
|
+
if (!m) return false;
|
|
423
|
+
const given = Buffer.from(m[1]);
|
|
424
|
+
const expected = Buffer.from(token);
|
|
425
|
+
if (given.length !== expected.length) return false;
|
|
426
|
+
return timingSafeEqual(given, expected);
|
|
427
|
+
}
|
|
428
|
+
var BodyTooLarge = class extends Error {
|
|
429
|
+
};
|
|
430
|
+
function readBody(req) {
|
|
431
|
+
return new Promise((resolve, reject) => {
|
|
432
|
+
const declared = Number(req.headers["content-length"]);
|
|
433
|
+
if (Number.isFinite(declared) && declared > MAX_BODY_BYTES) {
|
|
434
|
+
req.resume();
|
|
435
|
+
reject(new BodyTooLarge());
|
|
436
|
+
return;
|
|
437
|
+
}
|
|
438
|
+
let size = 0;
|
|
439
|
+
const chunks = [];
|
|
440
|
+
req.on("data", (chunk) => {
|
|
441
|
+
size += chunk.length;
|
|
442
|
+
if (size > MAX_BODY_BYTES) {
|
|
443
|
+
req.removeAllListeners("data");
|
|
444
|
+
req.resume();
|
|
445
|
+
reject(new BodyTooLarge());
|
|
446
|
+
return;
|
|
447
|
+
}
|
|
448
|
+
chunks.push(chunk);
|
|
449
|
+
});
|
|
450
|
+
req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
|
|
451
|
+
req.on("error", reject);
|
|
452
|
+
});
|
|
453
|
+
}
|
|
454
|
+
function parseIfMatch(header) {
|
|
455
|
+
if (header === void 0) return void 0;
|
|
456
|
+
const value = Array.isArray(header) ? header[0] : header;
|
|
457
|
+
const m = value.trim().match(/^"?(\d{1,12})"?$/);
|
|
458
|
+
return m ? Number(m[1]) : null;
|
|
459
|
+
}
|
|
460
|
+
async function handle(req, res, storage, port, config) {
|
|
461
|
+
const noCors = {};
|
|
462
|
+
if (!hostAllowed(req.headers.host, port)) {
|
|
463
|
+
fail(res, 403, "bad_host", "request Host does not name this loopback server", noCors);
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
let pathname;
|
|
467
|
+
try {
|
|
468
|
+
pathname = new URL(req.url ?? "/", "http://localhost").pathname;
|
|
469
|
+
} catch {
|
|
470
|
+
fail(res, 400, "bad_url", "malformed request URL", noCors);
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
473
|
+
if (pathname === "/health" && (req.method === "GET" || req.method === "OPTIONS")) {
|
|
474
|
+
const openCors = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, OPTIONS" };
|
|
475
|
+
if (req.method === "OPTIONS") {
|
|
476
|
+
res.writeHead(204, openCors);
|
|
477
|
+
res.end();
|
|
478
|
+
return;
|
|
479
|
+
}
|
|
480
|
+
send(res, 200, { ok: true, protocol: PROTOCOL_VERSION }, openCors);
|
|
481
|
+
return;
|
|
482
|
+
}
|
|
483
|
+
const origin = req.headers.origin;
|
|
484
|
+
let cors = noCors;
|
|
485
|
+
if (origin !== void 0) {
|
|
486
|
+
if (origin === "null" || !originAllowed(origin, config.allowedOrigins)) {
|
|
487
|
+
fail(res, 403, "forbidden_origin", "origin is not allowed to use this server; add it to allowedOrigins in .remarq/config.json if it is yours", noCors);
|
|
488
|
+
return;
|
|
489
|
+
}
|
|
490
|
+
cors = {
|
|
491
|
+
"Access-Control-Allow-Origin": origin,
|
|
492
|
+
"Vary": "Origin",
|
|
493
|
+
"Access-Control-Allow-Methods": "GET, PUT, DELETE, OPTIONS",
|
|
494
|
+
"Access-Control-Allow-Headers": "authorization, content-type, if-match",
|
|
495
|
+
"Access-Control-Max-Age": "600"
|
|
496
|
+
};
|
|
497
|
+
}
|
|
498
|
+
if (req.method === "OPTIONS") {
|
|
499
|
+
res.writeHead(204, cors);
|
|
500
|
+
res.end();
|
|
501
|
+
return;
|
|
502
|
+
}
|
|
503
|
+
if (!tokenMatches(req.headers.authorization, config.token)) {
|
|
504
|
+
res.setHeader("WWW-Authenticate", 'Bearer realm="web-remarq"');
|
|
505
|
+
fail(res, 401, "unauthorized", "missing or wrong token; the widget and CLI read it from .remarq/config.json", cors);
|
|
506
|
+
return;
|
|
507
|
+
}
|
|
508
|
+
const annMatch = pathname.match(/^\/annotations\/([^/]+)$/);
|
|
509
|
+
let id = null;
|
|
510
|
+
if (annMatch) {
|
|
511
|
+
try {
|
|
512
|
+
id = decodeURIComponent(annMatch[1]);
|
|
513
|
+
} catch {
|
|
514
|
+
fail(res, 400, "invalid_id", "annotation id is not valid URL encoding", cors);
|
|
515
|
+
return;
|
|
516
|
+
}
|
|
517
|
+
if (!isSafeAnnotationId(id)) {
|
|
518
|
+
fail(res, 400, "invalid_id", "invalid annotation id", cors);
|
|
519
|
+
return;
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
try {
|
|
523
|
+
if (req.method === "GET" && pathname === "/store") {
|
|
524
|
+
const rev = storage.rev;
|
|
525
|
+
const store = await storage.load() ?? { version: 1, annotations: [] };
|
|
526
|
+
send(res, 200, { rev, protocol: PROTOCOL_VERSION, projectId: config.projectId, store }, cors);
|
|
527
|
+
return;
|
|
528
|
+
}
|
|
529
|
+
if (req.method === "PUT" && id !== null) {
|
|
530
|
+
const contentType = String(req.headers["content-type"] ?? "");
|
|
531
|
+
if (!/^application\/json\b/i.test(contentType)) {
|
|
532
|
+
fail(res, 415, "unsupported_media_type", "content-type must be application/json", cors);
|
|
533
|
+
return;
|
|
534
|
+
}
|
|
535
|
+
const expectedRev = parseIfMatch(req.headers["if-match"]);
|
|
536
|
+
if (expectedRev === null) {
|
|
537
|
+
fail(res, 400, "invalid_if_match", "If-Match must be a revision number", cors);
|
|
538
|
+
return;
|
|
539
|
+
}
|
|
540
|
+
let raw;
|
|
541
|
+
try {
|
|
542
|
+
raw = JSON.parse(await readBody(req));
|
|
543
|
+
} catch (err) {
|
|
544
|
+
if (err instanceof BodyTooLarge) {
|
|
545
|
+
fail(res, 413, "payload_too_large", `body exceeds ${MAX_BODY_BYTES} bytes`, cors);
|
|
546
|
+
} else {
|
|
547
|
+
fail(res, 400, "invalid_json", "invalid JSON body", cors);
|
|
548
|
+
}
|
|
549
|
+
return;
|
|
550
|
+
}
|
|
551
|
+
const validated = validateAnnotation(raw);
|
|
552
|
+
if (!validated.ok) {
|
|
553
|
+
fail(res, 400, "invalid_annotation", "annotation failed validation", cors, validated.errors);
|
|
554
|
+
return;
|
|
555
|
+
}
|
|
556
|
+
if (validated.annotation.id !== id) {
|
|
557
|
+
fail(res, 400, "id_mismatch", "annotation.id must match the URL id", cors);
|
|
558
|
+
return;
|
|
559
|
+
}
|
|
560
|
+
const result = await storage.saveIfMatch(validated.annotation, expectedRev ?? null);
|
|
561
|
+
if (!result.ok) {
|
|
562
|
+
const status = result.reason === "conflict" ? 409 : 428;
|
|
563
|
+
fail(res, status, result.reason, result.reason === "conflict" ? "annotation changed since you last read it" : "If-Match is required to update an existing annotation", cors, { current: result.current, rev: result.rev });
|
|
564
|
+
return;
|
|
565
|
+
}
|
|
566
|
+
send(res, 200, { rev: result.rev, annotation: result.annotation }, cors);
|
|
567
|
+
return;
|
|
568
|
+
}
|
|
569
|
+
if (req.method === "DELETE" && id !== null) {
|
|
570
|
+
const expectedRev = parseIfMatch(req.headers["if-match"]);
|
|
571
|
+
if (expectedRev === null) {
|
|
572
|
+
fail(res, 400, "invalid_if_match", "If-Match must be a revision number", cors);
|
|
573
|
+
return;
|
|
574
|
+
}
|
|
575
|
+
const result = await storage.removeIfMatch(id, expectedRev ?? null);
|
|
576
|
+
if (!result.ok) {
|
|
577
|
+
fail(res, 409, "conflict", "annotation changed since you last read it", cors, { current: result.current, rev: result.rev });
|
|
578
|
+
return;
|
|
579
|
+
}
|
|
580
|
+
send(res, 200, { rev: result.rev }, cors);
|
|
581
|
+
return;
|
|
582
|
+
}
|
|
583
|
+
if (req.method === "DELETE" && pathname === "/annotations") {
|
|
584
|
+
await storage.clear();
|
|
585
|
+
send(res, 200, { rev: storage.rev }, cors);
|
|
586
|
+
return;
|
|
587
|
+
}
|
|
588
|
+
fail(res, 404, "not_found", "not found", cors);
|
|
589
|
+
} catch (err) {
|
|
590
|
+
fail(res, 500, "internal", err instanceof Error ? err.message : String(err), cors);
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
function startHttpServer(storage, port, config) {
|
|
594
|
+
const server = http.createServer((req, res) => {
|
|
595
|
+
const boundPort = server.address()?.port ?? port;
|
|
596
|
+
void handle(req, res, storage, boundPort, config);
|
|
597
|
+
});
|
|
598
|
+
return new Promise((resolve, reject) => {
|
|
599
|
+
server.once("error", reject);
|
|
600
|
+
server.listen(port, "127.0.0.1", () => resolve(server));
|
|
601
|
+
});
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
// src/channel-delivery.ts
|
|
605
|
+
import { mkdirSync as mkdirSync3, readFileSync as readFileSync3, renameSync as renameSync2, writeFileSync as writeFileSync3 } from "fs";
|
|
606
|
+
import { dirname as dirname2 } from "path";
|
|
607
|
+
import { generateAgentExport } from "web-remarq/core";
|
|
608
|
+
var UNFINISHED = /* @__PURE__ */ new Set(["pending", "in_progress"]);
|
|
609
|
+
function readLedger(path) {
|
|
610
|
+
try {
|
|
611
|
+
const raw = JSON.parse(readFileSync3(path, "utf8"));
|
|
612
|
+
if (!raw || !Array.isArray(raw.inFlight) || !raw.inFlight.every((x) => typeof x === "string")) return null;
|
|
613
|
+
return {
|
|
614
|
+
version: 1,
|
|
615
|
+
inFlight: raw.inFlight,
|
|
616
|
+
sentAt: typeof raw.sentAt === "number" ? raw.sentAt : 0,
|
|
617
|
+
redelivered: raw.redelivered === true
|
|
618
|
+
};
|
|
619
|
+
} catch {
|
|
620
|
+
return null;
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
function writeLedger(path, ledger) {
|
|
624
|
+
mkdirSync3(dirname2(path), { recursive: true });
|
|
625
|
+
const tmp = `${path}.tmp`;
|
|
626
|
+
writeFileSync3(tmp, JSON.stringify(ledger, null, 2));
|
|
627
|
+
renameSync2(tmp, path);
|
|
628
|
+
}
|
|
629
|
+
function renderMarks(annotations) {
|
|
630
|
+
const blocks = annotations.map((a) => {
|
|
631
|
+
const agent = generateAgentExport([a], a.viewportBucket).annotations[0];
|
|
632
|
+
const lines = [`Mark ${agent.id}`, `route: ${agent.route}`, `comment: ${agent.comment.trim()}`];
|
|
633
|
+
if (agent.source) {
|
|
634
|
+
const component = agent.source.component ? ` (component ${agent.source.component})` : "";
|
|
635
|
+
lines.push(`source: ${agent.source.file}:${agent.source.line}:${agent.source.column}${component}`);
|
|
636
|
+
}
|
|
637
|
+
lines.push(`element: <${agent.searchHints.tagName}> ${agent.searchHints.domContext}`);
|
|
638
|
+
for (const q of agent.searchHints.grepQueries.slice(0, 3)) {
|
|
639
|
+
lines.push(`search [${q.confidence}]: ${q.query} in ${q.glob}`);
|
|
640
|
+
}
|
|
641
|
+
const qc = a.qualityCheck;
|
|
642
|
+
if (qc && qc.score !== "clear") {
|
|
643
|
+
lines.push(`note: comment rated ${qc.score}; if you cannot act on it confidently, dismiss with a reason`);
|
|
644
|
+
}
|
|
645
|
+
return lines.join("\n");
|
|
646
|
+
});
|
|
647
|
+
return blocks.join("\n\n");
|
|
648
|
+
}
|
|
649
|
+
var ChannelDelivery = class {
|
|
650
|
+
constructor(opts) {
|
|
651
|
+
this.opts = opts;
|
|
652
|
+
this.inFlight = [];
|
|
653
|
+
this.sentAt = 0;
|
|
654
|
+
this.redelivered = false;
|
|
655
|
+
/** False until the MCP client finished initialization; nothing is sent before. */
|
|
656
|
+
this.ready = false;
|
|
657
|
+
this.chain = Promise.resolve();
|
|
658
|
+
this.stopped = false;
|
|
659
|
+
this.log = opts.log ?? ((m) => console.error(`[web-remarq-mcp] ${m}`));
|
|
660
|
+
const ledger = readLedger(opts.ledgerPath);
|
|
661
|
+
if (ledger) {
|
|
662
|
+
this.inFlight = ledger.inFlight;
|
|
663
|
+
this.sentAt = ledger.sentAt;
|
|
664
|
+
this.redelivered = ledger.redelivered;
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
/** Call on every store change. Never throws. */
|
|
668
|
+
onChange() {
|
|
669
|
+
void this.serialize(() => this.step(false));
|
|
670
|
+
}
|
|
671
|
+
/** Call once the MCP client finished initialization. Never throws. */
|
|
672
|
+
onInitialized() {
|
|
673
|
+
if (this.stopped || this.startupTimer) return;
|
|
674
|
+
this.startupTimer = setTimeout(() => {
|
|
675
|
+
void this.serialize(() => this.step(true));
|
|
676
|
+
}, this.opts.config.redeliverMs);
|
|
677
|
+
this.startupTimer.unref?.();
|
|
678
|
+
}
|
|
679
|
+
stop() {
|
|
680
|
+
this.stopped = true;
|
|
681
|
+
clearTimeout(this.gateTimer);
|
|
682
|
+
clearTimeout(this.watchdog);
|
|
683
|
+
clearTimeout(this.startupTimer);
|
|
684
|
+
}
|
|
685
|
+
/** Resolves when every queued step finished. */
|
|
686
|
+
idle() {
|
|
687
|
+
return this.chain;
|
|
688
|
+
}
|
|
689
|
+
serialize(fn) {
|
|
690
|
+
const job = this.chain.then(async () => {
|
|
691
|
+
if (this.stopped) return;
|
|
692
|
+
try {
|
|
693
|
+
await fn();
|
|
694
|
+
} catch (err) {
|
|
695
|
+
this.log(`channel delivery failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
696
|
+
}
|
|
697
|
+
});
|
|
698
|
+
this.chain = job;
|
|
699
|
+
return job;
|
|
700
|
+
}
|
|
701
|
+
persist() {
|
|
702
|
+
try {
|
|
703
|
+
writeLedger(this.opts.ledgerPath, {
|
|
704
|
+
version: 1,
|
|
705
|
+
inFlight: this.inFlight,
|
|
706
|
+
sentAt: this.sentAt,
|
|
707
|
+
redelivered: this.redelivered
|
|
708
|
+
});
|
|
709
|
+
} catch (err) {
|
|
710
|
+
this.log(`channel ledger write failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
armWatchdog() {
|
|
714
|
+
clearTimeout(this.watchdog);
|
|
715
|
+
this.watchdog = void 0;
|
|
716
|
+
if (this.inFlight.length === 0 || this.redelivered) return;
|
|
717
|
+
this.watchdog = setTimeout(() => {
|
|
718
|
+
void this.serialize(() => this.repush(true));
|
|
719
|
+
}, this.opts.config.staleMs);
|
|
720
|
+
this.watchdog.unref?.();
|
|
721
|
+
}
|
|
722
|
+
startGate() {
|
|
723
|
+
clearTimeout(this.gateTimer);
|
|
724
|
+
this.gateTimer = setTimeout(() => {
|
|
725
|
+
this.gateTimer = void 0;
|
|
726
|
+
void this.serialize(() => this.step(false));
|
|
727
|
+
}, this.opts.config.settleMs);
|
|
728
|
+
this.gateTimer.unref?.();
|
|
729
|
+
}
|
|
730
|
+
/** Re-evaluates in-flight progress against the store, then pumps if the gate is open. */
|
|
731
|
+
async step(startup) {
|
|
732
|
+
const annotations = (await this.opts.storage.load())?.annotations ?? [];
|
|
733
|
+
const byId = new Map(annotations.map((a) => [a.id, a]));
|
|
734
|
+
if (startup) this.ready = true;
|
|
735
|
+
if (this.inFlight.length > 0) {
|
|
736
|
+
const unfinished = this.inFlight.filter((id) => UNFINISHED.has(byId.get(id)?.status ?? ""));
|
|
737
|
+
if (unfinished.length < this.inFlight.length) {
|
|
738
|
+
this.inFlight = unfinished;
|
|
739
|
+
this.sentAt = Date.now();
|
|
740
|
+
this.persist();
|
|
741
|
+
if (unfinished.length === 0) {
|
|
742
|
+
clearTimeout(this.watchdog);
|
|
743
|
+
this.watchdog = void 0;
|
|
744
|
+
this.redelivered = false;
|
|
745
|
+
this.persist();
|
|
746
|
+
this.startGate();
|
|
747
|
+
} else {
|
|
748
|
+
this.armWatchdog();
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
if (startup && this.inFlight.length > 0) {
|
|
753
|
+
this.redelivered = false;
|
|
754
|
+
await this.repush(false, byId);
|
|
755
|
+
return;
|
|
756
|
+
}
|
|
757
|
+
if (this.inFlight.length > 0 || !this.ready || this.gateTimer) return;
|
|
758
|
+
const batch = annotations.filter((a) => a.status === "pending");
|
|
759
|
+
if (batch.length === 0) return;
|
|
760
|
+
await this.sendBatch(batch, {});
|
|
761
|
+
this.inFlight = batch.map((a) => a.id);
|
|
762
|
+
this.sentAt = Date.now();
|
|
763
|
+
this.redelivered = false;
|
|
764
|
+
this.persist();
|
|
765
|
+
this.armWatchdog();
|
|
766
|
+
}
|
|
767
|
+
/** Re-sends the unfinished in-flight marks (watchdog or startup). */
|
|
768
|
+
async repush(fromWatchdog, known) {
|
|
769
|
+
if (this.inFlight.length === 0 || fromWatchdog && this.redelivered) return;
|
|
770
|
+
const byId = known ?? new Map(((await this.opts.storage.load())?.annotations ?? []).map((a) => [a.id, a]));
|
|
771
|
+
const batch = this.inFlight.map((id) => byId.get(id)).filter((a) => !!a && UNFINISHED.has(a.status));
|
|
772
|
+
if (batch.length === 0) return;
|
|
773
|
+
if (fromWatchdog) this.log(`batch ${this.inFlight.join(",")} in flight over ${this.opts.config.staleMs}ms, re-pushing once`);
|
|
774
|
+
await this.sendBatch(batch, { redelivered: "true" });
|
|
775
|
+
this.sentAt = Date.now();
|
|
776
|
+
if (fromWatchdog) this.redelivered = true;
|
|
777
|
+
this.persist();
|
|
778
|
+
this.armWatchdog();
|
|
779
|
+
}
|
|
780
|
+
sendBatch(batch, extra) {
|
|
781
|
+
return this.opts.send(renderMarks(batch), {
|
|
782
|
+
kind: "marks",
|
|
783
|
+
count: String(batch.length),
|
|
784
|
+
ids: batch.map((a) => a.id).join(","),
|
|
785
|
+
...extra
|
|
786
|
+
});
|
|
787
|
+
}
|
|
788
|
+
};
|
|
148
789
|
|
|
149
790
|
// src/task-folder.ts
|
|
150
|
-
import { existsSync as
|
|
791
|
+
import { existsSync as existsSync3, mkdirSync as mkdirSync4, readFileSync as readFileSync4, readdirSync, unlinkSync as unlinkSync2, writeFileSync as writeFileSync4 } from "fs";
|
|
151
792
|
import { join as join2 } from "path";
|
|
152
|
-
import { actionableOnly, generateAgentExport } from "web-remarq/core";
|
|
793
|
+
import { actionableOnly, generateAgentExport as generateAgentExport2, isSafeAnnotationId as isSafeAnnotationId2 } from "web-remarq/core";
|
|
153
794
|
function yamlString(value) {
|
|
154
795
|
return JSON.stringify(value);
|
|
155
796
|
}
|
|
156
|
-
function isSafeAnnotationId(id) {
|
|
157
|
-
return /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(id);
|
|
158
|
-
}
|
|
159
797
|
function renderTaskFile(annotation) {
|
|
160
|
-
const agent =
|
|
798
|
+
const agent = generateAgentExport2([annotation], annotation.viewportBucket).annotations[0];
|
|
161
799
|
const lines = [];
|
|
162
800
|
lines.push("---");
|
|
163
801
|
lines.push(`id: ${yamlString(agent.id)}`);
|
|
@@ -196,9 +834,9 @@ function renderTaskFile(annotation) {
|
|
|
196
834
|
lines.push("");
|
|
197
835
|
}
|
|
198
836
|
lines.push("## Agent instructions", "");
|
|
199
|
-
lines.push(`1. BEFORE touching code, call the web-remarq MCP tool \`acknowledge\` with \`{ "id": ${yamlString(agent.id)} }\`. If it
|
|
837
|
+
lines.push(`1. BEFORE touching code, call the web-remarq MCP tool \`acknowledge\` with \`{ "id": ${yamlString(agent.id)}, "operationId": "<a fresh unique id you keep for retries>" }\`. Exactly one caller wins this transition. If it returns \`invalid_transition\`, someone else already moved this annotation: do NOT start work, re-read it with \`get_annotation\` and skip this file. If the call itself fails without an answer (timeout, transport error), retry with the SAME operationId - a retry is recognised and never counted twice.`);
|
|
200
838
|
lines.push("2. Apply the fix described in the comment.");
|
|
201
|
-
lines.push(`3. When the fix is committed to the working tree, call \`claim_fix\` with \`{ "id": ${yamlString(agent.id)} }\`. A human verifies afterwards - never mark anything as done yourself.`);
|
|
839
|
+
lines.push(`3. When the fix is committed to the working tree, call \`claim_fix\` with \`{ "id": ${yamlString(agent.id)}, "operationId": "<another fresh id>" }\`. A human verifies afterwards - never mark anything as done yourself. An \`invalid_transition\` here means the annotation changed under you (dismissed, reopened, edited): re-read it before deciding anything.`);
|
|
202
840
|
lines.push("");
|
|
203
841
|
lines.push("This file is a live projection maintained by the web-remarq MCP server: it updates when the annotation changes and disappears once the annotation is verified or dismissed. Do not edit or delete it.");
|
|
204
842
|
lines.push("");
|
|
@@ -217,17 +855,17 @@ var TaskFolder = class {
|
|
|
217
855
|
const actionable = actionableOnly(store?.annotations ?? []);
|
|
218
856
|
const desired = /* @__PURE__ */ new Map();
|
|
219
857
|
for (const a of actionable) {
|
|
220
|
-
if (!
|
|
858
|
+
if (!isSafeAnnotationId2(a.id)) {
|
|
221
859
|
console.error(`[web-remarq-mcp] skipping annotation with unsafe id: ${JSON.stringify(a.id)}`);
|
|
222
860
|
continue;
|
|
223
861
|
}
|
|
224
862
|
desired.set(`${a.id}.md`, renderTaskFile(a));
|
|
225
863
|
}
|
|
226
|
-
|
|
864
|
+
mkdirSync4(this.dir, { recursive: true });
|
|
227
865
|
for (const entry of readdirSync(this.dir, { withFileTypes: true })) {
|
|
228
866
|
if (!entry.isFile() || !entry.name.endsWith(".md") || desired.has(entry.name)) continue;
|
|
229
867
|
try {
|
|
230
|
-
|
|
868
|
+
unlinkSync2(join2(this.dir, entry.name));
|
|
231
869
|
} catch (err) {
|
|
232
870
|
console.error(`[web-remarq-mcp] failed to remove stale task file ${entry.name}:`, err);
|
|
233
871
|
}
|
|
@@ -235,8 +873,8 @@ var TaskFolder = class {
|
|
|
235
873
|
for (const [name, content] of desired) {
|
|
236
874
|
try {
|
|
237
875
|
const path = join2(this.dir, name);
|
|
238
|
-
if (
|
|
239
|
-
|
|
876
|
+
if (existsSync3(path) && readFileSync4(path, "utf8") === content) continue;
|
|
877
|
+
writeFileSync4(path, content);
|
|
240
878
|
} catch (err) {
|
|
241
879
|
console.error(`[web-remarq-mcp] failed to write task file ${name}:`, err);
|
|
242
880
|
}
|
|
@@ -262,102 +900,8 @@ var TaskFolder = class {
|
|
|
262
900
|
}
|
|
263
901
|
};
|
|
264
902
|
|
|
265
|
-
// src/http-server.ts
|
|
266
|
-
var CORS_HEADERS = {
|
|
267
|
-
"Access-Control-Allow-Origin": "*",
|
|
268
|
-
"Access-Control-Allow-Methods": "GET, PUT, DELETE, OPTIONS",
|
|
269
|
-
"Access-Control-Allow-Headers": "content-type"
|
|
270
|
-
};
|
|
271
|
-
var MAX_BODY_BYTES = 1024 * 1024;
|
|
272
|
-
function json(res, status, body) {
|
|
273
|
-
res.writeHead(status, { ...CORS_HEADERS, "content-type": "application/json" });
|
|
274
|
-
res.end(JSON.stringify(body));
|
|
275
|
-
}
|
|
276
|
-
function readBody(req) {
|
|
277
|
-
return new Promise((resolve, reject) => {
|
|
278
|
-
let size = 0;
|
|
279
|
-
const chunks = [];
|
|
280
|
-
req.on("data", (chunk) => {
|
|
281
|
-
size += chunk.length;
|
|
282
|
-
if (size > MAX_BODY_BYTES) {
|
|
283
|
-
reject(new Error("body too large"));
|
|
284
|
-
req.destroy();
|
|
285
|
-
return;
|
|
286
|
-
}
|
|
287
|
-
chunks.push(chunk);
|
|
288
|
-
});
|
|
289
|
-
req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
|
|
290
|
-
req.on("error", reject);
|
|
291
|
-
});
|
|
292
|
-
}
|
|
293
|
-
async function handle(req, res, storage) {
|
|
294
|
-
if (req.method === "OPTIONS") {
|
|
295
|
-
res.writeHead(204, CORS_HEADERS);
|
|
296
|
-
res.end();
|
|
297
|
-
return;
|
|
298
|
-
}
|
|
299
|
-
const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
|
|
300
|
-
const annMatch = pathname.match(/^\/annotations\/([^/]+)$/);
|
|
301
|
-
try {
|
|
302
|
-
if (req.method === "GET" && pathname === "/store") {
|
|
303
|
-
const rev = storage.rev;
|
|
304
|
-
const store = await storage.load() ?? { version: 1, annotations: [] };
|
|
305
|
-
json(res, 200, { rev, store });
|
|
306
|
-
return;
|
|
307
|
-
}
|
|
308
|
-
if (req.method === "PUT" && annMatch) {
|
|
309
|
-
const id = decodeURIComponent(annMatch[1]);
|
|
310
|
-
if (!isSafeAnnotationId(id)) {
|
|
311
|
-
json(res, 400, { error: "invalid annotation id" });
|
|
312
|
-
return;
|
|
313
|
-
}
|
|
314
|
-
let annotation;
|
|
315
|
-
try {
|
|
316
|
-
annotation = JSON.parse(await readBody(req));
|
|
317
|
-
} catch {
|
|
318
|
-
json(res, 400, { error: "invalid JSON body" });
|
|
319
|
-
return;
|
|
320
|
-
}
|
|
321
|
-
if (!annotation || annotation.id !== id) {
|
|
322
|
-
json(res, 400, { error: "annotation.id must match the URL id" });
|
|
323
|
-
return;
|
|
324
|
-
}
|
|
325
|
-
await storage.save(annotation);
|
|
326
|
-
json(res, 200, { rev: storage.rev });
|
|
327
|
-
return;
|
|
328
|
-
}
|
|
329
|
-
if (req.method === "DELETE" && annMatch) {
|
|
330
|
-
const id = decodeURIComponent(annMatch[1]);
|
|
331
|
-
if (!isSafeAnnotationId(id)) {
|
|
332
|
-
json(res, 400, { error: "invalid annotation id" });
|
|
333
|
-
return;
|
|
334
|
-
}
|
|
335
|
-
await storage.remove(id);
|
|
336
|
-
json(res, 200, { rev: storage.rev });
|
|
337
|
-
return;
|
|
338
|
-
}
|
|
339
|
-
if (req.method === "DELETE" && pathname === "/annotations") {
|
|
340
|
-
await storage.clear();
|
|
341
|
-
json(res, 200, { rev: storage.rev });
|
|
342
|
-
return;
|
|
343
|
-
}
|
|
344
|
-
json(res, 404, { error: "not found" });
|
|
345
|
-
} catch (err) {
|
|
346
|
-
json(res, 500, { error: err instanceof Error ? err.message : String(err) });
|
|
347
|
-
}
|
|
348
|
-
}
|
|
349
|
-
function startHttpServer(storage, port) {
|
|
350
|
-
const server = http.createServer((req, res) => {
|
|
351
|
-
void handle(req, res, storage);
|
|
352
|
-
});
|
|
353
|
-
return new Promise((resolve, reject) => {
|
|
354
|
-
server.once("error", reject);
|
|
355
|
-
server.listen(port, "127.0.0.1", () => resolve(server));
|
|
356
|
-
});
|
|
357
|
-
}
|
|
358
|
-
|
|
359
903
|
// src/prompts.ts
|
|
360
|
-
var DUTY_PROMPT = "You are on annotation duty for this project. Designers drop feedback via the web-remarq MCP server. Run this loop until told to stop: call watch_annotations (timeoutSeconds: 60); if it times out, call it again. For EACH annotation it returns, call acknowledge with its id first. Then, if you can run background subagents, dispatch one that applies the fix to the project files and calls claim_fix when done - do not fix anything yourself in the main loop and do not wait for subagents, go straight back to watch_annotations so new feedback is never missed. Without background subagents, apply the fix inline after acknowledging, then return to watch_annotations. If a comment is ambiguous or unactionable, dismiss it with a reason instead of guessing.";
|
|
904
|
+
var DUTY_PROMPT = "You are on annotation duty for this project. Designers drop feedback via the web-remarq MCP server. Run this loop until told to stop: call watch_annotations (timeoutSeconds: 60); if it times out, call it again. For EACH annotation it returns, call acknowledge with its id first, passing a fresh operationId you keep for retries; if acknowledge answers invalid_transition, another agent already holds it - skip it and do not start work; if the call fails without an answer, retry with the same operationId. Then, if you can run background subagents, dispatch one that applies the fix to the project files and calls claim_fix when done - do not fix anything yourself in the main loop and do not wait for subagents, go straight back to watch_annotations so new feedback is never missed. Without background subagents, apply the fix inline after acknowledging, then return to watch_annotations. If a comment is ambiguous or unactionable, dismiss it with a reason instead of guessing.";
|
|
361
905
|
function registerPrompts(server) {
|
|
362
906
|
server.registerPrompt(
|
|
363
907
|
"watch",
|
|
@@ -448,7 +992,7 @@ async function handleListAnnotations(input, storage) {
|
|
|
448
992
|
|
|
449
993
|
// src/tools/get-annotation.ts
|
|
450
994
|
import { z as z2 } from "zod";
|
|
451
|
-
import { generateAgentExport as
|
|
995
|
+
import { generateAgentExport as generateAgentExport3 } from "web-remarq/core";
|
|
452
996
|
var getAnnotationInputSchema = z2.object({
|
|
453
997
|
id: z2.string()
|
|
454
998
|
});
|
|
@@ -463,18 +1007,54 @@ async function handleGetAnnotation(input, storage) {
|
|
|
463
1007
|
if (!annotation) {
|
|
464
1008
|
return toolError("annotation_not_found", `Annotation ${input.id} not found in this project`);
|
|
465
1009
|
}
|
|
466
|
-
const agentExport =
|
|
1010
|
+
const agentExport = generateAgentExport3([annotation], annotation.viewportBucket);
|
|
467
1011
|
const agentAnnotation = agentExport.annotations[0];
|
|
468
1012
|
return toolSuccess(agentAnnotation);
|
|
469
1013
|
}
|
|
470
1014
|
|
|
471
1015
|
// src/tools/acknowledge.ts
|
|
1016
|
+
import { z as z4 } from "zod";
|
|
1017
|
+
|
|
1018
|
+
// src/tools/transition-tool.ts
|
|
472
1019
|
import { z as z3 } from "zod";
|
|
473
|
-
import { transition, InvalidTransitionError } from "web-remarq/core";
|
|
474
|
-
var
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
1020
|
+
import { transition, InvalidTransitionError, AnnotationNotFoundError as AnnotationNotFoundError2 } from "web-remarq/core";
|
|
1021
|
+
var operationIdSchema = z3.string().min(1).max(128).optional();
|
|
1022
|
+
async function runTransition(input, storage, action, requestedTransition) {
|
|
1023
|
+
let replayed = false;
|
|
1024
|
+
let seen = null;
|
|
1025
|
+
const apply = (current) => {
|
|
1026
|
+
seen = current;
|
|
1027
|
+
if (input.operationId && current.lifecycle.some((e) => e.opId === input.operationId)) {
|
|
1028
|
+
replayed = true;
|
|
1029
|
+
return current;
|
|
1030
|
+
}
|
|
1031
|
+
const result = transition(current, action, { actor: "agent", reason: input.reason });
|
|
1032
|
+
const event = input.operationId ? { ...result.event, opId: input.operationId } : result.event;
|
|
1033
|
+
return { ...current, status: result.status, lifecycle: [...current.lifecycle, event] };
|
|
1034
|
+
};
|
|
1035
|
+
const conflict = (current, err) => {
|
|
1036
|
+
const last = current.lifecycle[current.lifecycle.length - 1];
|
|
1037
|
+
return toolError("invalid_transition", `${err.message} - another actor moved this annotation first; do not start work on it, re-read it with get_annotation`, {
|
|
1038
|
+
conflict: true,
|
|
1039
|
+
currentStatus: current.status,
|
|
1040
|
+
currentRev: current.rev ?? null,
|
|
1041
|
+
lastEvent: last ? { type: last.type, actor: last.actor, timestamp: last.timestamp } : null,
|
|
1042
|
+
requestedTransition
|
|
1043
|
+
});
|
|
1044
|
+
};
|
|
1045
|
+
if (typeof storage.mutate === "function") {
|
|
1046
|
+
let saved;
|
|
1047
|
+
try {
|
|
1048
|
+
saved = await storage.mutate(input.id, apply);
|
|
1049
|
+
} catch (err) {
|
|
1050
|
+
if (err instanceof AnnotationNotFoundError2) {
|
|
1051
|
+
return toolError("annotation_not_found", `Annotation ${input.id} not found in this project`);
|
|
1052
|
+
}
|
|
1053
|
+
if (err instanceof InvalidTransitionError && seen) return conflict(seen, err);
|
|
1054
|
+
return toolError("storage_error", err instanceof Error ? err.message : String(err));
|
|
1055
|
+
}
|
|
1056
|
+
return toolSuccess({ ok: true, status: saved.status, rev: saved.rev ?? null, ...replayed ? { replayed: true } : {} });
|
|
1057
|
+
}
|
|
478
1058
|
let store;
|
|
479
1059
|
try {
|
|
480
1060
|
store = await storage.load();
|
|
@@ -485,121 +1065,58 @@ async function handleAcknowledge(input, storage) {
|
|
|
485
1065
|
if (!annotation) {
|
|
486
1066
|
return toolError("annotation_not_found", `Annotation ${input.id} not found in this project`);
|
|
487
1067
|
}
|
|
488
|
-
let
|
|
1068
|
+
let updated;
|
|
489
1069
|
try {
|
|
490
|
-
|
|
1070
|
+
updated = apply(annotation);
|
|
491
1071
|
} catch (err) {
|
|
492
|
-
if (err instanceof InvalidTransitionError)
|
|
493
|
-
return toolError("invalid_transition", err.message, {
|
|
494
|
-
currentStatus: annotation.status,
|
|
495
|
-
requestedTransition: "acknowledge"
|
|
496
|
-
});
|
|
497
|
-
}
|
|
1072
|
+
if (err instanceof InvalidTransitionError) return conflict(annotation, err);
|
|
498
1073
|
throw err;
|
|
499
1074
|
}
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
await storage.save(updated);
|
|
507
|
-
} catch (err) {
|
|
508
|
-
return toolError("storage_error", err instanceof Error ? err.message : String(err));
|
|
1075
|
+
if (!replayed) {
|
|
1076
|
+
try {
|
|
1077
|
+
await storage.save(updated);
|
|
1078
|
+
} catch (err) {
|
|
1079
|
+
return toolError("storage_error", err instanceof Error ? err.message : String(err));
|
|
1080
|
+
}
|
|
509
1081
|
}
|
|
510
|
-
return toolSuccess({ ok: true, status:
|
|
1082
|
+
return toolSuccess({ ok: true, status: updated.status, atomic: false, ...replayed ? { replayed: true } : {} });
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
// src/tools/acknowledge.ts
|
|
1086
|
+
var acknowledgeInputSchema = z4.object({
|
|
1087
|
+
id: z4.string(),
|
|
1088
|
+
operationId: operationIdSchema
|
|
1089
|
+
});
|
|
1090
|
+
async function handleAcknowledge(input, storage) {
|
|
1091
|
+
return runTransition(input, storage, "acknowledge", "acknowledge");
|
|
511
1092
|
}
|
|
512
1093
|
|
|
513
1094
|
// src/tools/claim-fix.ts
|
|
514
|
-
import { z as
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
1095
|
+
import { z as z5 } from "zod";
|
|
1096
|
+
var claimFixInputSchema = z5.object({
|
|
1097
|
+
id: z5.string(),
|
|
1098
|
+
operationId: operationIdSchema
|
|
518
1099
|
});
|
|
519
1100
|
async function handleClaimFix(input, storage) {
|
|
520
|
-
|
|
521
|
-
try {
|
|
522
|
-
store = await storage.load();
|
|
523
|
-
} catch (err) {
|
|
524
|
-
return toolError("storage_error", err instanceof Error ? err.message : String(err));
|
|
525
|
-
}
|
|
526
|
-
const annotation = store?.annotations.find((a) => a.id === input.id);
|
|
527
|
-
if (!annotation) {
|
|
528
|
-
return toolError("annotation_not_found", `Annotation ${input.id} not found in this project`);
|
|
529
|
-
}
|
|
530
|
-
let result;
|
|
531
|
-
try {
|
|
532
|
-
result = transition2(annotation, "claimFix", { actor: "agent" });
|
|
533
|
-
} catch (err) {
|
|
534
|
-
if (err instanceof InvalidTransitionError2) {
|
|
535
|
-
return toolError("invalid_transition", err.message, {
|
|
536
|
-
currentStatus: annotation.status,
|
|
537
|
-
requestedTransition: "claimFix"
|
|
538
|
-
});
|
|
539
|
-
}
|
|
540
|
-
throw err;
|
|
541
|
-
}
|
|
542
|
-
const updated = {
|
|
543
|
-
...annotation,
|
|
544
|
-
status: result.status,
|
|
545
|
-
lifecycle: [...annotation.lifecycle, result.event]
|
|
546
|
-
};
|
|
547
|
-
try {
|
|
548
|
-
await storage.save(updated);
|
|
549
|
-
} catch (err) {
|
|
550
|
-
return toolError("storage_error", err instanceof Error ? err.message : String(err));
|
|
551
|
-
}
|
|
552
|
-
return toolSuccess({ ok: true, status: result.status });
|
|
1101
|
+
return runTransition(input, storage, "claimFix", "claimFix");
|
|
553
1102
|
}
|
|
554
1103
|
|
|
555
1104
|
// src/tools/dismiss.ts
|
|
556
|
-
import { z as
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
1105
|
+
import { z as z6 } from "zod";
|
|
1106
|
+
var dismissInputSchema = z6.object({
|
|
1107
|
+
id: z6.string(),
|
|
1108
|
+
reason: z6.string().optional(),
|
|
1109
|
+
operationId: operationIdSchema
|
|
561
1110
|
});
|
|
562
1111
|
async function handleDismiss(input, storage) {
|
|
563
|
-
|
|
564
|
-
try {
|
|
565
|
-
store = await storage.load();
|
|
566
|
-
} catch (err) {
|
|
567
|
-
return toolError("storage_error", err instanceof Error ? err.message : String(err));
|
|
568
|
-
}
|
|
569
|
-
const annotation = store?.annotations.find((a) => a.id === input.id);
|
|
570
|
-
if (!annotation) {
|
|
571
|
-
return toolError("annotation_not_found", `Annotation ${input.id} not found in this project`);
|
|
572
|
-
}
|
|
573
|
-
let result;
|
|
574
|
-
try {
|
|
575
|
-
result = transition3(annotation, "dismiss", { actor: "agent", reason: input.reason });
|
|
576
|
-
} catch (err) {
|
|
577
|
-
if (err instanceof InvalidTransitionError3) {
|
|
578
|
-
return toolError("invalid_transition", err.message, {
|
|
579
|
-
currentStatus: annotation.status,
|
|
580
|
-
requestedTransition: "dismiss"
|
|
581
|
-
});
|
|
582
|
-
}
|
|
583
|
-
throw err;
|
|
584
|
-
}
|
|
585
|
-
const updated = {
|
|
586
|
-
...annotation,
|
|
587
|
-
status: result.status,
|
|
588
|
-
lifecycle: [...annotation.lifecycle, result.event]
|
|
589
|
-
};
|
|
590
|
-
try {
|
|
591
|
-
await storage.save(updated);
|
|
592
|
-
} catch (err) {
|
|
593
|
-
return toolError("storage_error", err instanceof Error ? err.message : String(err));
|
|
594
|
-
}
|
|
595
|
-
return toolSuccess({ ok: true, status: result.status });
|
|
1112
|
+
return runTransition(input, storage, "dismiss", "dismiss");
|
|
596
1113
|
}
|
|
597
1114
|
|
|
598
1115
|
// src/tools/watch-annotations.ts
|
|
599
|
-
import { z as
|
|
1116
|
+
import { z as z7 } from "zod";
|
|
600
1117
|
var DEFAULT_TIMEOUT_SECONDS = 25;
|
|
601
|
-
var watchAnnotationsInputSchema =
|
|
602
|
-
timeoutSeconds:
|
|
1118
|
+
var watchAnnotationsInputSchema = z7.object({
|
|
1119
|
+
timeoutSeconds: z7.number().int().min(1).max(120).optional()
|
|
603
1120
|
});
|
|
604
1121
|
async function handleWatchAnnotations(input, storage, waitForChange) {
|
|
605
1122
|
const timeoutMs = (input.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS) * 1e3;
|
|
@@ -647,7 +1164,7 @@ function registerTools(server, storage, opts) {
|
|
|
647
1164
|
server.registerTool(
|
|
648
1165
|
"acknowledge",
|
|
649
1166
|
{
|
|
650
|
-
description: "Mark an annotation as in-progress (pending \u2192 in_progress).",
|
|
1167
|
+
description: "Mark an annotation as in-progress (pending \u2192 in_progress). Atomic: of several concurrent callers exactly one wins; the others get invalid_transition with details.conflict=true - then do not start work, re-read the annotation. Pass operationId (any unique string you keep) so a retry after a lost response is recognised instead of double-counted.",
|
|
651
1168
|
inputSchema: acknowledgeInputSchema.shape
|
|
652
1169
|
},
|
|
653
1170
|
(input) => cast(handleAcknowledge(input, storage))
|
|
@@ -655,7 +1172,7 @@ function registerTools(server, storage, opts) {
|
|
|
655
1172
|
server.registerTool(
|
|
656
1173
|
"claim_fix",
|
|
657
1174
|
{
|
|
658
|
-
description: "Claim a fix for an annotation (\u2192 fixed_unverified). Human verification still required.",
|
|
1175
|
+
description: "Claim a fix for an annotation (\u2192 fixed_unverified). Human verification still required. Atomic with the same operationId retry semantics as acknowledge; invalid_transition means the annotation changed under you - re-read it.",
|
|
659
1176
|
inputSchema: claimFixInputSchema.shape
|
|
660
1177
|
},
|
|
661
1178
|
(input) => cast(handleClaimFix(input, storage))
|
|
@@ -663,7 +1180,7 @@ function registerTools(server, storage, opts) {
|
|
|
663
1180
|
server.registerTool(
|
|
664
1181
|
"dismiss",
|
|
665
1182
|
{
|
|
666
|
-
description: "Dismiss an annotation with an optional reason (terminal state).",
|
|
1183
|
+
description: "Dismiss an annotation with an optional reason (terminal state). Atomic with the same operationId retry semantics as acknowledge.",
|
|
667
1184
|
inputSchema: dismissInputSchema.shape
|
|
668
1185
|
},
|
|
669
1186
|
(input) => cast(handleDismiss(input, storage))
|
|
@@ -680,6 +1197,7 @@ function registerTools(server, storage, opts) {
|
|
|
680
1197
|
|
|
681
1198
|
// src/server.ts
|
|
682
1199
|
var CLOUD_POLL_MS = 3e3;
|
|
1200
|
+
var CHANNEL_INSTRUCTIONS = `Browser marks arrive as <channel source="web-remarq" kind="marks" count="..." ids="...">. The user sends them deliberately from their own browser widget, so they are the user's own fix requests. Marks come one batch at a time. Fix each mark in the code, then call claim_fix for each id (or dismiss with a reason if it cannot or should not be fixed). Do not ask the user to confirm receipt or whether to proceed. The next batch is sent only after every mark of the current batch is reported.`;
|
|
683
1201
|
async function main() {
|
|
684
1202
|
let config;
|
|
685
1203
|
try {
|
|
@@ -693,15 +1211,41 @@ async function main() {
|
|
|
693
1211
|
}
|
|
694
1212
|
let storage;
|
|
695
1213
|
let waitForChange;
|
|
1214
|
+
let delivery = null;
|
|
1215
|
+
let sendChannel = async () => {
|
|
1216
|
+
};
|
|
696
1217
|
if (config.mode === "local") {
|
|
1218
|
+
const storeDir = dirname3(config.dataFile);
|
|
1219
|
+
let local;
|
|
1220
|
+
let port;
|
|
1221
|
+
try {
|
|
1222
|
+
local = readOrCreateLocalConfig(storeDir);
|
|
1223
|
+
port = effectivePort(config, local);
|
|
1224
|
+
acquireStoreLock(storeDir, port);
|
|
1225
|
+
} catch (err) {
|
|
1226
|
+
if (err instanceof LocalConfigError || err instanceof StoreLockedError) {
|
|
1227
|
+
console.error(`[web-remarq-mcp] ${err.message}`);
|
|
1228
|
+
process.exit(1);
|
|
1229
|
+
}
|
|
1230
|
+
throw err;
|
|
1231
|
+
}
|
|
697
1232
|
const adapter = new FileStorageAdapter(config.dataFile);
|
|
698
|
-
const tasksDir = join3(
|
|
1233
|
+
const tasksDir = join3(storeDir, "tasks");
|
|
699
1234
|
const taskFolder = new TaskFolder(adapter, tasksDir);
|
|
700
1235
|
adapter.onChange(() => taskFolder.schedule());
|
|
1236
|
+
if (config.channel.enabled) {
|
|
1237
|
+
delivery = new ChannelDelivery({
|
|
1238
|
+
storage: adapter,
|
|
1239
|
+
send: (content, meta) => sendChannel(content, meta),
|
|
1240
|
+
ledgerPath: join3(storeDir, "delivery.json"),
|
|
1241
|
+
config: config.channel
|
|
1242
|
+
});
|
|
1243
|
+
adapter.onChange(() => delivery?.onChange());
|
|
1244
|
+
}
|
|
701
1245
|
taskFolder.schedule();
|
|
702
|
-
await startHttpServer(adapter,
|
|
1246
|
+
await startHttpServer(adapter, port, local);
|
|
703
1247
|
console.error(
|
|
704
|
-
`[web-remarq-mcp] local mode \u2014 widget endpoint http://127.0.0.1:${config.
|
|
1248
|
+
`[web-remarq-mcp] local mode \u2014 project ${local.projectId}, widget endpoint http://127.0.0.1:${port} (token in ${join3(storeDir, "config.json")}), store ${config.dataFile}, tasks ${tasksDir}`
|
|
705
1249
|
);
|
|
706
1250
|
storage = adapter;
|
|
707
1251
|
waitForChange = (ms) => adapter.waitForChange(ms);
|
|
@@ -709,10 +1253,18 @@ async function main() {
|
|
|
709
1253
|
storage = createStorage(config);
|
|
710
1254
|
waitForChange = (ms) => new Promise((resolve) => setTimeout(() => resolve(false), Math.min(ms, CLOUD_POLL_MS)));
|
|
711
1255
|
}
|
|
712
|
-
const server = new McpServer(
|
|
713
|
-
name: "web-remarq",
|
|
714
|
-
|
|
715
|
-
|
|
1256
|
+
const server = new McpServer(
|
|
1257
|
+
{ name: "web-remarq", version: "0.6.0" },
|
|
1258
|
+
delivery ? { capabilities: { experimental: { "claude/channel": {} } }, instructions: CHANNEL_INSTRUCTIONS } : void 0
|
|
1259
|
+
);
|
|
1260
|
+
if (delivery) {
|
|
1261
|
+
sendChannel = (content, meta) => server.server.notification({
|
|
1262
|
+
method: "notifications/claude/channel",
|
|
1263
|
+
params: { content, meta }
|
|
1264
|
+
});
|
|
1265
|
+
const d = delivery;
|
|
1266
|
+
server.server.oninitialized = () => d.onInitialized();
|
|
1267
|
+
}
|
|
716
1268
|
registerTools(server, storage, { waitForChange });
|
|
717
1269
|
registerPrompts(server);
|
|
718
1270
|
const transport = new StdioServerTransport();
|