@hanfang5057/co-space 0.1.9 → 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/README.md CHANGED
@@ -4,7 +4,7 @@ CoSpace Local Server provides stdio MCP tools and a local document-review web ap
4
4
 
5
5
  ## Configure an Agent
6
6
 
7
- Add this stdio MCP server to an Agent that supports Node.js 24 or later:
7
+ Add this stdio MCP server to an Agent that supports Node.js 22.22.2 or later:
8
8
 
9
9
  ```json
10
10
  {
@@ -17,7 +17,7 @@ Add this stdio MCP server to an Agent that supports Node.js 24 or later:
17
17
  }
18
18
  ```
19
19
 
20
- Restart or reconnect the Agent after changing its MCP configuration. The review URL is returned by MCP and can be opened later with `npx -y @hanfang5057/co-space@latest service open`. Publishing a newer package does not replace a running daemon: after all Agents disconnect, run `npx -y @hanfang5057/co-space@latest service restart`, then reconnect the Agent to apply the update.
20
+ Restart or reconnect the Agent after changing its MCP configuration. The review URL is returned by MCP and can be opened later with `npx -y @hanfang5057/co-space@latest service open`. Starting with the first release that includes automatic updates, the background service checks npm's `latest` release periodically, downloads and verifies it in the background, and switches versions when no Agent MCP connection is active. The first upgrade to that release still requires `npx -y @hanfang5057/co-space@latest service restart`; older daemons cannot update themselves. A service restart briefly disconnects the review page, which reconnects when reopened or refreshed. User data is kept in its existing data directory.
21
21
 
22
22
  ## Manage the local service
23
23
 
@@ -32,6 +32,14 @@ npx -y @hanfang5057/co-space@latest service rollback
32
32
  Stopping the service preserves user data. Uninstalling the package or removing an Agent's MCP configuration also preserves data.
33
33
  Stop or restart is refused while an Agent is actively connected; disconnect the Agent first.
34
34
 
35
+ ## Develop from the workspace
36
+
37
+ With Node.js 22.22.2 or later, run `npm install` and `npm run dev:local` at the repository root. The command builds and opens a separate development service, watches its source dependencies, and rebuilds on save. Refresh the page after a successful rebuild. The terminal reports errors without replacing the running service when a build fails. If an Agent is connected, the restart waits until it disconnects. Press Ctrl-C to stop; the development documents are preserved.
38
+
39
+ Development data defaults to `cospace-local-dev` under the system temporary directory. Set `COSPACE_DEV_HOME` to use another directory. Automatic npm updates are disabled for this service. To connect an Agent to the running development service, use `node` with the absolute path to `scripts/dev-local.mjs` followed by `mcp`; set the same `COSPACE_DEV_HOME` in the Agent environment when using a custom directory. This connection does not use the normal Local Server profile.
40
+
41
+ After stopping the watcher and disconnecting Agents, `node scripts/dev-local.mjs clean` removes accumulated development runtime builds without deleting documents.
42
+
35
43
  ## Local data
36
44
 
37
- By default, CoSpace uses the existing Desktop data directory `~/.cospace/webapp`. Set `COSPACE_WEB_HOME` to select another profile. Desktop and all generic Agent integrations using the same profile share one service and dataset. The DSH plugin remains isolated under its DSH-specific data home.
45
+ By default, CoSpace uses `~/.cospace/webapp`. Set `COSPACE_WEB_HOME` to select another profile. Agent integrations using the same profile share one service and dataset. The DSH plugin remains isolated under its DSH-specific data home.
File without changes
package/dist/cli.js CHANGED
@@ -117,7 +117,7 @@ async function reachableEndpoint(runtimeHome) {
117
117
  const response = await fetch(`http://${endpoint.host}:${endpoint.port}/__cospace/health`, { signal: AbortSignal.timeout(700) });
118
118
  const health = await response.json();
119
119
  if (!response.ok || health.ready !== true || health.runtimeId !== endpoint.runtimeId) return null;
120
- return { ...endpoint, version: health.version, protocolVersion: health.protocolVersion, activeMcpClients: health.activeMcpClients || 0 };
120
+ return { ...endpoint, version: health.version, protocolVersion: health.protocolVersion, updaterEnabled: health.updaterEnabled === true, activeMcpClients: health.activeMcpClients || 0 };
121
121
  } catch {
122
122
  return null;
123
123
  }
@@ -127,7 +127,7 @@ function assertCompatible(endpoint) {
127
127
  throw Object.assign(new Error(`CoSpace Local Server protocol ${endpoint.protocolVersion} is incompatible with this client. Stop or upgrade the service before reconnecting.`), { code: "LOCAL_SERVER_PROTOCOL_MISMATCH" });
128
128
  }
129
129
  }
130
- async function ensureLocalDaemon({ dataHome = resolveDataHome(), runtimeHome = resolveRuntimeHome({ dataHome }), versionHome, sourceVersionHome, version = "0.0.0", node = process.execPath, timeoutMs = 2e4 } = {}) {
130
+ async function ensureLocalDaemon({ dataHome = resolveDataHome(), runtimeHome = resolveRuntimeHome({ dataHome }), versionHome, sourceVersionHome, version = "0.0.0", autoUpdate = false, node = process.execPath, timeoutMs = 2e4 } = {}) {
131
131
  if (!versionHome) versionHome = await installRuntimeVersion({ sourceVersionHome, runtimeHome, version });
132
132
  await mkdir(runtimeHome, { recursive: true, mode: 448 });
133
133
  await ensureSecrets(runtimeHome);
@@ -190,7 +190,8 @@ async function ensureLocalDaemon({ dataHome = resolveDataHome(), runtimeHome = r
190
190
  COSPACE_DATA_HOME: dataHome,
191
191
  COSPACE_RUNTIME_HOME: runtimeHome,
192
192
  COSPACE_VERSION_HOME: versionHome,
193
- COSPACE_PACKAGE_VERSION: version
193
+ COSPACE_PACKAGE_VERSION: version,
194
+ COSPACE_AUTO_UPDATE: autoUpdate ? "1" : "0"
194
195
  }
195
196
  });
196
197
  child.unref();
@@ -241,6 +242,18 @@ async function stopLocalDaemon({ dataHome = resolveDataHome(), runtimeHome = res
241
242
  }
242
243
  throw Object.assign(new Error("CoSpace Local Server did not stop before the timeout"), { code: "LOCAL_SERVER_STOP_TIMEOUT" });
243
244
  }
245
+ async function enableLocalUpdater(runtimeHome) {
246
+ const endpoint = await reachableEndpoint(runtimeHome);
247
+ if (!endpoint) return false;
248
+ if (endpoint.updaterEnabled) return true;
249
+ const secrets = await readSecrets(runtimeHome);
250
+ const response = await fetch(`http://${endpoint.host}:${endpoint.port}/__cospace/control/updater/enable`, {
251
+ method: "POST",
252
+ headers: { "x-cospace-rpc-token": secrets?.rpcToken || "" },
253
+ signal: AbortSignal.timeout(2e3)
254
+ });
255
+ return response.ok;
256
+ }
244
257
  async function ensureSecrets(runtimeHome, { randomBytesFn = randomBytes } = {}) {
245
258
  await mkdir(runtimeHome, { recursive: true, mode: 448 });
246
259
  const file = secretFile(runtimeHome);
@@ -285,7 +298,9 @@ async function currentPaths() {
285
298
  }
286
299
  async function ensureService() {
287
300
  const paths = await currentPaths();
288
- return ensureLocalDaemon({ ...paths, version: metadata.version });
301
+ const endpoint = await ensureLocalDaemon({ ...paths, version: metadata.version, autoUpdate: true });
302
+ await enableLocalUpdater(paths.runtimeHome);
303
+ return endpoint;
289
304
  }
290
305
  async function rollbackService(targetVersion) {
291
306
  const dataHome = resolveDataHome();
@@ -308,7 +323,7 @@ async function rollbackService(targetVersion) {
308
323
  if (!target || !installed.includes(target)) throw new Error(targetVersion ? `Local Server runtime ${targetVersion} is not installed` : "No previous Local Server runtime is available to roll back to");
309
324
  const sourceVersionHome = path3.join(versionsRoot, target);
310
325
  const versionHome = await installRuntimeVersion({ sourceVersionHome, runtimeHome, version: target });
311
- const endpoint = await ensureLocalDaemon({ dataHome, runtimeHome, versionHome, version: target });
326
+ const endpoint = await ensureLocalDaemon({ dataHome, runtimeHome, versionHome, version: target, autoUpdate: true });
312
327
  return endpoint;
313
328
  }
314
329
  async function runMcp() {
package/dist/daemon.cjs CHANGED
@@ -22,7 +22,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
22
22
  ));
23
23
 
24
24
  // apps/local-server/src/daemon-entry.js
25
- var import_node_path5 = __toESM(require("node:path"), 1);
25
+ var import_node_path6 = __toESM(require("node:path"), 1);
26
26
 
27
27
  // packages/local-runtime/src/service.js
28
28
  var import_node_crypto6 = require("node:crypto");
@@ -133,8 +133,8 @@ var fingerprint = (x) => (0, import_node_crypto2.createHash)("sha256").update(js
133
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
134
  var context = (s, from, to) => ({ before: s.slice(Math.max(0, from - 32), from), after: s.slice(to, to + 32) });
135
135
  var ReviewStore = class {
136
- constructor(path6) {
137
- this.db = new import_node_sqlite2.DatabaseSync(path6, { timeout: 5e3 });
136
+ constructor(path7) {
137
+ this.db = new import_node_sqlite2.DatabaseSync(path7, { timeout: 5e3 });
138
138
  this.db.exec("PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA busy_timeout=5000");
139
139
  const old = this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='review_documents'").get();
140
140
  const marker = this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='space_meta'").get();
@@ -767,7 +767,7 @@ var SpaceService = class {
767
767
  // packages/host-api/src/index.js
768
768
  var import_node_crypto4 = require("node:crypto");
769
769
 
770
- // ../../../Users/hanfang/codes/dsh-space/packages/adapter-contract/src/prompts.js
770
+ // packages/adapter-contract/src/prompts.js
771
771
  function commentProcessingPrompt(documentReference, commentIds) {
772
772
  const ids = [...new Set(commentIds)];
773
773
  return `${documentReference}
@@ -951,6 +951,7 @@ var secretFile = (runtimeHome) => import_node_path3.default.join(runtimeHome, "s
951
951
  // packages/local-runtime/src/service.js
952
952
  var MAX_RPC_BODY = 1024 * 1024;
953
953
  var MCP_SESSION_TTL_MS = 6e4;
954
+ var UI_SESSION_TTL_MS = 10 * 6e4;
954
955
  var json2 = (res, status, body) => {
955
956
  res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
956
957
  res.end(JSON.stringify(body));
@@ -995,7 +996,7 @@ async function dispatchMcp(space, collaboration, method, args = {}) {
995
996
  throw Object.assign(new Error("\u672A\u77E5 MCP \u64CD\u4F5C"), { code: "METHOD_NOT_FOUND" });
996
997
  }
997
998
  }
998
- async function startLocalService({ dataHome, runtimeHome, versionHome, version = "0.0.0", host = "127.0.0.1", port = 0 } = {}) {
999
+ async function startLocalService({ dataHome, runtimeHome, versionHome, version = "0.0.0", updaterEnabled = false, onEnableUpdater, host = "127.0.0.1", port = 0, allowStopWithUi = false } = {}) {
999
1000
  if (!dataHome || !runtimeHome || !versionHome) throw new TypeError("dataHome, runtimeHome, and versionHome are required");
1000
1001
  await Promise.all([
1001
1002
  (0, import_promises.mkdir)(dataHome, { recursive: true, mode: 448 }),
@@ -1010,9 +1011,31 @@ async function startLocalService({ dataHome, runtimeHome, versionHome, version =
1010
1011
  const webRoot = import_node_path4.default.join(versionHome, "web");
1011
1012
  const runtimeId = import_node_path4.default.basename(runtimeHome);
1012
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
+ };
1013
1033
  const pruneSessions = () => {
1014
1034
  const expiredBefore = Date.now() - MCP_SESSION_TTL_MS;
1015
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();
1016
1039
  };
1017
1040
  let server;
1018
1041
  let endpoint;
@@ -1026,7 +1049,7 @@ async function startLocalService({ dataHome, runtimeHome, versionHome, version =
1026
1049
  }
1027
1050
  if (req.method === "GET" && req.url === "/__cospace/health") {
1028
1051
  pruneSessions();
1029
- json2(res, 200, { ready: true, runtimeId, version, protocolVersion: LOCAL_PROTOCOL_VERSION, activeMcpClients: mcpSessions.size });
1052
+ json2(res, 200, { ready: true, runtimeId, version, protocolVersion: LOCAL_PROTOCOL_VERSION, updaterEnabled: automaticUpdatesEnabled, activeMcpClients: mcpSessions.size, activeUiSessions: uiSessions.size });
1030
1053
  return;
1031
1054
  }
1032
1055
  if (req.method === "POST" && req.url === "/__cospace/mcp/session") {
@@ -1042,14 +1065,37 @@ async function startLocalService({ dataHome, runtimeHome, versionHome, version =
1042
1065
  pruneSessions();
1043
1066
  if (input.action === "open" && typeof input.id === "string" && input.id.length >= 16 && input.id.length <= 128) mcpSessions.set(input.id, Date.now());
1044
1067
  else if (input.action === "heartbeat" && mcpSessions.has(input.id)) mcpSessions.set(input.id, Date.now());
1045
- else if (input.action === "close") mcpSessions.delete(input.id);
1046
- else {
1068
+ else if (input.action === "close") {
1069
+ mcpSessions.delete(input.id);
1070
+ maybeUpgrade();
1071
+ } else {
1047
1072
  json2(res, 400, { error: { code: "INVALID_SESSION", message: "Invalid MCP session action" } });
1048
1073
  return;
1049
1074
  }
1050
1075
  json2(res, 200, { result: { activeMcpClients: mcpSessions.size } });
1051
1076
  return;
1052
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
+ }
1053
1099
  if (req.method === "POST" && req.url === "/__cospace/mcp/rpc") {
1054
1100
  if (req.headers["x-cospace-rpc-token"] !== secrets.rpcToken || req.headers.origin && req.headers.origin !== `http://${expectedHost}`) {
1055
1101
  json2(res, 403, { error: { code: "FORBIDDEN", message: "Invalid local RPC authorization" } });
@@ -1070,17 +1116,52 @@ async function startLocalService({ dataHome, runtimeHome, versionHome, version =
1070
1116
  return;
1071
1117
  }
1072
1118
  pruneSessions();
1073
- if (mcpSessions.size > 0) {
1074
- json2(res, 409, { error: { code: "ACTIVE_MCP_CLIENTS", message: `Cannot stop CoSpace while ${mcpSessions.size} Agent MCP connection(s) are active.` } });
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.` } });
1075
1121
  return;
1076
1122
  }
1077
1123
  json2(res, 200, { result: { stopping: true } });
1078
1124
  setImmediate(() => process.kill(process.pid, "SIGTERM"));
1079
1125
  return;
1080
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
+ }
1081
1160
  if (req.method === "GET" && req.url === "/") {
1082
1161
  let html = await (0, import_promises.readFile)(import_node_path4.default.join(webRoot, "index.html"), "utf8");
1083
- html = html.replace("<!--COSPACE_TOKEN-->", `<script>window.__COSPACE_LOCAL_TOKEN__=${JSON.stringify(secrets.uiToken)}</script>`);
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>`);
1084
1165
  res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
1085
1166
  res.end(html);
1086
1167
  return;
@@ -1120,7 +1201,10 @@ async function startLocalService({ dataHome, runtimeHome, versionHome, version =
1120
1201
  await (0, import_promises.rm)(import_node_path4.default.join(runtimeHome, "start.lock"), { force: true });
1121
1202
  let closing;
1122
1203
  const close = () => closing ??= (async () => {
1123
- await new Promise((resolve) => server.close(resolve));
1204
+ await new Promise((resolve) => {
1205
+ server.close(resolve);
1206
+ server.closeAllConnections();
1207
+ });
1124
1208
  api.close();
1125
1209
  collaboration.close();
1126
1210
  space.close();
@@ -1130,18 +1214,246 @@ async function startLocalService({ dataHome, runtimeHome, versionHome, version =
1130
1214
  } catch {
1131
1215
  }
1132
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
+ };
1133
1274
  return { ...endpoint, url: `http://${host}:${address.port}/`, uiToken: secrets.uiToken, rpcToken: secrets.rpcToken, close };
1134
1275
  }
1135
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
+
1136
1373
  // apps/local-server/src/daemon-entry.js
1137
1374
  async function run() {
1138
- const dataHome = import_node_path5.default.resolve(process.env.COSPACE_DATA_HOME || resolveDataHome());
1139
- const runtimeHome = import_node_path5.default.resolve(process.env.COSPACE_RUNTIME_HOME || resolveRuntimeHome({ dataHome }));
1140
- const versionHome = import_node_path5.default.resolve(process.env.COSPACE_VERSION_HOME || import_node_path5.default.dirname(process.argv[1]));
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]));
1141
1378
  const version = process.env.COSPACE_PACKAGE_VERSION || "0.0.0";
1142
- const service = await startLocalService({ dataHome, runtimeHome, versionHome, version });
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
+ }
1143
1450
  let stopping;
1144
- const shutdown = () => stopping ??= service.close().finally(() => process.exit(0));
1451
+ const shutdown = () => stopping ??= (async () => {
1452
+ if (updateTimer) clearInterval(updateTimer);
1453
+ if (initialUpdateCheck) clearTimeout(initialUpdateCheck);
1454
+ await service.close();
1455
+ process.exit(0);
1456
+ })();
1145
1457
  process.once("SIGINT", shutdown);
1146
1458
  process.once("SIGTERM", shutdown);
1147
1459
  }