diff --git a/.changeset/cli-space-refs.md b/.changeset/cli-space-refs.md new file mode 100644 index 000000000..2461c8d35 --- /dev/null +++ b/.changeset/cli-space-refs.md @@ -0,0 +1,5 @@ +--- +"@neta-art/cohub-cli": patch +--- + +Space arguments on `spaces get/setup/update/rename/config/pin/unpin/archive/unarchive`, `search --space-id`, `references aggregate`, `apps authorize --space`, and `run -s` (before or after `run`) accept an ID, `home`, your own slug, or `username/slug`. `cohub -s search` scopes the search. `spaces sessions tail --json` now writes only JSONL to stdout. diff --git a/packages/cli/src/commands/apps.ts b/packages/cli/src/commands/apps.ts index 95a587596..f6c0e3f1e 100644 --- a/packages/cli/src/commands/apps.ts +++ b/packages/cli/src/commands/apps.ts @@ -4,7 +4,7 @@ import { getCohubContext, HttpError, isUserAppFilter, type CohubHttpClient, type import type { Command } from "commander"; import { createClient, createClientWithAccessToken } from "../client.js"; import { error, handleHttp, json as outJson, jsonRequested, ok, table } from "../output.js"; -import { resolveSpace } from "../space.js"; +import { explicitSpaceFlag, failSpaceTarget, resolveSpace, resolveSpaceRef } from "../space.js"; import { downloadApp } from "../app-download.js"; import { getAppByRef, parseAppRef } from "../app-ref.js"; import { checkAppTarget } from "../app-target.js"; @@ -799,22 +799,25 @@ export function registerApps(program: Command): void { .command("authorize ") .description("Grant an app scopes as the current user") .requiredOption("--scope ", "Scope to grant (repeatable)", collectOption, []) - .option("--space ", "Target space; defaults to the app's own space") + .option("--space ", "Target space (ID, home, slug, or username/slug); defaults to the app's own space") .option("--extend", "Add scopes without replacing active grants") .option("--json", "Output as JSON") - .action(async (appRef: string, opts: { scope: string[]; space?: string; extend?: boolean; json?: boolean }) => { + .action(async (appRef: string, opts: { scope: string[]; space?: string; extend?: boolean; json?: boolean }, command: Command) => { const client = createClient(); try { + // The root `-s, --space` option claims `--space` after the subcommand too; COHUB_SPACE_ID must not apply here. + const spaceRef = explicitSpaceFlag(command); + const spaceId = spaceRef ? await resolveSpaceRef(spaceRef) : undefined; const detail = await getAppByRef(client, appRef); const result = await client.apps.authorize(detail.app.id, { scopes: opts.scope as Permission[], - ...(opts.space ? { spaceId: opts.space } : {}), + ...(spaceId ? { spaceId } : {}), ...(opts.extend ? { scopeMode: "extend" as const } : {}), }); if (jsonRequested(opts)) return outJson(result); ok(`Granted ${result.grant.scopes.join(", ")} on space ${result.grant.spaceId}`); } catch (e: unknown) { - handleHttp(e); + failSpaceTarget(e); } }); diff --git a/packages/cli/src/commands/models.ts b/packages/cli/src/commands/models.ts index f9a7393fc..f4d9a4908 100644 --- a/packages/cli/src/commands/models.ts +++ b/packages/cli/src/commands/models.ts @@ -199,7 +199,7 @@ export function registerModels(program: Command): void { Examples: cohub models ls - cohub models ls --space + cohub models ls --space cohub models ls --model-type multimodal cohub models ls --model-type multimodal --category video cohub models ls --model-type multimodal --json diff --git a/packages/cli/src/commands/references.ts b/packages/cli/src/commands/references.ts index 01f8def2d..bdce80219 100644 --- a/packages/cli/src/commands/references.ts +++ b/packages/cli/src/commands/references.ts @@ -1,13 +1,13 @@ -import { - isUuid, - type ReferenceAggregateGroupBy, - type ReferenceDirection, - type ReferenceKind, - type ReferenceQueryableType, +import type { + ReferenceAggregateGroupBy, + ReferenceDirection, + ReferenceKind, + ReferenceQueryableType, } from "@neta-art/cohub"; import type { Command } from "commander"; import { createClient } from "../client.js"; import { formatLocalDateTime, table, json as outJson, jsonRequested, error, handleHttp, type Row } from "../output.js"; +import { failSpaceTarget, resolveSpaceRef } from "../space.js"; const RESOURCE_TYPES = new Set([ "turn", @@ -152,7 +152,7 @@ Examples: references .command("aggregate") .description("Grouped reference counts for a space") - .argument("", "Space id") + .argument("", "Space: ID, home, slug, or username/slug") .option("--group-by ", "kind | targetType | target | sourceType | day", "kind") .option("--kinds ", "Comma-separated kinds (see list below)") .option("--days ", "Only references seen within the last N days") @@ -166,21 +166,21 @@ Notes: --group-by target: file targets look like {spaceId}:{path} Examples: - cohub references aggregate --json - cohub references aggregate --group-by targetType - cohub references aggregate --group-by target --kinds agent_tool_file_read --limit 20 - cohub references aggregate --group-by day --days 30 + cohub references aggregate --json + cohub references aggregate --group-by targetType + cohub references aggregate --group-by target --kinds agent_tool_file_read --limit 20 + cohub references aggregate --group-by day --days 30 `) - .action(async (spaceId: string, opts: AggregateOpts) => { + .action(async (space: string, opts: AggregateOpts) => { const client = createClient(); try { - if (!isUuid(spaceId.trim())) return error("Invalid space id"); const groupBy = (opts.groupBy ?? "kind") as ReferenceAggregateGroupBy; if (!GROUP_BYS.has(groupBy)) return error(`Invalid group-by: ${opts.groupBy}`); const kinds = parseKinds(opts.kinds); const days = opts.days ? clampNumber(opts.days, 30, 1, 365) : undefined; const limit = clampNumber(opts.limit, 200, 1, 500); - const result = await client.references.aggregate({ spaceId: spaceId.trim(), groupBy, kinds, days, limit }); + const spaceId = await resolveSpaceRef(space).catch(failSpaceTarget); + const result = await client.references.aggregate({ spaceId, groupBy, kinds, days, limit }); if (jsonRequested(opts)) return outJson(result); const rows: Row[] = result.groups.map((g) => ({ group: g.group, diff --git a/packages/cli/src/commands/run.ts b/packages/cli/src/commands/run.ts index b71543ac2..dd6470f5c 100644 --- a/packages/cli/src/commands/run.ts +++ b/packages/cli/src/commands/run.ts @@ -53,17 +53,19 @@ function topLevelRunIndex(argv: string[]): number { return -1; } -function parseSpaceId(tokens: string[]): string | undefined { - for (let index = 0; index < tokens.length; index += 1) { - const token = tokens[index] ?? ""; - if (token === "-s" || token === "--space") { - const value = tokens[index + 1]; - if (!value) return error("Missing space", `${token} requires a value`); - return value.trim() || undefined; - } - if (token.startsWith("--space=")) return token.slice("--space=".length).trim() || undefined; +function parseSpaceOption(tokens: string[], index: number): { value: string; nextIndex: number } | null { + const token = tokens[index] ?? ""; + if (token === "-s" || token === "--space") { + const value = tokens[index + 1]?.trim(); + if (!value) return error("Missing space", `${token} requires a value`); + return { value, nextIndex: index + 1 }; + } + if (token.startsWith("--space=")) { + const value = token.slice("--space=".length).trim(); + if (!value) return error("Missing space", "--space requires a value"); + return { value, nextIndex: index }; } - return undefined; + return null; } export async function parseRunCliOptions( @@ -76,12 +78,20 @@ export async function parseRunCliOptions( const beforeRun = argv.slice(0, runIndex); const afterRun = argv.slice(runIndex + 1); + let explicitSpaceId: string | undefined; for (let index = 0; index < beforeRun.length; index += 1) { - index = consumeBaseUrlOption(beforeRun, index) ?? index; - if (beforeRun[index] === "-s" || beforeRun[index] === "--space") index += 1; + const endpointIndex = consumeBaseUrlOption(beforeRun, index); + if (endpointIndex !== null) { + index = endpointIndex; + continue; + } + const spaceOption = parseSpaceOption(beforeRun, index); + if (spaceOption) { + explicitSpaceId = spaceOption.value; + index = spaceOption.nextIndex; + } } - const explicitSpaceId = parseSpaceId(beforeRun) ?? process.env.COHUB_SPACE_ID?.trim() ?? ""; let json = beforeRun.includes("--json"); let async = false; let commandOption: string | null = null; @@ -96,6 +106,13 @@ export async function parseRunCliOptions( continue; } + const spaceOption = parseSpaceOption(afterRun, index); + if (spaceOption) { + explicitSpaceId = spaceOption.value; + index = spaceOption.nextIndex; + continue; + } + if (token === "-h" || token === "--help") { printRunHelp(); process.exit(0); @@ -159,9 +176,11 @@ export function printRunHelp(): void { process.stdout.write(` Usage: cohub [--base-url ] [-s ] run [options] -- + cohub run [-s ] [options] -- cohub [-s ] run --command Options: + -s, --space Target Space: ID, slug, or username/slug --base-url API base URL (overrides COHUB_BASE_URL) -c, --command Shell command to execute in the space workspace --async Queue the command and return immediately @@ -169,9 +188,9 @@ Options: -h, --help Show this help Examples: - cohub -s run --command "git status" - cohub -s run --async --command "pnpm test" - cohub -s run -- git status -sb + cohub -s run --command "git status" + cohub -s run --async --command "pnpm test" + cohub -s run -- git status -sb Notes: - Without -s or COHUB_SPACE_ID, the command uses the current directory Runtime binding; it never falls back to Home. diff --git a/packages/cli/src/commands/search.ts b/packages/cli/src/commands/search.ts index 540ddec61..1f15d4a09 100644 --- a/packages/cli/src/commands/search.ts +++ b/packages/cli/src/commands/search.ts @@ -1,7 +1,8 @@ -import { isUuid, type GlobalSearchResult, type GlobalSearchType } from "@neta-art/cohub"; +import type { GlobalSearchResult, GlobalSearchType } from "@neta-art/cohub"; import type { Command } from "commander"; import { createClient } from "../client.js"; -import { formatLocalDateTime, table, json as outJson, jsonRequested, error, handleHttp, truncateText, type Row } from "../output.js"; +import { formatLocalDateTime, table, json as outJson, jsonRequested, error, truncateText, type Row } from "../output.js"; +import { explicitSpaceFlag, failSpaceTarget, resolveSpaceRef } from "../space.js"; const DEFAULT_LIMIT = 20; const MAX_TITLE_LENGTH = 72; @@ -48,13 +49,6 @@ function parseTypes(value: string | undefined): GlobalSearchType[] | undefined { return [...new Set(types)] as GlobalSearchType[]; } -function parseSearchInput(opts: SearchCliOptions) { - const types = parseTypes(opts.types); - const spaceId = opts.spaceId?.trim(); - if (spaceId && !isUuid(spaceId)) throw new Error("Invalid space id"); - return { types, spaceId: spaceId || undefined, labelRef: opts.labelRef?.trim() || undefined }; -} - function rowsFor(items: GlobalSearchResult[]): Row[] { return items.map((item) => ({ type: item.type, @@ -73,7 +67,7 @@ export function registerSearch(program: Command): void { .argument("[query]", "Search query") .option("--limit ", "Maximum results, 1-50", String(DEFAULT_LIMIT)) .option("--types ", "Comma-separated result types: chat,space,label") - .option("--space-id ", "Limit search to a space") + .option("--space-id ", "Limit search to a space (ID, home, slug, or username/slug)") .option("--label-ref ", "Search items under an exact label ref") .option("--json", "Output as JSON") .addHelpText("after", ` @@ -81,23 +75,27 @@ export function registerSearch(program: Command): void { Examples: cohub search "release notes" cohub search "failing tests" --limit 10 - cohub search "bug" --types chat --space-id + cohub search "bug" --types chat --space-id + cohub -s search "bug" --types chat cohub search --types label --label-ref bug cohub search "login" --types label --label-ref bug cohub search "design review" --json `) - .action(async (query: string | undefined, opts: SearchCliOptions) => { + .action(async (query: string | undefined, opts: SearchCliOptions, command: Command) => { const client = createClient(); try { - const input = parseSearchInput(opts); + const types = parseTypes(opts.types); + const labelRef = opts.labelRef?.trim() || undefined; const q = query ?? ""; - if (!q.trim() && !input.labelRef) return error("Search query is required unless --label-ref is provided."); + if (!q.trim() && !labelRef) return error("Search query is required unless --label-ref is provided."); + const spaceRef = opts.spaceId?.trim() || explicitSpaceFlag(command); + const spaceId = spaceRef ? await resolveSpaceRef(spaceRef) : undefined; const result = await client.search.query({ q, limit: clampLimit(opts.limit), - types: input.types, - spaceId: input.spaceId, - labelRef: input.labelRef, + types, + spaceId, + labelRef, }); if (jsonRequested(opts)) return outJson(result); @@ -114,10 +112,10 @@ Examples: { key: "href", label: "Href" }, ]); } catch (e: unknown) { - if (e instanceof Error && (e.message === "Invalid space id" || e.message.startsWith("Invalid search type:"))) { + if (e instanceof Error && e.message.startsWith("Invalid search type:")) { return error(e.message); } - handleHttp(e); + failSpaceTarget(e); } }); } diff --git a/packages/cli/src/commands/spaces.ts b/packages/cli/src/commands/spaces.ts index d4a73c402..433f4d35b 100644 --- a/packages/cli/src/commands/spaces.ts +++ b/packages/cli/src/commands/spaces.ts @@ -17,7 +17,7 @@ import { createClient, createRealtimeClient } from "../client.js"; import { collectOption, readPromptContent } from "../command-input.js"; import { table, json as outJson, jsonRequested, ok, error, handleHttp, formatEpochMs, truncateText } from "../output.js"; import { SESSION_INITIATOR_COLUMN, SESSION_STATUS_COLUMN, sessionArchiveFilter } from "../session-status.js"; -import { resolveSpace } from "../space.js"; +import { explicitSpace, failSpaceTarget, resolveSpace, resolveSpaceRef, resolveSpaceTarget } from "../space.js"; import { uploadLocalFiles, type LocalUploadEntry } from "../space-files/upload.js"; import { registerDecisionCommand } from "./decision.js"; import { registerSpaceCommerce } from "./space-commerce.js"; @@ -558,12 +558,12 @@ function registerUserLabels(program: Command) { export function registerSpaceSetup(spacesCmd: Command, deps: { createClient?: typeof createClient } = {}): void { spacesCmd - .command("setup [id]") + .command("setup [space]") .description("Show cloud sandbox startup scripts, results, and log paths") .option("--json", "Output as JSON") .action(async (id: string | undefined, opts: { json?: boolean }) => { try { - const spaceId = id ?? await resolveSpace(spacesCmd); + const spaceId = await resolveSpaceTarget(id?.trim() || explicitSpace(spacesCmd)); const { sandbox } = await (deps.createClient ?? createClient)().space(spaceId).sandbox.get(); const setup = sandbox?.meta?.setup ?? null; if (jsonRequested(opts)) return outJson({ provider: sandbox?.provider ?? null, setup }); @@ -580,7 +580,7 @@ export function registerSpaceSetup(spacesCmd: Command, deps: { createClient?: ty { key: "script", label: "Script" }, { key: "status", label: "Status" }, { key: "duration", label: "Duration" }, { key: "logs", label: "Logs" }, ]); - } catch (e: unknown) { handleHttp(e); } + } catch (e: unknown) { failSpaceTarget(e); } }); } @@ -632,31 +632,33 @@ export function registerSpaces(program: Command): void { for (const archive of [true, false]) { spacesCmd - .command(archive ? "archive " : "unarchive ") + .command(archive ? "archive " : "unarchive ") .description(archive ? "Archive spaces in your personal view" : "Restore archived spaces") .option("--json", "Output as JSON") .action(async (ids: string[], opts: { json?: boolean }) => { const client = createClient(); try { - const chunks = Array.from({ length: Math.ceil(ids.length / 200) }, (_, index) => ids.slice(index * 200, (index + 1) * 200)); + const resolvedIds: string[] = []; + for (const id of ids) resolvedIds.push(await resolveSpaceRef(id)); + const chunks = Array.from({ length: Math.ceil(resolvedIds.length / 200) }, (_, index) => resolvedIds.slice(index * 200, (index + 1) * 200)); for (const chunk of chunks) await client.user.labels.patchResources(chunk, archive ? { addLabelRefs: ["Archived"], removeLabelRefs: ["Pinned"] } : { removeLabelRefs: ["Archived"] }); - if (jsonRequested(opts)) return outJson({ ids, archived: archive }); - ok(`${archive ? "Archived" : "Unarchived"} ${ids.length} space(s)`); - } catch (e: unknown) { handleHttp(e); } + if (jsonRequested(opts)) return outJson({ ids: resolvedIds, archived: archive }); + ok(`${archive ? "Archived" : "Unarchived"} ${resolvedIds.length} space(s)`); + } catch (e: unknown) { failSpaceTarget(e); } }); } // ── spaces get ── spacesCmd - .command("get [id]") + .command("get [space]") .description("Show space details") .option("--json", "Output as JSON") .action(async (id: string | undefined, opts: { json?: boolean }) => { - const spaceId = id?.trim() || await resolveSpace(spacesCmd); const client = createClient(); try { + const spaceId = await resolveSpaceTarget(id?.trim() || explicitSpace(spacesCmd)); const [space, overview] = await Promise.all([ client.spaces.get(spaceId), client.space(spaceId).overview.get().catch(() => null), @@ -677,7 +679,7 @@ export function registerSpaces(program: Command): void { ]); if (overview) printSpaceOverview(overview); } catch (e: unknown) { - handleHttp(e); + failSpaceTarget(e); } }); @@ -686,7 +688,7 @@ export function registerSpaces(program: Command): void { // ── spaces update ── spacesCmd - .command("update ") + .command("update ") .description("Update a space") .option("--name ", "Space name") .option("--slug ", "Public space slug") @@ -702,7 +704,8 @@ export function registerSpaces(program: Command): void { const client = createClient(); try { - const result = await client.space(id).update(input); + const spaceId = await resolveSpaceRef(id); + const result = await client.space(spaceId).update(input); if (jsonRequested(opts)) return outJson(result); ok("Space updated"); table([result.space], [ @@ -711,21 +714,22 @@ export function registerSpaces(program: Command): void { { key: "slug", label: "Slug" }, ]); } catch (e: unknown) { - handleHttp(e); + failSpaceTarget(e); } }); // ── spaces rename ── spacesCmd - .command("rename ") + .command("rename ") .description("Rename a space") .action(async (id: string, name: string) => { const client = createClient(); try { - await client.space(id).rename(name); + const spaceId = await resolveSpaceRef(id); + await client.space(spaceId).rename(name); ok(`Space renamed to "${name}"`); } catch (e: unknown) { - handleHttp(e); + failSpaceTarget(e); } }); @@ -771,7 +775,7 @@ export function registerSpaces(program: Command): void { // ── spaces config ── spacesCmd - .command("config ") + .command("config ") .description("Show or update space configuration") .option("--auto-destroy ", "Sandbox auto destroy mode: idle or never") .option("--idle-ttl ", "Idle auto destroy TTL in seconds, max 2592000 (30d)") @@ -785,10 +789,11 @@ export function registerSpaces(program: Command): void { const autoDestroy = parseAutoDestroy(opts); const spec = opts.spec === "auto" ? null : parseSandboxSpec(opts.spec); const image = opts.image === "auto" ? null : opts.image ? parseChoice(opts.image, "sandbox image", ["default", "game"] as const) : undefined; - const guest = opts.guestApp === undefined ? undefined : await resolveGuestApp(client, id, opts.guestApp); + const spaceId = await resolveSpaceRef(id); + const guest = opts.guestApp === undefined ? undefined : await resolveGuestApp(client, spaceId, opts.guestApp); const sandboxChanged = Boolean(autoDestroy) || spec !== undefined || image !== undefined; if (sandboxChanged || guest !== undefined) { - const result = await client.space(id).updateConfig({ + const result = await client.space(spaceId).updateConfig({ ...(sandboxChanged ? { sandbox: { ...(autoDestroy ? { autoDestroy } : {}), ...(spec !== undefined ? { spec } : {}), ...(image !== undefined ? { image } : {}) } } : {}), ...(guest !== undefined ? { guest } : {}), }); @@ -796,7 +801,7 @@ export function registerSpaces(program: Command): void { ok(`Space config updated${autoDestroy ? ` — sandbox auto destroy: ${formatAutoDestroy(autoDestroy)}` : ""}${spec ? ` — sandbox spec: ${spec}` : ""}${result.sandbox?.pendingRestart ? " — restart the sandbox to apply" : ""}`); return; } - const result = await client.space(id).getConfig(); + const result = await client.space(spaceId).getConfig(); if (jsonRequested(opts)) return outJson(result); table([ { key: "sandbox.autoDestroy", value: formatAutoDestroy(result.config.sandbox.autoDestroy) }, @@ -814,7 +819,7 @@ export function registerSpaces(program: Command): void { { key: "value", label: "Value" }, ]); } catch (e: unknown) { - handleHttp(e); + failSpaceTarget(e); } }); @@ -893,28 +898,30 @@ export function registerSpaces(program: Command): void { // ── spaces pin / unpin (user-scope label convenience) ── spacesCmd - .command("pin ") + .command("pin ") .description("Pin a space (add the Pinned user label)") .action(async (id: string) => { const client = createClient(); try { - await client.user.labels.patchResourceLabels("space", id.trim(), { addLabelRefs: ["Pinned"] }); + const spaceId = await resolveSpaceRef(id); + await client.user.labels.patchResourceLabels("space", spaceId, { addLabelRefs: ["Pinned"] }); ok("Space pinned"); } catch (e: unknown) { - handleHttp(e); + failSpaceTarget(e); } }); spacesCmd - .command("unpin ") + .command("unpin ") .description("Unpin a space (remove the Pinned user label)") .action(async (id: string) => { const client = createClient(); try { - await client.user.labels.patchResourceLabels("space", id.trim(), { removeLabelRefs: ["Pinned"] }); + const spaceId = await resolveSpaceRef(id); + await client.user.labels.patchResourceLabels("space", spaceId, { removeLabelRefs: ["Pinned"] }); ok("Space unpinned"); } catch (e: unknown) { - handleHttp(e); + failSpaceTarget(e); } }); @@ -1511,6 +1518,73 @@ type SessionCreateOptions = { json?: boolean; }; +type TailSession = { + on(event: "turn.patch" | "turn.finalized" | "turn.error", handler: (event: { payload?: Record }) => void): unknown; +}; + +type TailClient = { + disconnect(): Promise; +}; + +export function attachSessionTail( + client: TailClient, + session: TailSession, + options: { + json: boolean; + stdout?: { write(chunk: string): unknown }; + stderr?: { write(chunk: string): unknown }; + exit?: (code: number) => void; + }, +): void { + const stdout = options.stdout ?? process.stdout; + const stderr = options.stderr ?? process.stderr; + // process.exit drops pending pipe writes; the empty write's callback runs once earlier records are flushed. + const exit = options.exit ?? ((code: number) => process.stdout.write("", () => process.exit(code))); + let exiting = false; + const finish = async (code: number) => { + if (exiting) return; + exiting = true; + await client.disconnect().catch(() => undefined); + exit(code); + }; + + if (!options.json) stdout.write(" Listening for events...\n\n"); + + let lastAppendPath: string | null = null; + session.on("turn.patch", (e: { payload?: Record }) => { + if (options.json) { + stdout.write(`${JSON.stringify(e)}\n`); + return; + } + const ops = e.payload?.ops as Array<{ o?: string; p?: string; v?: unknown }> | undefined; + for (const op of ops ?? []) { + if (op.o === "append" && typeof op.v === "string" && op.p?.endsWith("/text")) { + lastAppendPath = op.p; + stdout.write(op.v); + continue; + } + if (op.o === "append" && typeof op.p === "string") { + lastAppendPath = op.p; + continue; + } + if (!op.o && !op.p && typeof op.v === "string" && lastAppendPath?.endsWith("/text")) { + stdout.write(op.v); + } + } + }); + + session.on("turn.finalized", () => { + if (!options.json) stdout.write("\n\n ✓ Done\n"); + void finish(0); + }); + + session.on("turn.error", (e: unknown) => { + stderr.write("\n ✗ Error\n"); + if (options.json) stderr.write(`${JSON.stringify(e)}\n`); + void finish(1); + }); +} + function registerSessions(spacesCmd: Command): void { const sessionsCmd = spacesCmd .command("sessions") @@ -1710,42 +1784,8 @@ function registerSessions(spacesCmd: Command): void { const client = createRealtimeClient(); const session = client.space(spaceId).session(id); - process.stdout.write(" Listening for events...\n\n"); - process.once("SIGINT", () => void client.disconnect().finally(() => process.exit(130))); - - let lastAppendPath: string | null = null; - session.on("turn.patch", (e: { payload?: Record }) => { - if (jsonRequested(opts)) { - console.log(JSON.stringify(e)); - } else { - const ops = e.payload?.ops as Array<{ o?: string; p?: string; v?: unknown }> | undefined; - for (const op of ops ?? []) { - if (op.o === "append" && typeof op.v === "string" && op.p?.endsWith("/text")) { - lastAppendPath = op.p; - process.stdout.write(op.v); - continue; - } - if (op.o === "append" && typeof op.p === "string") { - lastAppendPath = op.p; - continue; - } - if (!op.o && !op.p && typeof op.v === "string" && lastAppendPath?.endsWith("/text")) { - process.stdout.write(op.v); - } - } - } - }); - - session.on("turn.finalized", () => { - process.stdout.write("\n\n ✓ Done\n"); - process.exit(0); - }); - - session.on("turn.error", (e: unknown) => { - process.stderr.write(`\n ✗ Error\n`); - if (jsonRequested(opts)) process.stderr.write(`${JSON.stringify(e)}\n`); - process.exit(1); - }); + process.once("SIGINT", () => void client.disconnect().catch(() => undefined).finally(() => process.exit(130))); + attachSessionTail(client, session, { json: jsonRequested(opts) }); }); // ── sessions turns ── diff --git a/packages/cli/src/help-path.ts b/packages/cli/src/help-path.ts index ef631cd98..2441407c6 100644 --- a/packages/cli/src/help-path.ts +++ b/packages/cli/src/help-path.ts @@ -83,11 +83,11 @@ function runRemainderRequestsHelp(argv: string[]): boolean { if (token === "--") return false; if (isHelpFlag(token)) return true; if (token === "--async" || token === "--json") continue; - if (token === "-c" || token === "--command" || token === "--base-url") { + if (token === "-c" || token === "--command" || token === "--base-url" || token === "-s" || token === "--space") { index += 1; continue; } - if (token.startsWith("--command=") || token.startsWith("--base-url=")) continue; + if (token.startsWith("--command=") || token.startsWith("--base-url=") || token.startsWith("--space=")) continue; return false; } return false; diff --git a/packages/cli/src/space.ts b/packages/cli/src/space.ts index e713302c4..1007c15b8 100644 --- a/packages/cli/src/space.ts +++ b/packages/cli/src/space.ts @@ -114,15 +114,20 @@ export function clearHomeSpaceCache(): void { } } -/** Explicit target from `-s/--space` (any ancestor) or `COHUB_SPACE_ID`, else null. */ -export function explicitSpace(program: Command): string | null { - let current: Command | null = program; +/** Explicit `-s/--space` flag from `command` or any ancestor, ignoring `COHUB_SPACE_ID`. */ +export function explicitSpaceFlag(command: Command): string | null { + let current: Command | null = command; while (current) { const opts = current.opts() as Record; if (typeof opts.space === "string" && opts.space.trim()) return opts.space.trim(); current = current.parent ?? null; } - return process.env.COHUB_SPACE_ID?.trim() || null; + return null; +} + +/** Explicit target from `-s/--space` (any ancestor) or `COHUB_SPACE_ID`, else null. */ +export function explicitSpace(program: Command): string | null { + return explicitSpaceFlag(program) ?? (process.env.COHUB_SPACE_ID?.trim() || null); } /** Cached per identity and memoized per process. */ diff --git a/packages/cli/tests/help-path.test.ts b/packages/cli/tests/help-path.test.ts index bdd182bd5..632e3f213 100644 --- a/packages/cli/tests/help-path.test.ts +++ b/packages/cli/tests/help-path.test.ts @@ -45,7 +45,10 @@ test("unknown prefixes error instead of dumping root help", () => { test("run help follows run's own parsing rules", () => { assert.equal(kind(["run", "--help"]), "run-help"); + assert.equal(kind(["run", "-s", "atou/project", "--help"]), "run-help"); + assert.equal(kind(["run", "--space=atou/project", "--help"]), "run-help"); assert.equal(kind(["run", "npm", "--help"]), "passthrough"); + assert.equal(kind(["run", "-s", "atou/project", "npm", "--help"]), "passthrough"); assert.equal(kind(["run", "--async", "npm", "--help"]), "passthrough"); assert.equal(kind(["run", "--command", "--help"]), "passthrough"); }); diff --git a/packages/cli/tests/run.test.ts b/packages/cli/tests/run.test.ts index 991addda2..d644a76dc 100644 --- a/packages/cli/tests/run.test.ts +++ b/packages/cli/tests/run.test.ts @@ -1,11 +1,14 @@ import assert from "node:assert/strict"; -import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { mkdtemp, realpath, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, test } from "node:test"; import { resolveCohubEnvironment } from "@neta-art/cohub"; import { parseRunCliOptions } from "../src/commands/run.js"; +const SPACE_A = "11111111-1111-4111-8111-111111111111"; +const SPACE_B = "22222222-2222-4222-8222-222222222222"; + const roots: string[] = []; function jwt(payload: Record): string { @@ -17,7 +20,7 @@ afterEach(async () => { }); test("cohub run uses the current directory Runtime binding", async () => { - const root = await mkdtemp(join(tmpdir(), "cohub-run-binding-")); + const root = await realpath(await mkdtemp(join(tmpdir(), "cohub-run-binding-"))); roots.push(root); const path = join(root, "runtime-spaces.json"); const previousToken = process.env.COHUB_EXECUTION_TOKEN; @@ -39,3 +42,25 @@ test("cohub run uses the current directory Runtime binding", async () => { else process.env.COHUB_SPACE_ID = previousSpace; } }); + +test("cohub run accepts -s/--space after run without taking the command's own flags", async () => { + const previousSpace = process.env.COHUB_SPACE_ID; + delete process.env.COHUB_SPACE_ID; + try { + assert.deepEqual( + await parseRunCliOptions(["run", "--space", SPACE_A, "--async", "--json", "--", "git", "status", "-s"]), + { spaceId: SPACE_A, json: true, async: true, command: "git status -s" }, + ); + assert.deepEqual( + await parseRunCliOptions(["run", `--space=${SPACE_A}`, "git", "status", "-s"]), + { spaceId: SPACE_A, json: false, async: false, command: "git status -s" }, + ); + assert.deepEqual( + await parseRunCliOptions(["-s", SPACE_A, "run", "-s", SPACE_B, "-c", "git status"]), + { spaceId: SPACE_B, json: false, async: false, command: "git status" }, + ); + } finally { + if (previousSpace === undefined) delete process.env.COHUB_SPACE_ID; + else process.env.COHUB_SPACE_ID = previousSpace; + } +}); diff --git a/packages/cli/tests/space-ref-cli.test.ts b/packages/cli/tests/space-ref-cli.test.ts new file mode 100644 index 000000000..fb4a73cf5 --- /dev/null +++ b/packages/cli/tests/space-ref-cli.test.ts @@ -0,0 +1,196 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { Command } from "commander"; +import { registerApps } from "../src/commands/apps.js"; +import { registerSearch } from "../src/commands/search.js"; +import { attachSessionTail, registerSpaces } from "../src/commands/spaces.js"; + +const HOME_ID = "11111111-1111-4111-8111-111111111111"; +const OWNED_ID = "22222222-2222-4222-8222-222222222222"; +const OTHER_ID = "33333333-3333-4333-8333-333333333333"; +const APP_ID = "44444444-4444-4444-8444-444444444444"; + +let mockApiSeq = 0; + +type RecordedRequest = { + method: string; + path: string; + query: URLSearchParams; + body: unknown; +}; + +function parseRequestBody(raw: BodyInit | null | undefined): unknown { + if (typeof raw !== "string" || !raw.trim()) return undefined; + return JSON.parse(raw); +} + +async function withMockApi( + fn: (ctx: { requests: RecordedRequest[]; runCli: (argv: string[]) => Promise }) => Promise, +): Promise { + const requests: RecordedRequest[] = []; + const previousFetch = globalThis.fetch; + const previousBaseUrl = process.env.COHUB_BASE_URL; + const previousToken = process.env.COHUB_EXECUTION_TOKEN; + const previousSpace = process.env.COHUB_SPACE_ID; + process.env.COHUB_BASE_URL = `https://cohub-space-ref-test-${++mockApiSeq}.invalid`; + process.env.COHUB_EXECUTION_TOKEN = "test-token"; + + globalThis.fetch = async (input, init) => { + const url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url); + const method = (init?.method ?? (input instanceof Request ? input.method : "GET")).toUpperCase(); + const body = parseRequestBody(init?.body); + requests.push({ method, path: url.pathname, query: url.searchParams, body }); + + const json = (status: number, payload: unknown) => + new Response(JSON.stringify(payload), { + status, + headers: { "content-type": "application/json" }, + }); + + if (method === "POST" && url.pathname === "/api/me/spaces/home") { + return json(200, { id: HOME_ID, name: "Home", slug: "home" }); + } + if (method === "GET" && url.pathname === "/api/me/spaces/by-slug/notes") { + return json(200, { id: OWNED_ID, name: "Notes", slug: "notes" }); + } + if (method === "GET" && url.pathname === "/api/spaces/by-slug/atou/project") { + return json(200, { id: OTHER_ID, name: "Project", slug: "project" }); + } + if (method === "GET" && url.pathname === "/api/search") { + return json(200, { items: [], degraded: false }); + } + if (method === "GET" && /^\/api\/spaces\/[^/]+$/.test(url.pathname)) { + const id = url.pathname.split("/").at(-1); + return json(200, { id, name: "Space", slug: "space", status: "active", createdAt: "2026-01-01T00:00:00.000Z" }); + } + if (method === "GET" && /^\/api\/spaces\/[^/]+\/overview$/.test(url.pathname)) { + return json(200, { days: 30, apps: { count: 0, views: 0, likes: 0 } }); + } + if (method === "PATCH" && /^\/api\/spaces\/[^/]+$/.test(url.pathname)) { + const id = url.pathname.split("/").at(-1); + return json(200, { space: { id, name: "Updated", slug: "updated" } }); + } + if (method === "PATCH" && /^\/api\/spaces\/[^/]+\/config$/.test(url.pathname)) { + return json(200, { config: { sandbox: { spec: "boost" }, guest: null }, sandbox: { pendingRestart: false } }); + } + if (method === "GET" && /^\/api\/apps\/space\/[^/]+$/.test(url.pathname)) { + return json(200, { apps: [{ id: "app-1", slug: "welcome" }] }); + } + if (method === "GET" && url.pathname === `/api/apps/${APP_ID}`) { + return json(200, { app: { id: APP_ID } }); + } + if (method === "POST" && url.pathname === `/api/apps/${APP_ID}/authorize`) { + return json(200, { grant: { scopes: ["space.view"], spaceId: (body as { spaceId?: string }).spaceId ?? "app-space" } }); + } + if (method === "PATCH" && url.pathname === "/api/me/resources/space/labels/batch") { + return json(200, { resourceRefs: [], affectedLabelIds: [] }); + } + return json(404, { message: `Unhandled ${method} ${url.pathname}` }); + }; + + const runCli = async (argv: string[]): Promise => { + const program = new Command("cohub") + .option("-s, --space ", "Target Space"); + registerSearch(program); + registerSpaces(program); + registerApps(program); + + const logs: string[] = []; + const originalLog = console.log; + console.log = (...values: unknown[]) => { + logs.push(values.join(" ")); + }; + try { + await program.parseAsync(["node", "cohub", ...argv]); + } finally { + console.log = originalLog; + } + return logs.join("\n"); + }; + + try { + await fn({ requests, runCli }); + } finally { + globalThis.fetch = previousFetch; + if (previousBaseUrl === undefined) delete process.env.COHUB_BASE_URL; + else process.env.COHUB_BASE_URL = previousBaseUrl; + if (previousToken === undefined) delete process.env.COHUB_EXECUTION_TOKEN; + else process.env.COHUB_EXECUTION_TOKEN = previousToken; + if (previousSpace === undefined) delete process.env.COHUB_SPACE_ID; + else process.env.COHUB_SPACE_ID = previousSpace; + } +} + +test("cohub search ignores COHUB_SPACE_ID, honors -s/--space, and resolves --space-id refs with priority", async () => { + await withMockApi(async ({ requests, runCli }) => { + process.env.COHUB_SPACE_ID = HOME_ID; + + await runCli(["search", "release", "--json"]); + const globalSearch = requests.findLast((r) => r.path === "/api/search"); + assert.equal(globalSearch?.query.get("q"), "release"); + assert.equal(globalSearch?.query.get("spaceId"), null); + + await runCli(["-s", "atou/project", "search", "bug", "--json"]); + const flagSearch = requests.findLast((r) => r.path === "/api/search"); + assert.equal(flagSearch?.query.get("spaceId"), OTHER_ID); + + await runCli(["search", "notes", "--space-id", "home", "--json"]); + const spaceIdSearch = requests.findLast((r) => r.path === "/api/search"); + assert.equal(spaceIdSearch?.query.get("spaceId"), HOME_ID); + + await runCli(["-s", "home", "search", "priority", "--space-id", "notes", "--json"]); + const overrideSearch = requests.findLast((r) => r.path === "/api/search"); + assert.equal(overrideSearch?.query.get("spaceId"), OWNED_ID); + }); +}); + +test("spaces commands resolve Space refs in positional arguments", async () => { + await withMockApi(async ({ requests, runCli }) => { + delete process.env.COHUB_SPACE_ID; + + await runCli(["spaces", "get", "home", "--json"]); + assert.ok(requests.some((r) => r.method === "GET" && r.path === `/api/spaces/${HOME_ID}`)); + + await runCli(["spaces", "update", "atou/project", "--name", "Renamed", "--json"]); + assert.ok(requests.some((r) => r.method === "PATCH" && r.path === `/api/spaces/${OTHER_ID}`)); + + await runCli(["spaces", "config", "notes", "--guest-app", "welcome", "--json"]); + assert.ok(requests.some((r) => r.method === "GET" && r.path === `/api/apps/space/${OWNED_ID}`)); + assert.ok(requests.some((r) => r.method === "PATCH" && r.path === `/api/spaces/${OWNED_ID}/config`)); + + const archiveOut = await runCli(["spaces", "archive", "home", "atou/project", "--json"]); + assert.deepEqual(JSON.parse(archiveOut), { ids: [HOME_ID, OTHER_ID], archived: true }); + }); +}); + +test("apps authorize --space resolves the ref and otherwise keeps the app's own Space", async () => { + await withMockApi(async ({ requests, runCli }) => { + process.env.COHUB_SPACE_ID = HOME_ID; + const authorizeBody = () => requests.findLast((r) => r.path === `/api/apps/${APP_ID}/authorize`)?.body; + + await runCli(["apps", "authorize", APP_ID, "--scope", "space.view", "--space", "atou/project", "--json"]); + assert.deepEqual(authorizeBody(), { scopes: ["space.view"], spaceId: OTHER_ID }); + + await runCli(["apps", "authorize", APP_ID, "--scope", "space.view", "--json"]); + assert.deepEqual(authorizeBody(), { scopes: ["space.view"] }); + }); +}); + +test("sessions tail --json writes only JSONL to stdout", async () => { + const handlers = new Map }) => void>(); + let stdout = ""; + const exited = new Promise((resolve) => { + attachSessionTail( + { disconnect: async () => {} }, + { on: (event, handler) => { handlers.set(event, handler); } }, + { json: true, stdout: { write: (chunk) => { stdout += chunk; } }, stderr: { write: () => {} }, exit: resolve }, + ); + }); + + const patch = { payload: { ops: [{ o: "append", p: "/message/content/blocks/0/text", v: "hello" }] } }; + handlers.get("turn.patch")?.(patch); + handlers.get("turn.finalized")?.({}); + + assert.equal(await exited, 0); + assert.deepEqual(stdout.trim().split("\n").map((line) => JSON.parse(line)), [patch]); +});