@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.
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)
@@ -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,2 @@
1
+ import type { Command } from "commander";
2
+ export declare function registerHost(program: Command): void;
@@ -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
+ }
@@ -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 directory = runtimeInstanceDirectory(identity, spaceId);
260
- const local = await requestRuntimeInstance(directory, "stop", Boolean(options.yes));
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>", "Validity in days, from 1 to 30", String(DEFAULT_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: "expiresInSeconds", label: "Expires in" },
159
+ { key: "expires", label: "Expires" },
139
160
  { key: "url", label: "URL" },
140
161
  ]);
141
162
  }
@@ -10,7 +10,7 @@ import { resolveSpace } from "../space.js";
10
10
  import { uploadLocalFiles } from "../space-files/upload.js";
11
11
  import { registerDecisionCommand } from "./decision.js";
12
12
  import { registerSpaceCommerce } from "./space-commerce.js";
13
- import { registerSpaceFileTransfer } from "./space-files.js";
13
+ import { formatBytes, registerSpaceFileTransfer } from "./space-files.js";
14
14
  import { registerSpaceWallet } from "./space-wallet.js";
15
15
  import { registerSpaceActivity } from "./space-activity.js";
16
16
  import { registerSpaceDisplays } from "./space-displays.js";
@@ -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
- return ok(`${opts.note ? "Note recorded" : "Prompt sent"} — sessionId: ${result.session.id}, turnId: ${result.turn.id}`);
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
@@ -586,13 +602,16 @@ export function registerSpaces(program) {
586
602
  const space = await client.spaces.get(spaceId);
587
603
  if (jsonRequested(opts))
588
604
  return outJson(space);
589
- table([space], [
605
+ const usage = space.workspaceUsage;
606
+ const storage = usage ? `${usage.bytes === null ? "-" : formatBytes(usage.bytes)} (${usage.status})` : undefined;
607
+ table([{ ...space, storage }], [
590
608
  { key: "id", label: "ID" },
591
609
  { key: "name", label: "Name" },
592
610
  { key: "slug", label: "Slug" },
593
611
  { key: "description", label: "Description", format: (value) => truncateText(value, SPACE_DESCRIPTION_COLUMN_WIDTH) },
594
612
  { key: "status", label: "Status" },
595
613
  { key: "createdAt", label: "Created" },
614
+ ...(storage ? [{ key: "storage", label: "Storage" }] : []),
596
615
  ]);
597
616
  }
598
617
  catch (e) {
@@ -674,6 +693,7 @@ export function registerSpaces(program) {
674
693
  .option("--idle-ttl <seconds>", "Idle auto destroy TTL in seconds, max 2592000 (30d)")
675
694
  .option("--spec <spec>", "Sandbox spec: standard, boost, ultra, or auto")
676
695
  .option("--image <image>", "Sandbox image: default, game, or auto")
696
+ .option("--guest-app <app>", "Published public App shown to visitors without access: id, slug, or none")
677
697
  .option("--json", "Output as JSON")
678
698
  .action(async (id, opts) => {
679
699
  const client = createClient();
@@ -681,8 +701,13 @@ export function registerSpaces(program) {
681
701
  const autoDestroy = parseAutoDestroy(opts);
682
702
  const spec = opts.spec === "auto" ? null : parseSandboxSpec(opts.spec);
683
703
  const image = opts.image === "auto" ? null : opts.image ? parseChoice(opts.image, "sandbox image", ["default", "game"]) : undefined;
684
- if (autoDestroy || spec !== undefined || image !== undefined) {
685
- const result = await client.space(id).updateConfig({ sandbox: { ...(autoDestroy ? { autoDestroy } : {}), ...(spec !== undefined ? { spec } : {}), ...(image !== undefined ? { image } : {}) } });
704
+ const guest = opts.guestApp === undefined ? undefined : await resolveGuestApp(client, id, opts.guestApp);
705
+ const sandboxChanged = Boolean(autoDestroy) || spec !== undefined || image !== undefined;
706
+ if (sandboxChanged || guest !== undefined) {
707
+ const result = await client.space(id).updateConfig({
708
+ ...(sandboxChanged ? { sandbox: { ...(autoDestroy ? { autoDestroy } : {}), ...(spec !== undefined ? { spec } : {}), ...(image !== undefined ? { image } : {}) } } : {}),
709
+ ...(guest !== undefined ? { guest } : {}),
710
+ });
686
711
  if (jsonRequested(opts))
687
712
  return outJson(result);
688
713
  ok(`Space config updated${autoDestroy ? ` — sandbox auto destroy: ${formatAutoDestroy(autoDestroy)}` : ""}${spec ? ` — sandbox spec: ${spec}` : ""}${result.sandbox?.pendingRestart ? " — restart the sandbox to apply" : ""}`);
@@ -701,6 +726,7 @@ export function registerSpaces(program) {
701
726
  { key: "sandbox.spec", value: result.config.sandbox.spec ?? "standard" },
702
727
  { key: "sandbox.appliedSpec", value: result.config.sandbox.appliedSpec ?? "—" },
703
728
  { key: "sandbox.allowedSpec", value: result.config.sandbox.allowedSpec ?? "standard" },
729
+ { key: "guest.appId", value: result.config.guest?.appId ?? "default" },
704
730
  ], [
705
731
  { key: "key", label: "Key" },
706
732
  { key: "value", label: "Value" },
@@ -731,6 +757,7 @@ export function registerSpaces(program) {
731
757
  .option("--env <key=value>", "Set an environment variable for this turn", collectOption, [])
732
758
  .option("--image <path>", "Attach an image", collectOption, [])
733
759
  .option("--note", "Record the message without an AI reply")
760
+ .option("--reply", "Send the final reply back to the calling Chat and run its Agent")
734
761
  .option("--json", "Output as JSON")
735
762
  .action((words, opts) => sendPrompt(spacesCmd, words, opts));
736
763
  // ── spaces completion ──
@@ -1873,6 +1900,10 @@ function registerMembers(spacesCmd) {
1873
1900
  });
1874
1901
  }
1875
1902
  // ── Access control ──
1903
+ const ACCESS_COLUMNS = [
1904
+ { key: "signed_in_user", label: "Signed-in" },
1905
+ { key: "anonymous_user", label: "Anonymous" },
1906
+ ];
1876
1907
  function registerAccess(spacesCmd) {
1877
1908
  const accCmd = spacesCmd
1878
1909
  .command("access")
@@ -1889,10 +1920,7 @@ function registerAccess(spacesCmd) {
1889
1920
  const policy = await client.space(spaceId).access.get();
1890
1921
  if (jsonRequested(opts))
1891
1922
  return outJson(policy);
1892
- table([policy], [
1893
- { key: "signed_in_user", label: "Signed-in" },
1894
- { key: "anonymous_user", label: "Anonymous" },
1895
- ]);
1923
+ table([policy], ACCESS_COLUMNS);
1896
1924
  }
1897
1925
  catch (e) {
1898
1926
  handleHttp(e);
@@ -1900,25 +1928,25 @@ function registerAccess(spacesCmd) {
1900
1928
  });
1901
1929
  accCmd
1902
1930
  .command("set")
1903
- .description("Set access policy")
1904
- .option("--signed-in <role>", "Role for signed-in users (host|builder|guest|null)")
1905
- .option("--anonymous <role>", "Role for anonymous users (host|builder|guest|null)")
1931
+ .description("Set access policy; omitted options stay unchanged")
1932
+ .option("--signed-in <role>", "Role for signed-in users (builder|guest|null)")
1933
+ .option("--anonymous <role>", "Role for anonymous users (guest|null)")
1906
1934
  .option("--json", "Output as JSON")
1907
1935
  .action(async (opts) => {
1908
1936
  const spaceId = await resolveSpace(spacesCmd);
1909
1937
  const client = createClient();
1938
+ if (opts.signedIn === undefined && opts.anonymous === undefined) {
1939
+ return error("Nothing to update", "Pass --signed-in or --anonymous");
1940
+ }
1910
1941
  try {
1911
1942
  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"),
1943
+ ...(opts.signedIn !== undefined ? { signed_in_user: parseNullableRole(opts.signedIn, "signed-in role") } : {}),
1944
+ ...(opts.anonymous !== undefined ? { anonymous_user: parseNullableRole(opts.anonymous, "anonymous role") } : {}),
1914
1945
  });
1915
1946
  if (jsonRequested(opts))
1916
1947
  return outJson(policy);
1917
1948
  ok("Access policy updated");
1918
- table([policy], [
1919
- { key: "signed_in_user", label: "Signed-in" },
1920
- { key: "anonymous_user", label: "Anonymous" },
1921
- ]);
1949
+ table([policy], ACCESS_COLUMNS);
1922
1950
  }
1923
1951
  catch (e) {
1924
1952
  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 {};