@neta-art/cohub-cli 10.15.0 → 10.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,250 @@
1
+ import { spawn } from "node:child_process";
2
+ import { mkdirSync, watch } from "node:fs";
3
+ import { readdir, realpath, stat } from "node:fs/promises";
4
+ import { homedir } from "node:os";
5
+ import { basename, dirname, join, relative, sep } from "node:path";
6
+ import { EXPECTED_IDENTITY_ENV } from "../runtime/launch.js";
7
+ import { requestRuntimeInstance, runtimeInstanceDirectory, runtimeInstancesRoot, stopRuntimeInstance, watchRuntimeInstance } from "../runtime/instance.js";
8
+ import { readRuntimeSpaceBindings, runtimeSpaceBindingsPath } from "../runtime/space-binding.js";
9
+ import { forgetHostRuntime, hostRuntimes, rememberHostRuntime } from "./runtimes.js";
10
+ const MAX_INSTANCES = 256;
11
+ const MAX_FOLDERS = 10_000;
12
+ const MAX_VOLUMES = 16;
13
+ const isRunning = (instance) => instance?.state === "connecting" || instance?.state === "ready";
14
+ const samePath = (a, b) => process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;
15
+ function deviceState(status) {
16
+ if (!status || status.state === "stopping")
17
+ return "stopped";
18
+ if (status.state === "ready")
19
+ return "ready";
20
+ return status.state === "attention" ? "error" : "connecting";
21
+ }
22
+ function displayPath(path, home = homedir()) {
23
+ if (process.platform === "win32")
24
+ return path;
25
+ const inside = relative(home, path);
26
+ if (!inside)
27
+ return "~";
28
+ return inside.startsWith("..") || inside.startsWith(sep) ? path : `~/${inside}`;
29
+ }
30
+ async function isDirectory(path) {
31
+ return stat(path).then((info) => info.isDirectory(), () => false);
32
+ }
33
+ async function volumes() {
34
+ const home = homedir();
35
+ const homeVolume = { path: home, label: basename(home) || home };
36
+ if (process.platform === "win32") {
37
+ const drives = await Promise.all([..."CDEFGHIJKLMNOPQRSTUVWXYZ"].map(async (letter) => {
38
+ const path = `${letter}:\\`;
39
+ return await isDirectory(path) ? { path, label: `${letter}:` } : null;
40
+ }));
41
+ return [homeVolume, ...drives.filter((drive) => drive !== null)].slice(0, MAX_VOLUMES);
42
+ }
43
+ if (process.platform === "darwin") {
44
+ const mounted = await readdir("/Volumes").catch(() => []);
45
+ const resolved = await Promise.all(mounted.map(async (name) => {
46
+ const path = await realpath(join("/Volumes", name)).catch(() => null);
47
+ return path ? { path, label: name } : null;
48
+ }));
49
+ return [homeVolume, ...resolved.filter((volume) => volume !== null)].slice(0, MAX_VOLUMES);
50
+ }
51
+ return [homeVolume, { path: "/", label: "/" }];
52
+ }
53
+ export class DeviceRuntimeHost {
54
+ emit;
55
+ options;
56
+ #watchers = [];
57
+ #subscriptions = new Map();
58
+ #debounce;
59
+ #published = "";
60
+ #restoring = Promise.resolve();
61
+ #unwatchable = new Set();
62
+ constructor(emit, options) {
63
+ this.emit = emit;
64
+ this.options = options;
65
+ }
66
+ watch() {
67
+ this.#watch();
68
+ void this.restore();
69
+ }
70
+ close() {
71
+ clearTimeout(this.#debounce);
72
+ for (const watcher of this.#watchers)
73
+ watcher.close();
74
+ for (const subscription of this.#subscriptions.values())
75
+ subscription.abort();
76
+ }
77
+ #watch() {
78
+ const bindings = runtimeSpaceBindingsPath();
79
+ const instances = runtimeInstancesRoot();
80
+ mkdirSync(dirname(bindings), { recursive: true, mode: 0o700 });
81
+ mkdirSync(instances, { recursive: true, mode: 0o700 });
82
+ const watchers = [
83
+ watch(dirname(bindings), (_event, name) => { if (!name || name === basename(bindings))
84
+ this.changed(); }),
85
+ watch(instances, { recursive: true }, () => this.changed()),
86
+ ];
87
+ this.#watchers = watchers;
88
+ const rewatch = () => {
89
+ if (this.#watchers !== watchers)
90
+ return;
91
+ this.#watchers = [];
92
+ for (const watcher of watchers)
93
+ watcher.close();
94
+ setTimeout(() => { this.#watch(); this.changed(); }, 1_000).unref();
95
+ };
96
+ for (const watcher of watchers)
97
+ watcher.on("error", rewatch);
98
+ }
99
+ changed() {
100
+ clearTimeout(this.#debounce);
101
+ this.#debounce = setTimeout(() => void this.#publish().catch(() => undefined), 100);
102
+ }
103
+ async list() {
104
+ const key = this.options.account();
105
+ if (!key)
106
+ return { instances: [] };
107
+ const bindings = (await readRuntimeSpaceBindings().catch(() => ({ bindings: [] }))).bindings;
108
+ const roots = new Map();
109
+ for (const binding of bindings) {
110
+ if (binding.key !== key)
111
+ continue;
112
+ roots.delete(binding.spaceId);
113
+ roots.set(binding.spaceId, binding.root);
114
+ }
115
+ const instances = await Promise.all([...roots].slice(-MAX_INSTANCES).map(async ([spaceId, root]) => {
116
+ const directory = runtimeInstanceDirectory(key, spaceId);
117
+ try {
118
+ const status = await requestRuntimeInstance(directory);
119
+ if (status)
120
+ this.#subscribe(directory, status.pid);
121
+ const path = status?.root ?? root;
122
+ return { spaceId, root: path, label: displayPath(path), state: deviceState(status), error: status?.state === "attention" ? "attention" : null };
123
+ }
124
+ catch {
125
+ return { spaceId, root, label: displayPath(root), state: "error", error: "unreachable" };
126
+ }
127
+ }));
128
+ return { instances };
129
+ }
130
+ async browse(path) {
131
+ const target = await realpath(path ?? homedir());
132
+ if (!await isDirectory(target))
133
+ throw new Error("Not a folder");
134
+ const entries = await readdir(target, { withFileTypes: true });
135
+ const folders = (await Promise.all(entries.map(async (entry) => {
136
+ if (entry.name.startsWith("."))
137
+ return null;
138
+ const folder = join(target, entry.name);
139
+ const directory = entry.isDirectory() || (entry.isSymbolicLink() && await isDirectory(folder));
140
+ return directory ? { name: entry.name, path: folder } : null;
141
+ })))
142
+ .filter((folder) => folder !== null)
143
+ .sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: "base" }))
144
+ .slice(0, MAX_FOLDERS);
145
+ const key = this.options.account();
146
+ const bindings = key ? (await readRuntimeSpaceBindings().catch(() => ({ bindings: [] }))).bindings : [];
147
+ const parent = dirname(target);
148
+ return {
149
+ path: target,
150
+ label: displayPath(target),
151
+ parent: parent === target ? null : parent,
152
+ spaceId: bindings.filter((binding) => binding.key === key && samePath(binding.root, target)).at(-1)?.spaceId ?? null,
153
+ folders,
154
+ volumes: await volumes(),
155
+ };
156
+ }
157
+ async connect(spaceId, root) {
158
+ const key = this.options.account();
159
+ if (!key)
160
+ throw new Error("Sign in first");
161
+ const folder = await realpath(root).catch(() => null);
162
+ const current = await this.list();
163
+ if (!folder || !await isDirectory(folder))
164
+ return { ...current, refused: "folder_unavailable" };
165
+ const serving = current.instances.find((instance) => instance.spaceId === spaceId);
166
+ if (isRunning(serving))
167
+ return { ...current, refused: samePath(serving.root, folder) ? null : "space_in_use" };
168
+ if (current.instances.some((instance) => isRunning(instance) && samePath(instance.root, folder)))
169
+ return { ...current, refused: "folder_in_use" };
170
+ await this.#launch(key, spaceId, folder);
171
+ await rememberHostRuntime({ key, spaceId, root: folder });
172
+ return { ...await this.#publish(), refused: null };
173
+ }
174
+ async disconnect(spaceId) {
175
+ const key = this.options.account();
176
+ if (!key)
177
+ throw new Error("Sign in first");
178
+ await stopRuntimeInstance(runtimeInstanceDirectory(key, spaceId));
179
+ await forgetHostRuntime(key, spaceId);
180
+ return this.#publish();
181
+ }
182
+ restore() {
183
+ this.#restoring = this.#restoring.then(async () => {
184
+ const key = this.options.account();
185
+ if (!key)
186
+ return;
187
+ // A failed read skips this restore; nothing is forgotten.
188
+ const { bindings } = await readRuntimeSpaceBindings();
189
+ for (const item of await hostRuntimes(key)) {
190
+ const bound = bindings.filter((binding) => binding.key === key && binding.spaceId === item.spaceId).at(-1);
191
+ if (!bound || !samePath(bound.root, item.root)) {
192
+ await forgetHostRuntime(key, item.spaceId);
193
+ continue;
194
+ }
195
+ const running = await requestRuntimeInstance(runtimeInstanceDirectory(key, item.spaceId)).catch(() => true);
196
+ if (running || !await isDirectory(item.root))
197
+ continue;
198
+ await this.#launch(key, item.spaceId, item.root).catch((error) => {
199
+ process.stderr.write(`Could not reconnect ${item.root}: ${error instanceof Error ? error.message : String(error)}\n`);
200
+ });
201
+ }
202
+ }).catch((error) => {
203
+ process.stderr.write(`Could not restore connected folders: ${error instanceof Error ? error.message : String(error)}\n`);
204
+ }).finally(() => this.changed());
205
+ return this.#restoring;
206
+ }
207
+ async #publish() {
208
+ const runtime = await this.list();
209
+ const serialized = JSON.stringify(runtime);
210
+ if (serialized !== this.#published) {
211
+ this.#published = serialized;
212
+ this.emit("runtime.changed", runtime);
213
+ }
214
+ return runtime;
215
+ }
216
+ #subscribe(directory, pid) {
217
+ const instance = `${directory}:${pid}`;
218
+ if (this.#subscriptions.has(directory) || this.#unwatchable.has(instance))
219
+ return;
220
+ const controller = new AbortController();
221
+ this.#subscriptions.set(directory, controller);
222
+ void watchRuntimeInstance(directory, () => this.changed(), controller.signal).then((streamed) => {
223
+ if (!streamed)
224
+ this.#unwatchable.add(instance);
225
+ }, () => undefined).finally(() => {
226
+ if (this.#subscriptions.get(directory) === controller)
227
+ this.#subscriptions.delete(directory);
228
+ if (!controller.signal.aborted)
229
+ this.changed();
230
+ });
231
+ }
232
+ async #launch(key, spaceId, root) {
233
+ const env = await this.options.env();
234
+ if (this.options.account() !== key)
235
+ throw new Error("The signed-in account changed");
236
+ const child = spawn(process.execPath, [this.options.cli, "runtime", "up", root, "--space", spaceId, "--detach", "--yes", "--no-display", "--json"], {
237
+ env: { ...env, [EXPECTED_IDENTITY_ENV]: key }, stdio: ["ignore", "ignore", "pipe"], windowsHide: true,
238
+ });
239
+ let stderr = "";
240
+ child.stderr.setEncoding("utf8").on("data", (chunk) => { stderr = `${stderr}${chunk}`.slice(-8_192); });
241
+ const code = await new Promise((resolve, reject) => {
242
+ child.once("error", reject);
243
+ child.once("close", resolve);
244
+ });
245
+ if (code === 0 || code === 2)
246
+ return;
247
+ const reason = stderr.trim().split("\n").at(-1)?.replace(/^Runtime failed: /, "");
248
+ throw new Error(reason || `Runtime exited (${code})`);
249
+ }
250
+ }
@@ -0,0 +1,9 @@
1
+ export type HostRuntime = {
2
+ key: string;
3
+ spaceId: string;
4
+ root: string;
5
+ };
6
+ export declare const hostRuntimesPath: () => string;
7
+ export declare const hostRuntimes: (key: string, path?: string) => Promise<HostRuntime[]>;
8
+ export declare const rememberHostRuntime: (runtime: HostRuntime, path?: string) => Promise<void>;
9
+ export declare const forgetHostRuntime: (key: string, spaceId: string, path?: string) => Promise<void>;
@@ -0,0 +1,42 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { dirname, join } from "node:path";
5
+ import { withRuntimeSpaceBindingsLock } from "../runtime/space-binding.js";
6
+ export const hostRuntimesPath = () => join(homedir(), ".local", "state", "cohub", "host", "runtimes.json");
7
+ // Only a missing file is empty; an unreadable one throws, so it is never overwritten.
8
+ async function read(path) {
9
+ let text;
10
+ try {
11
+ text = await readFile(path, "utf8");
12
+ }
13
+ catch (error) {
14
+ if (error.code === "ENOENT")
15
+ return [];
16
+ throw error;
17
+ }
18
+ const file = JSON.parse(text);
19
+ if (file.version !== 1 || !Array.isArray(file.runtimes))
20
+ throw new Error(`Unsupported desktop Runtime state: ${path}`);
21
+ return file.runtimes.filter((item) => typeof item?.key === "string" && typeof item.spaceId === "string" && typeof item.root === "string");
22
+ }
23
+ async function update(path, change) {
24
+ await withRuntimeSpaceBindingsLock(async () => {
25
+ const before = await read(path);
26
+ const after = change(before);
27
+ if (JSON.stringify(after) === JSON.stringify(before))
28
+ return;
29
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
30
+ const temporary = `${path}.${randomUUID()}.tmp`;
31
+ try {
32
+ await writeFile(temporary, `${JSON.stringify({ version: 1, runtimes: after }, null, 2)}\n`, { mode: 0o600, flag: "wx" });
33
+ await rename(temporary, path);
34
+ }
35
+ finally {
36
+ await rm(temporary, { force: true });
37
+ }
38
+ }, { path });
39
+ }
40
+ export const hostRuntimes = (key, path = hostRuntimesPath()) => read(path).then((runtimes) => runtimes.filter((item) => item.key === key));
41
+ export const rememberHostRuntime = (runtime, path = hostRuntimesPath()) => update(path, (runtimes) => [...runtimes.filter((item) => item.key !== runtime.key || item.spaceId !== runtime.spaceId), runtime]);
42
+ export const forgetHostRuntime = (key, spaceId, path = hostRuntimesPath()) => update(path, (runtimes) => runtimes.filter((item) => item.key !== key || item.spaceId !== spaceId));
@@ -0,0 +1,2 @@
1
+ export type HostEmit = (name: string, payload?: unknown) => void;
2
+ export declare function serveHost(entry?: string): Promise<void>;
@@ -0,0 +1,73 @@
1
+ import { createInterface } from "node:readline";
2
+ import { fileURLToPath } from "node:url";
3
+ import { HOST_BRIDGE_ERROR, HOST_BRIDGE_METHODS, HOST_SERVICE_VERSION, hostBridgeRequestSchema, } from "@neta-art/cohub/host-bridge";
4
+ import { currentIdentityKey } from "../space.js";
5
+ import { HostAuth } from "./auth.js";
6
+ import { loginShellEnv } from "./login-env.js";
7
+ import { DeviceRuntimeHost } from "./runtime.js";
8
+ const CAPABILITIES = ["auth.token", "auth.signIn", "auth.session", "runtime"];
9
+ const MAX_LINE = 1024 * 1024;
10
+ const write = (message) => process.stdout.write(`${JSON.stringify(message)}\n`);
11
+ export async function serveHost(entry = fileURLToPath(new URL("../../bin/cohub.js", import.meta.url))) {
12
+ const emit = (name, payload) => write({ type: "event", name, ...(payload === undefined ? {} : { payload }) });
13
+ let environment = null;
14
+ const runtime = new DeviceRuntimeHost(emit, {
15
+ cli: entry,
16
+ env: () => (environment ??= loginShellEnv()),
17
+ account: currentIdentityKey,
18
+ });
19
+ const auth = new HostAuth(emit, () => {
20
+ runtime.changed();
21
+ void runtime.restore();
22
+ });
23
+ const handlers = {
24
+ "auth.getAccessToken": (params) => auth.accessToken(params.forceRefresh === true),
25
+ "auth.getSessionVersion": () => auth.sessionVersion(),
26
+ "auth.getSession": () => auth.session(),
27
+ "auth.signIn": (params) => auth.signIn(typeof params.redirectPath === "string" ? params.redirectPath : undefined),
28
+ "auth.signOut": () => auth.signOut(),
29
+ "runtime.list": () => runtime.list(),
30
+ "runtime.browse": (params) => runtime.browse(typeof params.path === "string" ? params.path : undefined),
31
+ "runtime.start": (params) => runtime.connect(String(params.spaceId), String(params.root)),
32
+ "runtime.stop": (params) => runtime.disconnect(String(params.spaceId)),
33
+ };
34
+ const methods = Object.keys(handlers);
35
+ const answer = async (line) => {
36
+ let raw;
37
+ try {
38
+ raw = JSON.parse(line);
39
+ }
40
+ catch {
41
+ return;
42
+ }
43
+ const request = hostBridgeRequestSchema.safeParse(raw);
44
+ if (!request.success)
45
+ return;
46
+ const { id, method } = request.data;
47
+ const fail = (code, message) => write({ type: "response", id, error: { code, message: message.slice(0, 2_000) || "Host call failed" } });
48
+ if (!(method in handlers))
49
+ return fail(HOST_BRIDGE_ERROR.unsupported, `Unsupported method: ${method}`);
50
+ const name = method;
51
+ const shape = HOST_BRIDGE_METHODS[name];
52
+ const params = shape.params.safeParse(request.data.params);
53
+ if (!params.success)
54
+ return fail(HOST_BRIDGE_ERROR.failed, `Invalid params for ${method}`);
55
+ try {
56
+ const result = await handlers[name]((params.data ?? {}));
57
+ write({ type: "response", id, result: shape.result.parse(result) });
58
+ }
59
+ catch (error) {
60
+ fail(HOST_BRIDGE_ERROR.failed, error instanceof Error ? error.message : String(error));
61
+ }
62
+ };
63
+ const hello = { type: "hello", version: HOST_SERVICE_VERSION, capabilities: [...CAPABILITIES], methods };
64
+ write(hello);
65
+ auth.watch();
66
+ runtime.watch();
67
+ const input = createInterface({ input: process.stdin, crlfDelay: Infinity });
68
+ input.on("line", (line) => { if (line.length <= MAX_LINE)
69
+ void answer(line); });
70
+ await new Promise((resolve) => input.once("close", resolve));
71
+ auth.close();
72
+ runtime.close();
73
+ }
package/dist/index.js CHANGED
@@ -22,6 +22,7 @@ import { maybeHandleRunCommand, printRunHelp } from "./commands/run.js";
22
22
  import { registerRuntime } from "./commands/runtime.js";
23
23
  import { registerTasks } from "./commands/tasks.js";
24
24
  import { registerDesktop, registerLegacyUi } from "./commands/desktop.js";
25
+ import { registerHost } from "./commands/host.js";
25
26
  import { registerApps } from "./commands/apps.js";
26
27
  import { registerRooms } from "./commands/rooms.js";
27
28
  import { formatUnknownCommandError, resolveHelpPath } from "./help-path.js";
@@ -113,6 +114,7 @@ registerRooms(program);
113
114
  registerFeedback(program);
114
115
  registerDesktop(program);
115
116
  registerLegacyUi(program);
117
+ registerHost(program);
116
118
  const argv = process.argv.slice(2);
117
119
  const help = resolveHelpPath(program, argv);
118
120
  if (help.kind === "help") {
@@ -1,4 +1,5 @@
1
1
  import type { RuntimeSummary } from "./presentation.js";
2
+ export declare function runtimeInstancesRoot(): string;
2
3
  export declare function runtimeInstanceDirectory(identity: string, spaceId: string): string;
3
4
  type Response = {
4
5
  status: RuntimeSummary;
@@ -7,6 +8,12 @@ type Response = {
7
8
  export declare function requestRuntimeInstance(directory: string, action?: "status" | "stop", force?: boolean): Promise<RuntimeSummary | null>;
8
9
  /** Send a control action to the running Runtime; `null` when none runs. */
9
10
  export declare function controlRuntimeInstance(directory: string, action: string, payload?: Record<string, unknown>, timeoutMs?: number): Promise<Response | null>;
11
+ export declare function stopRuntimeInstance(directory: string, force?: boolean): Promise<RuntimeSummary | null>;
12
+ export declare function watchRuntimeInstance(directory: string, onStatus: (status: RuntimeSummary) => void, signal?: AbortSignal): Promise<boolean>;
13
+ export type RuntimeInstanceHandle = {
14
+ changed(): void;
15
+ close(): Promise<void>;
16
+ };
10
17
  /** Private local IPC is both the single-instance guard and the control surface. */
11
- export declare function ownRuntimeInstance(directory: string, status: () => RuntimeSummary, stop: (force: boolean) => Promise<void>, control?: (action: string, message: Record<string, unknown>) => Promise<unknown>): Promise<() => Promise<void>>;
18
+ export declare function ownRuntimeInstance(directory: string, status: () => RuntimeSummary, stop: (force: boolean) => Promise<void>, control?: (action: string, message: Record<string, unknown>) => Promise<unknown>): Promise<RuntimeInstanceHandle>;
12
19
  export {};
@@ -3,10 +3,15 @@ import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"
3
3
  import { createConnection, createServer } from "node:net";
4
4
  import { homedir } from "node:os";
5
5
  import { join } from "node:path";
6
+ import { setTimeout as delay } from "node:timers/promises";
6
7
  import { withRuntimeSpaceBindingsLock } from "./space-binding.js";
8
+ const MAX_WATCHERS = 16;
9
+ export function runtimeInstancesRoot() {
10
+ return join(homedir(), ".local", "state", "cohub", "instances");
11
+ }
7
12
  export function runtimeInstanceDirectory(identity, spaceId) {
8
13
  const key = createHash("sha256").update(`${identity}\0${spaceId}`).digest("hex").slice(0, 24);
9
- return join(homedir(), ".local", "state", "cohub", "instances", key);
14
+ return join(runtimeInstancesRoot(), key);
10
15
  }
11
16
  function alive(pid) {
12
17
  if (!Number.isSafeInteger(pid) || pid <= 0)
@@ -94,6 +99,61 @@ export async function controlRuntimeInstance(directory, action, payload = {}, ti
94
99
  throw error;
95
100
  }
96
101
  }
102
+ export async function stopRuntimeInstance(directory, force = false) {
103
+ const local = await requestRuntimeInstance(directory, "stop", force);
104
+ const until = Date.now() + 15_000;
105
+ let running = Boolean(local);
106
+ while (running && Date.now() < until) {
107
+ await delay(250);
108
+ try {
109
+ running = Boolean(await requestRuntimeInstance(directory));
110
+ }
111
+ catch {
112
+ running = true;
113
+ } // An unreachable control socket does not prove the process stopped.
114
+ }
115
+ if (running)
116
+ throw new Error("Runtime is still stopping; inspect logs");
117
+ return local;
118
+ }
119
+ export async function watchRuntimeInstance(directory, onStatus, signal) {
120
+ const record = await readRecord(directory).catch(() => null);
121
+ if (!record || !alive(record.pid) || signal?.aborted)
122
+ return false;
123
+ let streamed = false;
124
+ await new Promise((resolve) => {
125
+ const socket = createConnection(record.socket);
126
+ const abort = () => socket.destroy();
127
+ let buffer = "";
128
+ signal?.addEventListener("abort", abort, { once: true });
129
+ socket.on("connect", () => socket.write(`${JSON.stringify({ action: "watch", nonce: record.nonce })}\n`));
130
+ socket.on("data", (chunk) => {
131
+ buffer += chunk.toString();
132
+ for (let end = buffer.indexOf("\n"); end >= 0; end = buffer.indexOf("\n")) {
133
+ const line = buffer.slice(0, end);
134
+ buffer = buffer.slice(end + 1);
135
+ try {
136
+ const response = JSON.parse(line);
137
+ if (response.nonce !== record.nonce || response.status?.pid !== record.pid) {
138
+ socket.destroy();
139
+ return;
140
+ }
141
+ streamed = true;
142
+ onStatus(response.status);
143
+ }
144
+ catch {
145
+ socket.destroy();
146
+ return;
147
+ }
148
+ }
149
+ if (buffer.length > 64 * 1024)
150
+ socket.destroy();
151
+ });
152
+ socket.on("error", () => socket.destroy());
153
+ socket.on("close", () => { signal?.removeEventListener("abort", abort); resolve(); });
154
+ });
155
+ return streamed;
156
+ }
97
157
  /** Private local IPC is both the single-instance guard and the control surface. */
98
158
  export async function ownRuntimeInstance(directory, status, stop, control = async () => { throw new Error("Unknown Runtime control request"); }) {
99
159
  await mkdir(directory, { recursive: true, mode: 0o700 });
@@ -107,11 +167,13 @@ export async function ownRuntimeInstance(directory, status, stop, control = asyn
107
167
  await rm(socketPath, { force: true });
108
168
  const record = { pid: process.pid, nonce: randomUUID(), socket: socketPath };
109
169
  const clients = new Set();
170
+ const watchers = new Set();
171
+ const statusLine = () => `${JSON.stringify({ nonce: record.nonce, status: status() })}\n`;
110
172
  const server = createServer((socket) => {
111
173
  clients.add(socket);
112
174
  socket.setTimeout(3000, () => socket.destroy());
113
175
  socket.on("error", () => socket.destroy());
114
- socket.on("close", () => clients.delete(socket));
176
+ socket.on("close", () => { clients.delete(socket); watchers.delete(socket); });
115
177
  let input = "";
116
178
  socket.on("data", (chunk) => {
117
179
  input += chunk.toString();
@@ -130,6 +192,15 @@ export async function ownRuntimeInstance(directory, status, stop, control = asyn
130
192
  socket.destroy();
131
193
  return;
132
194
  }
195
+ if (message.action === "watch") {
196
+ if (watchers.size >= MAX_WATCHERS) {
197
+ socket.destroy();
198
+ return;
199
+ }
200
+ watchers.add(socket);
201
+ socket.write(statusLine());
202
+ return;
203
+ }
133
204
  let result;
134
205
  if (message.action === "stop")
135
206
  await stop(message.force === true);
@@ -154,13 +225,22 @@ export async function ownRuntimeInstance(directory, status, stop, control = asyn
154
225
  server.close();
155
226
  throw error;
156
227
  }
157
- return async () => {
158
- for (const client of clients)
159
- client.destroy();
160
- await new Promise((resolve) => server.close(() => resolve()));
161
- // Never remove a replacement owner's files.
162
- if ((await readRecord(directory))?.nonce === record.nonce)
163
- await rm(join(directory, "owner.json"));
228
+ return {
229
+ changed: () => {
230
+ if (!watchers.size)
231
+ return;
232
+ const line = statusLine();
233
+ for (const watcher of watchers)
234
+ watcher.write(line);
235
+ },
236
+ close: async () => {
237
+ for (const client of clients)
238
+ client.destroy();
239
+ await new Promise((resolve) => server.close(() => resolve()));
240
+ // Never remove a replacement owner's files.
241
+ if ((await readRecord(directory))?.nonce === record.nonce)
242
+ await rm(join(directory, "owner.json"));
243
+ },
164
244
  };
165
245
  }, { path: join(directory, "owner.json") });
166
246
  }
@@ -3,6 +3,7 @@ import { type HarnessExecutables } from "./harnesses/index.js";
3
3
  import type { Command } from "commander";
4
4
  import { type RuntimeSummary } from "./presentation.js";
5
5
  import { type RuntimeLaunch } from "./supervisor.js";
6
+ export declare const EXPECTED_IDENTITY_ENV = "COHUB_RUNTIME_EXPECTED_IDENTITY";
6
7
  export type RuntimeUpOptions = HarnessExecutables & {
7
8
  space?: string;
8
9
  new?: boolean;
@@ -15,6 +15,7 @@ import { ensureNativeSync, repairIntegrations } from "./native/attach.js";
15
15
  import { serializeDiagnosticError } from "./diagnostics.js";
16
16
  import { createDiagnosticConsole, printRuntimeSummary, runtimeWebUrl } from "./presentation.js";
17
17
  import { runRuntime } from "./supervisor.js";
18
+ export const EXPECTED_IDENTITY_ENV = "COHUB_RUNTIME_EXPECTED_IDENTITY";
18
19
  /** Executable overrides come from the per-harness `--<harness> <path>` options. */
19
20
  export const runtimeExecutables = (options) => Object.fromEntries(LOCAL_HARNESSES.flatMap((harness) => options[harness] ? [[harness, options[harness]]] : []));
20
21
  export const resolveLocalSpaceName = (root, name) => name?.trim() || basename(root) || "local-space";
@@ -123,6 +124,11 @@ export async function runtimeUp(program, dir, options) {
123
124
  await requireAccessToken();
124
125
  throw new Error("Cannot identify the signed-in account");
125
126
  }
127
+ // Consumed here, so the Runtime and the tools it runs never inherit it.
128
+ const expected = process.env[EXPECTED_IDENTITY_ENV];
129
+ delete process.env[EXPECTED_IDENTITY_ENV];
130
+ if (expected && expected !== identity)
131
+ throw new Error("The signed-in account changed");
126
132
  const binding = await getRuntimeSpaceBinding(root, identity);
127
133
  const existingId = requested || binding?.spaceId;
128
134
  let harnesses = parseRuntimeHarnesses(options.harness);
@@ -73,6 +73,7 @@ export async function runRuntime(config, onState, externalSignal, onDiagnostic)
73
73
  diagnosticsPath: diagnostics.directory,
74
74
  };
75
75
  const summary = () => ({ ...status, native: native.status() });
76
+ let instance;
76
77
  let hasBeenReady = false;
77
78
  const update = (patch) => {
78
79
  const next = { ...status, ...patch };
@@ -87,8 +88,8 @@ export async function runRuntime(config, onState, externalSignal, onDiagnostic)
87
88
  diagnostics.log("info", "runtime.available");
88
89
  }
89
90
  onState({ ...status });
91
+ instance?.changed();
90
92
  };
91
- let closeInstance;
92
93
  let bridgeTask;
93
94
  let retryDisconnectedBridge;
94
95
  let nativeStarted = false;
@@ -107,7 +108,7 @@ export async function runRuntime(config, onState, externalSignal, onDiagnostic)
107
108
  return tokenInFlight;
108
109
  };
109
110
  try {
110
- closeInstance = await ownRuntimeInstance(runtimeInstanceDirectory(config.identity, config.spaceId), summary, async (force) => {
111
+ instance = await ownRuntimeInstance(runtimeInstanceDirectory(config.identity, config.spaceId), summary, async (force) => {
111
112
  if (!force)
112
113
  for await (const batch of native.executor.results.pendingBatches()) {
113
114
  if (batch.length)
@@ -344,7 +345,7 @@ export async function runRuntime(config, onState, externalSignal, onDiagnostic)
344
345
  }
345
346
  finally {
346
347
  try {
347
- await closeInstance?.();
348
+ await instance?.close();
348
349
  }
349
350
  finally {
350
351
  process.removeListener("SIGINT", stop);
package/dist/space.d.ts CHANGED
@@ -4,6 +4,7 @@ export declare class SpaceTargetError extends Error {
4
4
  name: string;
5
5
  constructor(message: string, detail?: string | undefined);
6
6
  }
7
+ export declare function jwtClaim(token: string | undefined | null, key: string): string | null;
7
8
  /**
8
9
  * Cache key aligned with auth: execution token is exclusive (same as
9
10
  * `resolveAccessToken`) and never falls back to a local Logto session.
package/dist/space.js CHANGED
@@ -21,7 +21,7 @@ export class SpaceTargetError extends Error {
21
21
  this.detail = detail;
22
22
  }
23
23
  }
24
- function jwtClaim(token, key) {
24
+ export function jwtClaim(token, key) {
25
25
  const payload = token?.split(".")[1];
26
26
  if (!payload)
27
27
  return null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@neta-art/cohub-cli",
3
- "version": "10.15.0",
3
+ "version": "10.17.0",
4
4
  "description": "CLI for Cohub — spaces, sessions, and agent collaboration.",
5
5
  "type": "module",
6
6
  "engines": {
@@ -18,8 +18,8 @@
18
18
  "NOTICE"
19
19
  ],
20
20
  "dependencies": {
21
- "@neta-art/cohub": "13.5.0",
22
- "@neta-art/generation": "0.2.8",
21
+ "@neta-art/cohub": "13.7.0",
22
+ "@neta-art/generation": "0.2.10",
23
23
  "commander": "^15.0.0",
24
24
  "sharp": "^0.35.4",
25
25
  "ws": "^8.21.3"