@hanfang5057/co-space 0.0.0-stage → 0.1.10
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 +44 -2
- package/bin/cospace-local.js +2 -0
- package/dist/cli.js +379 -0
- package/dist/daemon.cjs +1464 -0
- package/dist/mcp.cjs +36826 -0
- package/dist/package.json +6 -0
- package/dist/web/app.css +1 -0
- package/dist/web/app.js +831 -0
- package/dist/web/index.html +1 -0
- package/package.json +45 -4
- package/skills/cospace-review/SKILL.md +15 -0
package/dist/daemon.cjs
ADDED
|
@@ -0,0 +1,1464 @@
|
|
|
1
|
+
var __create = Object.create;
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
6
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
+
var __copyProps = (to, from, except, desc) => {
|
|
8
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
9
|
+
for (let key of __getOwnPropNames(from))
|
|
10
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
11
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
12
|
+
}
|
|
13
|
+
return to;
|
|
14
|
+
};
|
|
15
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
16
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
17
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
18
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
19
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
20
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
21
|
+
mod
|
|
22
|
+
));
|
|
23
|
+
|
|
24
|
+
// apps/local-server/src/daemon-entry.js
|
|
25
|
+
var import_node_path6 = __toESM(require("node:path"), 1);
|
|
26
|
+
|
|
27
|
+
// packages/local-runtime/src/service.js
|
|
28
|
+
var import_node_crypto6 = require("node:crypto");
|
|
29
|
+
var import_node_http = require("node:http");
|
|
30
|
+
var import_promises = require("node:fs/promises");
|
|
31
|
+
var import_node_path4 = __toESM(require("node:path"), 1);
|
|
32
|
+
|
|
33
|
+
// packages/review-core/src/collaboration-store.js
|
|
34
|
+
var import_node_sqlite = require("node:sqlite");
|
|
35
|
+
var import_node_crypto = require("node:crypto");
|
|
36
|
+
var import_node_fs = require("node:fs");
|
|
37
|
+
var import_node_path = __toESM(require("node:path"), 1);
|
|
38
|
+
var fail = (code, message) => {
|
|
39
|
+
throw Object.assign(new Error(message), { code });
|
|
40
|
+
};
|
|
41
|
+
var MAX_INSTRUCTIONS = 12e3;
|
|
42
|
+
var CollaborationStore = class {
|
|
43
|
+
constructor(home) {
|
|
44
|
+
(0, import_node_fs.mkdirSync)(home, { recursive: true, mode: 448 });
|
|
45
|
+
this.db = new import_node_sqlite.DatabaseSync(import_node_path.default.join(home, "collaboration.sqlite"), { timeout: 5e3 });
|
|
46
|
+
this.db.exec(`
|
|
47
|
+
CREATE TABLE IF NOT EXISTS collaboration_instructions (
|
|
48
|
+
scope TEXT PRIMARY KEY,
|
|
49
|
+
content TEXT NOT NULL,
|
|
50
|
+
version INTEGER NOT NULL,
|
|
51
|
+
updated_at TEXT NOT NULL
|
|
52
|
+
);
|
|
53
|
+
CREATE TABLE IF NOT EXISTS collaboration_operations (
|
|
54
|
+
id TEXT PRIMARY KEY,
|
|
55
|
+
fingerprint TEXT NOT NULL,
|
|
56
|
+
result TEXT NOT NULL
|
|
57
|
+
);
|
|
58
|
+
`);
|
|
59
|
+
}
|
|
60
|
+
close() {
|
|
61
|
+
this.db.close();
|
|
62
|
+
}
|
|
63
|
+
readInstructions(docId) {
|
|
64
|
+
const global = this.db.prepare("SELECT content,version,updated_at FROM collaboration_instructions WHERE scope='global'").get();
|
|
65
|
+
const local = this.db.prepare("SELECT content,version,updated_at FROM collaboration_instructions WHERE scope=?").get(`doc:${docId}`);
|
|
66
|
+
return {
|
|
67
|
+
global: global ? { content: global.content, version: global.version, updatedAt: global.updated_at } : null,
|
|
68
|
+
document: local ? { content: local.content, version: local.version, updatedAt: local.updated_at } : null
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
saveInstructions({ scope = "global", docId, content, baseVersion, operationId }) {
|
|
72
|
+
if (!["global", "document"].includes(scope) || scope === "document" && (!docId || typeof docId !== "string")) fail("INVALID_INPUT", "Invalid instruction scope");
|
|
73
|
+
if (typeof content !== "string" || content.length > MAX_INSTRUCTIONS) fail("INVALID_INPUT", `Instructions must be text under ${MAX_INSTRUCTIONS} characters`);
|
|
74
|
+
if (!Number.isInteger(baseVersion) || baseVersion < 0) fail("INVALID_INPUT", "Instruction version required");
|
|
75
|
+
if (typeof operationId !== "string" || !operationId) fail("INVALID_INPUT", "Operation ID required");
|
|
76
|
+
const key = scope === "global" ? "global" : `doc:${docId}`;
|
|
77
|
+
const fingerprint2 = (0, import_node_crypto.createHash)("sha256").update(JSON.stringify({ key, content, baseVersion })).digest("hex");
|
|
78
|
+
const next = content.trim();
|
|
79
|
+
const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
80
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
81
|
+
try {
|
|
82
|
+
const replay = this.db.prepare("SELECT fingerprint,result FROM collaboration_operations WHERE id=?").get(operationId);
|
|
83
|
+
if (replay) {
|
|
84
|
+
if (replay.fingerprint !== fingerprint2) fail("OPERATION_ID_CONFLICT", "Operation ID reused with different input");
|
|
85
|
+
this.db.exec("COMMIT");
|
|
86
|
+
return JSON.parse(replay.result);
|
|
87
|
+
}
|
|
88
|
+
const row = this.db.prepare("SELECT version FROM collaboration_instructions WHERE scope=?").get(key);
|
|
89
|
+
const version = row?.version ?? 0;
|
|
90
|
+
if (version !== baseVersion) fail("VERSION_CONFLICT", "Instructions changed; reload before saving");
|
|
91
|
+
this.db.prepare(`
|
|
92
|
+
INSERT INTO collaboration_instructions(scope,content,version,updated_at) VALUES(?,?,?,?)
|
|
93
|
+
ON CONFLICT(scope) DO UPDATE SET content=excluded.content,version=excluded.version,updated_at=excluded.updated_at
|
|
94
|
+
`).run(key, next, version + 1, updatedAt);
|
|
95
|
+
const result = { scope, ...scope === "document" ? { docId } : {}, content: next, version: version + 1, updatedAt };
|
|
96
|
+
this.db.prepare("INSERT INTO collaboration_operations(id,fingerprint,result) VALUES(?,?,?)").run(operationId, fingerprint2, JSON.stringify(result));
|
|
97
|
+
this.db.exec("COMMIT");
|
|
98
|
+
return result;
|
|
99
|
+
} catch (error) {
|
|
100
|
+
try {
|
|
101
|
+
this.db.exec("ROLLBACK");
|
|
102
|
+
} catch {
|
|
103
|
+
}
|
|
104
|
+
throw error;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
deleteDocument(docId) {
|
|
108
|
+
this.db.prepare("DELETE FROM collaboration_instructions WHERE scope=?").run(`doc:${docId}`);
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
// packages/review-core/src/space-service.js
|
|
113
|
+
var import_node_fs2 = require("node:fs");
|
|
114
|
+
var import_node_path2 = __toESM(require("node:path"), 1);
|
|
115
|
+
|
|
116
|
+
// packages/review-core/src/review-core.js
|
|
117
|
+
var import_node_sqlite2 = require("node:sqlite");
|
|
118
|
+
var import_node_crypto2 = require("node:crypto");
|
|
119
|
+
var ReviewError = class extends Error {
|
|
120
|
+
constructor(code, message, details = {}) {
|
|
121
|
+
super(message);
|
|
122
|
+
this.code = code;
|
|
123
|
+
this.details = details;
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
var fail2 = (code, message, details) => {
|
|
127
|
+
throw new ReviewError(code, message, details);
|
|
128
|
+
};
|
|
129
|
+
var json = JSON.stringify;
|
|
130
|
+
var parse = JSON.parse;
|
|
131
|
+
var validId = (x) => typeof x === "string" && x.length > 0 && x.length <= 200;
|
|
132
|
+
var fingerprint = (x) => (0, import_node_crypto2.createHash)("sha256").update(json(x)).digest("hex");
|
|
133
|
+
var boundarySafe = (s, n) => !(n > 0 && n < s.length && s.charCodeAt(n - 1) >= 55296 && s.charCodeAt(n - 1) <= 56319 && s.charCodeAt(n) >= 56320 && s.charCodeAt(n) <= 57343);
|
|
134
|
+
var context = (s, from, to) => ({ before: s.slice(Math.max(0, from - 32), from), after: s.slice(to, to + 32) });
|
|
135
|
+
var ReviewStore = class {
|
|
136
|
+
constructor(path7) {
|
|
137
|
+
this.db = new import_node_sqlite2.DatabaseSync(path7, { timeout: 5e3 });
|
|
138
|
+
this.db.exec("PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA busy_timeout=5000");
|
|
139
|
+
const old = this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='review_documents'").get();
|
|
140
|
+
const marker = this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='space_meta'").get();
|
|
141
|
+
const schemaVersion = marker ? this.db.prepare("SELECT value FROM space_meta WHERE key='schema'").get()?.value : null;
|
|
142
|
+
if (old && schemaVersion !== "markdown-text-v1" && schemaVersion !== "markdown-text-v2") {
|
|
143
|
+
this.db.close();
|
|
144
|
+
throw new ReviewError("UNSUPPORTED_SCHEMA", "Unmarked or unsupported review database; back it up and migrate explicitly", { schema: schemaVersion ?? null });
|
|
145
|
+
}
|
|
146
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
147
|
+
try {
|
|
148
|
+
this.db.exec(`CREATE TABLE IF NOT EXISTS space_meta(key TEXT PRIMARY KEY,value TEXT NOT NULL);
|
|
149
|
+
INSERT OR IGNORE INTO space_meta VALUES('schema','markdown-text-v2');
|
|
150
|
+
CREATE TABLE IF NOT EXISTS review_documents(id TEXT PRIMARY KEY, version INTEGER NOT NULL, content TEXT NOT NULL, created_at TEXT NOT NULL DEFAULT '', updated_at TEXT NOT NULL DEFAULT '');
|
|
151
|
+
CREATE TABLE IF NOT EXISTS review_suggestions(id INTEGER PRIMARY KEY AUTOINCREMENT,doc_id TEXT NOT NULL,status TEXT NOT NULL,base_version INTEGER NOT NULL,from_pos INTEGER NOT NULL,to_pos INTEGER NOT NULL,expected TEXT NOT NULL,replacement TEXT NOT NULL,before_context TEXT NOT NULL,after_context TEXT NOT NULL,created_order INTEGER NOT NULL,author TEXT NOT NULL DEFAULT 'Agent',created_at TEXT NOT NULL DEFAULT '');
|
|
152
|
+
CREATE TABLE IF NOT EXISTS review_operations(id TEXT PRIMARY KEY,fingerprint TEXT NOT NULL,result TEXT NOT NULL);
|
|
153
|
+
CREATE TABLE IF NOT EXISTS review_changes(doc_id TEXT NOT NULL,version INTEGER NOT NULL,from_pos INTEGER NOT NULL,to_pos INTEGER NOT NULL,inserted_length INTEGER NOT NULL,suggestion_order INTEGER NOT NULL DEFAULT 0,PRIMARY KEY(doc_id,version));`);
|
|
154
|
+
const documentColumns = new Set(this.db.prepare("PRAGMA table_info(review_documents)").all().map((column) => column.name));
|
|
155
|
+
if (!documentColumns.has("created_at")) this.db.exec("ALTER TABLE review_documents ADD COLUMN created_at TEXT NOT NULL DEFAULT ''");
|
|
156
|
+
if (!documentColumns.has("updated_at")) this.db.exec("ALTER TABLE review_documents ADD COLUMN updated_at TEXT NOT NULL DEFAULT ''");
|
|
157
|
+
const suggestionColumns = new Set(this.db.prepare("PRAGMA table_info(review_suggestions)").all().map((column) => column.name));
|
|
158
|
+
if (!suggestionColumns.has("author")) this.db.exec("ALTER TABLE review_suggestions ADD COLUMN author TEXT NOT NULL DEFAULT 'Agent'");
|
|
159
|
+
if (!suggestionColumns.has("created_at")) this.db.exec("ALTER TABLE review_suggestions ADD COLUMN created_at TEXT NOT NULL DEFAULT ''");
|
|
160
|
+
this.db.prepare("UPDATE space_meta SET value='markdown-text-v2' WHERE key='schema'").run();
|
|
161
|
+
this.db.exec("COMMIT");
|
|
162
|
+
} catch (error) {
|
|
163
|
+
try {
|
|
164
|
+
this.db.exec("ROLLBACK");
|
|
165
|
+
} catch {
|
|
166
|
+
}
|
|
167
|
+
this.db.close();
|
|
168
|
+
throw error;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
close() {
|
|
172
|
+
this.db.close();
|
|
173
|
+
}
|
|
174
|
+
operation(id, payload, fn) {
|
|
175
|
+
if (!validId(id)) fail2("INVALID_INPUT", "Stable operationId required");
|
|
176
|
+
const fp = fingerprint(payload);
|
|
177
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
178
|
+
try {
|
|
179
|
+
const old = this.db.prepare("SELECT * FROM review_operations WHERE id=?").get(id);
|
|
180
|
+
if (old) {
|
|
181
|
+
if (old.fingerprint !== fp) fail2("OPERATION_ID_CONFLICT", "Operation ID reused");
|
|
182
|
+
this.db.exec("COMMIT");
|
|
183
|
+
return parse(old.result);
|
|
184
|
+
}
|
|
185
|
+
const result = fn();
|
|
186
|
+
this.db.prepare("INSERT INTO review_operations VALUES(?,?,?)").run(id, fp, json(result));
|
|
187
|
+
this.db.exec("COMMIT");
|
|
188
|
+
return result;
|
|
189
|
+
} catch (e) {
|
|
190
|
+
try {
|
|
191
|
+
this.db.exec("ROLLBACK");
|
|
192
|
+
} catch {
|
|
193
|
+
}
|
|
194
|
+
throw e;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
createDocument({ id, content, operationId }) {
|
|
198
|
+
if (!validId(id) || typeof content !== "string") fail2("INVALID_INPUT", "Document ID and Markdown text are required");
|
|
199
|
+
return this.operation(operationId, { action: "create", id, content }, () => {
|
|
200
|
+
if (this.db.prepare("SELECT id FROM review_documents WHERE id=?").get(id)) fail2("DOCUMENT_EXISTS", "Document exists");
|
|
201
|
+
const createdAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
202
|
+
this.db.prepare("INSERT INTO review_documents(id,version,content,created_at,updated_at) VALUES(?,0,?,?,?)").run(id, content, createdAt, createdAt);
|
|
203
|
+
return { id, version: 0, content };
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
canEditDocument(id) {
|
|
207
|
+
const hasSuggestion = this.db.prepare("SELECT 1 FROM review_suggestions WHERE doc_id=? AND status IN ('pending','conflicted') LIMIT 1").get(id);
|
|
208
|
+
const hasCommentTable = this.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='space_comments'").get();
|
|
209
|
+
const hasComment = hasCommentTable && this.db.prepare("SELECT 1 FROM space_comments WHERE doc_id=? AND status IN ('pending','sending','failed','unknown') LIMIT 1").get(id);
|
|
210
|
+
return !hasSuggestion && !hasComment;
|
|
211
|
+
}
|
|
212
|
+
readDocument(id) {
|
|
213
|
+
const d = this.db.prepare("SELECT * FROM review_documents WHERE id=?").get(id);
|
|
214
|
+
if (!d) fail2("DOCUMENT_NOT_FOUND", "Document not found");
|
|
215
|
+
const suggestions = this.db.prepare("SELECT * FROM review_suggestions WHERE doc_id=? AND status IN ('pending','conflicted') ORDER BY created_order").all(id).map((s) => ({ id: s.id, status: s.status, order: s.created_order, baseVersion: s.base_version, from: s.from_pos, to: s.to_pos, expected: s.expected, replacement: s.replacement, before: s.before_context, after: s.after_context, author: s.author, createdAt: s.created_at || null }));
|
|
216
|
+
return { id: d.id, version: d.version, content: d.content, createdAt: d.created_at || null, updatedAt: d.updated_at || null, suggestions, editable: this.canEditDocument(id) };
|
|
217
|
+
}
|
|
218
|
+
updateContent({ docId, baseVersion, content, operationId }) {
|
|
219
|
+
if (!validId(docId) || !Number.isInteger(baseVersion) || baseVersion < 0 || typeof content !== "string") fail2("INVALID_INPUT", "Document, base version and Markdown content are required");
|
|
220
|
+
return this.operation(operationId, { action: "edit", docId, baseVersion, content }, () => {
|
|
221
|
+
const d = this.db.prepare("SELECT version,content FROM review_documents WHERE id=?").get(docId);
|
|
222
|
+
if (!d) fail2("DOCUMENT_NOT_FOUND", "Document not found");
|
|
223
|
+
if (d.version !== baseVersion) fail2("VERSION_CONFLICT", "Document changed", { currentVersion: d.version });
|
|
224
|
+
if (!this.canEditDocument(docId)) fail2("EDIT_REQUIRES_UNANNOTATED_DOCUMENT", "Direct editing is only available before suggestions or comments exist");
|
|
225
|
+
if (content === d.content) return { id: docId, version: baseVersion, content, unchanged: true };
|
|
226
|
+
const version = baseVersion + 1, updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
227
|
+
this.db.prepare("UPDATE review_documents SET content=?,version=?,updated_at=? WHERE id=?").run(content, version, updatedAt, docId);
|
|
228
|
+
this.db.prepare("INSERT INTO review_changes(doc_id,version,from_pos,to_pos,inserted_length,suggestion_order) VALUES(?,?,?,?,?,0)").run(docId, version, 0, d.content.length, content.length);
|
|
229
|
+
return { id: docId, version, content };
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
propose({ docId, baseVersion, from, to, expected, replacement, operationId, author = "Agent" }) {
|
|
233
|
+
return this.operation(operationId, { action: "propose", docId, baseVersion, from, to, expected, replacement, author }, () => {
|
|
234
|
+
const d = this.readDocument(docId);
|
|
235
|
+
if (d.version !== baseVersion) fail2("VERSION_CONFLICT", "Document changed", { currentVersion: d.version });
|
|
236
|
+
if (!Number.isInteger(from) || !Number.isInteger(to) || from < 0 || to < from || to > d.content.length || !boundarySafe(d.content, from) || !boundarySafe(d.content, to)) fail2("INVALID_RANGE", "Invalid UTF-16 range");
|
|
237
|
+
if (typeof expected !== "string" || typeof replacement !== "string" || !expected && !replacement || d.content.slice(from, to) !== expected) fail2("ANCHOR_STALE", "Expected text does not match document");
|
|
238
|
+
for (const s of d.suggestions) {
|
|
239
|
+
if (s.status !== "pending") continue;
|
|
240
|
+
const hit = from === to && s.from === to && s.to === to ? false : from === to ? from > s.from && from < s.to : s.from === s.to ? s.from > from && s.from < to : from < s.to && s.from < to;
|
|
241
|
+
if (hit) fail2("OVERLAPPING_SUGGESTION", "Suggestion overlaps pending suggestion", { conflicts: [s.id] });
|
|
242
|
+
}
|
|
243
|
+
const c = context(d.content, from, to);
|
|
244
|
+
const order = this.db.prepare("SELECT COALESCE(MAX(created_order),0)+1 n FROM review_suggestions WHERE doc_id=?").get(docId).n;
|
|
245
|
+
const createdAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
246
|
+
const id = this.db.prepare("INSERT INTO review_suggestions(doc_id,status,base_version,from_pos,to_pos,expected,replacement,before_context,after_context,created_order,author,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)").run(docId, "pending", baseVersion, from, to, expected, replacement, c.before, c.after, order, author, createdAt).lastInsertRowid;
|
|
247
|
+
return { docId, id, version: d.version, suggestion: { id, from, to, expected, replacement, author, createdAt } };
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
decide({ docId, suggestionId, decision, operationId }) {
|
|
251
|
+
if (!["accept", "reject"].includes(decision)) fail2("INVALID_INPUT", "Invalid decision");
|
|
252
|
+
return this.operation(operationId, { action: "decide", docId, suggestionId, decision }, () => {
|
|
253
|
+
const d = this.readDocument(docId), s = d.suggestions.find((x) => x.id === suggestionId);
|
|
254
|
+
if (!s || s.status !== "pending") fail2("DECISION_CONFLICT", "Suggestion is no longer pending");
|
|
255
|
+
if (decision === "reject") {
|
|
256
|
+
this.db.prepare("UPDATE review_suggestions SET status='rejected' WHERE id=?").run(suggestionId);
|
|
257
|
+
return { id: suggestionId, status: "rejected", version: d.version };
|
|
258
|
+
}
|
|
259
|
+
let from = s.from, to = s.to;
|
|
260
|
+
if (d.version !== s.baseVersion) {
|
|
261
|
+
for (let v = s.baseVersion + 1; v <= d.version; v++) {
|
|
262
|
+
const changes = this.db.prepare("SELECT * FROM review_changes WHERE doc_id=? AND version=?").all(docId, v);
|
|
263
|
+
for (const ch of changes) {
|
|
264
|
+
const insertion = ch.from_pos === ch.to_pos;
|
|
265
|
+
if (insertion && from === to && from === ch.from_pos) {
|
|
266
|
+
if (ch.suggestion_order <= s.order) from += ch.inserted_length, to += ch.inserted_length;
|
|
267
|
+
continue;
|
|
268
|
+
}
|
|
269
|
+
if (ch.from_pos < to && ch.to_pos > from) fail2("ANCHOR_STALE", "Suggestion target changed; review again", { suggestionId });
|
|
270
|
+
if (ch.to_pos <= from) {
|
|
271
|
+
const delta = ch.inserted_length - (ch.to_pos - ch.from_pos);
|
|
272
|
+
from += delta;
|
|
273
|
+
to += delta;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
if (d.content.slice(from, to) !== s.expected) fail2("ANCHOR_STALE", "Suggestion target changed; review again", { suggestionId });
|
|
279
|
+
const content = d.content.slice(0, from) + s.replacement + d.content.slice(to), version = d.version + 1, updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
280
|
+
this.db.prepare("UPDATE review_documents SET content=?,version=?,updated_at=? WHERE id=?").run(content, version, updatedAt, docId);
|
|
281
|
+
this.db.prepare("INSERT INTO review_changes(doc_id,version,from_pos,to_pos,inserted_length,suggestion_order) VALUES(?,?,?,?,?,?)").run(docId, version, from, to, s.replacement.length, s.order);
|
|
282
|
+
this.db.prepare("UPDATE review_suggestions SET status='accepted' WHERE id=?").run(suggestionId);
|
|
283
|
+
const pending = this.db.prepare("SELECT id,base_version,from_pos,to_pos,expected,created_order FROM review_suggestions WHERE doc_id=? AND status='pending'").all(docId);
|
|
284
|
+
for (const other of pending) {
|
|
285
|
+
let a = other.from_pos, b = other.to_pos, conflict = false;
|
|
286
|
+
for (let v = other.base_version + 1; v <= version; v++) {
|
|
287
|
+
for (const ch of this.db.prepare("SELECT * FROM review_changes WHERE doc_id=? AND version=?").all(docId, v)) {
|
|
288
|
+
if (ch.from_pos === ch.to_pos && a === b && a === ch.from_pos) {
|
|
289
|
+
if (ch.suggestion_order <= other.created_order) {
|
|
290
|
+
a += ch.inserted_length;
|
|
291
|
+
b += ch.inserted_length;
|
|
292
|
+
}
|
|
293
|
+
continue;
|
|
294
|
+
}
|
|
295
|
+
if (ch.from_pos < b && ch.to_pos > a) {
|
|
296
|
+
conflict = true;
|
|
297
|
+
break;
|
|
298
|
+
}
|
|
299
|
+
if (ch.to_pos <= a) {
|
|
300
|
+
const delta = ch.inserted_length - (ch.to_pos - ch.from_pos);
|
|
301
|
+
a += delta;
|
|
302
|
+
b += delta;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
if (conflict) break;
|
|
306
|
+
}
|
|
307
|
+
if (!conflict && content.slice(a, b) === other.expected) this.db.prepare("UPDATE review_suggestions SET from_pos=?,to_pos=?,base_version=? WHERE id=?").run(a, b, version, other.id);
|
|
308
|
+
else this.db.prepare("UPDATE review_suggestions SET status='conflicted' WHERE id=?").run(other.id);
|
|
309
|
+
}
|
|
310
|
+
return { id: suggestionId, status: "accepted", version, content };
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
|
|
315
|
+
// packages/review-core/src/comments.js
|
|
316
|
+
var import_node_sqlite3 = require("node:sqlite");
|
|
317
|
+
var import_node_crypto3 = require("node:crypto");
|
|
318
|
+
var fail3 = (code, message) => {
|
|
319
|
+
throw new ReviewError(code, message);
|
|
320
|
+
};
|
|
321
|
+
var nonempty = (x) => typeof x === "string" && x.trim().length > 0 && x.length <= 4e3;
|
|
322
|
+
var digest = (x) => (0, import_node_crypto3.createHash)("sha256").update(JSON.stringify(x)).digest("hex");
|
|
323
|
+
var parse2 = JSON.parse;
|
|
324
|
+
var CONTEXT = 32;
|
|
325
|
+
function locateQuote(text, quote, contextBefore, contextAfter) {
|
|
326
|
+
const found = [];
|
|
327
|
+
for (let at = text.indexOf(quote); at !== -1; at = text.indexOf(quote, at + 1)) {
|
|
328
|
+
const before = text.slice(Math.max(0, at - contextBefore.length), at);
|
|
329
|
+
const after = text.slice(at + quote.length, at + quote.length + contextAfter.length);
|
|
330
|
+
let score = 0;
|
|
331
|
+
if (contextBefore && (before === contextBefore || before.endsWith(contextBefore) || contextBefore.endsWith(before))) score++;
|
|
332
|
+
if (contextAfter && (after === contextAfter || after.startsWith(contextAfter) || contextAfter.startsWith(after))) score++;
|
|
333
|
+
found.push({ from: at, to: at + quote.length, score });
|
|
334
|
+
}
|
|
335
|
+
if (!found.length) return null;
|
|
336
|
+
if (found.length === 1) return { from: found[0].from, to: found[0].to };
|
|
337
|
+
found.sort((a, b) => b.score - a.score);
|
|
338
|
+
return found[0].score > found[1].score ? { from: found[0].from, to: found[0].to } : null;
|
|
339
|
+
}
|
|
340
|
+
function occurrences(text, needle) {
|
|
341
|
+
const found = [];
|
|
342
|
+
for (let at = text.indexOf(needle); at !== -1; at = text.indexOf(needle, at + 1)) found.push(at);
|
|
343
|
+
return found;
|
|
344
|
+
}
|
|
345
|
+
function locateContext(text, contextBefore, contextAfter, oldFrom) {
|
|
346
|
+
if (!contextBefore && !contextAfter) return null;
|
|
347
|
+
const lengths = (value) => [...new Set([value.length, 24, 16, 8].filter((length) => length >= 4 && length <= value.length))];
|
|
348
|
+
const before = [];
|
|
349
|
+
for (const length of lengths(contextBefore)) for (const at of occurrences(text, contextBefore.slice(-length))) before.push({ end: at + length, score: length });
|
|
350
|
+
const after = [];
|
|
351
|
+
for (const length of lengths(contextAfter)) for (const at of occurrences(text, contextAfter.slice(0, length))) after.push({ start: at, score: length });
|
|
352
|
+
if (!contextBefore) before.push({ end: 0, score: 0 });
|
|
353
|
+
if (!contextAfter) after.push({ start: text.length, score: 0 });
|
|
354
|
+
const candidates = [];
|
|
355
|
+
for (const left of before) for (const right of after) {
|
|
356
|
+
if (left.end >= right.start) continue;
|
|
357
|
+
const from = left.end, to = right.start;
|
|
358
|
+
if (from >= to) continue;
|
|
359
|
+
candidates.push({ from, to, score: left.score + right.score, distance: Math.abs(from - oldFrom) });
|
|
360
|
+
}
|
|
361
|
+
if (!candidates.length) return null;
|
|
362
|
+
candidates.sort((a, b) => b.score - a.score || a.distance - b.distance);
|
|
363
|
+
if (candidates.length > 1 && candidates[0].score === candidates[1].score && candidates[0].distance === candidates[1].distance) return null;
|
|
364
|
+
return { from: candidates[0].from, to: candidates[0].to };
|
|
365
|
+
}
|
|
366
|
+
function contextFor(doc, from, to) {
|
|
367
|
+
return {
|
|
368
|
+
before: doc.slice(0, from).slice(-CONTEXT),
|
|
369
|
+
after: doc.slice(to, to + CONTEXT)
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
function resolveAnchor(doc, row, currentVersion) {
|
|
373
|
+
if (row.doc_version === void 0 || row.doc_version === null) return null;
|
|
374
|
+
if (row.doc_version === currentVersion) {
|
|
375
|
+
const exact = row.from_pos >= 0 && row.to_pos <= doc.length && doc.slice(row.from_pos, row.to_pos) === row.quote;
|
|
376
|
+
if (exact) return { from: row.from_pos, to: row.to_pos };
|
|
377
|
+
}
|
|
378
|
+
const byQuote = locateQuote(doc, row.quote, row.context_before || "", row.context_after || "");
|
|
379
|
+
if (byQuote) return byQuote;
|
|
380
|
+
return locateContext(doc, row.context_before || "", row.context_after || "", row.from_pos);
|
|
381
|
+
}
|
|
382
|
+
var CommentStore = class {
|
|
383
|
+
constructor(database) {
|
|
384
|
+
this.ownsDatabase = typeof database === "string";
|
|
385
|
+
this.db = this.ownsDatabase ? new import_node_sqlite3.DatabaseSync(database, { timeout: 5e3 }) : database;
|
|
386
|
+
if (!this.db?.prepare || !this.db?.exec) throw new TypeError("CommentStore requires a database path or SQLite connection");
|
|
387
|
+
if (this.ownsDatabase) this.db.exec("PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL");
|
|
388
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
389
|
+
try {
|
|
390
|
+
this.db.exec(`
|
|
391
|
+
CREATE TABLE IF NOT EXISTS space_comments(id TEXT PRIMARY KEY, doc_id TEXT NOT NULL, quote TEXT NOT NULL, body TEXT NOT NULL, from_pos INTEGER NOT NULL, to_pos INTEGER NOT NULL, doc_version INTEGER NOT NULL, status TEXT NOT NULL DEFAULT 'pending', request_id TEXT, context_before TEXT NOT NULL DEFAULT '', context_after TEXT NOT NULL DEFAULT '', created_at TEXT);
|
|
392
|
+
CREATE TABLE IF NOT EXISTS space_comment_sends(id TEXT PRIMARY KEY, fingerprint TEXT NOT NULL, session_id TEXT NOT NULL, doc_id TEXT NOT NULL, payload TEXT NOT NULL, status TEXT NOT NULL, error TEXT);
|
|
393
|
+
CREATE TABLE IF NOT EXISTS space_comment_completions(id TEXT PRIMARY KEY, fingerprint TEXT NOT NULL, doc_id TEXT NOT NULL, result TEXT NOT NULL, created_at TEXT NOT NULL);
|
|
394
|
+
CREATE TABLE IF NOT EXISTS space_comment_results(comment_id TEXT PRIMARY KEY, doc_id TEXT NOT NULL, suggestion_ids TEXT NOT NULL, operation_id TEXT NOT NULL, updated_at TEXT NOT NULL);`);
|
|
395
|
+
const columns = new Set(this.db.prepare("PRAGMA table_info(space_comments)").all().map((column) => column.name));
|
|
396
|
+
if (!columns.has("context_before")) this.db.exec("ALTER TABLE space_comments ADD COLUMN context_before TEXT NOT NULL DEFAULT ''");
|
|
397
|
+
if (!columns.has("context_after")) this.db.exec("ALTER TABLE space_comments ADD COLUMN context_after TEXT NOT NULL DEFAULT ''");
|
|
398
|
+
if (!columns.has("created_at")) this.db.exec("ALTER TABLE space_comments ADD COLUMN created_at TEXT");
|
|
399
|
+
const legacy = this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='space_comment_processing'").get();
|
|
400
|
+
if (legacy) {
|
|
401
|
+
this.db.exec("DELETE FROM space_comments; DELETE FROM space_comment_sends; DELETE FROM space_comment_results; DELETE FROM space_comment_completions; DROP TABLE space_comment_processing");
|
|
402
|
+
}
|
|
403
|
+
this.db.exec("COMMIT");
|
|
404
|
+
} catch (error) {
|
|
405
|
+
try {
|
|
406
|
+
this.db.exec("ROLLBACK");
|
|
407
|
+
} catch {
|
|
408
|
+
}
|
|
409
|
+
if (this.ownsDatabase) this.db.close();
|
|
410
|
+
throw error;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
close() {
|
|
414
|
+
if (this.ownsDatabase) this.db.close();
|
|
415
|
+
}
|
|
416
|
+
transaction(fn) {
|
|
417
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
418
|
+
try {
|
|
419
|
+
const result = fn();
|
|
420
|
+
this.db.exec("COMMIT");
|
|
421
|
+
return result;
|
|
422
|
+
} catch (e) {
|
|
423
|
+
try {
|
|
424
|
+
this.db.exec("ROLLBACK");
|
|
425
|
+
} catch {
|
|
426
|
+
}
|
|
427
|
+
throw e;
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
create({ docId, quote, body, anchor }) {
|
|
431
|
+
if (!nonempty(docId) || !nonempty(quote) || !nonempty(body) || !anchor || !Number.isInteger(anchor.from) || !Number.isInteger(anchor.to) || !Number.isInteger(anchor.version) || anchor.from >= anchor.to) fail3("INVALID_INPUT", "Comment requires document, body and non-empty selection");
|
|
432
|
+
return this.transaction(() => {
|
|
433
|
+
const row = this.db.prepare("SELECT version,content FROM review_documents WHERE id=?").get(docId);
|
|
434
|
+
if (!row) fail3("DOCUMENT_NOT_FOUND", "Document not found");
|
|
435
|
+
if (row.version !== anchor.version) fail3("VERSION_CONFLICT", "Document changed; select the text again");
|
|
436
|
+
let doc, contextBefore = "", contextAfter = "";
|
|
437
|
+
try {
|
|
438
|
+
doc = row.content;
|
|
439
|
+
if (anchor.from < 0 || anchor.to > doc.length || doc.slice(anchor.from, anchor.to) !== quote) fail3("ANCHOR_STALE", "Selected text does not match");
|
|
440
|
+
contextBefore = doc.slice(Math.max(0, anchor.from - CONTEXT), anchor.from);
|
|
441
|
+
contextAfter = doc.slice(anchor.to, anchor.to + CONTEXT);
|
|
442
|
+
} catch (e) {
|
|
443
|
+
if (e instanceof ReviewError) throw e;
|
|
444
|
+
fail3("ANCHOR_STALE", "Invalid selected range");
|
|
445
|
+
}
|
|
446
|
+
const id = (0, import_node_crypto3.randomUUID)();
|
|
447
|
+
const createdAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
448
|
+
this.db.prepare("INSERT INTO space_comments (id,doc_id,quote,body,from_pos,to_pos,doc_version,status,request_id,context_before,context_after,created_at) VALUES (?,?,?,?,?,?,?,?,NULL,?,?,?)").run(id, docId, quote, body, anchor.from, anchor.to, anchor.version, "pending", contextBefore, contextAfter, createdAt);
|
|
449
|
+
return { id, docId, quote, body, anchor, status: "pending", stale: false, createdAt };
|
|
450
|
+
});
|
|
451
|
+
}
|
|
452
|
+
delete({ docId, commentId }) {
|
|
453
|
+
if (!nonempty(docId) || !nonempty(commentId)) fail3("INVALID_INPUT", "Comment id and document are required");
|
|
454
|
+
return this.transaction(() => {
|
|
455
|
+
const row = this.db.prepare("SELECT id,doc_id,status FROM space_comments WHERE id=? AND doc_id=?").get(commentId, docId);
|
|
456
|
+
if (!row) fail3("COMMENT_NOT_FOUND", "Comment not found");
|
|
457
|
+
if (row.status === "sending") fail3("COMMENT_BUSY", "Comment is being sent");
|
|
458
|
+
this.db.prepare("DELETE FROM space_comment_results WHERE comment_id=?").run(commentId);
|
|
459
|
+
this.db.prepare("DELETE FROM space_comments WHERE id=? AND doc_id=?").run(commentId, docId);
|
|
460
|
+
return { id: commentId, deleted: true };
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
deleteDocument(docId) {
|
|
464
|
+
if (!nonempty(docId)) fail3("INVALID_INPUT", "Document ID is required");
|
|
465
|
+
return this.transaction(() => {
|
|
466
|
+
if (this.db.prepare("SELECT id FROM space_comments WHERE doc_id=? AND status='sending' LIMIT 1").get(docId)) fail3("COMMENT_BUSY", "A comment for this document is being sent");
|
|
467
|
+
this.db.prepare("DELETE FROM space_comments WHERE doc_id=?").run(docId);
|
|
468
|
+
this.db.prepare("DELETE FROM space_comment_sends WHERE doc_id=?").run(docId);
|
|
469
|
+
this.db.prepare("DELETE FROM space_comment_results WHERE doc_id=?").run(docId);
|
|
470
|
+
this.db.prepare("DELETE FROM space_comment_completions WHERE doc_id=?").run(docId);
|
|
471
|
+
return { docId, deleted: true };
|
|
472
|
+
});
|
|
473
|
+
}
|
|
474
|
+
list(docId) {
|
|
475
|
+
const document = this.db.prepare("SELECT version,content FROM review_documents WHERE id=?").get(docId);
|
|
476
|
+
if (!document) fail3("DOCUMENT_NOT_FOUND", "Document not found");
|
|
477
|
+
const doc = document.content;
|
|
478
|
+
const backfill = this.db.prepare("UPDATE space_comments SET context_before=?,context_after=? WHERE id=?");
|
|
479
|
+
const results = new Map(this.db.prepare("SELECT * FROM space_comment_results WHERE doc_id=?").all(docId).map((row) => [row.comment_id, row]));
|
|
480
|
+
return this.db.prepare("SELECT * FROM space_comments WHERE doc_id=? ORDER BY rowid").all(docId).map((r) => {
|
|
481
|
+
let contextBefore = r.context_before || "", contextAfter = r.context_after || "";
|
|
482
|
+
if (!contextBefore && !contextAfter && r.from_pos >= 0 && r.to_pos <= doc.length) {
|
|
483
|
+
try {
|
|
484
|
+
if (doc.slice(r.from_pos, r.to_pos) === r.quote) {
|
|
485
|
+
const context2 = contextFor(doc, r.from_pos, r.to_pos);
|
|
486
|
+
contextBefore = context2.before;
|
|
487
|
+
contextAfter = context2.after;
|
|
488
|
+
backfill.run(contextBefore, contextAfter, r.id);
|
|
489
|
+
}
|
|
490
|
+
} catch {
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
const row = { ...r, context_before: contextBefore, context_after: contextAfter };
|
|
494
|
+
const resolved = resolveAnchor(doc, row, document.version);
|
|
495
|
+
const state = results.get(r.id);
|
|
496
|
+
const suggestionIds = state ? parse2(state.suggestion_ids) : [];
|
|
497
|
+
const suggestions = suggestionIds.map((id) => this.db.prepare("SELECT id,status FROM review_suggestions WHERE id=? AND doc_id=?").get(id, r.doc_id)).filter(Boolean);
|
|
498
|
+
return { id: r.id, docId: r.doc_id, quote: r.quote, body: r.body, anchor: { from: r.from_pos, to: r.to_pos, version: r.doc_version }, resolved, status: r.status, stale: resolved === null, requestId: r.request_id, createdAt: r.created_at || null, processing: { suggestionIds, suggestions, operationId: state?.operation_id ?? null, updatedAt: state?.updated_at ?? null } };
|
|
499
|
+
});
|
|
500
|
+
}
|
|
501
|
+
completeProcessing({ docId, operationId, results }) {
|
|
502
|
+
if (!nonempty(docId) || !nonempty(operationId) || !Array.isArray(results) || !results.length) fail3("INVALID_INPUT", "Document, operation ID and comment results are required");
|
|
503
|
+
const normalized = results.map((result) => ({
|
|
504
|
+
commentId: result?.commentId,
|
|
505
|
+
suggestionIds: [...result?.suggestionIds || []].sort((a, b) => a - b)
|
|
506
|
+
})).sort((a, b) => String(a.commentId).localeCompare(String(b.commentId)));
|
|
507
|
+
if (normalized.some((x) => !nonempty(x.commentId)) || new Set(normalized.map((x) => x.commentId)).size !== normalized.length) fail3("INVALID_INPUT", "Comment IDs must be non-empty and unique");
|
|
508
|
+
for (const result of normalized) {
|
|
509
|
+
if (result.suggestionIds.some((id) => !Number.isSafeInteger(id) || id <= 0) || new Set(result.suggestionIds).size !== result.suggestionIds.length) fail3("INVALID_INPUT", "Comment suggestion IDs must be unique positive integers");
|
|
510
|
+
}
|
|
511
|
+
const normalizedResults = normalized;
|
|
512
|
+
const fingerprint2 = digest({ docId, results: normalizedResults });
|
|
513
|
+
return this.transaction(() => {
|
|
514
|
+
const prior = this.db.prepare("SELECT fingerprint,result FROM space_comment_completions WHERE id=?").get(operationId);
|
|
515
|
+
if (prior) {
|
|
516
|
+
if (prior.fingerprint !== fingerprint2) fail3("OPERATION_ID_CONFLICT", "Completion ID already used");
|
|
517
|
+
return { ...parse2(prior.result), replay: true };
|
|
518
|
+
}
|
|
519
|
+
const suggestionExists = this.db.prepare("SELECT id FROM review_suggestions WHERE id=? AND doc_id=?");
|
|
520
|
+
for (const result2 of normalizedResults) {
|
|
521
|
+
const comment = this.db.prepare("SELECT id,status FROM space_comments WHERE id=? AND doc_id=?").get(result2.commentId, docId);
|
|
522
|
+
if (!comment) fail3("COMMENT_NOT_FOUND", "Comment not found", { commentId: result2.commentId });
|
|
523
|
+
if (comment.status === "processed") fail3("COMMENT_ALREADY_PROCESSED", "Comment was already processed", { commentId: result2.commentId });
|
|
524
|
+
if (result2.suggestionIds.length) for (const suggestionId of result2.suggestionIds) {
|
|
525
|
+
if (!suggestionExists.get(suggestionId, docId)) fail3("SUGGESTION_NOT_FOUND", "Suggestion does not belong to this document", { commentId: result2.commentId, suggestionId });
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
529
|
+
const upsert = this.db.prepare(`INSERT INTO space_comment_results(comment_id,doc_id,suggestion_ids,operation_id,updated_at) VALUES(?,?,?,?,?) ON CONFLICT(comment_id) DO UPDATE SET suggestion_ids=excluded.suggestion_ids,operation_id=excluded.operation_id,updated_at=excluded.updated_at`);
|
|
530
|
+
const updateStatus = this.db.prepare("UPDATE space_comments SET status=? WHERE id=? AND doc_id=?");
|
|
531
|
+
for (const result2 of normalizedResults) {
|
|
532
|
+
upsert.run(result2.commentId, docId, JSON.stringify(result2.suggestionIds), operationId, updatedAt);
|
|
533
|
+
updateStatus.run(result2.suggestionIds.length ? "processed" : "pending", result2.commentId, docId);
|
|
534
|
+
}
|
|
535
|
+
const result = { docId, operationId, results: normalizedResults.map(({ commentId, suggestionIds }) => ({ commentId, suggestionIds })) };
|
|
536
|
+
this.db.prepare("INSERT INTO space_comment_completions(id,fingerprint,doc_id,result,created_at) VALUES(?,?,?,?,?)").run(operationId, fingerprint2, docId, JSON.stringify(result), updatedAt);
|
|
537
|
+
return { ...result, replay: false };
|
|
538
|
+
});
|
|
539
|
+
}
|
|
540
|
+
findSend(operationId) {
|
|
541
|
+
if (!nonempty(operationId)) return void 0;
|
|
542
|
+
const row = this.db.prepare("SELECT session_id,status FROM space_comment_sends WHERE id=?").get(operationId);
|
|
543
|
+
return row ? { sessionId: row.session_id, status: row.status } : void 0;
|
|
544
|
+
}
|
|
545
|
+
prepareSend({ docId, commentIds, sessionId, operationId }) {
|
|
546
|
+
if (!nonempty(docId) || !nonempty(sessionId) || !nonempty(operationId) || !Array.isArray(commentIds) || !commentIds.length || commentIds.some((x) => !nonempty(x)) || new Set(commentIds).size !== commentIds.length) fail3("INVALID_INPUT", "Choose comments and a current session");
|
|
547
|
+
const fp = digest({ docId, commentIds, sessionId });
|
|
548
|
+
return this.transaction(() => {
|
|
549
|
+
const prior = this.db.prepare("SELECT * FROM space_comment_sends WHERE id=?").get(operationId);
|
|
550
|
+
if (prior) {
|
|
551
|
+
if (prior.fingerprint !== fp) fail3("OPERATION_ID_CONFLICT", "Send ID already used");
|
|
552
|
+
return { requestId: operationId, sessionId, comments: parse2(prior.payload), status: prior.status, replay: true };
|
|
553
|
+
}
|
|
554
|
+
const all = this.list(docId), selected = commentIds.map((id) => all.find((x) => x.id === id));
|
|
555
|
+
if (selected.some((x) => !x)) fail3("COMMENT_NOT_FOUND", "Comment not found");
|
|
556
|
+
if (selected.some((x) => !["pending", "failed"].includes(x.status))) fail3("COMMENT_NOT_SENDABLE", "Comment is currently sending, awaiting Agent processing, or already processed");
|
|
557
|
+
const payload = selected.map(({ id, docId: docId2, quote, body, anchor, stale }) => ({ id, docId: docId2, quote, body, anchor, stale }));
|
|
558
|
+
this.db.prepare("INSERT INTO space_comment_sends VALUES (?,?,?,?,?,?,NULL)").run(operationId, fp, sessionId, docId, JSON.stringify(payload), "sending");
|
|
559
|
+
const update = this.db.prepare("UPDATE space_comments SET status='sending',request_id=? WHERE id=?");
|
|
560
|
+
for (const id of commentIds) update.run(operationId, id);
|
|
561
|
+
return { requestId: operationId, sessionId, comments: payload, status: "sending", replay: false };
|
|
562
|
+
});
|
|
563
|
+
}
|
|
564
|
+
finishSend({ operationId, status, error = null }) {
|
|
565
|
+
if (!["sent", "failed", "unknown"].includes(status)) fail3("INVALID_INPUT", "Invalid send status");
|
|
566
|
+
return this.transaction(() => {
|
|
567
|
+
const row = this.db.prepare("SELECT * FROM space_comment_sends WHERE id=?").get(operationId);
|
|
568
|
+
if (!row) fail3("SEND_NOT_FOUND", "Send not found");
|
|
569
|
+
if (row.status !== "sending") {
|
|
570
|
+
if (row.status === status) return { requestId: operationId, status };
|
|
571
|
+
fail3("SEND_CONFLICT", "Send already resolved");
|
|
572
|
+
}
|
|
573
|
+
this.db.prepare("UPDATE space_comment_sends SET status=?,error=? WHERE id=?").run(status, error === null ? null : String(error).slice(0, 1e3), operationId);
|
|
574
|
+
this.db.prepare("UPDATE space_comments SET status=? WHERE request_id=?").run(status, operationId);
|
|
575
|
+
return { requestId: operationId, status };
|
|
576
|
+
});
|
|
577
|
+
}
|
|
578
|
+
markInterruptedUnknown() {
|
|
579
|
+
return this.transaction(() => {
|
|
580
|
+
this.db.prepare("UPDATE space_comments SET status='unknown' WHERE status='sending'").run();
|
|
581
|
+
this.db.prepare("UPDATE space_comment_sends SET status='unknown',error='interrupted' WHERE status='sending'").run();
|
|
582
|
+
});
|
|
583
|
+
}
|
|
584
|
+
};
|
|
585
|
+
|
|
586
|
+
// packages/review-core/src/space-repository.js
|
|
587
|
+
var fail4 = (code, message) => {
|
|
588
|
+
throw Object.assign(new Error(message), { code });
|
|
589
|
+
};
|
|
590
|
+
var SpaceRepository = class {
|
|
591
|
+
constructor(databaseFile) {
|
|
592
|
+
this.store = new ReviewStore(databaseFile);
|
|
593
|
+
this.comments = new CommentStore(this.store.db);
|
|
594
|
+
}
|
|
595
|
+
close() {
|
|
596
|
+
this.comments.close();
|
|
597
|
+
this.store.close();
|
|
598
|
+
}
|
|
599
|
+
createDocument(input) {
|
|
600
|
+
return this.store.createDocument(input);
|
|
601
|
+
}
|
|
602
|
+
readDocument(id) {
|
|
603
|
+
return this.store.readDocument(id);
|
|
604
|
+
}
|
|
605
|
+
propose(input) {
|
|
606
|
+
return this.store.propose(input);
|
|
607
|
+
}
|
|
608
|
+
decide(input) {
|
|
609
|
+
return this.store.decide(input);
|
|
610
|
+
}
|
|
611
|
+
updateContent(input) {
|
|
612
|
+
return this.store.updateContent(input);
|
|
613
|
+
}
|
|
614
|
+
createComment(input) {
|
|
615
|
+
return this.comments.create(input);
|
|
616
|
+
}
|
|
617
|
+
deleteComment(input) {
|
|
618
|
+
return this.comments.delete(input);
|
|
619
|
+
}
|
|
620
|
+
listComments(docId) {
|
|
621
|
+
return this.comments.list(docId);
|
|
622
|
+
}
|
|
623
|
+
completeCommentProcessing(input) {
|
|
624
|
+
return this.comments.completeProcessing(input);
|
|
625
|
+
}
|
|
626
|
+
findSend(id) {
|
|
627
|
+
return this.comments.findSend(id);
|
|
628
|
+
}
|
|
629
|
+
prepareSend(input) {
|
|
630
|
+
return this.comments.prepareSend(input);
|
|
631
|
+
}
|
|
632
|
+
finishSend(input) {
|
|
633
|
+
return this.comments.finishSend(input);
|
|
634
|
+
}
|
|
635
|
+
markInterruptedUnknown() {
|
|
636
|
+
return this.comments.markInterruptedUnknown();
|
|
637
|
+
}
|
|
638
|
+
listDocuments() {
|
|
639
|
+
return this.store.db.prepare("SELECT id,content,version,created_at,updated_at,(SELECT COUNT(*) FROM review_suggestions s WHERE s.doc_id=d.id AND s.status IN ('pending','conflicted')) AS pending FROM review_documents d ORDER BY COALESCE(NULLIF(updated_at,''), NULLIF(created_at,'')) DESC, rowid DESC").all();
|
|
640
|
+
}
|
|
641
|
+
listSuggestions(id, status) {
|
|
642
|
+
const doc = this.readDocument(id);
|
|
643
|
+
const allowed = /* @__PURE__ */ new Set(["all", "pending", "accepted", "rejected", "conflicted"]);
|
|
644
|
+
if (!allowed.has(status)) fail4("INVALID_INPUT", "Invalid suggestion status");
|
|
645
|
+
const rows = this.store.db.prepare("SELECT id,status,base_version,from_pos,to_pos,expected,replacement,author,created_at,created_order FROM review_suggestions WHERE doc_id=? ORDER BY created_order").all(id);
|
|
646
|
+
return { id, version: doc.version, suggestions: rows.filter((row) => status === "all" || row.status === status).map((row) => ({ id: row.id, status: row.status, baseVersion: row.base_version, from: row.from_pos, to: row.to_pos, expected: row.expected, replacement: row.replacement, author: row.author, createdAt: row.created_at || null, order: row.created_order })) };
|
|
647
|
+
}
|
|
648
|
+
deleteDocument(id) {
|
|
649
|
+
if (typeof id !== "string" || !id) fail4("INVALID_INPUT", "Document ID is required");
|
|
650
|
+
const db = this.store.db;
|
|
651
|
+
db.exec("BEGIN IMMEDIATE");
|
|
652
|
+
try {
|
|
653
|
+
if (!db.prepare("SELECT id FROM review_documents WHERE id=?").get(id)) fail4("DOCUMENT_NOT_FOUND", "Document not found");
|
|
654
|
+
if (db.prepare("SELECT id FROM space_comments WHERE doc_id=? AND status='sending' LIMIT 1").get(id)) fail4("COMMENT_BUSY", "A comment for this document is being sent");
|
|
655
|
+
db.prepare("DELETE FROM space_comments WHERE doc_id=?").run(id);
|
|
656
|
+
db.prepare("DELETE FROM space_comment_sends WHERE doc_id=?").run(id);
|
|
657
|
+
db.prepare("DELETE FROM space_comment_results WHERE doc_id=?").run(id);
|
|
658
|
+
db.prepare("DELETE FROM space_comment_completions WHERE doc_id=?").run(id);
|
|
659
|
+
db.prepare("DELETE FROM review_suggestions WHERE doc_id=?").run(id);
|
|
660
|
+
db.prepare("DELETE FROM review_changes WHERE doc_id=?").run(id);
|
|
661
|
+
for (const operation of db.prepare("SELECT id,result FROM review_operations").all()) {
|
|
662
|
+
try {
|
|
663
|
+
const result = JSON.parse(operation.result);
|
|
664
|
+
if (result?.id === id && typeof result.content === "string") db.prepare("DELETE FROM review_operations WHERE id=?").run(operation.id);
|
|
665
|
+
} catch {
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
db.prepare("DELETE FROM review_documents WHERE id=?").run(id);
|
|
669
|
+
db.exec("COMMIT");
|
|
670
|
+
return { id, deleted: true };
|
|
671
|
+
} catch (error) {
|
|
672
|
+
try {
|
|
673
|
+
db.exec("ROLLBACK");
|
|
674
|
+
} catch {
|
|
675
|
+
}
|
|
676
|
+
throw error;
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
};
|
|
680
|
+
|
|
681
|
+
// packages/review-core/src/space-service.js
|
|
682
|
+
var SPACE_ID = "personal";
|
|
683
|
+
function titleFor(content, id) {
|
|
684
|
+
const heading = content.match(/^#{1,6}\s+(.+)$/m)?.[1];
|
|
685
|
+
return (heading || content.trim().split(/\r?\n/)[0] || id).replace(/[*_`~\[\]#>]/g, "").slice(0, 100);
|
|
686
|
+
}
|
|
687
|
+
function documentWithTitle(title) {
|
|
688
|
+
if (typeof title !== "string" || !title.trim()) throw Object.assign(new Error("title must be a non-empty string"), { code: "INVALID_INPUT" });
|
|
689
|
+
const text = title.trim().slice(0, 100);
|
|
690
|
+
return `# ${text}
|
|
691
|
+
|
|
692
|
+
|
|
693
|
+
`;
|
|
694
|
+
}
|
|
695
|
+
var SpaceService = class {
|
|
696
|
+
constructor(home) {
|
|
697
|
+
if (typeof home !== "string" || !home) throw new Error("Space home is required");
|
|
698
|
+
this.home = import_node_path2.default.resolve(home);
|
|
699
|
+
(0, import_node_fs2.mkdirSync)(this.home, { recursive: true, mode: 448 });
|
|
700
|
+
const databaseFile = import_node_path2.default.join(this.home, "review.sqlite");
|
|
701
|
+
this.repository = new SpaceRepository(databaseFile);
|
|
702
|
+
}
|
|
703
|
+
close() {
|
|
704
|
+
this.repository.close();
|
|
705
|
+
}
|
|
706
|
+
listSpaces() {
|
|
707
|
+
return [{ id: SPACE_ID, name: "Space" }];
|
|
708
|
+
}
|
|
709
|
+
listDocuments() {
|
|
710
|
+
return this.repository.listDocuments().map((row) => ({ id: row.id, title: titleFor(row.content, row.id), version: row.version, pending: row.pending, createdAt: row.created_at || null, updatedAt: row.updated_at || null }));
|
|
711
|
+
}
|
|
712
|
+
createDocument({ id, content, operationId }) {
|
|
713
|
+
const created = this.repository.createDocument({ id, content, operationId });
|
|
714
|
+
return { ...created, title: titleFor(created.content, id) };
|
|
715
|
+
}
|
|
716
|
+
readDocument(id) {
|
|
717
|
+
const doc = this.repository.readDocument(id);
|
|
718
|
+
return { ...doc, title: titleFor(doc.content, id), comments: this.repository.listComments(id) };
|
|
719
|
+
}
|
|
720
|
+
/**
|
|
721
|
+
* Read the complete suggestion history, including decisions the UI already
|
|
722
|
+
* applied. `readDocument` intentionally returns pending/conflicted records
|
|
723
|
+
* only; an Agent needs the decided rows to know whether a proposal was
|
|
724
|
+
* accepted or rejected.
|
|
725
|
+
*/
|
|
726
|
+
listSuggestions(id, status = "all") {
|
|
727
|
+
return this.repository.listSuggestions(id, status);
|
|
728
|
+
}
|
|
729
|
+
deleteDocument(id) {
|
|
730
|
+
return this.repository.deleteDocument(id);
|
|
731
|
+
}
|
|
732
|
+
propose(input) {
|
|
733
|
+
return this.repository.propose(input);
|
|
734
|
+
}
|
|
735
|
+
decide(input) {
|
|
736
|
+
return this.repository.decide(input);
|
|
737
|
+
}
|
|
738
|
+
updateContent(input) {
|
|
739
|
+
return this.repository.updateContent(input);
|
|
740
|
+
}
|
|
741
|
+
createComment(input) {
|
|
742
|
+
return this.repository.createComment(input);
|
|
743
|
+
}
|
|
744
|
+
deleteComment(input) {
|
|
745
|
+
return this.repository.deleteComment(input);
|
|
746
|
+
}
|
|
747
|
+
listComments(docId) {
|
|
748
|
+
return this.repository.listComments(docId);
|
|
749
|
+
}
|
|
750
|
+
completeCommentProcessing(input) {
|
|
751
|
+
return this.repository.completeCommentProcessing(input);
|
|
752
|
+
}
|
|
753
|
+
findSend(id) {
|
|
754
|
+
return this.repository.findSend(id);
|
|
755
|
+
}
|
|
756
|
+
prepareSend(input) {
|
|
757
|
+
return this.repository.prepareSend(input);
|
|
758
|
+
}
|
|
759
|
+
finishSend(input) {
|
|
760
|
+
return this.repository.finishSend(input);
|
|
761
|
+
}
|
|
762
|
+
markInterruptedUnknown() {
|
|
763
|
+
return this.repository.markInterruptedUnknown();
|
|
764
|
+
}
|
|
765
|
+
};
|
|
766
|
+
|
|
767
|
+
// packages/host-api/src/index.js
|
|
768
|
+
var import_node_crypto4 = require("node:crypto");
|
|
769
|
+
|
|
770
|
+
// packages/adapter-contract/src/prompts.js
|
|
771
|
+
function commentProcessingPrompt(documentReference, commentIds) {
|
|
772
|
+
const ids = [...new Set(commentIds)];
|
|
773
|
+
return `${documentReference}
|
|
774
|
+
\u8BF7\u901A\u8FC7 CoSpace MCP \u6309\u8BC4\u8BBA\u63D0\u51FA\u4FEE\u6539\u5EFA\u8BAE\uFF0C\u53EA\u5904\u7406\u4EE5\u4E0B\u8BC4\u8BBA ID\uFF1A${ids.join("\u3001")}\u3002\u8C03\u7528 space_document_read \u8BFB\u53D6\u6B63\u6587\u548C\u8FD9\u4E9B\u8BC4\u8BBA\u7684\u5F15\u7528\u6587\u672C\u3001\u951A\u70B9\u53CA\u6B63\u6587\uFF1B\u9010\u6761\u7406\u89E3\u8BC4\u8BBA\uFF0C\u5E76\u5BF9\u6BCF\u6761\u660E\u786E\u4E14\u53EF\u5B9A\u4F4D\u7684\u4FEE\u6539\u8981\u6C42\u63D0\u4EA4\u5BF9\u5E94\u7684\u5177\u4F53\u5EFA\u8BAE\u3002\u4E0D\u8981\u53EA\u590D\u8FF0\u6216\u5206\u7C7B\u8BC4\u8BBA\uFF0C\u4E5F\u4E0D\u8981\u5728\u8BC4\u8BBA\u8981\u6C42\u4E4B\u5916\u81EA\u4E3B\u5BA1\u9605\u6216\u589E\u52A0\u5EFA\u8BAE\u3002\u8BC4\u8BBA\u542B\u7CCA\u6216\u65E0\u6CD5\u5B89\u5168\u5B9A\u4F4D\u65F6\uFF0C\u8BF4\u660E\u539F\u56E0\u5E76\u8BE2\u95EE\uFF0C\u4E0D\u8981\u731C\u6D4B\u3002\u5B8C\u6210\u540E\u8C03\u7528 space_comment_complete\uFF0C\u4E3A\u6BCF\u6761\u5DF2\u5904\u7406\u8BC4\u8BBA\u5173\u8054\u5BF9\u5E94\u5EFA\u8BAE ID\uFF1B\u672A\u5904\u7406\u7684\u8BC4\u8BBA\u4F20\u7A7A suggestionIds\uFF0C\u4F7F\u5176\u4FDD\u6301\u5F85\u5904\u7406\u3002\u4E0D\u8981\u76F4\u63A5\u8986\u76D6\u5DF2\u63A5\u53D7\u5185\u5BB9\uFF1B\u6240\u6709\u4FEE\u6539\u4EE5\u5EFA\u8BAE\u63D0\u4EA4\uFF0C\u7B49\u5F85\u6211\u5728 CoSpace \u4E2D\u63A5\u53D7\u6216\u62D2\u7EDD\u3002\u4E0D\u8981\u66FF\u6211\u53D1\u9001\u8BC4\u8BBA\u3002`;
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
// packages/host-api/src/index.js
|
|
778
|
+
function createHostApi({ home, prompt, getUser, resolveTarget, space: providedSpace, collaboration: providedCollaboration, markInterrupted = true }) {
|
|
779
|
+
const ownsSpace = !providedSpace;
|
|
780
|
+
const ownsCollaboration = !providedCollaboration;
|
|
781
|
+
const space = providedSpace || new SpaceService(home);
|
|
782
|
+
const collaboration = providedCollaboration || new CollaborationStore(home);
|
|
783
|
+
if (markInterrupted) space.markInterruptedUnknown();
|
|
784
|
+
const dispatch = async (method, args = {}) => {
|
|
785
|
+
switch (method) {
|
|
786
|
+
case "listSpaces":
|
|
787
|
+
return space.listSpaces();
|
|
788
|
+
case "listDocuments":
|
|
789
|
+
return space.listDocuments();
|
|
790
|
+
case "createDocument": {
|
|
791
|
+
const operationId = typeof args.operationId === "string" && args.operationId ? args.operationId : (0, import_node_crypto4.randomUUID)();
|
|
792
|
+
const title = typeof args.title === "string" ? args.title.trim() : "";
|
|
793
|
+
if (!title) throw Object.assign(new Error("Title required"), { code: "INVALID_INPUT" });
|
|
794
|
+
return space.createDocument({ id: `doc-${operationId}`.slice(0, 200), content: documentWithTitle(title), operationId });
|
|
795
|
+
}
|
|
796
|
+
case "readDocument":
|
|
797
|
+
return space.readDocument(args.docId);
|
|
798
|
+
case "readCollaboration":
|
|
799
|
+
return collaboration.readInstructions(args.docId);
|
|
800
|
+
case "saveInstructions":
|
|
801
|
+
return collaboration.saveInstructions(args);
|
|
802
|
+
case "deleteDocument": {
|
|
803
|
+
const result = space.deleteDocument(args.docId);
|
|
804
|
+
collaboration.deleteDocument(args.docId);
|
|
805
|
+
return result;
|
|
806
|
+
}
|
|
807
|
+
case "decide":
|
|
808
|
+
return space.decide(args);
|
|
809
|
+
case "updateDocument":
|
|
810
|
+
return space.updateContent(args);
|
|
811
|
+
case "listComments":
|
|
812
|
+
return space.listComments(args.docId);
|
|
813
|
+
case "createComment":
|
|
814
|
+
return space.createComment(args);
|
|
815
|
+
case "deleteComment":
|
|
816
|
+
return space.deleteComment(args);
|
|
817
|
+
case "getUser": {
|
|
818
|
+
if (typeof getUser !== "function") return null;
|
|
819
|
+
try {
|
|
820
|
+
return await getUser();
|
|
821
|
+
} catch {
|
|
822
|
+
return null;
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
case "sendComments": {
|
|
826
|
+
if (typeof prompt !== "function") throw Object.assign(new Error("\u5F53\u524D\u5BF9\u8BDD\u53D1\u9001\u80FD\u529B\u4E0D\u53EF\u7528"), { code: "SESSION_UNAVAILABLE" });
|
|
827
|
+
const operationId = args.operationId || (0, import_node_crypto4.randomUUID)();
|
|
828
|
+
const prior = space.findSend(operationId);
|
|
829
|
+
const requestedSessionId = prior?.sessionId || (typeof args.sessionId === "string" && args.sessionId !== "" ? args.sessionId : void 0);
|
|
830
|
+
let target;
|
|
831
|
+
if (requestedSessionId) {
|
|
832
|
+
target = { sessionId: requestedSessionId, created: false };
|
|
833
|
+
} else {
|
|
834
|
+
if (typeof resolveTarget !== "function") throw Object.assign(new Error("\u5F53\u524D\u5BF9\u8BDD\u53D1\u9001\u80FD\u529B\u4E0D\u53EF\u7528"), { code: "SESSION_UNAVAILABLE" });
|
|
835
|
+
target = await resolveTarget({ operationId, ...args.forceNew === true ? { forceNew: true } : {}, ...args.newSessionFrom ? { excludeSessionId: args.newSessionFrom } : {} });
|
|
836
|
+
if (!target?.sessionId) throw Object.assign(new Error("\u65E0\u6CD5\u786E\u5B9A\u53D1\u9001\u5BF9\u8BDD"), { code: "SESSION_UNAVAILABLE" });
|
|
837
|
+
}
|
|
838
|
+
const prepared = space.prepareSend({ ...args, sessionId: target.sessionId, operationId });
|
|
839
|
+
if (prepared.replay) return { requestId: operationId, status: prepared.status, sessionId: target.sessionId, createdSession: false };
|
|
840
|
+
const reference = `space:${encodeURIComponent(args.docId)}`;
|
|
841
|
+
const text = commentProcessingPrompt(reference, prepared.comments.map((comment) => comment.id));
|
|
842
|
+
try {
|
|
843
|
+
const receipt = await prompt({ requestId: operationId, sessionId: target.sessionId, mode: "queue", content: [{ type: "text", text }] });
|
|
844
|
+
if (receipt?.accepted !== true) throw new Error("\u5BBF\u4E3B\u672A\u786E\u8BA4\u63A5\u6536");
|
|
845
|
+
return {
|
|
846
|
+
...space.finishSend({ operationId, status: "sent" }),
|
|
847
|
+
sessionId: target.sessionId,
|
|
848
|
+
createdSession: target.created === true,
|
|
849
|
+
...target.workspace ? { workspace: target.workspace } : {}
|
|
850
|
+
};
|
|
851
|
+
} catch (error) {
|
|
852
|
+
return {
|
|
853
|
+
...space.finishSend({ operationId, status: "unknown", error: error?.message || "\u53D1\u9001\u7ED3\u679C\u672A\u77E5" }),
|
|
854
|
+
sessionId: target.sessionId,
|
|
855
|
+
createdSession: target.created === true,
|
|
856
|
+
...target.workspace ? { workspace: target.workspace } : {}
|
|
857
|
+
};
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
default:
|
|
861
|
+
throw Object.assign(new Error("\u672A\u77E5\u64CD\u4F5C"), { code: "METHOD_NOT_FOUND" });
|
|
862
|
+
}
|
|
863
|
+
};
|
|
864
|
+
return { dispatch, space, collaboration, close() {
|
|
865
|
+
if (ownsCollaboration) collaboration.close();
|
|
866
|
+
if (ownsSpace) space.close();
|
|
867
|
+
} };
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
// packages/transport-http/http-handler.js
|
|
871
|
+
var COSPACE_API_PATH = "/cospace-api";
|
|
872
|
+
function createHttpHandler(api, { token } = {}) {
|
|
873
|
+
return async (req, res) => {
|
|
874
|
+
if (token && req.headers?.["x-cospace-token"] !== token) {
|
|
875
|
+
res.writeHead(403, { "content-type": "application/json" });
|
|
876
|
+
res.end(JSON.stringify({ error: { code: "FORBIDDEN", message: "Invalid local session" } }));
|
|
877
|
+
return;
|
|
878
|
+
}
|
|
879
|
+
if (req.headers?.origin && req.headers.origin !== `http://${req.headers.host}`) {
|
|
880
|
+
res.writeHead(403, { "content-type": "application/json" });
|
|
881
|
+
res.end(JSON.stringify({ error: { code: "FORBIDDEN", message: "Cross-origin request denied" } }));
|
|
882
|
+
return;
|
|
883
|
+
}
|
|
884
|
+
if (req.url !== void 0 && req.url !== COSPACE_API_PATH) {
|
|
885
|
+
res.writeHead(404);
|
|
886
|
+
res.end();
|
|
887
|
+
return;
|
|
888
|
+
}
|
|
889
|
+
if (req.method !== "POST") {
|
|
890
|
+
res.writeHead(405, { "content-type": "application/json" });
|
|
891
|
+
res.end(JSON.stringify({ error: { code: "METHOD_NOT_ALLOWED", message: "\u4EC5\u652F\u6301 POST" } }));
|
|
892
|
+
return;
|
|
893
|
+
}
|
|
894
|
+
try {
|
|
895
|
+
let size = 0;
|
|
896
|
+
const chunks = [];
|
|
897
|
+
for await (const chunk of req) {
|
|
898
|
+
size += chunk.length;
|
|
899
|
+
if (size > 1024 * 1024) throw Object.assign(new Error("\u8BF7\u6C42\u8FC7\u5927"), { code: "LIMIT_EXCEEDED" });
|
|
900
|
+
chunks.push(chunk);
|
|
901
|
+
}
|
|
902
|
+
const input = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
903
|
+
const result = await api.dispatch(input.method, input.args);
|
|
904
|
+
res.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
905
|
+
res.end(JSON.stringify({ result }));
|
|
906
|
+
} catch (error) {
|
|
907
|
+
res.writeHead(400, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
908
|
+
res.end(JSON.stringify({ error: { code: error.code || "INVALID_INPUT", message: error.message || "\u8BF7\u6C42\u5931\u8D25", details: error.details } }));
|
|
909
|
+
}
|
|
910
|
+
};
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
// packages/local-runtime/src/paths.js
|
|
914
|
+
var import_node_crypto5 = require("node:crypto");
|
|
915
|
+
var import_node_os = require("node:os");
|
|
916
|
+
var import_node_fs3 = require("node:fs");
|
|
917
|
+
var import_node_path3 = __toESM(require("node:path"), 1);
|
|
918
|
+
var LOCAL_PROTOCOL_VERSION = 1;
|
|
919
|
+
function resolveDataHome(env = process.env) {
|
|
920
|
+
return import_node_path3.default.resolve(env.COSPACE_WEB_HOME || import_node_path3.default.join((0, import_node_os.homedir)(), ".cospace", "webapp"));
|
|
921
|
+
}
|
|
922
|
+
function canonicalPathIncludingMissingSegments(target) {
|
|
923
|
+
const resolved = import_node_path3.default.resolve(target);
|
|
924
|
+
const missingSegments = [];
|
|
925
|
+
let current = resolved;
|
|
926
|
+
while (true) {
|
|
927
|
+
try {
|
|
928
|
+
return import_node_path3.default.resolve(import_node_fs3.realpathSync.native(current), ...missingSegments);
|
|
929
|
+
} catch (error) {
|
|
930
|
+
if (error.code !== "ENOENT" && error.code !== "ENOTDIR") return resolved;
|
|
931
|
+
const parent = import_node_path3.default.dirname(current);
|
|
932
|
+
if (parent === current) return resolved;
|
|
933
|
+
missingSegments.unshift(import_node_path3.default.basename(current));
|
|
934
|
+
current = parent;
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
function appDataRoot(env, platform) {
|
|
939
|
+
if (platform === "win32") return env.LOCALAPPDATA || import_node_path3.default.join((0, import_node_os.homedir)(), "AppData", "Local");
|
|
940
|
+
if (platform === "darwin") return import_node_path3.default.join((0, import_node_os.homedir)(), "Library", "Application Support");
|
|
941
|
+
return env.XDG_DATA_HOME || import_node_path3.default.join((0, import_node_os.homedir)(), ".local", "share");
|
|
942
|
+
}
|
|
943
|
+
function resolveRuntimeHome({ dataHome = resolveDataHome(), env = process.env, platform = process.platform } = {}) {
|
|
944
|
+
const canonicalHome = canonicalPathIncludingMissingSegments(dataHome);
|
|
945
|
+
const profile = (0, import_node_crypto5.createHash)("sha256").update(canonicalHome).digest("hex").slice(0, 16);
|
|
946
|
+
return import_node_path3.default.join(appDataRoot(env, platform), "CoSpace", "local-server", "profiles", profile);
|
|
947
|
+
}
|
|
948
|
+
var endpointFile = (runtimeHome) => import_node_path3.default.join(runtimeHome, "endpoint.json");
|
|
949
|
+
var secretFile = (runtimeHome) => import_node_path3.default.join(runtimeHome, "secrets.json");
|
|
950
|
+
|
|
951
|
+
// packages/local-runtime/src/service.js
|
|
952
|
+
var MAX_RPC_BODY = 1024 * 1024;
|
|
953
|
+
var MCP_SESSION_TTL_MS = 6e4;
|
|
954
|
+
var UI_SESSION_TTL_MS = 10 * 6e4;
|
|
955
|
+
var json2 = (res, status, body) => {
|
|
956
|
+
res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
957
|
+
res.end(JSON.stringify(body));
|
|
958
|
+
};
|
|
959
|
+
async function readJsonBody(req) {
|
|
960
|
+
let size = 0;
|
|
961
|
+
const chunks = [];
|
|
962
|
+
for await (const chunk of req) {
|
|
963
|
+
size += chunk.length;
|
|
964
|
+
if (size > MAX_RPC_BODY) throw Object.assign(new Error("\u8BF7\u6C42\u8FC7\u5927"), { code: "LIMIT_EXCEEDED" });
|
|
965
|
+
chunks.push(chunk);
|
|
966
|
+
}
|
|
967
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
968
|
+
}
|
|
969
|
+
async function loadSecrets(runtimeHome) {
|
|
970
|
+
const file = secretFile(runtimeHome);
|
|
971
|
+
try {
|
|
972
|
+
return JSON.parse(await (0, import_promises.readFile)(file, "utf8"));
|
|
973
|
+
} catch (error) {
|
|
974
|
+
if (error.code !== "ENOENT") throw error;
|
|
975
|
+
const secrets = { uiToken: (0, import_node_crypto6.randomBytes)(32).toString("base64url"), rpcToken: (0, import_node_crypto6.randomBytes)(32).toString("base64url") };
|
|
976
|
+
await (0, import_promises.writeFile)(file, `${JSON.stringify(secrets)}
|
|
977
|
+
`, { mode: 384, flag: "wx" });
|
|
978
|
+
return secrets;
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
async function dispatchMcp(space, collaboration, method, args = {}) {
|
|
982
|
+
switch (method) {
|
|
983
|
+
case "createDocument":
|
|
984
|
+
return space.createDocument(args);
|
|
985
|
+
case "readDocument":
|
|
986
|
+
return space.readDocument(args.id);
|
|
987
|
+
case "propose":
|
|
988
|
+
return space.propose(args);
|
|
989
|
+
case "listSuggestions":
|
|
990
|
+
return space.listSuggestions(args.id, args.status || "all");
|
|
991
|
+
case "completeCommentProcessing":
|
|
992
|
+
return space.completeCommentProcessing(args);
|
|
993
|
+
case "readInstructions":
|
|
994
|
+
return collaboration.readInstructions(args.docId);
|
|
995
|
+
default:
|
|
996
|
+
throw Object.assign(new Error("\u672A\u77E5 MCP \u64CD\u4F5C"), { code: "METHOD_NOT_FOUND" });
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
async function startLocalService({ dataHome, runtimeHome, versionHome, version = "0.0.0", updaterEnabled = false, onEnableUpdater, host = "127.0.0.1", port = 0, allowStopWithUi = false } = {}) {
|
|
1000
|
+
if (!dataHome || !runtimeHome || !versionHome) throw new TypeError("dataHome, runtimeHome, and versionHome are required");
|
|
1001
|
+
await Promise.all([
|
|
1002
|
+
(0, import_promises.mkdir)(dataHome, { recursive: true, mode: 448 }),
|
|
1003
|
+
(0, import_promises.mkdir)(runtimeHome, { recursive: true, mode: 448 })
|
|
1004
|
+
]);
|
|
1005
|
+
const secrets = await loadSecrets(runtimeHome);
|
|
1006
|
+
const space = new SpaceService(dataHome);
|
|
1007
|
+
const collaboration = new CollaborationStore(dataHome);
|
|
1008
|
+
space.markInterruptedUnknown();
|
|
1009
|
+
const api = createHostApi({ home: dataHome, space, collaboration, markInterrupted: false });
|
|
1010
|
+
const uiHandler = createHttpHandler(api, { token: secrets.uiToken });
|
|
1011
|
+
const webRoot = import_node_path4.default.join(versionHome, "web");
|
|
1012
|
+
const runtimeId = import_node_path4.default.basename(runtimeHome);
|
|
1013
|
+
const mcpSessions = /* @__PURE__ */ new Map();
|
|
1014
|
+
const uiSessions = /* @__PURE__ */ new Map();
|
|
1015
|
+
let automaticUpdatesEnabled = updaterEnabled;
|
|
1016
|
+
let pendingUpgrade = null;
|
|
1017
|
+
let upgradeRunning = false;
|
|
1018
|
+
let serviceCloseForUpgrade;
|
|
1019
|
+
const maybeUpgrade = () => {
|
|
1020
|
+
if (!pendingUpgrade || upgradeRunning || mcpSessions.size || uiSessions.size) return;
|
|
1021
|
+
const target = pendingUpgrade;
|
|
1022
|
+
upgradeRunning = true;
|
|
1023
|
+
setTimeout(() => {
|
|
1024
|
+
void (0, import_promises.appendFile)(import_node_path4.default.join(runtimeHome, "upgrade.log"), `${(/* @__PURE__ */ new Date()).toISOString()} switching to ${target}
|
|
1025
|
+
`, { mode: 384 });
|
|
1026
|
+
void serviceCloseForUpgrade?.(target).catch((error) => {
|
|
1027
|
+
void (0, import_promises.appendFile)(import_node_path4.default.join(runtimeHome, "upgrade.log"), `${(/* @__PURE__ */ new Date()).toISOString()} switch failed: ${error.stack || error.message}
|
|
1028
|
+
`, { mode: 384 });
|
|
1029
|
+
upgradeRunning = false;
|
|
1030
|
+
});
|
|
1031
|
+
}, 500).unref?.();
|
|
1032
|
+
};
|
|
1033
|
+
const pruneSessions = () => {
|
|
1034
|
+
const expiredBefore = Date.now() - MCP_SESSION_TTL_MS;
|
|
1035
|
+
for (const [id, touchedAt] of mcpSessions) if (touchedAt < expiredBefore) mcpSessions.delete(id);
|
|
1036
|
+
const expiredUiBefore = Date.now() - UI_SESSION_TTL_MS;
|
|
1037
|
+
for (const [id, touchedAt] of uiSessions) if (touchedAt < expiredUiBefore) uiSessions.delete(id);
|
|
1038
|
+
maybeUpgrade();
|
|
1039
|
+
};
|
|
1040
|
+
let server;
|
|
1041
|
+
let endpoint;
|
|
1042
|
+
server = (0, import_node_http.createServer)(async (req, res) => {
|
|
1043
|
+
try {
|
|
1044
|
+
const expectedHost = endpoint ? `${host}:${endpoint.port}` : null;
|
|
1045
|
+
if (!expectedHost || req.headers.host !== expectedHost) {
|
|
1046
|
+
res.writeHead(403);
|
|
1047
|
+
res.end();
|
|
1048
|
+
return;
|
|
1049
|
+
}
|
|
1050
|
+
if (req.method === "GET" && req.url === "/__cospace/health") {
|
|
1051
|
+
pruneSessions();
|
|
1052
|
+
json2(res, 200, { ready: true, runtimeId, version, protocolVersion: LOCAL_PROTOCOL_VERSION, updaterEnabled: automaticUpdatesEnabled, activeMcpClients: mcpSessions.size, activeUiSessions: uiSessions.size });
|
|
1053
|
+
return;
|
|
1054
|
+
}
|
|
1055
|
+
if (req.method === "POST" && req.url === "/__cospace/mcp/session") {
|
|
1056
|
+
if (req.headers["x-cospace-rpc-token"] !== secrets.rpcToken) {
|
|
1057
|
+
json2(res, 403, { error: { code: "FORBIDDEN", message: "Invalid local RPC authorization" } });
|
|
1058
|
+
return;
|
|
1059
|
+
}
|
|
1060
|
+
if (!req.headers["content-type"]?.toLowerCase().startsWith("application/json")) {
|
|
1061
|
+
json2(res, 415, { error: { code: "UNSUPPORTED_MEDIA_TYPE", message: "JSON required" } });
|
|
1062
|
+
return;
|
|
1063
|
+
}
|
|
1064
|
+
const input = await readJsonBody(req);
|
|
1065
|
+
pruneSessions();
|
|
1066
|
+
if (input.action === "open" && typeof input.id === "string" && input.id.length >= 16 && input.id.length <= 128) mcpSessions.set(input.id, Date.now());
|
|
1067
|
+
else if (input.action === "heartbeat" && mcpSessions.has(input.id)) mcpSessions.set(input.id, Date.now());
|
|
1068
|
+
else if (input.action === "close") {
|
|
1069
|
+
mcpSessions.delete(input.id);
|
|
1070
|
+
maybeUpgrade();
|
|
1071
|
+
} else {
|
|
1072
|
+
json2(res, 400, { error: { code: "INVALID_SESSION", message: "Invalid MCP session action" } });
|
|
1073
|
+
return;
|
|
1074
|
+
}
|
|
1075
|
+
json2(res, 200, { result: { activeMcpClients: mcpSessions.size } });
|
|
1076
|
+
return;
|
|
1077
|
+
}
|
|
1078
|
+
if (req.method === "POST" && req.url === "/__cospace/ui/session") {
|
|
1079
|
+
if (req.headers["x-cospace-token"] !== secrets.uiToken || !req.headers["content-type"]?.toLowerCase().startsWith("application/json")) {
|
|
1080
|
+
json2(res, 403, { error: { code: "FORBIDDEN", message: "Invalid local UI session authorization" } });
|
|
1081
|
+
return;
|
|
1082
|
+
}
|
|
1083
|
+
const input = await readJsonBody(req);
|
|
1084
|
+
pruneSessions();
|
|
1085
|
+
if (!/^[0-9a-f-]{36}$/i.test(input.id || "")) {
|
|
1086
|
+
json2(res, 400, { error: { code: "INVALID_SESSION", message: "Invalid UI session id" } });
|
|
1087
|
+
return;
|
|
1088
|
+
}
|
|
1089
|
+
if (input.action === "open" || input.action === "heartbeat") uiSessions.set(input.id, Date.now());
|
|
1090
|
+
else if (input.action === "close") uiSessions.delete(input.id);
|
|
1091
|
+
else {
|
|
1092
|
+
json2(res, 400, { error: { code: "INVALID_SESSION", message: "Invalid UI session action" } });
|
|
1093
|
+
return;
|
|
1094
|
+
}
|
|
1095
|
+
maybeUpgrade();
|
|
1096
|
+
json2(res, 200, { result: { activeUiSessions: uiSessions.size } });
|
|
1097
|
+
return;
|
|
1098
|
+
}
|
|
1099
|
+
if (req.method === "POST" && req.url === "/__cospace/mcp/rpc") {
|
|
1100
|
+
if (req.headers["x-cospace-rpc-token"] !== secrets.rpcToken || req.headers.origin && req.headers.origin !== `http://${expectedHost}`) {
|
|
1101
|
+
json2(res, 403, { error: { code: "FORBIDDEN", message: "Invalid local RPC authorization" } });
|
|
1102
|
+
return;
|
|
1103
|
+
}
|
|
1104
|
+
if (!req.headers["content-type"]?.toLowerCase().startsWith("application/json")) {
|
|
1105
|
+
json2(res, 415, { error: { code: "UNSUPPORTED_MEDIA_TYPE", message: "JSON required" } });
|
|
1106
|
+
return;
|
|
1107
|
+
}
|
|
1108
|
+
const input = await readJsonBody(req);
|
|
1109
|
+
const result = await dispatchMcp(space, collaboration, input.method, input.args);
|
|
1110
|
+
json2(res, 200, { result });
|
|
1111
|
+
return;
|
|
1112
|
+
}
|
|
1113
|
+
if (req.method === "POST" && req.url === "/__cospace/control/stop") {
|
|
1114
|
+
if (req.headers["x-cospace-rpc-token"] !== secrets.rpcToken) {
|
|
1115
|
+
json2(res, 403, { error: { code: "FORBIDDEN", message: "Invalid service authorization" } });
|
|
1116
|
+
return;
|
|
1117
|
+
}
|
|
1118
|
+
pruneSessions();
|
|
1119
|
+
if (mcpSessions.size > 0 || !allowStopWithUi && uiSessions.size > 0) {
|
|
1120
|
+
json2(res, 409, { error: { code: "ACTIVE_MCP_CLIENTS", message: `Cannot stop CoSpace while ${mcpSessions.size} Agent and ${uiSessions.size} review page connection(s) are active.` } });
|
|
1121
|
+
return;
|
|
1122
|
+
}
|
|
1123
|
+
json2(res, 200, { result: { stopping: true } });
|
|
1124
|
+
setImmediate(() => process.kill(process.pid, "SIGTERM"));
|
|
1125
|
+
return;
|
|
1126
|
+
}
|
|
1127
|
+
if (req.method === "POST" && req.url === "/__cospace/control/upgrade") {
|
|
1128
|
+
if (req.headers["x-cospace-rpc-token"] !== secrets.rpcToken) {
|
|
1129
|
+
json2(res, 403, { error: { code: "FORBIDDEN", message: "Invalid service authorization" } });
|
|
1130
|
+
return;
|
|
1131
|
+
}
|
|
1132
|
+
const input = await readJsonBody(req);
|
|
1133
|
+
if (typeof input.version !== "string" || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(input.version)) {
|
|
1134
|
+
json2(res, 400, { error: { code: "INVALID_VERSION", message: "Invalid runtime version" } });
|
|
1135
|
+
return;
|
|
1136
|
+
}
|
|
1137
|
+
pruneSessions();
|
|
1138
|
+
const target = import_node_path4.default.join(import_node_path4.default.dirname(versionHome), input.version, "daemon.cjs");
|
|
1139
|
+
try {
|
|
1140
|
+
await (0, import_promises.readFile)(target);
|
|
1141
|
+
} catch {
|
|
1142
|
+
json2(res, 404, { error: { code: "RUNTIME_NOT_INSTALLED", message: "Runtime is not installed" } });
|
|
1143
|
+
return;
|
|
1144
|
+
}
|
|
1145
|
+
pendingUpgrade = input.version;
|
|
1146
|
+
json2(res, 200, { result: { scheduled: true, waitingForConnections: mcpSessions.size > 0 || uiSessions.size > 0 } });
|
|
1147
|
+
maybeUpgrade();
|
|
1148
|
+
return;
|
|
1149
|
+
}
|
|
1150
|
+
if (req.method === "POST" && req.url === "/__cospace/control/updater/enable") {
|
|
1151
|
+
if (req.headers["x-cospace-rpc-token"] !== secrets.rpcToken) {
|
|
1152
|
+
json2(res, 403, { error: { code: "FORBIDDEN", message: "Invalid service authorization" } });
|
|
1153
|
+
return;
|
|
1154
|
+
}
|
|
1155
|
+
automaticUpdatesEnabled = true;
|
|
1156
|
+
onEnableUpdater?.();
|
|
1157
|
+
json2(res, 200, { result: { enabled: true } });
|
|
1158
|
+
return;
|
|
1159
|
+
}
|
|
1160
|
+
if (req.method === "GET" && req.url === "/") {
|
|
1161
|
+
let html = await (0, import_promises.readFile)(import_node_path4.default.join(webRoot, "index.html"), "utf8");
|
|
1162
|
+
const uiSessionId = (0, import_node_crypto6.randomBytes)(18).toString("hex");
|
|
1163
|
+
uiSessions.set(uiSessionId, Date.now());
|
|
1164
|
+
html = html.replace("<!--COSPACE_TOKEN-->", `<script>window.__COSPACE_LOCAL_TOKEN__=${JSON.stringify(secrets.uiToken)};(()=>{const id=${JSON.stringify(uiSessionId)},token=${JSON.stringify(secrets.uiToken)},base='http://${host}:'+location.port;const send=action=>fetch(base+'/__cospace/ui/session',{method:'POST',headers:{'content-type':'application/json','x-cospace-token':token},body:JSON.stringify({id,action}),keepalive:action==='close'}).catch(()=>{});send('open');const timer=setInterval(()=>send('heartbeat'),20000);addEventListener('pagehide',()=>{clearInterval(timer);send('close')},{once:true})})()</script>`);
|
|
1165
|
+
res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
|
|
1166
|
+
res.end(html);
|
|
1167
|
+
return;
|
|
1168
|
+
}
|
|
1169
|
+
if (req.method === "GET" && (req.url === "/app.js" || req.url === "/app.css")) {
|
|
1170
|
+
const name = req.url.slice(1);
|
|
1171
|
+
const content = await (0, import_promises.readFile)(import_node_path4.default.join(webRoot, name));
|
|
1172
|
+
res.writeHead(200, { "content-type": name.endsWith(".js") ? "text/javascript; charset=utf-8" : "text/css; charset=utf-8", "cache-control": "no-store" });
|
|
1173
|
+
res.end(content);
|
|
1174
|
+
return;
|
|
1175
|
+
}
|
|
1176
|
+
if (req.url === "/cospace-api") {
|
|
1177
|
+
await uiHandler(req, res);
|
|
1178
|
+
return;
|
|
1179
|
+
}
|
|
1180
|
+
res.writeHead(404);
|
|
1181
|
+
res.end("Not found");
|
|
1182
|
+
} catch (error) {
|
|
1183
|
+
if (res.headersSent) {
|
|
1184
|
+
res.destroy(error);
|
|
1185
|
+
return;
|
|
1186
|
+
}
|
|
1187
|
+
json2(res, 400, { error: { code: error.code || "INVALID_REQUEST", message: error.message || "Request failed" } });
|
|
1188
|
+
}
|
|
1189
|
+
});
|
|
1190
|
+
await new Promise((resolve, reject) => {
|
|
1191
|
+
server.once("error", reject);
|
|
1192
|
+
server.listen(port, host, resolve);
|
|
1193
|
+
});
|
|
1194
|
+
const address = server.address();
|
|
1195
|
+
endpoint = { pid: process.pid, runtimeId, host, port: address.port, version, protocolVersion: LOCAL_PROTOCOL_VERSION };
|
|
1196
|
+
const endpointPath = endpointFile(runtimeHome);
|
|
1197
|
+
const tempPath = `${endpointPath}.${process.pid}.tmp`;
|
|
1198
|
+
await (0, import_promises.writeFile)(tempPath, `${JSON.stringify(endpoint)}
|
|
1199
|
+
`, { mode: 384 });
|
|
1200
|
+
await (0, import_promises.rename)(tempPath, endpointPath);
|
|
1201
|
+
await (0, import_promises.rm)(import_node_path4.default.join(runtimeHome, "start.lock"), { force: true });
|
|
1202
|
+
let closing;
|
|
1203
|
+
const close = () => closing ??= (async () => {
|
|
1204
|
+
await new Promise((resolve) => {
|
|
1205
|
+
server.close(resolve);
|
|
1206
|
+
server.closeAllConnections();
|
|
1207
|
+
});
|
|
1208
|
+
api.close();
|
|
1209
|
+
collaboration.close();
|
|
1210
|
+
space.close();
|
|
1211
|
+
try {
|
|
1212
|
+
const current = JSON.parse(await (0, import_promises.readFile)(endpointPath, "utf8"));
|
|
1213
|
+
if (current.pid === process.pid) await (0, import_promises.rm)(endpointPath, { force: true });
|
|
1214
|
+
} catch {
|
|
1215
|
+
}
|
|
1216
|
+
})();
|
|
1217
|
+
serviceCloseForUpgrade = async (version2) => {
|
|
1218
|
+
await (0, import_promises.appendFile)(import_node_path4.default.join(runtimeHome, "upgrade.log"), `${(/* @__PURE__ */ new Date()).toISOString()} closing old service
|
|
1219
|
+
`, { mode: 384 });
|
|
1220
|
+
await close();
|
|
1221
|
+
await (0, import_promises.appendFile)(import_node_path4.default.join(runtimeHome, "upgrade.log"), `${(/* @__PURE__ */ new Date()).toISOString()} old service closed
|
|
1222
|
+
`, { mode: 384 });
|
|
1223
|
+
const { spawn: spawn2 } = await import("node:child_process");
|
|
1224
|
+
const launch = (target) => {
|
|
1225
|
+
const targetHome = import_node_path4.default.join(import_node_path4.default.dirname(versionHome), target);
|
|
1226
|
+
const child = spawn2(process.execPath, [import_node_path4.default.join(targetHome, "daemon.cjs")], {
|
|
1227
|
+
detached: true,
|
|
1228
|
+
stdio: "ignore",
|
|
1229
|
+
windowsHide: true,
|
|
1230
|
+
env: { ...process.env, COSPACE_DATA_HOME: dataHome, COSPACE_RUNTIME_HOME: runtimeHome, COSPACE_VERSION_HOME: targetHome, COSPACE_PACKAGE_VERSION: target, COSPACE_AUTO_UPDATE: automaticUpdatesEnabled ? "1" : "0" }
|
|
1231
|
+
});
|
|
1232
|
+
child.once("error", (error) => {
|
|
1233
|
+
void (0, import_promises.appendFile)(import_node_path4.default.join(runtimeHome, "upgrade.log"), `${(/* @__PURE__ */ new Date()).toISOString()} ${target}: ${error.stack || error.message}
|
|
1234
|
+
`, { mode: 384 });
|
|
1235
|
+
});
|
|
1236
|
+
child.once("exit", (code, signal) => {
|
|
1237
|
+
void (0, import_promises.appendFile)(import_node_path4.default.join(runtimeHome, "upgrade.log"), `${(/* @__PURE__ */ new Date()).toISOString()} ${target} exited code=${code} signal=${signal}
|
|
1238
|
+
`, { mode: 384 });
|
|
1239
|
+
});
|
|
1240
|
+
child.unref();
|
|
1241
|
+
return child;
|
|
1242
|
+
};
|
|
1243
|
+
const healthy = async (target) => {
|
|
1244
|
+
const deadline = Date.now() + 15e3;
|
|
1245
|
+
while (Date.now() < deadline) {
|
|
1246
|
+
try {
|
|
1247
|
+
const current = JSON.parse(await (0, import_promises.readFile)(endpointPath, "utf8"));
|
|
1248
|
+
if (current.host !== host || !Number.isInteger(current.port)) throw new Error("Candidate endpoint is invalid");
|
|
1249
|
+
const response = await fetch(`http://${current.host}:${current.port}/__cospace/health`, { signal: AbortSignal.timeout(600) });
|
|
1250
|
+
const body = await response.json();
|
|
1251
|
+
if (response.ok && body.ready && body.version === target && body.runtimeId === runtimeId) return true;
|
|
1252
|
+
} catch {
|
|
1253
|
+
}
|
|
1254
|
+
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
1255
|
+
}
|
|
1256
|
+
return false;
|
|
1257
|
+
};
|
|
1258
|
+
const candidateProcess = launch(version2);
|
|
1259
|
+
await (0, import_promises.appendFile)(import_node_path4.default.join(runtimeHome, "upgrade.log"), `${(/* @__PURE__ */ new Date()).toISOString()} candidate spawned pid=${candidateProcess.pid}
|
|
1260
|
+
`, { mode: 384 });
|
|
1261
|
+
if (await healthy(version2)) {
|
|
1262
|
+
process.exit(0);
|
|
1263
|
+
return;
|
|
1264
|
+
}
|
|
1265
|
+
if (candidateProcess.exitCode === null && candidateProcess.signalCode === null) {
|
|
1266
|
+
candidateProcess.kill();
|
|
1267
|
+
await Promise.race([new Promise((resolve) => candidateProcess.once("exit", resolve)), new Promise((resolve) => setTimeout(resolve, 2e3))]);
|
|
1268
|
+
}
|
|
1269
|
+
await (0, import_promises.rm)(endpointPath, { force: true });
|
|
1270
|
+
launch(process.env.COSPACE_PREVIOUS_VERSION || endpoint.version);
|
|
1271
|
+
await healthy(process.env.COSPACE_PREVIOUS_VERSION || endpoint.version);
|
|
1272
|
+
process.exit(1);
|
|
1273
|
+
};
|
|
1274
|
+
return { ...endpoint, url: `http://${host}:${address.port}/`, uiToken: secrets.uiToken, rpcToken: secrets.rpcToken, close };
|
|
1275
|
+
}
|
|
1276
|
+
|
|
1277
|
+
// apps/local-server/src/daemon-entry.js
|
|
1278
|
+
var import_promises3 = require("node:fs/promises");
|
|
1279
|
+
var import_node_child_process = require("node:child_process");
|
|
1280
|
+
var import_node_os2 = __toESM(require("node:os"), 1);
|
|
1281
|
+
|
|
1282
|
+
// packages/local-runtime/src/manager.js
|
|
1283
|
+
var import_node_crypto7 = require("node:crypto");
|
|
1284
|
+
var import_promises2 = require("node:fs/promises");
|
|
1285
|
+
var import_node_path5 = __toESM(require("node:path"), 1);
|
|
1286
|
+
async function readEndpoint(runtimeHome) {
|
|
1287
|
+
try {
|
|
1288
|
+
return JSON.parse(await (0, import_promises2.readFile)(endpointFile(runtimeHome), "utf8"));
|
|
1289
|
+
} catch {
|
|
1290
|
+
return null;
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
async function readSecrets(runtimeHome) {
|
|
1294
|
+
try {
|
|
1295
|
+
return JSON.parse(await (0, import_promises2.readFile)(secretFile(runtimeHome), "utf8"));
|
|
1296
|
+
} catch {
|
|
1297
|
+
return null;
|
|
1298
|
+
}
|
|
1299
|
+
}
|
|
1300
|
+
async function installRuntimeVersion({ sourceVersionHome, runtimeHome, version }) {
|
|
1301
|
+
if (!sourceVersionHome || !runtimeHome || !version) throw new TypeError("sourceVersionHome, runtimeHome, and version are required");
|
|
1302
|
+
const versionHome = import_node_path5.default.join(runtimeHome, "versions", version);
|
|
1303
|
+
const assetFiles = ["daemon.cjs", "web/index.html", "web/app.js", "web/app.css"];
|
|
1304
|
+
const digests = async (home) => Object.fromEntries(await Promise.all(assetFiles.map(async (name) => {
|
|
1305
|
+
const content = await (0, import_promises2.readFile)(import_node_path5.default.join(home, name));
|
|
1306
|
+
return [name, (0, import_node_crypto7.createHash)("sha256").update(content).digest("hex")];
|
|
1307
|
+
})));
|
|
1308
|
+
const expectedHashes = await digests(sourceVersionHome);
|
|
1309
|
+
try {
|
|
1310
|
+
const marker = JSON.parse(await (0, import_promises2.readFile)(import_node_path5.default.join(versionHome, "runtime.json"), "utf8"));
|
|
1311
|
+
if (marker.version === version && marker.protocolVersion === LOCAL_PROTOCOL_VERSION && JSON.stringify(marker.hashes) === JSON.stringify(expectedHashes)) {
|
|
1312
|
+
const installedHashes2 = await digests(versionHome);
|
|
1313
|
+
if (JSON.stringify(installedHashes2) === JSON.stringify(expectedHashes)) return versionHome;
|
|
1314
|
+
}
|
|
1315
|
+
throw Object.assign(new Error(`Installed CoSpace runtime ${version} is incomplete or incompatible`), { code: "RUNTIME_ASSETS_INVALID" });
|
|
1316
|
+
} catch (error) {
|
|
1317
|
+
if (error.code !== "ENOENT" && error.code !== "ENOTDIR") throw error;
|
|
1318
|
+
}
|
|
1319
|
+
await (0, import_promises2.mkdir)(import_node_path5.default.join(runtimeHome, "versions"), { recursive: true, mode: 448 });
|
|
1320
|
+
const staging = `${versionHome}.staging-${process.pid}-${(0, import_node_crypto7.randomBytes)(6).toString("hex")}`;
|
|
1321
|
+
await (0, import_promises2.rm)(staging, { recursive: true, force: true });
|
|
1322
|
+
await (0, import_promises2.mkdir)(import_node_path5.default.join(staging, "web"), { recursive: true, mode: 448 });
|
|
1323
|
+
await (0, import_promises2.copyFile)(import_node_path5.default.join(sourceVersionHome, "daemon.cjs"), import_node_path5.default.join(staging, "daemon.cjs"));
|
|
1324
|
+
for (const name of ["index.html", "app.js", "app.css"]) await (0, import_promises2.copyFile)(import_node_path5.default.join(sourceVersionHome, "web", name), import_node_path5.default.join(staging, "web", name));
|
|
1325
|
+
const installedHashes = await digests(staging);
|
|
1326
|
+
if (JSON.stringify(installedHashes) !== JSON.stringify(expectedHashes)) {
|
|
1327
|
+
await (0, import_promises2.rm)(staging, { recursive: true, force: true });
|
|
1328
|
+
throw Object.assign(new Error("CoSpace runtime copy failed its integrity check"), { code: "RUNTIME_INTEGRITY_FAILED" });
|
|
1329
|
+
}
|
|
1330
|
+
await (0, import_promises2.writeFile)(import_node_path5.default.join(staging, "runtime.json"), `${JSON.stringify({ version, protocolVersion: LOCAL_PROTOCOL_VERSION, hashes: installedHashes })}
|
|
1331
|
+
`, { mode: 384 });
|
|
1332
|
+
try {
|
|
1333
|
+
await (0, import_promises2.rename)(staging, versionHome);
|
|
1334
|
+
} catch (error) {
|
|
1335
|
+
await (0, import_promises2.rm)(staging, { recursive: true, force: true });
|
|
1336
|
+
if (error.code !== "EEXIST" && error.code !== "ENOTEMPTY") throw error;
|
|
1337
|
+
try {
|
|
1338
|
+
const marker = JSON.parse(await (0, import_promises2.readFile)(import_node_path5.default.join(versionHome, "runtime.json"), "utf8"));
|
|
1339
|
+
if (marker.version === version && marker.protocolVersion === LOCAL_PROTOCOL_VERSION && JSON.stringify(marker.hashes) === JSON.stringify(expectedHashes)) return versionHome;
|
|
1340
|
+
} catch {
|
|
1341
|
+
}
|
|
1342
|
+
throw Object.assign(new Error(`Could not install CoSpace runtime ${version}`), { code: "RUNTIME_INSTALL_CONFLICT" });
|
|
1343
|
+
}
|
|
1344
|
+
return versionHome;
|
|
1345
|
+
}
|
|
1346
|
+
async function reachableEndpoint(runtimeHome) {
|
|
1347
|
+
const endpoint = await readEndpoint(runtimeHome);
|
|
1348
|
+
if (!endpoint || endpoint.runtimeId !== import_node_path5.default.basename(runtimeHome) || endpoint.host !== "127.0.0.1" || !Number.isInteger(endpoint.port) || endpoint.port < 1 || endpoint.port > 65535) return null;
|
|
1349
|
+
try {
|
|
1350
|
+
const response = await fetch(`http://${endpoint.host}:${endpoint.port}/__cospace/health`, { signal: AbortSignal.timeout(700) });
|
|
1351
|
+
const health = await response.json();
|
|
1352
|
+
if (!response.ok || health.ready !== true || health.runtimeId !== endpoint.runtimeId) return null;
|
|
1353
|
+
return { ...endpoint, version: health.version, protocolVersion: health.protocolVersion, updaterEnabled: health.updaterEnabled === true, activeMcpClients: health.activeMcpClients || 0 };
|
|
1354
|
+
} catch {
|
|
1355
|
+
return null;
|
|
1356
|
+
}
|
|
1357
|
+
}
|
|
1358
|
+
async function requestRuntimeUpgrade(runtimeHome, version) {
|
|
1359
|
+
const endpoint = await reachableEndpoint(runtimeHome);
|
|
1360
|
+
if (!endpoint) return { scheduled: false, reason: "service-unavailable" };
|
|
1361
|
+
const secrets = await readSecrets(runtimeHome);
|
|
1362
|
+
const response = await fetch(`http://${endpoint.host}:${endpoint.port}/__cospace/control/upgrade`, {
|
|
1363
|
+
method: "POST",
|
|
1364
|
+
headers: { "content-type": "application/json", "x-cospace-rpc-token": secrets?.rpcToken || "" },
|
|
1365
|
+
body: JSON.stringify({ version }),
|
|
1366
|
+
signal: AbortSignal.timeout(1500)
|
|
1367
|
+
});
|
|
1368
|
+
const body = await response.json().catch(() => ({}));
|
|
1369
|
+
if (!response.ok) return { scheduled: false, reason: body.error?.code || "upgrade-rejected" };
|
|
1370
|
+
return body.result;
|
|
1371
|
+
}
|
|
1372
|
+
|
|
1373
|
+
// apps/local-server/src/daemon-entry.js
|
|
1374
|
+
async function run() {
|
|
1375
|
+
const dataHome = import_node_path6.default.resolve(process.env.COSPACE_DATA_HOME || resolveDataHome());
|
|
1376
|
+
const runtimeHome = import_node_path6.default.resolve(process.env.COSPACE_RUNTIME_HOME || resolveRuntimeHome({ dataHome }));
|
|
1377
|
+
const versionHome = import_node_path6.default.resolve(process.env.COSPACE_VERSION_HOME || import_node_path6.default.dirname(process.argv[1]));
|
|
1378
|
+
const version = process.env.COSPACE_PACKAGE_VERSION || "0.0.0";
|
|
1379
|
+
let updaterEnabled = process.env.COSPACE_AUTO_UPDATE === "1";
|
|
1380
|
+
let updateTimer = null;
|
|
1381
|
+
let initialUpdateCheck = null;
|
|
1382
|
+
let checkForUpdate;
|
|
1383
|
+
const enableUpdater = () => {
|
|
1384
|
+
if (updaterEnabled) return;
|
|
1385
|
+
updaterEnabled = true;
|
|
1386
|
+
if (checkForUpdate) void checkForUpdate();
|
|
1387
|
+
updateTimer = setInterval(() => {
|
|
1388
|
+
void checkForUpdate?.();
|
|
1389
|
+
}, 6 * 60 * 60 * 1e3);
|
|
1390
|
+
updateTimer.unref?.();
|
|
1391
|
+
};
|
|
1392
|
+
const port = process.env.COSPACE_DEV_PORT ? Number(process.env.COSPACE_DEV_PORT) : 0;
|
|
1393
|
+
const service = await startLocalService({ dataHome, runtimeHome, versionHome, version, port, updaterEnabled, onEnableUpdater: enableUpdater, allowStopWithUi: process.env.COSPACE_DEV_ALLOW_UI_STOP === "1" });
|
|
1394
|
+
let checking = false;
|
|
1395
|
+
const npmInstall = (args) => new Promise((resolve, reject) => {
|
|
1396
|
+
const child = (0, import_node_child_process.spawn)(process.platform === "win32" ? "npm.cmd" : "npm", args, { windowsHide: true, shell: process.platform === "win32", stdio: ["ignore", "ignore", "pipe"] });
|
|
1397
|
+
let stderr = "";
|
|
1398
|
+
const timer = setTimeout(() => child.kill(), 12e4);
|
|
1399
|
+
child.stderr.on("data", (chunk) => {
|
|
1400
|
+
stderr += chunk.toString();
|
|
1401
|
+
});
|
|
1402
|
+
child.once("error", (error) => {
|
|
1403
|
+
clearTimeout(timer);
|
|
1404
|
+
reject(error);
|
|
1405
|
+
});
|
|
1406
|
+
child.once("close", (code) => {
|
|
1407
|
+
clearTimeout(timer);
|
|
1408
|
+
if (code === 0) resolve();
|
|
1409
|
+
else reject(new Error(stderr || `npm exited with status ${code}`));
|
|
1410
|
+
});
|
|
1411
|
+
});
|
|
1412
|
+
checkForUpdate = async () => {
|
|
1413
|
+
if (checking) return;
|
|
1414
|
+
checking = true;
|
|
1415
|
+
let temp;
|
|
1416
|
+
try {
|
|
1417
|
+
const registry = process.env.COSPACE_NPM_REGISTRY || "https://registry.npmjs.org";
|
|
1418
|
+
const response = await fetch(`${registry}/@hanfang5057%2fco-space/latest`, { headers: { accept: "application/vnd.npm.install-v1+json" }, signal: AbortSignal.timeout(1e4) });
|
|
1419
|
+
if (!response.ok) throw new Error(`npm registry returned ${response.status}`);
|
|
1420
|
+
const manifest = await response.json();
|
|
1421
|
+
const candidate = manifest.version;
|
|
1422
|
+
if (!/^\d+\.\d+\.\d+$/.test(candidate) || candidate.localeCompare(version, "en", { numeric: true }) <= 0) return;
|
|
1423
|
+
if (!manifest.dist?.integrity?.startsWith("sha512-")) throw new Error("npm package metadata has no SHA-512 integrity");
|
|
1424
|
+
temp = await (0, import_promises3.mkdtemp)(import_node_path6.default.join(import_node_os2.default.tmpdir(), "cospace-update-"));
|
|
1425
|
+
await npmInstall(["install", "--ignore-scripts", "--no-audit", "--no-fund", "--prefix", temp, `@hanfang5057/co-space@${candidate}`]);
|
|
1426
|
+
const packageDir = import_node_path6.default.join(temp, "node_modules", "@hanfang5057", "co-space");
|
|
1427
|
+
const source = import_node_path6.default.join(packageDir, "dist");
|
|
1428
|
+
const packageJson = JSON.parse(await (0, import_promises3.readFile)(import_node_path6.default.join(packageDir, "package.json"), "utf8"));
|
|
1429
|
+
if (packageJson.name !== "@hanfang5057/co-space" || packageJson.version !== candidate || packageJson.engines?.node !== ">=22.22.2") throw new Error("Downloaded package metadata is invalid");
|
|
1430
|
+
await installRuntimeVersion({ sourceVersionHome: source, runtimeHome, version: candidate });
|
|
1431
|
+
await requestRuntimeUpgrade(runtimeHome, candidate);
|
|
1432
|
+
} catch (error) {
|
|
1433
|
+
process.stderr.write(`CoSpace update check: ${error.message}
|
|
1434
|
+
`);
|
|
1435
|
+
} finally {
|
|
1436
|
+
if (temp) await (0, import_promises3.rm)(temp, { recursive: true, force: true });
|
|
1437
|
+
checking = false;
|
|
1438
|
+
}
|
|
1439
|
+
};
|
|
1440
|
+
if (updaterEnabled) {
|
|
1441
|
+
updateTimer = setInterval(() => {
|
|
1442
|
+
void checkForUpdate();
|
|
1443
|
+
}, 6 * 60 * 60 * 1e3);
|
|
1444
|
+
updateTimer.unref?.();
|
|
1445
|
+
initialUpdateCheck = setTimeout(() => {
|
|
1446
|
+
void checkForUpdate();
|
|
1447
|
+
}, 3e4);
|
|
1448
|
+
initialUpdateCheck.unref?.();
|
|
1449
|
+
}
|
|
1450
|
+
let stopping;
|
|
1451
|
+
const shutdown = () => stopping ??= (async () => {
|
|
1452
|
+
if (updateTimer) clearInterval(updateTimer);
|
|
1453
|
+
if (initialUpdateCheck) clearTimeout(initialUpdateCheck);
|
|
1454
|
+
await service.close();
|
|
1455
|
+
process.exit(0);
|
|
1456
|
+
})();
|
|
1457
|
+
process.once("SIGINT", shutdown);
|
|
1458
|
+
process.once("SIGTERM", shutdown);
|
|
1459
|
+
}
|
|
1460
|
+
run().catch((error) => {
|
|
1461
|
+
process.stderr.write(`CoSpace Local Server daemon: ${error.stack || error.message}
|
|
1462
|
+
`);
|
|
1463
|
+
process.exitCode = 1;
|
|
1464
|
+
});
|