@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/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 hanfang
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,45 @@
|
|
|
1
|
-
#
|
|
1
|
+
# CoSpace Local Server
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
CoSpace Local Server provides stdio MCP tools and a local document-review web app. The Agent MCP process starts or connects to a separate local daemon. The daemon keeps serving the review page after the Agent exits.
|
|
4
|
+
|
|
5
|
+
## Configure an Agent
|
|
6
|
+
|
|
7
|
+
Add this stdio MCP server to an Agent that supports Node.js 22.22.2 or later:
|
|
8
|
+
|
|
9
|
+
```json
|
|
10
|
+
{
|
|
11
|
+
"mcpServers": {
|
|
12
|
+
"cospace": {
|
|
13
|
+
"command": "npx",
|
|
14
|
+
"args": ["-y", "@hanfang5057/co-space@latest", "mcp"]
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
```
|
|
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`. 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
|
+
|
|
22
|
+
## Manage the local service
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
npx -y @hanfang5057/co-space@latest service status
|
|
26
|
+
npx -y @hanfang5057/co-space@latest service open
|
|
27
|
+
npx -y @hanfang5057/co-space@latest service stop
|
|
28
|
+
npx -y @hanfang5057/co-space@latest service restart
|
|
29
|
+
npx -y @hanfang5057/co-space@latest service rollback
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Stopping the service preserves user data. Uninstalling the package or removing an Agent's MCP configuration also preserves data.
|
|
33
|
+
Stop or restart is refused while an Agent is actively connected; disconnect the Agent first.
|
|
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
|
+
|
|
43
|
+
## Local data
|
|
44
|
+
|
|
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.
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
// apps/local-server/src/cli.js
|
|
2
|
+
import { readFile as readFile2, readdir } from "node:fs/promises";
|
|
3
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
4
|
+
import path3 from "node:path";
|
|
5
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
6
|
+
|
|
7
|
+
// packages/local-runtime/src/manager.js
|
|
8
|
+
import { createHash as createHash2, randomBytes } from "node:crypto";
|
|
9
|
+
import { open, mkdir, readFile, rm, stat, writeFile, copyFile, rename, chmod } from "node:fs/promises";
|
|
10
|
+
import { spawn } from "node:child_process";
|
|
11
|
+
import path2 from "node:path";
|
|
12
|
+
|
|
13
|
+
// packages/local-runtime/src/paths.js
|
|
14
|
+
import { createHash } from "node:crypto";
|
|
15
|
+
import { homedir } from "node:os";
|
|
16
|
+
import { realpathSync } from "node:fs";
|
|
17
|
+
import path from "node:path";
|
|
18
|
+
var LOCAL_PROTOCOL_VERSION = 1;
|
|
19
|
+
function resolveDataHome(env = process.env) {
|
|
20
|
+
return path.resolve(env.COSPACE_WEB_HOME || path.join(homedir(), ".cospace", "webapp"));
|
|
21
|
+
}
|
|
22
|
+
function canonicalPathIncludingMissingSegments(target) {
|
|
23
|
+
const resolved = path.resolve(target);
|
|
24
|
+
const missingSegments = [];
|
|
25
|
+
let current = resolved;
|
|
26
|
+
while (true) {
|
|
27
|
+
try {
|
|
28
|
+
return path.resolve(realpathSync.native(current), ...missingSegments);
|
|
29
|
+
} catch (error) {
|
|
30
|
+
if (error.code !== "ENOENT" && error.code !== "ENOTDIR") return resolved;
|
|
31
|
+
const parent = path.dirname(current);
|
|
32
|
+
if (parent === current) return resolved;
|
|
33
|
+
missingSegments.unshift(path.basename(current));
|
|
34
|
+
current = parent;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
function appDataRoot(env, platform) {
|
|
39
|
+
if (platform === "win32") return env.LOCALAPPDATA || path.join(homedir(), "AppData", "Local");
|
|
40
|
+
if (platform === "darwin") return path.join(homedir(), "Library", "Application Support");
|
|
41
|
+
return env.XDG_DATA_HOME || path.join(homedir(), ".local", "share");
|
|
42
|
+
}
|
|
43
|
+
function resolveRuntimeHome({ dataHome = resolveDataHome(), env = process.env, platform = process.platform } = {}) {
|
|
44
|
+
const canonicalHome = canonicalPathIncludingMissingSegments(dataHome);
|
|
45
|
+
const profile = createHash("sha256").update(canonicalHome).digest("hex").slice(0, 16);
|
|
46
|
+
return path.join(appDataRoot(env, platform), "CoSpace", "local-server", "profiles", profile);
|
|
47
|
+
}
|
|
48
|
+
var endpointFile = (runtimeHome) => path.join(runtimeHome, "endpoint.json");
|
|
49
|
+
var secretFile = (runtimeHome) => path.join(runtimeHome, "secrets.json");
|
|
50
|
+
|
|
51
|
+
// packages/local-runtime/src/manager.js
|
|
52
|
+
var sleep = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
|
|
53
|
+
async function readEndpoint(runtimeHome) {
|
|
54
|
+
try {
|
|
55
|
+
return JSON.parse(await readFile(endpointFile(runtimeHome), "utf8"));
|
|
56
|
+
} catch {
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
async function readSecrets(runtimeHome) {
|
|
61
|
+
try {
|
|
62
|
+
return JSON.parse(await readFile(secretFile(runtimeHome), "utf8"));
|
|
63
|
+
} catch {
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
async function installRuntimeVersion({ sourceVersionHome, runtimeHome, version }) {
|
|
68
|
+
if (!sourceVersionHome || !runtimeHome || !version) throw new TypeError("sourceVersionHome, runtimeHome, and version are required");
|
|
69
|
+
const versionHome = path2.join(runtimeHome, "versions", version);
|
|
70
|
+
const assetFiles = ["daemon.cjs", "web/index.html", "web/app.js", "web/app.css"];
|
|
71
|
+
const digests = async (home) => Object.fromEntries(await Promise.all(assetFiles.map(async (name) => {
|
|
72
|
+
const content = await readFile(path2.join(home, name));
|
|
73
|
+
return [name, createHash2("sha256").update(content).digest("hex")];
|
|
74
|
+
})));
|
|
75
|
+
const expectedHashes = await digests(sourceVersionHome);
|
|
76
|
+
try {
|
|
77
|
+
const marker = JSON.parse(await readFile(path2.join(versionHome, "runtime.json"), "utf8"));
|
|
78
|
+
if (marker.version === version && marker.protocolVersion === LOCAL_PROTOCOL_VERSION && JSON.stringify(marker.hashes) === JSON.stringify(expectedHashes)) {
|
|
79
|
+
const installedHashes2 = await digests(versionHome);
|
|
80
|
+
if (JSON.stringify(installedHashes2) === JSON.stringify(expectedHashes)) return versionHome;
|
|
81
|
+
}
|
|
82
|
+
throw Object.assign(new Error(`Installed CoSpace runtime ${version} is incomplete or incompatible`), { code: "RUNTIME_ASSETS_INVALID" });
|
|
83
|
+
} catch (error) {
|
|
84
|
+
if (error.code !== "ENOENT" && error.code !== "ENOTDIR") throw error;
|
|
85
|
+
}
|
|
86
|
+
await mkdir(path2.join(runtimeHome, "versions"), { recursive: true, mode: 448 });
|
|
87
|
+
const staging = `${versionHome}.staging-${process.pid}-${randomBytes(6).toString("hex")}`;
|
|
88
|
+
await rm(staging, { recursive: true, force: true });
|
|
89
|
+
await mkdir(path2.join(staging, "web"), { recursive: true, mode: 448 });
|
|
90
|
+
await copyFile(path2.join(sourceVersionHome, "daemon.cjs"), path2.join(staging, "daemon.cjs"));
|
|
91
|
+
for (const name of ["index.html", "app.js", "app.css"]) await copyFile(path2.join(sourceVersionHome, "web", name), path2.join(staging, "web", name));
|
|
92
|
+
const installedHashes = await digests(staging);
|
|
93
|
+
if (JSON.stringify(installedHashes) !== JSON.stringify(expectedHashes)) {
|
|
94
|
+
await rm(staging, { recursive: true, force: true });
|
|
95
|
+
throw Object.assign(new Error("CoSpace runtime copy failed its integrity check"), { code: "RUNTIME_INTEGRITY_FAILED" });
|
|
96
|
+
}
|
|
97
|
+
await writeFile(path2.join(staging, "runtime.json"), `${JSON.stringify({ version, protocolVersion: LOCAL_PROTOCOL_VERSION, hashes: installedHashes })}
|
|
98
|
+
`, { mode: 384 });
|
|
99
|
+
try {
|
|
100
|
+
await rename(staging, versionHome);
|
|
101
|
+
} catch (error) {
|
|
102
|
+
await rm(staging, { recursive: true, force: true });
|
|
103
|
+
if (error.code !== "EEXIST" && error.code !== "ENOTEMPTY") throw error;
|
|
104
|
+
try {
|
|
105
|
+
const marker = JSON.parse(await readFile(path2.join(versionHome, "runtime.json"), "utf8"));
|
|
106
|
+
if (marker.version === version && marker.protocolVersion === LOCAL_PROTOCOL_VERSION && JSON.stringify(marker.hashes) === JSON.stringify(expectedHashes)) return versionHome;
|
|
107
|
+
} catch {
|
|
108
|
+
}
|
|
109
|
+
throw Object.assign(new Error(`Could not install CoSpace runtime ${version}`), { code: "RUNTIME_INSTALL_CONFLICT" });
|
|
110
|
+
}
|
|
111
|
+
return versionHome;
|
|
112
|
+
}
|
|
113
|
+
async function reachableEndpoint(runtimeHome) {
|
|
114
|
+
const endpoint = await readEndpoint(runtimeHome);
|
|
115
|
+
if (!endpoint || endpoint.runtimeId !== path2.basename(runtimeHome) || endpoint.host !== "127.0.0.1" || !Number.isInteger(endpoint.port) || endpoint.port < 1 || endpoint.port > 65535) return null;
|
|
116
|
+
try {
|
|
117
|
+
const response = await fetch(`http://${endpoint.host}:${endpoint.port}/__cospace/health`, { signal: AbortSignal.timeout(700) });
|
|
118
|
+
const health = await response.json();
|
|
119
|
+
if (!response.ok || health.ready !== true || health.runtimeId !== endpoint.runtimeId) return null;
|
|
120
|
+
return { ...endpoint, version: health.version, protocolVersion: health.protocolVersion, updaterEnabled: health.updaterEnabled === true, activeMcpClients: health.activeMcpClients || 0 };
|
|
121
|
+
} catch {
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
function assertCompatible(endpoint) {
|
|
126
|
+
if (endpoint && endpoint.protocolVersion !== LOCAL_PROTOCOL_VERSION) {
|
|
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
|
+
}
|
|
129
|
+
}
|
|
130
|
+
async function ensureLocalDaemon({ dataHome = resolveDataHome(), runtimeHome = resolveRuntimeHome({ dataHome }), versionHome, sourceVersionHome, version = "0.0.0", autoUpdate = false, node = process.execPath, timeoutMs = 2e4 } = {}) {
|
|
131
|
+
if (!versionHome) versionHome = await installRuntimeVersion({ sourceVersionHome, runtimeHome, version });
|
|
132
|
+
await mkdir(runtimeHome, { recursive: true, mode: 448 });
|
|
133
|
+
await ensureSecrets(runtimeHome);
|
|
134
|
+
let endpoint = await reachableEndpoint(runtimeHome);
|
|
135
|
+
assertCompatible(endpoint);
|
|
136
|
+
if (endpoint) {
|
|
137
|
+
const secrets = await readSecrets(runtimeHome);
|
|
138
|
+
if (!secrets?.rpcToken || !secrets?.uiToken) throw new Error("CoSpace service credentials are missing; stop and restart the service to recover.");
|
|
139
|
+
return { ...endpoint, dataHome, runtimeHome, rpcToken: secrets.rpcToken, uiToken: secrets.uiToken };
|
|
140
|
+
}
|
|
141
|
+
const lockPath = path2.join(runtimeHome, "start.lock");
|
|
142
|
+
const nonce = randomBytes(16).toString("hex");
|
|
143
|
+
const deadline = Date.now() + timeoutMs;
|
|
144
|
+
let ownsLock = false;
|
|
145
|
+
while (Date.now() < deadline) {
|
|
146
|
+
endpoint = await reachableEndpoint(runtimeHome);
|
|
147
|
+
assertCompatible(endpoint);
|
|
148
|
+
if (endpoint) {
|
|
149
|
+
const secrets = await readSecrets(runtimeHome);
|
|
150
|
+
if (!secrets?.rpcToken || !secrets?.uiToken) throw new Error("CoSpace service credentials are missing; stop and restart the service to recover.");
|
|
151
|
+
return { ...endpoint, dataHome, runtimeHome, rpcToken: secrets.rpcToken, uiToken: secrets.uiToken };
|
|
152
|
+
}
|
|
153
|
+
try {
|
|
154
|
+
const lock = await open(lockPath, "wx", 384);
|
|
155
|
+
await lock.writeFile(JSON.stringify({ pid: process.pid, nonce, startedAt: Date.now() }));
|
|
156
|
+
await lock.close();
|
|
157
|
+
ownsLock = true;
|
|
158
|
+
break;
|
|
159
|
+
} catch (error) {
|
|
160
|
+
if (error.code !== "EEXIST") throw error;
|
|
161
|
+
let lockInfo = null;
|
|
162
|
+
try {
|
|
163
|
+
lockInfo = JSON.parse(await readFile(lockPath, "utf8"));
|
|
164
|
+
} catch {
|
|
165
|
+
}
|
|
166
|
+
if (lockInfo?.pid && lockInfo.pid !== process.pid) {
|
|
167
|
+
try {
|
|
168
|
+
process.kill(lockInfo.pid, 0);
|
|
169
|
+
} catch {
|
|
170
|
+
await rm(lockPath, { force: true });
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
} else {
|
|
174
|
+
const info = await stat(lockPath).catch(() => null);
|
|
175
|
+
if (info && Date.now() - info.mtimeMs > timeoutMs) await rm(lockPath, { force: true });
|
|
176
|
+
}
|
|
177
|
+
await sleep(200);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
if (ownsLock) {
|
|
181
|
+
const daemonPath = path2.join(versionHome, "daemon.cjs");
|
|
182
|
+
const logHandle = await open(path2.join(runtimeHome, "daemon.log"), "a", 384);
|
|
183
|
+
try {
|
|
184
|
+
const child = spawn(node, [daemonPath], {
|
|
185
|
+
detached: true,
|
|
186
|
+
windowsHide: true,
|
|
187
|
+
stdio: ["ignore", logHandle.fd, logHandle.fd],
|
|
188
|
+
env: {
|
|
189
|
+
...process.env,
|
|
190
|
+
COSPACE_DATA_HOME: dataHome,
|
|
191
|
+
COSPACE_RUNTIME_HOME: runtimeHome,
|
|
192
|
+
COSPACE_VERSION_HOME: versionHome,
|
|
193
|
+
COSPACE_PACKAGE_VERSION: version,
|
|
194
|
+
COSPACE_AUTO_UPDATE: autoUpdate ? "1" : "0"
|
|
195
|
+
}
|
|
196
|
+
});
|
|
197
|
+
child.unref();
|
|
198
|
+
} finally {
|
|
199
|
+
await logHandle.close();
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
while (Date.now() < deadline) {
|
|
203
|
+
endpoint = await reachableEndpoint(runtimeHome);
|
|
204
|
+
assertCompatible(endpoint);
|
|
205
|
+
if (endpoint) {
|
|
206
|
+
const secrets = await readSecrets(runtimeHome);
|
|
207
|
+
if (!secrets?.rpcToken) throw new Error("CoSpace service started without an RPC credential");
|
|
208
|
+
return { ...endpoint, dataHome, runtimeHome, rpcToken: secrets.rpcToken, uiToken: secrets.uiToken };
|
|
209
|
+
}
|
|
210
|
+
await sleep(200);
|
|
211
|
+
}
|
|
212
|
+
if (ownsLock) {
|
|
213
|
+
try {
|
|
214
|
+
const lockInfo = JSON.parse(await readFile(lockPath, "utf8"));
|
|
215
|
+
if (lockInfo.nonce === nonce) await rm(lockPath, { force: true });
|
|
216
|
+
} catch {
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
throw Object.assign(new Error("CoSpace Local Server did not become ready. Run `cospace-local service status` for details."), { code: "LOCAL_SERVER_START_TIMEOUT" });
|
|
220
|
+
}
|
|
221
|
+
async function localServiceStatus({ dataHome = resolveDataHome(), runtimeHome = resolveRuntimeHome({ dataHome }) } = {}) {
|
|
222
|
+
const endpoint = await reachableEndpoint(runtimeHome);
|
|
223
|
+
return endpoint ? { running: true, compatible: endpoint.protocolVersion === LOCAL_PROTOCOL_VERSION, ...endpoint, url: `http://${endpoint.host}:${endpoint.port}/` } : { running: false, dataHome, runtimeHome };
|
|
224
|
+
}
|
|
225
|
+
async function stopLocalDaemon({ dataHome = resolveDataHome(), runtimeHome = resolveRuntimeHome({ dataHome }), timeoutMs = 8e3 } = {}) {
|
|
226
|
+
const endpoint = await reachableEndpoint(runtimeHome);
|
|
227
|
+
if (!endpoint) return { stopped: true, wasRunning: false };
|
|
228
|
+
const secrets = await readSecrets(runtimeHome);
|
|
229
|
+
const response = await fetch(`http://${endpoint.host}:${endpoint.port}/__cospace/control/stop`, {
|
|
230
|
+
method: "POST",
|
|
231
|
+
headers: { "x-cospace-rpc-token": secrets?.rpcToken || "" },
|
|
232
|
+
signal: AbortSignal.timeout(1500)
|
|
233
|
+
});
|
|
234
|
+
if (!response.ok) {
|
|
235
|
+
const body = await response.json().catch(() => ({}));
|
|
236
|
+
throw Object.assign(new Error(body.error?.message || `CoSpace service refused to stop (${response.status})`), { code: body.error?.code || "LOCAL_SERVER_STOP_REJECTED", details: body.error?.details });
|
|
237
|
+
}
|
|
238
|
+
const deadline = Date.now() + timeoutMs;
|
|
239
|
+
while (Date.now() < deadline) {
|
|
240
|
+
if (!await reachableEndpoint(runtimeHome)) return { stopped: true, wasRunning: true };
|
|
241
|
+
await sleep(150);
|
|
242
|
+
}
|
|
243
|
+
throw Object.assign(new Error("CoSpace Local Server did not stop before the timeout"), { code: "LOCAL_SERVER_STOP_TIMEOUT" });
|
|
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
|
+
}
|
|
257
|
+
async function ensureSecrets(runtimeHome, { randomBytesFn = randomBytes } = {}) {
|
|
258
|
+
await mkdir(runtimeHome, { recursive: true, mode: 448 });
|
|
259
|
+
const file = secretFile(runtimeHome);
|
|
260
|
+
try {
|
|
261
|
+
const secrets = JSON.parse(await readFile(file, "utf8"));
|
|
262
|
+
if (typeof secrets?.uiToken !== "string" || typeof secrets?.rpcToken !== "string") throw Object.assign(new Error("Invalid CoSpace credentials file"), { code: "LOCAL_SERVER_CREDENTIALS_INVALID" });
|
|
263
|
+
await chmod(file, 384).catch(() => {
|
|
264
|
+
});
|
|
265
|
+
return secrets;
|
|
266
|
+
} catch (error) {
|
|
267
|
+
if (error.code !== "ENOENT") throw error;
|
|
268
|
+
const secrets = { uiToken: randomBytesFn(32).toString("base64url"), rpcToken: randomBytesFn(32).toString("base64url") };
|
|
269
|
+
try {
|
|
270
|
+
await writeFile(file, `${JSON.stringify(secrets)}
|
|
271
|
+
`, { mode: 384, flag: "wx" });
|
|
272
|
+
} catch (writeError) {
|
|
273
|
+
if (writeError.code !== "EEXIST") throw writeError;
|
|
274
|
+
}
|
|
275
|
+
const saved = JSON.parse(await readFile(file, "utf8"));
|
|
276
|
+
if (typeof saved?.uiToken !== "string" || typeof saved?.rpcToken !== "string") throw Object.assign(new Error("Invalid CoSpace credentials file"), { code: "LOCAL_SERVER_CREDENTIALS_INVALID" });
|
|
277
|
+
return saved;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// apps/local-server/src/cli.js
|
|
282
|
+
var distRoot = path3.dirname(fileURLToPath(import.meta.url));
|
|
283
|
+
var metadata = JSON.parse(await readFile2(path3.join(distRoot, "package.json"), "utf8"));
|
|
284
|
+
function openBrowser(url) {
|
|
285
|
+
const [command, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", url]] : ["xdg-open", [url]];
|
|
286
|
+
const child = spawn2(command, args, { detached: true, stdio: "ignore", windowsHide: true });
|
|
287
|
+
child.once("error", (error) => {
|
|
288
|
+
process.stderr.write(`Could not open browser: ${error.message}
|
|
289
|
+
`);
|
|
290
|
+
});
|
|
291
|
+
child.unref();
|
|
292
|
+
}
|
|
293
|
+
async function currentPaths() {
|
|
294
|
+
const dataHome = resolveDataHome();
|
|
295
|
+
const runtimeHome = resolveRuntimeHome({ dataHome });
|
|
296
|
+
const versionHome = await installRuntimeVersion({ sourceVersionHome: distRoot, runtimeHome, version: metadata.version });
|
|
297
|
+
return { dataHome, runtimeHome, versionHome };
|
|
298
|
+
}
|
|
299
|
+
async function ensureService() {
|
|
300
|
+
const paths = await currentPaths();
|
|
301
|
+
const endpoint = await ensureLocalDaemon({ ...paths, version: metadata.version, autoUpdate: true });
|
|
302
|
+
await enableLocalUpdater(paths.runtimeHome);
|
|
303
|
+
return endpoint;
|
|
304
|
+
}
|
|
305
|
+
async function rollbackService(targetVersion) {
|
|
306
|
+
const dataHome = resolveDataHome();
|
|
307
|
+
const runtimeHome = resolveRuntimeHome({ dataHome });
|
|
308
|
+
const running = await localServiceStatus({ dataHome, runtimeHome });
|
|
309
|
+
if (running.running) await stopLocalDaemon({ dataHome, runtimeHome });
|
|
310
|
+
const versionsRoot = path3.join(runtimeHome, "versions");
|
|
311
|
+
const names = await readdir(versionsRoot).catch(() => []);
|
|
312
|
+
const installed = [];
|
|
313
|
+
for (const name of names) {
|
|
314
|
+
if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(name)) continue;
|
|
315
|
+
try {
|
|
316
|
+
const marker = JSON.parse(await readFile2(path3.join(versionsRoot, name, "runtime.json"), "utf8"));
|
|
317
|
+
if (marker.version === name && marker.protocolVersion === metadata.protocolVersion) installed.push(name);
|
|
318
|
+
} catch {
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
const currentVersion = running.version || metadata.version;
|
|
322
|
+
const target = targetVersion || installed.filter((version) => version.localeCompare(currentVersion, "en", { numeric: true }) < 0).sort((left, right) => right.localeCompare(left, "en", { numeric: true }))[0];
|
|
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");
|
|
324
|
+
const sourceVersionHome = path3.join(versionsRoot, target);
|
|
325
|
+
const versionHome = await installRuntimeVersion({ sourceVersionHome, runtimeHome, version: target });
|
|
326
|
+
const endpoint = await ensureLocalDaemon({ dataHome, runtimeHome, versionHome, version: target, autoUpdate: true });
|
|
327
|
+
return endpoint;
|
|
328
|
+
}
|
|
329
|
+
async function runMcp() {
|
|
330
|
+
const endpoint = await ensureService();
|
|
331
|
+
const { startStdioMcp } = await import(pathToFileURL(path3.join(distRoot, "mcp.cjs")).href);
|
|
332
|
+
await startStdioMcp({ ...endpoint, url: `http://${endpoint.host}:${endpoint.port}/` }, { packageVersion: metadata.version });
|
|
333
|
+
}
|
|
334
|
+
async function runService(command, argument2) {
|
|
335
|
+
if (command === "status") {
|
|
336
|
+
const status = await localServiceStatus();
|
|
337
|
+
process.stdout.write(status.running ? `CoSpace Local Server ${status.version}
|
|
338
|
+
${status.url}
|
|
339
|
+
Active Agent connections: ${status.activeMcpClients}
|
|
340
|
+
` : "CoSpace Local Server is not running.\n");
|
|
341
|
+
return;
|
|
342
|
+
}
|
|
343
|
+
if (command === "stop") {
|
|
344
|
+
const result = await stopLocalDaemon();
|
|
345
|
+
process.stdout.write(result.wasRunning ? "CoSpace Local Server stopped. Data was preserved.\n" : "CoSpace Local Server was not running.\n");
|
|
346
|
+
return;
|
|
347
|
+
}
|
|
348
|
+
if (command === "start" || command === "restart") {
|
|
349
|
+
if (command === "restart") await stopLocalDaemon();
|
|
350
|
+
const endpoint = await ensureService();
|
|
351
|
+
process.stdout.write(`CoSpace Local Server ${endpoint.version} is running at http://${endpoint.host}:${endpoint.port}/
|
|
352
|
+
`);
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
if (command === "rollback") {
|
|
356
|
+
const endpoint = await rollbackService(argument2);
|
|
357
|
+
process.stdout.write(`CoSpace Local Server rolled back to ${endpoint.version} at http://${endpoint.host}:${endpoint.port}/
|
|
358
|
+
`);
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
361
|
+
if (command === "open") {
|
|
362
|
+
const endpoint = await ensureService();
|
|
363
|
+
openBrowser(`http://${endpoint.host}:${endpoint.port}/`);
|
|
364
|
+
process.stdout.write(`Opening CoSpace at http://${endpoint.host}:${endpoint.port}/
|
|
365
|
+
`);
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
throw new Error(`Unknown service command: ${command || "(missing)"}`);
|
|
369
|
+
}
|
|
370
|
+
var [mode = "mcp", subcommand, argument] = process.argv.slice(2);
|
|
371
|
+
try {
|
|
372
|
+
if (mode === "mcp") await runMcp();
|
|
373
|
+
else if (mode === "service") await runService(subcommand, argument);
|
|
374
|
+
else throw new Error(`Unknown command: ${mode}`);
|
|
375
|
+
} catch (error) {
|
|
376
|
+
process.stderr.write(`CoSpace Local Server: ${error.message}
|
|
377
|
+
`);
|
|
378
|
+
process.exitCode = 1;
|
|
379
|
+
}
|