@neta-art/cohub-cli 10.15.0 → 10.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -1
- package/dist/auth.d.ts +3 -1
- package/dist/auth.js +4 -0
- package/dist/bootstrap.js +5 -0
- package/dist/commands/auth.js +12 -1
- package/dist/commands/host.d.ts +2 -0
- package/dist/commands/host.js +11 -0
- package/dist/commands/runtime.js +4 -16
- package/dist/commands/space-invitations.d.ts +3 -2
- package/dist/commands/space-invitations.js +29 -8
- package/dist/commands/spaces.js +42 -17
- package/dist/host/auth.d.ts +20 -0
- package/dist/host/auth.js +107 -0
- package/dist/host/login-env.d.ts +1 -0
- package/dist/host/login-env.js +31 -0
- package/dist/host/runtime.d.ts +25 -0
- package/dist/host/runtime.js +250 -0
- package/dist/host/runtimes.d.ts +9 -0
- package/dist/host/runtimes.js +42 -0
- package/dist/host/serve.d.ts +2 -0
- package/dist/host/serve.js +73 -0
- package/dist/index.js +2 -0
- package/dist/runtime/instance.d.ts +8 -1
- package/dist/runtime/instance.js +89 -9
- package/dist/runtime/launch.d.ts +1 -0
- package/dist/runtime/launch.js +6 -0
- package/dist/runtime/supervisor.js +4 -3
- package/dist/space.d.ts +1 -0
- package/dist/space.js +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -122,8 +122,10 @@ cohub spaces create --name "<name>" --checkpoint <checkpointId> --json
|
|
|
122
122
|
cohub spaces update <spaceId> --slug <space-slug>
|
|
123
123
|
cohub spaces rename <spaceId> "<new name>"
|
|
124
124
|
cohub -s <spaceId> spaces invites create --role builder --days 7
|
|
125
|
-
cohub -s <spaceId> spaces invites
|
|
125
|
+
cohub -s <spaceId> spaces invites create --role guest --never-expires
|
|
126
|
+
cohub -s <spaceId> spaces invites ls --all
|
|
126
127
|
cohub -s <spaceId> spaces invites revoke <code> --yes
|
|
128
|
+
cohub spaces config <spaceId> --guest-app <app>
|
|
127
129
|
cohub -s <spaceId> run -- git status
|
|
128
130
|
```
|
|
129
131
|
|
package/dist/auth.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type CohubEnvironment } from "@neta-art/cohub";
|
|
2
2
|
export type AuthSource = "execution-token" | "logto" | null;
|
|
3
|
-
type DeviceCode = {
|
|
3
|
+
export type DeviceCode = {
|
|
4
4
|
deviceCode: string;
|
|
5
5
|
userCode: string;
|
|
6
6
|
verificationUri: string;
|
|
@@ -29,6 +29,7 @@ export declare class AuthRequiredError extends Error {
|
|
|
29
29
|
constructor(message?: string);
|
|
30
30
|
}
|
|
31
31
|
export declare const readAuthSession: () => AuthSession | null;
|
|
32
|
+
export declare const authSessionPath: () => string;
|
|
32
33
|
export declare const clearAuthSession: (env?: CohubEnvironment, baseUrl?: string) => void;
|
|
33
34
|
export declare const authSource: () => AuthSource;
|
|
34
35
|
export declare function resolveAccessToken(options?: {
|
|
@@ -39,5 +40,6 @@ export declare function refreshAccessToken(session?: AuthSession | null): Promis
|
|
|
39
40
|
export declare function requestDeviceCode(): Promise<DeviceCode>;
|
|
40
41
|
export declare function verifyDeviceCode(): Promise<AuthSession>;
|
|
41
42
|
export declare function loginWithDeviceFlow(onCode: (code: DeviceCode) => void, onPoll?: () => void): Promise<AuthSession>;
|
|
43
|
+
export declare function pollDeviceCode(code: DeviceCode, onPoll?: () => void): Promise<AuthSession>;
|
|
42
44
|
export declare function revokeAndClearAuthSession(): Promise<void>;
|
|
43
45
|
export {};
|
package/dist/auth.js
CHANGED
|
@@ -129,6 +129,7 @@ const toSession = (token, config, env, previous) => {
|
|
|
129
129
|
};
|
|
130
130
|
};
|
|
131
131
|
export const readAuthSession = () => readJson(sessionPath());
|
|
132
|
+
export const authSessionPath = () => sessionPath();
|
|
132
133
|
export const clearAuthSession = (env = currentEnv(), baseUrl = resolveApiBaseUrl({ env })) => {
|
|
133
134
|
removeIfExists(sessionPath(env, baseUrl));
|
|
134
135
|
removeIfExists(deviceCodePath(env, baseUrl));
|
|
@@ -262,6 +263,9 @@ export async function verifyDeviceCode() {
|
|
|
262
263
|
export async function loginWithDeviceFlow(onCode, onPoll) {
|
|
263
264
|
const code = await requestDeviceCode();
|
|
264
265
|
onCode(code);
|
|
266
|
+
return pollDeviceCode(code, onPoll);
|
|
267
|
+
}
|
|
268
|
+
export async function pollDeviceCode(code, onPoll) {
|
|
265
269
|
while (Date.now() < code.expiresAt) {
|
|
266
270
|
await delay(code.interval * 1000);
|
|
267
271
|
onPoll?.();
|
package/dist/bootstrap.js
CHANGED
|
@@ -21,6 +21,11 @@ if (!isVersionRequest && shouldRelaunchWithEnvProxy()) {
|
|
|
21
21
|
}));
|
|
22
22
|
}
|
|
23
23
|
}
|
|
24
|
+
if (argv[0] === "host" && argv[1] === "serve" && argv.length === 2) {
|
|
25
|
+
const { serveHost } = await import("./host/serve.js");
|
|
26
|
+
await serveHost();
|
|
27
|
+
process.exit(0);
|
|
28
|
+
}
|
|
24
29
|
if (!isVersionRequest) {
|
|
25
30
|
const entrypoint = process.argv[1];
|
|
26
31
|
if (entrypoint)
|
package/dist/commands/auth.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { authSource, loginWithDeviceFlow, readAuthSession, refreshAccessToken, requestDeviceCode, revokeAndClearAuthSession, verifyDeviceCode } from "../auth.js";
|
|
1
|
+
import { authSource, loginWithDeviceFlow, readAuthSession, refreshAccessToken, requestDeviceCode, requireAccessToken, revokeAndClearAuthSession, verifyDeviceCode } from "../auth.js";
|
|
2
2
|
import { clearHomeSpaceCache } from "../space.js";
|
|
3
3
|
import { createClient } from "../client.js";
|
|
4
4
|
import { table, json as outJson, jsonRequested, ok, error, spinner, handleHttp } from "../output.js";
|
|
@@ -48,6 +48,17 @@ export function registerAuth(program) {
|
|
|
48
48
|
const asJson = jsonRequested(opts);
|
|
49
49
|
return showSignedIn(asJson);
|
|
50
50
|
});
|
|
51
|
+
auth
|
|
52
|
+
.command("token")
|
|
53
|
+
.description("Print a valid access token, refreshing it when needed")
|
|
54
|
+
.action(async () => {
|
|
55
|
+
try {
|
|
56
|
+
process.stdout.write(`${await requireAccessToken()}\n`);
|
|
57
|
+
}
|
|
58
|
+
catch (e) {
|
|
59
|
+
handleHttp(e);
|
|
60
|
+
}
|
|
61
|
+
});
|
|
51
62
|
auth
|
|
52
63
|
.command("refresh")
|
|
53
64
|
.description("Refresh the stored Logto access token")
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export function registerHost(program) {
|
|
2
|
+
program
|
|
3
|
+
.command("host", { hidden: true })
|
|
4
|
+
.description("Machine interface for native desktop hosts")
|
|
5
|
+
.command("serve")
|
|
6
|
+
.description("Answer host bridge requests over stdio, one JSON message per line")
|
|
7
|
+
.action(async () => {
|
|
8
|
+
const { serveHost } = await import("../host/serve.js");
|
|
9
|
+
await serveHost();
|
|
10
|
+
});
|
|
11
|
+
}
|
package/dist/commands/runtime.js
CHANGED
|
@@ -10,7 +10,8 @@ import { RuntimeArchiveStore } from "../runtime/archive-store.js";
|
|
|
10
10
|
import { readNativeConfig, runtimeStateRoot, writeNativeConfig } from "../runtime/native/config.js";
|
|
11
11
|
import { MAX_IMPORT_CONCURRENCY, DEFAULT_IMPORT_CONCURRENCY } from "../runtime/native/ingest.js";
|
|
12
12
|
import { installPiExtension, piExtensionState } from "../runtime/native/install.js";
|
|
13
|
-
import { controlRuntimeInstance, requestRuntimeInstance, runtimeInstanceDirectory } from "../runtime/instance.js";
|
|
13
|
+
import { controlRuntimeInstance, requestRuntimeInstance, runtimeInstanceDirectory, stopRuntimeInstance } from "../runtime/instance.js";
|
|
14
|
+
import { forgetHostRuntime } from "../host/runtimes.js";
|
|
14
15
|
import { atLeastLevel, diagnosticLevels, formatDiagnostic, formatImportProgress, formatNativeSync, printRuntimeSummary } from "../runtime/presentation.js";
|
|
15
16
|
import { readRuntimeDiagnosticEvents, RuntimeDiagnosticReader, runtimeDiagnosticsDirectory, serializeDiagnosticError } from "../runtime/diagnostics.js";
|
|
16
17
|
export { resolveLocalSpaceName, parseRuntimeDisplay, parseRuntimeHarnesses } from "../runtime/launch.js";
|
|
@@ -256,21 +257,8 @@ export function registerRuntime(program) {
|
|
|
256
257
|
const identity = currentIdentityKey();
|
|
257
258
|
if (!identity)
|
|
258
259
|
throw new Error("Sign in to the Runtime account");
|
|
259
|
-
const
|
|
260
|
-
|
|
261
|
-
const until = Date.now() + 15_000;
|
|
262
|
-
let running = Boolean(local);
|
|
263
|
-
while (running && Date.now() < until) {
|
|
264
|
-
await delay(250);
|
|
265
|
-
try {
|
|
266
|
-
running = Boolean(await requestRuntimeInstance(directory));
|
|
267
|
-
}
|
|
268
|
-
catch {
|
|
269
|
-
running = true;
|
|
270
|
-
} // An unreachable control socket does not prove the process stopped.
|
|
271
|
-
}
|
|
272
|
-
if (running)
|
|
273
|
-
throw new Error("Runtime is still stopping; inspect logs");
|
|
260
|
+
const local = await stopRuntimeInstance(runtimeInstanceDirectory(identity, spaceId), Boolean(options.yes));
|
|
261
|
+
await forgetHostRuntime(identity, spaceId).catch((cause) => process.stderr.write(`Desktop app may reconnect this folder: ${serializeDiagnosticError(cause).message}\n`));
|
|
274
262
|
if (jsonRequested(options))
|
|
275
263
|
outJson({ spaceId, stopped: true });
|
|
276
264
|
else {
|
|
@@ -1,15 +1,16 @@
|
|
|
1
|
-
import { type CreateInvitationInput, type CreateInvitationResponse, type SpaceInvitationListResponse } from "@neta-art/cohub";
|
|
1
|
+
import { type CreateInvitationInput, type CreateInvitationResponse, type SpaceInvitationListOptions, type SpaceInvitationListResponse } from "@neta-art/cohub";
|
|
2
2
|
import type { Command } from "commander";
|
|
3
3
|
export type SpaceInvitationCreateCliOptions = {
|
|
4
4
|
role?: string;
|
|
5
5
|
days?: string;
|
|
6
|
+
neverExpires?: boolean;
|
|
6
7
|
maxUses?: string;
|
|
7
8
|
json?: boolean;
|
|
8
9
|
};
|
|
9
10
|
type SpaceInvitationCommandClient = {
|
|
10
11
|
space(spaceId: string): {
|
|
11
12
|
invitations: {
|
|
12
|
-
list(): Promise<SpaceInvitationListResponse>;
|
|
13
|
+
list(options?: SpaceInvitationListOptions): Promise<SpaceInvitationListResponse>;
|
|
13
14
|
create(input: CreateInvitationInput): Promise<CreateInvitationResponse>;
|
|
14
15
|
revoke(token: string): Promise<{
|
|
15
16
|
ok: true;
|
|
@@ -30,10 +30,31 @@ export function parseSpaceInvitationCreateOptions(options) {
|
|
|
30
30
|
if (!SPACE_ROLES.includes(role)) {
|
|
31
31
|
throw new InvalidSpaceInvitationCliOptionsError("Invalid role", `Use one of: ${SPACE_ROLES.join(", ")}`);
|
|
32
32
|
}
|
|
33
|
-
const days = parseInteger(options.days ?? String(DEFAULT_DAYS), "days", 1, MAX_DAYS);
|
|
34
33
|
const maxUses = parseInteger(options.maxUses ?? "0", "max uses", 0, MAX_USES);
|
|
34
|
+
if (options.neverExpires) {
|
|
35
|
+
if (options.days !== undefined) {
|
|
36
|
+
throw new InvalidSpaceInvitationCliOptionsError("Conflicting options", "Use either --days or --never-expires");
|
|
37
|
+
}
|
|
38
|
+
if (role === "host") {
|
|
39
|
+
throw new InvalidSpaceInvitationCliOptionsError("Invalid expiry", `Host invite links expire within ${MAX_DAYS} days`);
|
|
40
|
+
}
|
|
41
|
+
return { role, ttlSeconds: null, maxUses };
|
|
42
|
+
}
|
|
43
|
+
const days = parseInteger(options.days ?? String(DEFAULT_DAYS), "days", 1, MAX_DAYS);
|
|
35
44
|
return { role, ttlSeconds: days * 24 * 60 * 60, maxUses };
|
|
36
45
|
}
|
|
46
|
+
const PAGE_SIZE = 100;
|
|
47
|
+
async function listAllInvitations(invitations, status) {
|
|
48
|
+
const items = [];
|
|
49
|
+
let cursor = null;
|
|
50
|
+
let page;
|
|
51
|
+
do {
|
|
52
|
+
page = await invitations.list({ status, limit: PAGE_SIZE, cursor });
|
|
53
|
+
items.push(...page.items);
|
|
54
|
+
cursor = page.pageInfo?.nextCursor ?? null;
|
|
55
|
+
} while (cursor);
|
|
56
|
+
return { ...page, items };
|
|
57
|
+
}
|
|
37
58
|
function invitationUrl(invitation) {
|
|
38
59
|
return webUrl(buildSpaceInvitePath({
|
|
39
60
|
spaceId: invitation.spaceId,
|
|
@@ -68,7 +89,8 @@ export function registerSpaceInvitations(spacesCommand, dependencies = {
|
|
|
68
89
|
.command("create")
|
|
69
90
|
.description("Create an invite link")
|
|
70
91
|
.option("--role <role>", "Member role: host, builder, or guest", "builder")
|
|
71
|
-
.option("--days <days>",
|
|
92
|
+
.option("--days <days>", `Validity in days, from 1 to ${MAX_DAYS} (default ${DEFAULT_DAYS})`)
|
|
93
|
+
.option("--never-expires", "Keep the link valid until revoked (not for hosts)")
|
|
72
94
|
.option("--max-uses <count>", "Usage limit, or 0 for unlimited", "0")
|
|
73
95
|
.option("--json", "Output as JSON")
|
|
74
96
|
.action(async (options) => {
|
|
@@ -108,15 +130,13 @@ export function registerSpaceInvitations(spacesCommand, dependencies = {
|
|
|
108
130
|
invitations
|
|
109
131
|
.command("ls")
|
|
110
132
|
.alias("list")
|
|
111
|
-
.description("List invite links")
|
|
133
|
+
.description("List active invite links")
|
|
134
|
+
.option("--all", "Include revoked, exhausted, and expired links")
|
|
112
135
|
.option("--json", "Output as JSON")
|
|
113
136
|
.action(async (options) => {
|
|
114
137
|
const spaceId = await resolveSpace(spacesCommand);
|
|
115
138
|
try {
|
|
116
|
-
const result = await dependencies
|
|
117
|
-
.createClient()
|
|
118
|
-
.space(spaceId)
|
|
119
|
-
.invitations.list();
|
|
139
|
+
const result = await listAllInvitations(dependencies.createClient().space(spaceId).invitations, options.all ? "all" : "active");
|
|
120
140
|
const items = result.items.map((item) => ({
|
|
121
141
|
...item,
|
|
122
142
|
url: invitationUrl({
|
|
@@ -127,6 +147,7 @@ export function registerSpaceInvitations(spacesCommand, dependencies = {
|
|
|
127
147
|
spaceSlug: result.spaceSlug ?? null,
|
|
128
148
|
}),
|
|
129
149
|
uses: item.maxUses ? `${item.useCount}/${item.maxUses}` : String(item.useCount),
|
|
150
|
+
expires: item.expiresAt ?? "never",
|
|
130
151
|
}));
|
|
131
152
|
if (jsonRequested(options))
|
|
132
153
|
return outJson({ ...result, items });
|
|
@@ -135,7 +156,7 @@ export function registerSpaceInvitations(spacesCommand, dependencies = {
|
|
|
135
156
|
{ key: "role", label: "Role" },
|
|
136
157
|
{ key: "status", label: "Status" },
|
|
137
158
|
{ key: "uses", label: "Uses" },
|
|
138
|
-
{ key: "
|
|
159
|
+
{ key: "expires", label: "Expires" },
|
|
139
160
|
{ key: "url", label: "URL" },
|
|
140
161
|
]);
|
|
141
162
|
}
|
package/dist/commands/spaces.js
CHANGED
|
@@ -73,6 +73,15 @@ const parseAutoDestroy = (opts) => {
|
|
|
73
73
|
return { mode: "idle", ttlSeconds };
|
|
74
74
|
};
|
|
75
75
|
const parseSandboxSpec = (value) => value ? parseChoice(value, "sandbox spec", SANDBOX_SPEC_IDS) : undefined;
|
|
76
|
+
async function resolveGuestApp(client, spaceId, value) {
|
|
77
|
+
if (value === "none")
|
|
78
|
+
return null;
|
|
79
|
+
const { apps } = await client.apps.listBySpace(spaceId);
|
|
80
|
+
const app = apps.find((item) => item.id === value || item.slug === value);
|
|
81
|
+
if (!app)
|
|
82
|
+
return error("App not found", `No App "${value}" in this Space`);
|
|
83
|
+
return { appId: app.id };
|
|
84
|
+
}
|
|
76
85
|
export function buildSpaceCreateInput(opts) {
|
|
77
86
|
const autoDestroy = parseAutoDestroy(opts);
|
|
78
87
|
const spec = parseSandboxSpec(opts.spec);
|
|
@@ -198,6 +207,9 @@ async function sendPrompt(command, words, opts) {
|
|
|
198
207
|
if (agentOnly.length)
|
|
199
208
|
return error("Conflicting options", `--note cannot be combined with ${agentOnly.join(", ")}`);
|
|
200
209
|
}
|
|
210
|
+
if (opts.reply && (opts.note || scheduleFlags.length)) {
|
|
211
|
+
return error("Conflicting options", "--reply cannot be combined with --note or scheduling");
|
|
212
|
+
}
|
|
201
213
|
const requestedThinkingLevel = opts.thinkingLevel?.trim() || undefined;
|
|
202
214
|
const thinkingLevel = isModelThinkingLevel(requestedThinkingLevel) ? requestedThinkingLevel : undefined;
|
|
203
215
|
if (requestedThinkingLevel && !thinkingLevel) {
|
|
@@ -255,11 +267,14 @@ async function sendPrompt(command, words, opts) {
|
|
|
255
267
|
env: parseEnvOptions(opts.env),
|
|
256
268
|
schedule,
|
|
257
269
|
labelRefs: opts.label?.length ? opts.label : undefined,
|
|
270
|
+
...(opts.reply ? { reply: "prompt" } : {}),
|
|
258
271
|
});
|
|
259
272
|
if (jsonRequested(opts))
|
|
260
273
|
return outJson(result);
|
|
261
|
-
if (result.mode === "immediate")
|
|
262
|
-
|
|
274
|
+
if (result.mode === "immediate") {
|
|
275
|
+
const label = opts.note ? "Note recorded" : opts.reply ? "Prompt sent; the reply will come back to this Chat" : "Prompt sent";
|
|
276
|
+
return ok(`${label} — sessionId: ${result.session.id}, turnId: ${result.turn.id}`);
|
|
277
|
+
}
|
|
263
278
|
if (result.mode === "repeat")
|
|
264
279
|
return ok(`Prompt scheduled — cronJobId: ${result.cronJobId}, nextRunAt: ${result.nextRunAt}`);
|
|
265
280
|
return ok(`Prompt scheduled — taskRunId: ${result.taskRunId}, scheduledAt: ${result.scheduledAt}`);
|
|
@@ -367,6 +382,7 @@ export function registerPrompt(program) {
|
|
|
367
382
|
.option("--env <key=value>", "Set an environment variable for this turn", collectOption, [])
|
|
368
383
|
.option("--image <path>", "Attach an image", collectOption, [])
|
|
369
384
|
.option("--note", "Record the message without an AI reply")
|
|
385
|
+
.option("--reply", "Send the final reply back to the calling Chat and run its Agent")
|
|
370
386
|
.option("--json", "Output as JSON")
|
|
371
387
|
.action((words, opts) => sendPrompt(program, words, opts));
|
|
372
388
|
program
|
|
@@ -674,6 +690,7 @@ export function registerSpaces(program) {
|
|
|
674
690
|
.option("--idle-ttl <seconds>", "Idle auto destroy TTL in seconds, max 2592000 (30d)")
|
|
675
691
|
.option("--spec <spec>", "Sandbox spec: standard, boost, ultra, or auto")
|
|
676
692
|
.option("--image <image>", "Sandbox image: default, game, or auto")
|
|
693
|
+
.option("--guest-app <app>", "Published public App shown to visitors without access: id, slug, or none")
|
|
677
694
|
.option("--json", "Output as JSON")
|
|
678
695
|
.action(async (id, opts) => {
|
|
679
696
|
const client = createClient();
|
|
@@ -681,8 +698,13 @@ export function registerSpaces(program) {
|
|
|
681
698
|
const autoDestroy = parseAutoDestroy(opts);
|
|
682
699
|
const spec = opts.spec === "auto" ? null : parseSandboxSpec(opts.spec);
|
|
683
700
|
const image = opts.image === "auto" ? null : opts.image ? parseChoice(opts.image, "sandbox image", ["default", "game"]) : undefined;
|
|
684
|
-
|
|
685
|
-
|
|
701
|
+
const guest = opts.guestApp === undefined ? undefined : await resolveGuestApp(client, id, opts.guestApp);
|
|
702
|
+
const sandboxChanged = Boolean(autoDestroy) || spec !== undefined || image !== undefined;
|
|
703
|
+
if (sandboxChanged || guest !== undefined) {
|
|
704
|
+
const result = await client.space(id).updateConfig({
|
|
705
|
+
...(sandboxChanged ? { sandbox: { ...(autoDestroy ? { autoDestroy } : {}), ...(spec !== undefined ? { spec } : {}), ...(image !== undefined ? { image } : {}) } } : {}),
|
|
706
|
+
...(guest !== undefined ? { guest } : {}),
|
|
707
|
+
});
|
|
686
708
|
if (jsonRequested(opts))
|
|
687
709
|
return outJson(result);
|
|
688
710
|
ok(`Space config updated${autoDestroy ? ` — sandbox auto destroy: ${formatAutoDestroy(autoDestroy)}` : ""}${spec ? ` — sandbox spec: ${spec}` : ""}${result.sandbox?.pendingRestart ? " — restart the sandbox to apply" : ""}`);
|
|
@@ -701,6 +723,7 @@ export function registerSpaces(program) {
|
|
|
701
723
|
{ key: "sandbox.spec", value: result.config.sandbox.spec ?? "standard" },
|
|
702
724
|
{ key: "sandbox.appliedSpec", value: result.config.sandbox.appliedSpec ?? "—" },
|
|
703
725
|
{ key: "sandbox.allowedSpec", value: result.config.sandbox.allowedSpec ?? "standard" },
|
|
726
|
+
{ key: "guest.appId", value: result.config.guest?.appId ?? "default" },
|
|
704
727
|
], [
|
|
705
728
|
{ key: "key", label: "Key" },
|
|
706
729
|
{ key: "value", label: "Value" },
|
|
@@ -731,6 +754,7 @@ export function registerSpaces(program) {
|
|
|
731
754
|
.option("--env <key=value>", "Set an environment variable for this turn", collectOption, [])
|
|
732
755
|
.option("--image <path>", "Attach an image", collectOption, [])
|
|
733
756
|
.option("--note", "Record the message without an AI reply")
|
|
757
|
+
.option("--reply", "Send the final reply back to the calling Chat and run its Agent")
|
|
734
758
|
.option("--json", "Output as JSON")
|
|
735
759
|
.action((words, opts) => sendPrompt(spacesCmd, words, opts));
|
|
736
760
|
// ── spaces completion ──
|
|
@@ -1873,6 +1897,10 @@ function registerMembers(spacesCmd) {
|
|
|
1873
1897
|
});
|
|
1874
1898
|
}
|
|
1875
1899
|
// ── Access control ──
|
|
1900
|
+
const ACCESS_COLUMNS = [
|
|
1901
|
+
{ key: "signed_in_user", label: "Signed-in" },
|
|
1902
|
+
{ key: "anonymous_user", label: "Anonymous" },
|
|
1903
|
+
];
|
|
1876
1904
|
function registerAccess(spacesCmd) {
|
|
1877
1905
|
const accCmd = spacesCmd
|
|
1878
1906
|
.command("access")
|
|
@@ -1889,10 +1917,7 @@ function registerAccess(spacesCmd) {
|
|
|
1889
1917
|
const policy = await client.space(spaceId).access.get();
|
|
1890
1918
|
if (jsonRequested(opts))
|
|
1891
1919
|
return outJson(policy);
|
|
1892
|
-
table([policy],
|
|
1893
|
-
{ key: "signed_in_user", label: "Signed-in" },
|
|
1894
|
-
{ key: "anonymous_user", label: "Anonymous" },
|
|
1895
|
-
]);
|
|
1920
|
+
table([policy], ACCESS_COLUMNS);
|
|
1896
1921
|
}
|
|
1897
1922
|
catch (e) {
|
|
1898
1923
|
handleHttp(e);
|
|
@@ -1900,25 +1925,25 @@ function registerAccess(spacesCmd) {
|
|
|
1900
1925
|
});
|
|
1901
1926
|
accCmd
|
|
1902
1927
|
.command("set")
|
|
1903
|
-
.description("Set access policy")
|
|
1904
|
-
.option("--signed-in <role>", "Role for signed-in users (
|
|
1905
|
-
.option("--anonymous <role>", "Role for anonymous users (
|
|
1928
|
+
.description("Set access policy; omitted options stay unchanged")
|
|
1929
|
+
.option("--signed-in <role>", "Role for signed-in users (builder|guest|null)")
|
|
1930
|
+
.option("--anonymous <role>", "Role for anonymous users (guest|null)")
|
|
1906
1931
|
.option("--json", "Output as JSON")
|
|
1907
1932
|
.action(async (opts) => {
|
|
1908
1933
|
const spaceId = await resolveSpace(spacesCmd);
|
|
1909
1934
|
const client = createClient();
|
|
1935
|
+
if (opts.signedIn === undefined && opts.anonymous === undefined) {
|
|
1936
|
+
return error("Nothing to update", "Pass --signed-in or --anonymous");
|
|
1937
|
+
}
|
|
1910
1938
|
try {
|
|
1911
1939
|
const policy = await client.space(spaceId).access.set({
|
|
1912
|
-
signed_in_user: parseNullableRole(opts.signedIn, "signed-in role"),
|
|
1913
|
-
anonymous_user: parseNullableRole(opts.anonymous, "anonymous role"),
|
|
1940
|
+
...(opts.signedIn !== undefined ? { signed_in_user: parseNullableRole(opts.signedIn, "signed-in role") } : {}),
|
|
1941
|
+
...(opts.anonymous !== undefined ? { anonymous_user: parseNullableRole(opts.anonymous, "anonymous role") } : {}),
|
|
1914
1942
|
});
|
|
1915
1943
|
if (jsonRequested(opts))
|
|
1916
1944
|
return outJson(policy);
|
|
1917
1945
|
ok("Access policy updated");
|
|
1918
|
-
table([policy],
|
|
1919
|
-
{ key: "signed_in_user", label: "Signed-in" },
|
|
1920
|
-
{ key: "anonymous_user", label: "Anonymous" },
|
|
1921
|
-
]);
|
|
1946
|
+
table([policy], ACCESS_COLUMNS);
|
|
1922
1947
|
}
|
|
1923
1948
|
catch (e) {
|
|
1924
1949
|
handleHttp(e);
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { HostEmit } from "./serve.js";
|
|
2
|
+
export declare class HostAuth {
|
|
3
|
+
#private;
|
|
4
|
+
private readonly emit;
|
|
5
|
+
private readonly onAccountChanged;
|
|
6
|
+
constructor(emit: HostEmit, onAccountChanged: () => void);
|
|
7
|
+
watch(): void;
|
|
8
|
+
close(): void;
|
|
9
|
+
get subject(): string | null;
|
|
10
|
+
accessToken(forceRefresh?: boolean): Promise<string | null>;
|
|
11
|
+
sessionVersion(): number;
|
|
12
|
+
session(): {
|
|
13
|
+
authenticated: boolean;
|
|
14
|
+
userUuid: null;
|
|
15
|
+
subject: string | null;
|
|
16
|
+
email: null;
|
|
17
|
+
};
|
|
18
|
+
signIn(redirectPath?: string): Promise<boolean>;
|
|
19
|
+
signOut(): Promise<boolean>;
|
|
20
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { mkdirSync, watch } from "node:fs";
|
|
2
|
+
import { basename, dirname } from "node:path";
|
|
3
|
+
import { HOST_SERVICE_SHELL_EVENTS, hostAuthChangedSchema, hostShellOpenSchema } from "@neta-art/cohub/host-bridge";
|
|
4
|
+
import { AuthRequiredError, authSessionPath, pollDeviceCode, readAuthSession, requestDeviceCode, resolveAccessToken, revokeAndClearAuthSession, } from "../auth.js";
|
|
5
|
+
import { clearHomeSpaceCache, jwtClaim } from "../space.js";
|
|
6
|
+
function snapshot() {
|
|
7
|
+
const session = readAuthSession();
|
|
8
|
+
if (!session)
|
|
9
|
+
return { subject: null, revision: null };
|
|
10
|
+
return {
|
|
11
|
+
subject: jwtClaim(session.idToken, "sub") ?? jwtClaim(session.accessToken, "sub"),
|
|
12
|
+
revision: `${session.updatedAt}:${session.refreshToken}`,
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
export class HostAuth {
|
|
16
|
+
emit;
|
|
17
|
+
onAccountChanged;
|
|
18
|
+
#current = snapshot();
|
|
19
|
+
#version = 0;
|
|
20
|
+
#watcher = null;
|
|
21
|
+
#debounce;
|
|
22
|
+
#rewatch;
|
|
23
|
+
#pending = null;
|
|
24
|
+
constructor(emit, onAccountChanged) {
|
|
25
|
+
this.emit = emit;
|
|
26
|
+
this.onAccountChanged = onAccountChanged;
|
|
27
|
+
}
|
|
28
|
+
watch() {
|
|
29
|
+
const path = authSessionPath();
|
|
30
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
31
|
+
this.#watcher = watch(dirname(path), (_event, name) => {
|
|
32
|
+
if (name && name !== basename(path))
|
|
33
|
+
return;
|
|
34
|
+
clearTimeout(this.#debounce);
|
|
35
|
+
this.#debounce = setTimeout(() => this.#sync(), 50);
|
|
36
|
+
});
|
|
37
|
+
this.#watcher.once("error", () => {
|
|
38
|
+
this.#watcher?.close();
|
|
39
|
+
this.#rewatch = setTimeout(() => this.watch(), 1_000).unref();
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
close() {
|
|
43
|
+
clearTimeout(this.#debounce);
|
|
44
|
+
clearTimeout(this.#rewatch);
|
|
45
|
+
this.#watcher?.close();
|
|
46
|
+
}
|
|
47
|
+
get subject() {
|
|
48
|
+
return this.#current.subject;
|
|
49
|
+
}
|
|
50
|
+
async accessToken(forceRefresh = false) {
|
|
51
|
+
try {
|
|
52
|
+
return await resolveAccessToken({ forceRefresh });
|
|
53
|
+
}
|
|
54
|
+
catch (error) {
|
|
55
|
+
if (error instanceof AuthRequiredError)
|
|
56
|
+
return null;
|
|
57
|
+
throw error;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
sessionVersion() {
|
|
61
|
+
return this.#version;
|
|
62
|
+
}
|
|
63
|
+
session() {
|
|
64
|
+
const { subject } = snapshot();
|
|
65
|
+
return { authenticated: subject !== null, userUuid: null, subject, email: null };
|
|
66
|
+
}
|
|
67
|
+
async signIn(redirectPath) {
|
|
68
|
+
const destination = hostAuthChangedSchema.shape.redirectPath.safeParse(redirectPath).data;
|
|
69
|
+
if (this.#pending && this.#pending.expiresAt > Date.now()) {
|
|
70
|
+
this.#pending.redirectPath = destination;
|
|
71
|
+
this.#open(this.#pending.url);
|
|
72
|
+
return true;
|
|
73
|
+
}
|
|
74
|
+
const code = await requestDeviceCode();
|
|
75
|
+
const pending = { url: code.verificationUriComplete, expiresAt: code.expiresAt, redirectPath: destination };
|
|
76
|
+
this.#pending = pending;
|
|
77
|
+
this.#open(pending.url);
|
|
78
|
+
void pollDeviceCode(code)
|
|
79
|
+
.then(() => this.#sync({ redirectPath: pending.redirectPath, signedIn: true }))
|
|
80
|
+
.catch((error) => process.stderr.write(`Sign-in did not complete: ${error instanceof Error ? error.message : String(error)}\n`))
|
|
81
|
+
.finally(() => { if (this.#pending === pending)
|
|
82
|
+
this.#pending = null; });
|
|
83
|
+
return true;
|
|
84
|
+
}
|
|
85
|
+
async signOut() {
|
|
86
|
+
await revokeAndClearAuthSession();
|
|
87
|
+
clearHomeSpaceCache();
|
|
88
|
+
this.#sync();
|
|
89
|
+
this.emit("auth.signedOut");
|
|
90
|
+
return true;
|
|
91
|
+
}
|
|
92
|
+
#open(url) {
|
|
93
|
+
this.emit(HOST_SERVICE_SHELL_EVENTS.open, hostShellOpenSchema.parse({ url }));
|
|
94
|
+
}
|
|
95
|
+
#sync({ redirectPath, signedIn = false } = {}) {
|
|
96
|
+
const next = snapshot();
|
|
97
|
+
const accountChanged = next.subject !== this.#current.subject;
|
|
98
|
+
if (next.revision !== this.#current.revision || accountChanged)
|
|
99
|
+
this.#version += 1;
|
|
100
|
+
this.#current = next;
|
|
101
|
+
if (accountChanged)
|
|
102
|
+
this.onAccountChanged();
|
|
103
|
+
if (!accountChanged && !signedIn)
|
|
104
|
+
return;
|
|
105
|
+
this.emit("auth.changed", hostAuthChangedSchema.parse({ authenticated: next.subject !== null, ...(redirectPath ? { redirectPath } : {}) }));
|
|
106
|
+
}
|
|
107
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function loginShellEnv(base?: NodeJS.ProcessEnv, platform?: NodeJS.Platform): Promise<NodeJS.ProcessEnv>;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
const TIMEOUT_MS = 10_000;
|
|
4
|
+
// Cohub settings come from the host, never from the user's shell.
|
|
5
|
+
const SCOPED = /^(COHUB_.*|ENV)$/;
|
|
6
|
+
const quote = (value) => `'${value.replaceAll("'", `'\\''`)}'`;
|
|
7
|
+
export async function loginShellEnv(base = process.env, platform = process.platform) {
|
|
8
|
+
const scoped = Object.fromEntries(Object.entries(base).filter(([key]) => SCOPED.test(key)));
|
|
9
|
+
if (platform === "win32")
|
|
10
|
+
return base;
|
|
11
|
+
const shell = base.SHELL || (platform === "darwin" ? "/bin/zsh" : "/bin/sh");
|
|
12
|
+
const mark = randomUUID();
|
|
13
|
+
const print = `${quote(process.execPath)} -e ${quote("process.stdout.write(JSON.stringify(process.env))")}`;
|
|
14
|
+
const output = await new Promise((resolve) => {
|
|
15
|
+
execFile(shell, ["-l", "-i", "-c", `printf %s ${mark}; ${print}; printf %s ${mark}`], {
|
|
16
|
+
encoding: "utf8", timeout: TIMEOUT_MS, maxBuffer: 4 * 1024 * 1024,
|
|
17
|
+
env: base,
|
|
18
|
+
}, (_error, stdout) => resolve(typeof stdout === "string" ? stdout : null));
|
|
19
|
+
});
|
|
20
|
+
const json = output?.split(mark)[1];
|
|
21
|
+
if (!json)
|
|
22
|
+
return base;
|
|
23
|
+
try {
|
|
24
|
+
const shellEnv = JSON.parse(json);
|
|
25
|
+
const inherited = Object.fromEntries(Object.entries(shellEnv).filter(([key]) => !SCOPED.test(key)));
|
|
26
|
+
return { ...inherited, ...scoped };
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
return base;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { DEVICE_RUNTIME_REFUSALS, DeviceFolderListing, DeviceRuntime } from "@neta-art/cohub/host-bridge";
|
|
2
|
+
import type { HostEmit } from "./serve.js";
|
|
3
|
+
type Refusal = (typeof DEVICE_RUNTIME_REFUSALS)[number];
|
|
4
|
+
export type DeviceRuntimeHostOptions = {
|
|
5
|
+
cli: string;
|
|
6
|
+
env: () => Promise<NodeJS.ProcessEnv>;
|
|
7
|
+
account: () => string | null;
|
|
8
|
+
};
|
|
9
|
+
export declare class DeviceRuntimeHost {
|
|
10
|
+
#private;
|
|
11
|
+
private readonly emit;
|
|
12
|
+
private readonly options;
|
|
13
|
+
constructor(emit: HostEmit, options: DeviceRuntimeHostOptions);
|
|
14
|
+
watch(): void;
|
|
15
|
+
close(): void;
|
|
16
|
+
changed(): void;
|
|
17
|
+
list(): Promise<DeviceRuntime>;
|
|
18
|
+
browse(path?: string): Promise<DeviceFolderListing>;
|
|
19
|
+
connect(spaceId: string, root: string): Promise<DeviceRuntime & {
|
|
20
|
+
refused: Refusal | null;
|
|
21
|
+
}>;
|
|
22
|
+
disconnect(spaceId: string): Promise<DeviceRuntime>;
|
|
23
|
+
restore(): Promise<void>;
|
|
24
|
+
}
|
|
25
|
+
export {};
|
|
@@ -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,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<
|
|
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 {};
|
package/dist/runtime/instance.js
CHANGED
|
@@ -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(
|
|
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
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
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
|
}
|
package/dist/runtime/launch.d.ts
CHANGED
|
@@ -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;
|
package/dist/runtime/launch.js
CHANGED
|
@@ -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
|
-
|
|
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
|
|
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
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@neta-art/cohub-cli",
|
|
3
|
-
"version": "10.
|
|
3
|
+
"version": "10.16.0",
|
|
4
4
|
"description": "CLI for Cohub — spaces, sessions, and agent collaboration.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"engines": {
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
"NOTICE"
|
|
19
19
|
],
|
|
20
20
|
"dependencies": {
|
|
21
|
-
"@neta-art/cohub": "13.
|
|
21
|
+
"@neta-art/cohub": "13.6.0",
|
|
22
22
|
"@neta-art/generation": "0.2.8",
|
|
23
23
|
"commander": "^15.0.0",
|
|
24
24
|
"sharp": "^0.35.4",
|