Compare commits

...
Author SHA1 Message Date
Mohamed Boudra b2ba24ee73 fix(cli): close Hub run gaps for unchecked inputs, expired logins, and retries 2026-11-30 08:52:15 +01:00
Mohamed Boudra 41a157cbb4 docs(cli): note Hub run key scopes and prompt contents 2026-11-30 08:52:15 +01:00
Mohamed Boudra 3d087e5399 feat(cli): run Hub manual triggers with paseo hub run
Starting a manual.run trigger meant hand-writing a curl request with a
project slug, actor, delivery key and a space-separated input string.

`paseo hub run <trigger> [prompt]` sends that request with the stored
Hub login or an API key. It rejects inputs Hub would silently read as
prompt text, lists declared inputs when Hub rejects them, and asks for
missing ones in a terminal.
2026-11-30 08:52:15 +01:00
23 changed files with 1636 additions and 55 deletions
+1 -1
View File
@@ -4,7 +4,7 @@ Paseo Hub is an explicit opt-in connection from one Paseo daemon to one Hub. Run
not register it with a Hub. The relationship begins only when a user runs
`paseo hub connect [url]` from the daemon machine with an explicit API key or matching stored CLI login.
The human CLI login and daemon relationship are separate identities. `paseo hub login [url]` stores a durable organization-scoped CLI credential keyed by normalized Hub origin under `PASEO_HOME`. Interactive login optionally connects the local daemon, then points to the Hub UI for trigger configuration; it does not scaffold or deploy configuration. `paseo hub init` remains the explicit triggers-as-code scaffold: it writes one self-contained organization trigger under `.paseo/triggers/`, validates it through the trigger API, and optionally installs it. `paseo hub deploy` validates and installs every trigger in that directory; passing `--project` keeps deploying the legacy project bundle instead. `paseo hub export [directory]` writes the active organization's current triggers in the same layout, using the active login unless another Hub or API key is selected. Origin resolution uses explicit command input, `PASEO_HUB_URL`, active login, then `https://hub.paseo.sh`. Connect uses exact-origin authority to request a one-time enrollment token, then passes only that token to the daemon. The daemon generates and persists its own relationship credential.
The human CLI login and daemon relationship are separate identities. `paseo hub login [url]` stores a durable organization-scoped CLI credential keyed by normalized Hub origin under `PASEO_HOME`. Interactive login optionally connects the local daemon, then points to the Hub UI for trigger configuration; it does not scaffold or deploy configuration. `paseo hub init` remains the explicit triggers-as-code scaffold: it writes one self-contained organization trigger under `.paseo/triggers/`, validates it through the trigger API, and optionally installs it. `paseo hub deploy` validates and installs every trigger in that directory; passing `--project` keeps deploying the legacy project bundle instead. `paseo hub export [directory]` writes the active organization's current triggers in the same layout, using the active login unless another Hub or API key is selected. `paseo hub run` dispatches a `manual.run` trigger through `POST /api/v1/manual-runs`, which takes inputs and prompt as one string; the CLI rejects what Hub would silently read as prompt text (`packages/cli/src/commands/hub/run/`). Origin resolution uses explicit command input, `PASEO_HUB_URL`, active login, then `https://hub.paseo.sh`. Connect uses exact-origin authority to request a one-time enrollment token, then passes only that token to the daemon. The daemon generates and persists its own relationship credential.
## Connection and authority
@@ -30,6 +30,7 @@ describe("Hub commands", () => {
"projects",
"export",
"deploy",
"run",
"logout",
]);
assert.match(connect?.helpInformation() ?? "", /--api-key <secret>/u);
+15
View File
@@ -1,10 +1,25 @@
/** What Hub itself answered, when a request reached it and failed. */
export interface HubProblem {
status: number;
code?: string;
}
export class HubCommandError extends Error {
// Private so `--json` error output, which spreads the error, does not gain a field.
readonly #hubProblem: HubProblem | undefined;
constructor(
readonly code: string,
message: string,
readonly details?: string,
hubProblem?: HubProblem,
) {
super(message);
this.name = "HubCommandError";
this.#hubProblem = hubProblem;
}
get hubProblem(): HubProblem | undefined {
return this.#hubProblem;
}
}
@@ -6,6 +6,7 @@ import {
configurationResourcesSchema,
enrollmentTokenSchema,
installResponseSchema,
manualRunResponseSchema,
projectsResponseSchema,
triggersResponseSchema,
triggerInstallationResponseSchema,
@@ -15,6 +16,7 @@ import {
type CliAuthorizationPoll,
type HubInstallResult,
type HubConfigurationResources,
type HubManualRun,
type HubProject,
type HubTrigger,
type HubTriggerInstallationResult,
@@ -28,6 +30,7 @@ export type {
CliAuthorizationPoll,
HubInstallResult,
HubConfigurationResources,
HubManualRun,
HubProject,
HubTrigger,
HubTriggerInstallationResult,
@@ -42,6 +45,15 @@ interface HubConfigurationInput {
files: readonly HubBundleFile[];
}
export interface HubManualRunRequest {
projectSlug: string;
trigger: string;
actor: string;
deliveryKey: string;
/** Hub reads inputs only from a string: leading `name=value` tokens, then the prompt. */
input: string;
}
export class HubHttpClient {
startCliAuthorization(origin: string): Promise<CliAuthorization> {
return requestHub({
@@ -100,11 +112,28 @@ export class HubHttpClient {
apiKey,
successStatus: 200,
schema: triggersResponseSchema,
failureMessage: "Hub trigger export failed",
failureMessage: "Hub trigger listing failed",
});
return response.triggers;
}
dispatchManualRun(
origin: string,
apiKey: string,
request: HubManualRunRequest,
): Promise<HubManualRun> {
return requestHub({
origin,
path: "/api/v1/manual-runs",
method: "POST",
apiKey,
body: request,
successStatus: 200,
schema: manualRunResponseSchema,
failureMessage: "Hub manual run failed",
});
}
validateTrigger(
origin: string,
apiKey: string,
@@ -62,6 +62,16 @@ export const triggerInstallationResponseSchema = z
})
.strict();
// Not strict: by the time this arrives the run exists. Rejecting a field a newer Hub adds
// would report a failure and invite a second run.
export const manualRunResponseSchema = z.object({
deliveryKey: z.string(),
providerEventReceiptId: z.string().min(1),
triggerRunId: z.string().min(1),
configuredTriggerName: z.string(),
workflowStatus: z.string().min(1),
});
export const configurationResourcesSchema = z
.object({
daemons: z.array(z.object({ id: z.string().uuid(), slug: z.string().min(1) }).strict()),
@@ -107,5 +117,6 @@ export type HubTrigger = z.infer<typeof triggerSchema>;
export type HubTriggerValidationResult = z.infer<typeof triggerValidationResponseSchema>;
export type HubTriggerInstallationResult = z.infer<typeof triggerInstallationResponseSchema>;
export type HubConfigurationResources = z.infer<typeof configurationResourcesSchema>;
export type HubManualRun = z.infer<typeof manualRunResponseSchema>;
export type HubInstallResult = z.infer<typeof installResponseSchema>;
export type HubValidationResult = z.infer<typeof validationResponseSchema>;
@@ -11,6 +11,7 @@ const problemSchema = z.object({
type: z.string().optional(),
title: z.string().optional(),
status: z.number().int().optional(),
code: z.string().optional(),
detail: z.string().optional(),
instance: z.string().optional(),
errors: z
@@ -29,6 +30,8 @@ export async function hubRequestFailure(
return new HubCommandError(
"HUB_REQUEST_FAILED",
`${failureMessage} with HTTP ${response.status}.`,
undefined,
{ status: response.status },
);
}
let body: unknown;
@@ -38,6 +41,8 @@ export async function hubRequestFailure(
return new HubCommandError(
"HUB_INVALID_RESPONSE",
`Hub returned malformed problem details for HTTP ${response.status}.`,
undefined,
{ status: response.status },
);
}
const parsed = problemSchema.safeParse(body);
@@ -48,6 +53,8 @@ export async function hubRequestFailure(
return new HubCommandError(
"HUB_INVALID_RESPONSE",
`Hub returned nonconforming problem details for HTTP ${response.status}.`,
undefined,
{ status: response.status },
);
}
const title = parsed.data.title ?? `${failureMessage} with HTTP ${response.status}`;
@@ -63,6 +70,7 @@ export async function hubRequestFailure(
code,
redactSecret(message, apiKey),
details === undefined ? undefined : redactSecret(details, apiKey),
{ status: response.status, code: parsed.data.code },
);
}
+10
View File
@@ -21,6 +21,7 @@ import { hubStatusResult } from "./status-output.js";
import { addHubResolutionHelp } from "./help.js";
import { addHubInitCommand, continueHubGuidedSetup } from "./init.js";
import { addHubPermissionsCommand } from "./permissions.js";
import { addHubRunCommand, terminalRunPrompts } from "./run/index.js";
interface HubCommandEnvironment {
env: Readonly<Record<string, string | undefined>>;
@@ -109,6 +110,15 @@ export function createHubCommand(overrides: Partial<HubCommandEnvironment> = {})
reporter: environment.reporter,
cwd: environment.cwd,
});
addHubRunCommand(hub, {
env: environment.env,
credentials: environment.credentials,
hub: environment.hub,
reporter: environment.reporter,
cwd: environment.cwd,
isInteractive: environment.isInteractive,
prompts: terminalRunPrompts,
});
addHubLogoutCommand(hub, {
credentials: environment.credentials,
daemon: environment.daemon,
@@ -0,0 +1,750 @@
import { strict as assert } from "node:assert";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { createServer } from "node:http";
import type { AddressInfo } from "node:net";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, describe, it } from "vitest";
import { render } from "../../../output/render.js";
import type { HubCredentialStore, StoredHubCredential } from "../credentials.js";
import { HubCommandError } from "../error.js";
import { HubHttpClient } from "../hub-client/index.js";
import { runHubRun, type HubRunOptions, type HubRunPrompts } from "./index.js";
const servers: Array<ReturnType<typeof createServer>> = [];
const directories: string[] = [];
afterEach(async () => {
await Promise.all(
servers.splice(0).map(
(server) =>
new Promise<void>((resolve) => {
server.closeAllConnections();
server.close(() => resolve());
}),
),
);
await Promise.all(directories.splice(0).map((directory) => rm(directory, { recursive: true })));
});
const deployTrigger = trigger(
"deploy",
`name: deploy
on:
manual.run: {}
inputs:
environment:
type: string
required: true
choices: [staging, production]
replicas:
type: number
default: 1
dry_run:
type: boolean
run:
prompt: Deploy.
`,
);
describe("Hub manual run", () => {
it("starts a trigger by name with the stored login and nothing else to type", async () => {
const hub = await startHub();
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
const result = await cli.run("deploy", undefined);
assert.equal(hub.requests.length, 1);
const [request] = hub.requests;
assert.equal(request?.route, "POST /api/v1/manual-runs");
assert.equal(request?.authorization, "Bearer stored-secret");
const { deliveryKey, ...body } = (request?.body ?? {}) as Record<string, unknown>;
assert.match(String(deliveryKey), /^[0-9a-f-]{36}$/u);
assert.deepEqual(body, {
projectSlug: "default",
trigger: "deploy",
actor: "paseo-cli",
input: "",
});
assert.deepEqual(result.data, { ...dispatched(String(deliveryKey)), origin: hub.origin });
assert.deepEqual(cli.progress, [`Running deploy on ${hub.origin}`]);
});
it("renders a calm table, the run ID alone, and Hub's fields as JSON and YAML", async () => {
const hub = await startHub();
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
const result = await cli.run("deploy", undefined, { deliveryKey: "build-42" });
const table = render(result, { format: "table", noColor: true });
assert.match(table, /^TRIGGER\s+RUN ID\s+STATUS\s+HUB/u);
assert.match(table, new RegExp(`deploy\\s+${runId}\\s+running\\s+${hub.origin}`, "u"));
assert.equal(render(result, { quiet: true }), runId);
assert.deepEqual(JSON.parse(render(result, { format: "json" })), {
...dispatched("build-42"),
origin: hub.origin,
});
assert.match(render(result, { format: "yaml" }), new RegExp(`triggerRunId: ${runId}`, "u"));
});
it("sends inputs as Hub's leading name=value tokens, followed by the prompt", async () => {
const hub = await startHub({ triggers: [deployTrigger] });
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
await cli.run("deploy", "ship the hotfix", {
input: ["environment=staging", "replicas=3"],
actor: "alice",
deliveryKey: "build-42",
});
assert.deepEqual(hub.dispatches(), [
{
projectSlug: "default",
trigger: "deploy",
actor: "alice",
deliveryKey: "build-42",
input: "environment=staging replicas=3 ship the hotfix",
},
]);
});
it("reads the prompt from a file and takes explicit Hub authority and project", async () => {
const hub = await startHub();
const cli = harness({
env: { PASEO_HUB_URL: hub.origin, PASEO_HUB_API_KEY: "env-secret" },
login: { origin: "https://other.test", credential: "stored-secret" },
});
const directory = await mkdtemp(path.join(tmpdir(), "paseo-hub-run-"));
directories.push(directory);
await writeFile(path.join(directory, "prompt.md"), "# Fix\n\nthe sync\n");
cli.cwd = directory;
await cli.run("deploy", undefined, {
promptFile: "prompt.md",
project: "payments",
apiKey: "flag-secret",
});
assert.equal(hub.requests[0]?.authorization, "Bearer flag-secret");
assert.deepEqual(
hub.dispatches().map(({ projectSlug, input }) => ({ projectSlug, input })),
[{ projectSlug: "payments", input: "# Fix\n\nthe sync" }],
);
});
it("refuses two prompt sources and an unreadable prompt file before contacting Hub", async () => {
const hub = await startHub();
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
await rejectsWith(
cli.run("deploy", "text", { promptFile: "prompt.md" }),
"HUB_RUN_PROMPT_CONFLICT",
/prompt argument or --prompt-file/u,
);
await rejectsWith(
cli.run("deploy", undefined, { promptFile: "/nonexistent/prompt.md" }),
"HUB_RUN_PROMPT_UNREADABLE",
/\/nonexistent\/prompt\.md/u,
);
assert.deepEqual(hub.requests, []);
});
it.each([
["environment", /name=value/u],
["Environment=staging", /lowercase/u],
["environment=eu west", /cannot contain spaces/u],
])("refuses --input %j before contacting Hub", async (input, message) => {
const hub = await startHub();
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
await rejectsWith(cli.run("deploy", undefined, { input: [input] }), "HUB_RUN_INPUT", message);
assert.deepEqual(hub.requests, []);
});
it("refuses an undeclared input, which Hub would silently read as prompt text", async () => {
const hub = await startHub({ triggers: [deployTrigger] });
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
const error = await rejectsWith(
cli.run("deploy", undefined, { input: ["enviroment=production"] }),
"HUB_RUN_INPUT",
/Trigger "deploy" has no input "enviroment"/u,
);
assert.equal(
error.details,
[
'Inputs of "deploy":',
" -i environment=<staging|production> required",
" -i replicas=<number> default 1",
" -i dry_run=<true|false>",
].join("\n"),
);
assert.deepEqual(hub.dispatches(), []);
});
it("reads declared inputs from a preserved legacy multistep trigger", async () => {
const legacy = {
...trigger(
"release",
`name: release
legacy_multistep:
trigger:
name: release
on: manual.run
inputs:
channel:
type: string
required: false
`,
),
format: "legacy_multistep" as const,
};
const hub = await startHub({ triggers: [legacy] });
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
await rejectsWith(
cli.run("release", undefined, { input: ["chanel=beta"] }),
"HUB_RUN_INPUT",
/no input "chanel"/u,
);
await cli.run("release", undefined, { input: ["channel=beta"] });
assert.deepEqual(
hub.dispatches().map(({ input }) => input),
["channel=beta"],
);
});
it("still runs with a dispatch-only API key and says the input names were not checked", async () => {
const hub = await startHub({
list: problem(403, "insufficient_scope", "Insufficient scope"),
});
const cli = harness({ env: { PASEO_HUB_URL: hub.origin, PASEO_HUB_API_KEY: "ci-secret" } });
await cli.run("deploy", undefined, { input: ["environment=staging"], json: true });
assert.deepEqual(
hub.dispatches().map(({ input }) => input),
["environment=staging"],
);
assert.deepEqual(cli.progress, [
"Input names were not checked: this credential cannot list triggers (configuration:validate).",
]);
});
it("does not run when the input names could not be checked because Hub failed", async () => {
const hub = await startHub({
list: problem(503, "infrastructure_unavailable", "Service unavailable"),
});
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
await assert.rejects(cli.run("deploy", undefined, { input: ["environment=staging"] }));
assert.deepEqual(hub.dispatches(), []);
});
it.each([
["nope", 'No manual trigger "nope" on', "Manual triggers: deploy"],
["paused", 'Trigger "paused" is disabled on', "Enable it in Hub, then run it again."],
[
"on-push",
'Trigger "on-push" has no manual.run event',
"Add `manual.run: {}` under `on` and deploy it.",
],
])("explains why %s cannot run", async (name, message, details) => {
const hub = await startHub({
triggers: [
deployTrigger,
{ ...trigger("paused", "name: paused\non:\n manual.run: {}\n"), enabled: false },
trigger("on-push", "name: on-push\non:\n github.push: {}\n"),
],
run: problem(404, "trigger_not_found", "Trigger not found"),
});
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
const error = await rejectsWith(
cli.run(name, undefined),
"HUB_TRIGGER_NOT_FOUND",
new RegExp(message, "u"),
);
assert.equal(error.details, details);
});
it("treats Hub's missing default project as an unknown trigger", async () => {
const hub = await startHub({
triggers: [deployTrigger],
run: problem(404, "project_not_found", "Project not found"),
});
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
await rejectsWith(
cli.run("nope", undefined),
"HUB_TRIGGER_NOT_FOUND",
/No manual trigger "nope"/u,
);
await rejectsWith(
cli.run("nope", undefined, { project: "payments" }),
"HUB_NOT_FOUND",
/Project not found/u,
);
});
it("prints Hub's input validation verbatim, with the declared inputs", async () => {
const hub = await startHub({
triggers: [deployTrigger],
run: problem(400, "invalid_input", "Invalid trigger input", [
{ path: ["input"], message: "required input environment is missing" },
]),
});
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
const error = await rejectsWith(
cli.run("deploy", undefined),
"HUB_INVALID_INPUT",
/^Invalid trigger input: required input environment is missing$/u,
);
assert.match(error.details ?? "", /^Inputs of "deploy":\n {2}-i environment=/u);
});
it.each([
[
problem(403, "actor_forbidden", "Actor forbidden"),
"HUB_REQUEST_FAILED",
/--actor <name>.*filters\.from_users/u,
],
[
problem(401, "unauthorized", "Authentication required"),
"HUB_REQUEST_FAILED",
/paseo hub login http/u,
],
[
problem(409, "dispatch_conflict", "Run not dispatched"),
"HUB_REQUEST_FAILED",
/--delivery-key build-42/u,
],
[
problem(503, "infrastructure_unavailable", "Service unavailable"),
"HUB_REQUEST_FAILED",
/--delivery-key build-42/u,
],
[
{ status: 200, body: { unexpected: true } },
"HUB_INVALID_RESPONSE",
/--delivery-key build-42/u,
],
])("says what to do after Hub answers %#", async (response, code, details) => {
const hub = await startHub({ run: response });
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
await assert.rejects(cli.run("deploy", undefined, { deliveryKey: "build-42" }), (error) => {
assert.ok(error instanceof HubCommandError);
assert.equal(error.code, code);
assert.match(error.details ?? "", details);
assert.equal(`${error.message}${error.details ?? ""}`.includes("stored-secret"), false);
return true;
});
});
it("offers a safe retry when Hub cannot be reached", async () => {
const cli = harness({
env: { PASEO_HUB_URL: "http://127.0.0.1:1", PASEO_HUB_API_KEY: "secret" },
});
const error = await rejectsWith(
cli.run("deploy", undefined, { deliveryKey: "build-42" }),
"HUB_NETWORK_ERROR",
/Could not reach Paseo Hub at http:\/\/127\.0\.0\.1:1/u,
);
assert.match(error.details ?? "", /--delivery-key build-42/u);
});
it("accepts a response with fields this CLI does not know yet", async () => {
const hub = await startHub({
run: { status: 200, body: { ...dispatched("build-42"), activityUrl: "https://hub.test/a" } },
});
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
const result = await cli.run("deploy", undefined, { deliveryKey: "build-42" });
assert.equal(result.data.triggerRunId, runId);
});
it("points at hub login when there is no credential", async () => {
const cli = harness({ env: { PASEO_HUB_URL: "https://hub.test" } });
await rejectsWith(
cli.run("deploy", undefined),
"HUB_API_KEY_REQUIRED",
/paseo hub login https:\/\/hub\.test/u,
);
});
it("fails immediately without a trigger name when it cannot ask", async () => {
const hub = await startHub({ triggers: [deployTrigger] });
const login = { origin: hub.origin, credential: "stored-secret" };
for (const cli of [
harness({ login }),
harness({ login, interactive: true, options: { json: true } }),
harness({ login, interactive: true, options: { quiet: true } }),
harness({ login, interactive: true, options: { format: "yaml" } }),
]) {
await rejectsWith(
cli.run(undefined, undefined),
"HUB_TRIGGER_REQUIRED",
/paseo hub run <trigger>/u,
);
}
assert.deepEqual(hub.requests, []);
});
it("in a terminal, offers the manual triggers and asks for missing required inputs", async () => {
const hub = await startHub({
triggers: [
deployTrigger,
trigger(
"audit",
"name: audit\non:\n manual.run: {}\ninputs:\n repo: {type: string, required: true}\n",
),
trigger("on-push", "name: on-push\non:\n github.push: {}\n"),
{ ...trigger("paused", "name: paused\non:\n manual.run: {}\n"), enabled: false },
],
});
const cli = harness({
login: { origin: hub.origin, credential: "stored-secret" },
interactive: true,
answers: ["deploy", "production"],
});
await cli.run(undefined, undefined);
assert.deepEqual(cli.asked, [
{ message: "Which trigger?", options: ["audit", "deploy"] },
{ message: "environment", options: ["staging", "production"] },
]);
assert.deepEqual(
hub.dispatches().map(({ trigger: name, input }) => ({ name, input })),
[{ name: "deploy", input: "environment=production" }],
);
});
it("asks for typed free text and rejects values Hub could not read", async () => {
const hub = await startHub({
triggers: [
trigger(
"scale",
"name: scale\non:\n manual.run: {}\ninputs:\n count: {type: number, required: true}\n",
),
],
});
const cli = harness({
login: { origin: hub.origin, credential: "stored-secret" },
interactive: true,
answers: ["4"],
});
await cli.run("scale", undefined);
assert.equal(cli.validators[0]?.("four"), "Enter a number");
assert.equal(cli.validators[0]?.(""), "Required");
assert.equal(cli.validators[0]?.("4 5"), "No spaces");
assert.equal(cli.validators[0]?.("4"), undefined);
assert.deepEqual(
hub.dispatches().map(({ input }) => input),
["count=4"],
);
});
it("does not ask again for an input already typed at the start of the prompt", async () => {
const hub = await startHub({ triggers: [deployTrigger] });
const cli = harness({
login: { origin: hub.origin, credential: "stored-secret" },
interactive: true,
});
await cli.run("deploy", "environment=staging ship it");
assert.deepEqual(cli.asked, []);
assert.deepEqual(
hub.dispatches().map(({ input }) => input),
["environment=staging ship it"],
);
});
it.each([
["a legacy project trigger", "legacy-deploy", [deployTrigger]],
[
"a trigger document it cannot read",
"odd",
[deployTrigger, trigger("odd", "name: odd\non: nonsense\n")],
],
])("says the input names were not checked for %s", async (_case, name, triggers) => {
const hub = await startHub({ triggers });
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
await cli.run(name, undefined, { input: ["environment=staging"] });
assert.equal(
cli.progress.at(-1),
`Input names were not checked: no readable organization trigger "${name}".`,
);
});
it("is not blocked by another trigger's unreadable document, and reads YAML merge keys", async () => {
const hub = await startHub({
triggers: [
trigger("odd", "name: odd\non: nonsense\n"),
trigger(
"merged",
"name: merged\non:\n manual.run: {}\ninputs:\n a: &text {type: string}\n b: {<<: *text}\n",
),
],
});
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
await cli.run("merged", undefined, { input: ["b=two"] });
assert.deepEqual(
hub.dispatches().map(({ input }) => input),
["b=two"],
);
assert.deepEqual(cli.progress, [`Running merged on ${hub.origin}`]);
});
it("adds nothing to the error output when an unchecked run fails", async () => {
const hub = await startHub({
list: problem(403, "insufficient_scope", "Insufficient scope"),
run: problem(503, "infrastructure_unavailable", "Service unavailable"),
});
const cli = harness({ env: { PASEO_HUB_URL: hub.origin, PASEO_HUB_API_KEY: "ci-secret" } });
await assert.rejects(cli.run("deploy", undefined, { input: ["a=b"], json: true }));
assert.deepEqual(cli.progress, []);
});
it("points at hub login when the credential expired before the triggers were listed", async () => {
const hub = await startHub({ list: problem(401, "unauthorized", "Authentication required") });
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
await assert.rejects(cli.run("deploy", undefined, { input: ["a=b"] }), (error) => {
assert.ok(error instanceof HubCommandError);
assert.match(error.details ?? "", /paseo hub login http/u);
return true;
});
assert.deepEqual(hub.dispatches(), []);
});
it.each([
problem(403, "actor_forbidden", "Actor forbidden"),
problem(400, "invalid_input", "Invalid trigger input"),
])("asks for a new delivery key to correct a rejected request: %#", async (response) => {
const hub = await startHub({ run: response });
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
const details = async (options: HubRunOptions) => {
let caught: unknown;
await cli.run("deploy", undefined, options).catch((error: unknown) => {
caught = error;
});
assert.ok(caught instanceof HubCommandError);
return caught.details ?? "";
};
assert.match(await details({ deliveryKey: "build-42" }), /new --delivery-key/u);
assert.doesNotMatch(await details({}), /--delivery-key/u);
});
it("does not send a picked choice that Hub would cut at the space", async () => {
const hub = await startHub({
triggers: [
trigger(
"region",
"name: region\non:\n manual.run: {}\ninputs:\n region: {type: string, required: true, choices: [us east]}\n",
),
],
});
const cli = harness({
login: { origin: hub.origin, credential: "stored-secret" },
interactive: true,
answers: ["us east"],
});
await rejectsWith(cli.run("region", undefined), "HUB_RUN_INPUT", /cannot contain spaces/u);
assert.deepEqual(hub.dispatches(), []);
});
it("starts nothing when the question is cancelled", async () => {
const hub = await startHub({ triggers: [deployTrigger] });
const cli = harness({
login: { origin: hub.origin, credential: "stored-secret" },
interactive: true,
answers: [null],
});
await rejectsWith(cli.run("deploy", undefined), "HUB_RUN_CANCELLED", /Nothing was started/u);
assert.deepEqual(hub.dispatches(), []);
});
});
const runId = "f83dc934-02a0-4849-8de7-699110be24ed";
function dispatched(deliveryKey: string) {
return {
deliveryKey,
providerEventReceiptId: "845e9d26-7977-45e1-bc69-d80a7b55a9cc",
triggerRunId: runId,
configuredTriggerName: "deploy",
workflowStatus: "running",
};
}
function trigger(name: string, yaml: string) {
return {
id: "a50e05af-4f20-4c8f-8dcc-58e5ea360663",
name,
enabled: true,
format: "single_run" as "single_run" | "legacy_multistep",
yaml,
};
}
interface FakeResponse {
status: number;
body: unknown;
}
function problem(
status: number,
code: string,
title: string,
issues?: Array<{ path: string[]; message: string }>,
): FakeResponse {
return {
status,
body: { title, status, code, detail: `${title}.`, ...(issues ? { issues } : {}) },
};
}
async function startHub(
input: {
triggers?: ReturnType<typeof trigger>[];
list?: FakeResponse;
run?: FakeResponse;
} = {},
) {
const requests: Array<{ route: string; authorization: string | undefined; body: unknown }> = [];
const server = createServer((request, response) => {
let body = "";
request.setEncoding("utf8");
request.on("data", (chunk: string) => {
body += chunk;
});
request.on("end", () => {
const route = `${request.method} ${request.url}`;
const parsed: unknown = body === "" ? undefined : JSON.parse(body);
requests.push({ route, authorization: request.headers.authorization, body: parsed });
const reply =
route === "GET /api/v1/triggers"
? (input.list ?? { status: 200, body: { triggers: input.triggers ?? [] } })
: (input.run ?? {
status: 200,
body: dispatched((parsed as { deliveryKey: string }).deliveryKey),
});
response.writeHead(reply.status, {
"content-type": reply.status >= 400 ? "application/problem+json" : "application/json",
});
response.end(JSON.stringify(reply.body));
});
});
servers.push(server);
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const { port } = server.address() as AddressInfo;
return {
origin: `http://127.0.0.1:${port}`,
requests,
dispatches: () =>
requests
.filter(({ route }) => route === "POST /api/v1/manual-runs")
.map(({ body }) => body as Record<string, string>),
};
}
function harness(
input: {
env?: Record<string, string>;
login?: StoredHubCredential;
interactive?: boolean;
answers?: Array<string | null>;
options?: HubRunOptions;
} = {},
) {
const progress: string[] = [];
const asked: Array<{ message: string; options?: string[] }> = [];
const validators: Array<(value: string) => string | undefined> = [];
const answers = [...(input.answers ?? [])];
const prompts: HubRunPrompts = {
async select(question) {
asked.push({ message: question.message, options: question.options });
return answers.shift() ?? null;
},
async text(question) {
asked.push({ message: question.message });
validators.push(question.validate);
return answers.shift() ?? null;
},
};
const state = {
progress,
asked,
validators,
cwd: process.cwd(),
run(name: string | undefined, prompt: string | undefined, options: HubRunOptions = {}) {
return runHubRun(
name,
prompt,
{ ...input.options, ...options },
{
env: input.env ?? {},
credentials: memoryCredentials(input.login),
hub: new HubHttpClient(),
reporter: { progress: (message) => progress.push(message) },
cwd: () => state.cwd,
isInteractive: () => input.interactive ?? false,
prompts,
},
);
},
};
return state;
}
function memoryCredentials(login: StoredHubCredential | undefined): HubCredentialStore {
return {
active: () => login ?? null,
get: (origin) => (login?.origin === origin ? login : null),
save: () => assert.fail("a run never writes credentials"),
logoutActive: () => assert.fail("a run never writes credentials"),
};
}
async function rejectsWith(
operation: Promise<unknown>,
code: string,
message: RegExp,
): Promise<HubCommandError> {
let caught: unknown;
await operation.catch((error: unknown) => {
caught = error;
});
assert.ok(caught instanceof HubCommandError, `expected ${code}, got ${String(caught)}`);
assert.equal(caught.code, code);
assert.match(caught.message, message);
return caught;
}
+261
View File
@@ -0,0 +1,261 @@
import { randomUUID } from "node:crypto";
import { readFile } from "node:fs/promises";
import path from "node:path";
import type { Command } from "commander";
import {
isHumanOutput,
withOutput,
type CommandOptions,
type OutputSchema,
type SingleResult,
} from "../../../output/index.js";
import { addJsonOption, collectMultiple } from "../../../utils/command-options.js";
import { resolveHubCredential, resolveHubOrigin } from "../authority.js";
import type { HubCredentialStore } from "../credentials.js";
import { HubCommandError } from "../error.js";
import { addHubResolutionHelp } from "../help.js";
import type { HubHttpClient } from "../hub-client/index.js";
import { reportHubProgress, type HubReporter } from "../reporter.js";
import { availableTriggers, explainRunFailure, explainSignIn } from "./internal/failures.js";
import {
assertDeclared,
encodeInvocation,
missingInputs,
parseInputFlags,
type InputValue,
} from "./internal/inputs.js";
import { isRunnable, readManualTrigger, type ManualTrigger } from "./internal/manual-trigger.js";
import { askInputs, chooseTrigger, type HubRunPrompts } from "./internal/prompts.js";
export { terminalRunPrompts, type HubRunPrompts } from "./internal/prompts.js";
const DEFAULT_ACTOR = "paseo-cli";
interface HubRunResult {
origin: string;
triggerRunId: string;
configuredTriggerName: string;
workflowStatus: string;
deliveryKey: string;
providerEventReceiptId: string;
}
const schema: OutputSchema<HubRunResult> = {
idField: "triggerRunId",
columns: [
{ header: "TRIGGER", field: "configuredTriggerName" },
{ header: "RUN ID", field: "triggerRunId" },
{ header: "STATUS", field: "workflowStatus" },
{ header: "HUB", field: "origin" },
],
};
export type HubRunOptions = Pick<CommandOptions, "json" | "quiet" | "format"> & {
input?: string[];
promptFile?: string;
actor?: string;
deliveryKey?: string;
project?: string;
hub?: string;
apiKey?: string;
};
export interface HubRunDependencies {
env: Readonly<Record<string, string | undefined>>;
credentials: HubCredentialStore;
hub: Pick<HubHttpClient, "listTriggers" | "dispatchManualRun">;
reporter: HubReporter;
cwd(): string;
isInteractive(): boolean;
prompts: HubRunPrompts;
}
export async function runHubRun(
triggerArgument: string | undefined,
promptArgument: string | undefined,
options: HubRunOptions,
dependencies: HubRunDependencies,
): Promise<SingleResult<HubRunResult>> {
const flags = parseInputFlags(options.input ?? []);
const prompt = await readPrompt(promptArgument, options.promptFile, dependencies.cwd());
const canAsk = dependencies.isInteractive() && isHumanOutput(options);
if (triggerArgument === undefined && !canAsk) throw triggerRequired();
const resolution = {
options: { origin: options.hub, apiKey: options.apiKey },
env: dependencies.env,
credentials: dependencies.credentials,
};
const origin = resolveHubOrigin(resolution);
const credential = resolveHubCredential({ ...resolution, origin });
const triggers = organizationTriggers(dependencies.hub, origin, credential);
const name = triggerArgument ?? (await pickTrigger(triggers, origin, dependencies.prompts));
const { inputs, unchecked } =
flags.length > 0 || canAsk
? await completeInputs({ name, flags, prompt, canAsk, dependencies, triggers })
: { inputs: flags, unchecked: undefined };
reportHubProgress(dependencies.reporter, options, `Running ${name} on ${origin}`);
const deliveryKey = options.deliveryKey ?? randomUUID();
try {
const run = await dependencies.hub.dispatchManualRun(origin, credential, {
// Required by Hub, and ignored when the name belongs to an organization trigger.
projectSlug: options.project ?? "default",
trigger: name,
actor: options.actor ?? DEFAULT_ACTOR,
deliveryKey,
input: encodeInvocation(inputs, prompt),
});
// Said once Hub has accepted: a failed `--json` run keeps stderr as the error alone.
if (unchecked !== undefined) {
dependencies.reporter.progress(`Input names were not checked: ${unchecked}.`);
}
return { type: "single", data: { ...run, origin }, schema };
} catch (error) {
throw await explainRunFailure(error, {
trigger: name,
origin,
project: options.project,
deliveryKey,
keyFromCaller: options.deliveryKey !== undefined,
triggers,
});
}
}
export function addHubRunCommand(parent: Command, dependencies: HubRunDependencies): void {
addJsonOption(
addHubResolutionHelp(
parent
.command("run")
.description("Run a manual trigger")
.argument("[trigger]", "Trigger name. Omit in a terminal to pick one")
.argument("[prompt]", "Text the trigger receives as ${{ paseo.prompt }}")
.option(
"-i, --input <name=value>",
"Set a declared input (repeatable)",
collectMultiple,
[],
)
.option("--prompt-file <path>", "Read the prompt from a UTF-8 text file")
.option("--actor <name>", "Name checked against filters.from_users", DEFAULT_ACTOR)
.option("--delivery-key <key>", "Reuse on retry to avoid starting a second run")
.option("-p, --project <slug>", "Run a trigger from a legacy project bundle")
.option("--hub <origin>", "Paseo Hub origin")
.option("--api-key <secret>", "Organization API key")
// An unquoted prompt must fail instead of silently losing every word after the first.
.allowExcessArguments(false)
.addHelpText(
"after",
'\nExamples:\n paseo hub run triage\n paseo hub run deploy -i environment=staging "ship the hotfix"\n RUN_ID=$(paseo hub run triage --prompt-file report.md --quiet)\n',
),
),
).action(
withOutput(async (...args) => {
const trigger = args[0] as string | undefined;
const prompt = args[1] as string | undefined;
const options = args.at(-2) as HubRunOptions;
return runHubRun(trigger, prompt, options, dependencies);
}),
);
}
type OrganizationTriggers = () => Promise<readonly ManualTrigger[] | null>;
/** Listed at most once, and only when needed. `null`: the credential may only dispatch. */
function organizationTriggers(
hub: Pick<HubHttpClient, "listTriggers">,
origin: string,
credential: string,
): OrganizationTriggers {
let listed: Promise<readonly ManualTrigger[] | null> | undefined;
const list = async () => {
try {
const documents = await hub.listTriggers(origin, credential);
return documents.flatMap((document) => readManualTrigger(document) ?? []);
} catch (error) {
if (error instanceof HubCommandError && error.hubProblem?.status === 403) return null;
throw explainSignIn(error, origin);
}
};
return () => (listed ??= list());
}
async function pickTrigger(
triggers: OrganizationTriggers,
origin: string,
prompts: HubRunPrompts,
): Promise<string> {
const listed = await triggers();
if (listed === null) throw triggerRequired();
const names = listed
.filter(isRunnable)
.map(({ name }) => name)
.toSorted();
if (names.length === 0) {
throw new HubCommandError(
"HUB_TRIGGER_NOT_FOUND",
`Nothing to run on ${origin}.`,
availableTriggers(listed),
);
}
return chooseTrigger(prompts, names);
}
async function completeInputs(input: {
name: string;
flags: InputValue[];
prompt: string;
canAsk: boolean;
dependencies: HubRunDependencies;
triggers: OrganizationTriggers;
}): Promise<{ inputs: InputValue[]; unchecked?: string }> {
const { name, flags, prompt, canAsk, dependencies } = input;
const listed = await input.triggers();
const trigger = listed?.find((candidate) => candidate.name === name);
if (trigger === undefined) {
if (flags.length === 0) return { inputs: flags };
const unchecked =
listed === null
? "this credential cannot list triggers (configuration:validate)"
: `no readable organization trigger "${name}"`;
return { inputs: flags, unchecked };
}
// A trigger that cannot run gets Hub's answer, not questions about its inputs.
if (!isRunnable(trigger)) return { inputs: flags };
assertDeclared(trigger, flags);
if (!canAsk) return { inputs: flags };
const missing = missingInputs(trigger, flags, prompt);
return { inputs: [...flags, ...(await askInputs(dependencies.prompts, missing))] };
}
async function readPrompt(
argument: string | undefined,
file: string | undefined,
cwd: string,
): Promise<string> {
if (file === undefined) return argument?.trim() ?? "";
if (argument !== undefined) {
throw new HubCommandError(
"HUB_RUN_PROMPT_CONFLICT",
"Pass the prompt as a prompt argument or --prompt-file, not both.",
);
}
const filePath = path.resolve(cwd, file);
try {
return (await readFile(filePath, "utf8")).trim();
} catch {
throw new HubCommandError(
"HUB_RUN_PROMPT_UNREADABLE",
`Could not read the prompt file ${filePath}.`,
);
}
}
function triggerRequired(): HubCommandError {
return new HubCommandError(
"HUB_TRIGGER_REQUIRED",
"Name the trigger to run: paseo hub run <trigger>",
);
}
@@ -0,0 +1,133 @@
import { HubCommandError } from "../../error.js";
import { describeInputs } from "./inputs.js";
import { isRunnable, type ManualTrigger } from "./manual-trigger.js";
interface RunAttempt {
trigger: string;
origin: string;
project: string | undefined;
deliveryKey: string;
keyFromCaller: boolean;
/** The organization's triggers, or null when they cannot be listed. */
triggers(): Promise<readonly ManualTrigger[] | null>;
}
/** Turn a failed dispatch into what went wrong and what to do next. */
export async function explainRunFailure(error: unknown, attempt: RunAttempt): Promise<unknown> {
if (!(error instanceof HubCommandError)) return error;
const problem = error.hubProblem;
// Hub answers `project_not_found` for an unknown name when no `default` project exists.
if (
attempt.project === undefined &&
(problem?.code === "trigger_not_found" || problem?.code === "project_not_found")
) {
return explainMissingTrigger(error, attempt);
}
if (problem?.code === "invalid_input") {
return forCorrection(await explainInvalidInput(error, attempt), attempt);
}
if (problem?.code === "actor_forbidden") {
const advice = "Pass --actor <name> with a name listed in the trigger's filters.from_users.";
return forCorrection(advise(error, advice), attempt);
}
if (problem?.status === 401) return explainSignIn(error, attempt.origin);
// Hub may hold the request already: only the same delivery key makes a retry safe.
if (
problem === undefined ||
problem.status >= 500 ||
problem.code === "dispatch_conflict" ||
error.code === "HUB_INVALID_RESPONSE"
) {
return advise(
error,
`If Hub received the request, retry with --delivery-key ${attempt.deliveryKey} to avoid starting it twice.`,
);
}
return error;
}
export function explainSignIn(error: unknown, origin: string): unknown {
if (!(error instanceof HubCommandError) || error.hubProblem?.status !== 401) return error;
return advise(
error,
`Run \`paseo hub login ${origin}\`, or check --api-key and PASEO_HUB_API_KEY.`,
);
}
// Hub stores a request before rejecting it, and replays the stored one for the same key.
function forCorrection(error: HubCommandError, attempt: RunAttempt): HubCommandError {
if (!attempt.keyFromCaller) return error;
return advise(error, "Send the corrected request with a new --delivery-key.");
}
async function explainInvalidInput(
error: HubCommandError,
attempt: RunAttempt,
): Promise<HubCommandError> {
const trigger = (await listForHint(attempt))?.find(({ name }) => name === attempt.trigger);
const reasons = error.details?.replace(/^input: /gmu, "").replaceAll("\n", "; ");
return new HubCommandError(
"HUB_INVALID_INPUT",
reasons === undefined ? error.message : `${error.message}: ${reasons}`,
trigger === undefined ? undefined : describeInputs(trigger),
error.hubProblem,
);
}
async function explainMissingTrigger(
error: HubCommandError,
attempt: RunAttempt,
): Promise<HubCommandError> {
const triggers = await listForHint(attempt);
const found = triggers?.find(({ name }) => name === attempt.trigger);
const notFound = (message: string, details?: string) =>
new HubCommandError("HUB_TRIGGER_NOT_FOUND", message, details, error.hubProblem);
if (found === undefined) {
return notFound(
`No manual trigger "${attempt.trigger}" on ${attempt.origin}.`,
triggers === null ? undefined : availableTriggers(triggers),
);
}
if (!found.enabled) {
return notFound(
`Trigger "${found.name}" is disabled on ${attempt.origin}.`,
"Enable it in Hub, then run it again.",
);
}
if (!found.manual) {
return notFound(
`Trigger "${found.name}" has no manual.run event on ${attempt.origin}.`,
"Add `manual.run: {}` under `on` and deploy it.",
);
}
return error;
}
export function availableTriggers(triggers: readonly ManualTrigger[]): string {
const names = triggers
.filter(isRunnable)
.map(({ name }) => name)
.toSorted();
return names.length === 0
? "No manual triggers yet. Add `manual.run: {}` under `on` and deploy one."
: `Manual triggers: ${names.join(", ")}`;
}
// A hint is optional: failing to fetch it must not replace the error the person needs.
async function listForHint(attempt: RunAttempt): Promise<readonly ManualTrigger[] | null> {
try {
return await attempt.triggers();
} catch {
return null;
}
}
function advise(error: HubCommandError, advice: string): HubCommandError {
return new HubCommandError(
error.code,
error.message,
error.details === undefined ? advice : `${error.details}\n${advice}`,
error.hubProblem,
);
}
@@ -0,0 +1,103 @@
import { HubCommandError } from "../../error.js";
import type { DeclaredInput, ManualTrigger } from "./manual-trigger.js";
// Hub's manual dispatch takes one string: leading `name=value` tokens, then the prompt. A token
// it does not recognise ends the inputs and becomes prompt text, and the run starts with defaults.
// These checks stop an `-i` value Hub would misread without saying so; Hub validates the rest.
// Pairs at the start of the prompt are Hub's own syntax and pass through.
const INPUT_NAME = /^[a-z][a-z0-9_-]*$/u;
const LEADING_TOKEN = /^([a-z][a-z0-9_-]*)=[^\s]*(?:\s+|$)/u;
export interface InputValue {
name: string;
value: string;
}
export function parseInputFlags(flags: readonly string[]): InputValue[] {
return flags.map((flag) => {
const separator = flag.indexOf("=");
if (separator < 1) throw invalidInput(`--input expects name=value, got "${flag}".`);
const name = flag.slice(0, separator);
const value = flag.slice(separator + 1);
if (!INPUT_NAME.test(name)) {
throw invalidInput(
`Input names are lowercase letters, digits, "-" and "_", starting with a letter. Got "${name}".`,
);
}
return sendableInput(name, value);
});
}
export function sendableInput(name: string, value: string): InputValue {
if (/\s/u.test(value)) {
throw invalidInput(
`Input "${name}" cannot contain spaces. Hub separates inputs by spaces; put free text in the prompt.`,
);
}
return { name, value };
}
export function encodeInvocation(inputs: readonly InputValue[], prompt: string): string {
return [...inputs.map(({ name, value }) => `${name}=${value}`), prompt]
.filter((part) => part !== "")
.join(" ");
}
export function assertDeclared(trigger: ManualTrigger, inputs: readonly InputValue[]): void {
const unknown = inputs.find(
({ name }) => !trigger.inputs.some((declared) => declared.name === name),
);
if (unknown === undefined) return;
throw invalidInput(
`Trigger "${trigger.name}" has no input "${unknown.name}".`,
describeInputs(trigger),
);
}
/** Required inputs that neither a flag nor a token typed at the start of the prompt supplies. */
export function missingInputs(
trigger: ManualTrigger,
inputs: readonly InputValue[],
prompt: string,
): DeclaredInput[] {
const supplied = new Set(inputs.map(({ name }) => name));
let rest = prompt;
for (let token = LEADING_TOKEN.exec(rest); token !== null; token = LEADING_TOKEN.exec(rest)) {
if (!trigger.inputs.some(({ name }) => name === token?.[1])) break;
supplied.add(token[1]!);
rest = rest.slice(token[0].length);
}
return trigger.inputs.filter(
(input) => input.required === true && input.default === undefined && !supplied.has(input.name),
);
}
export function describeInputs(trigger: ManualTrigger): string {
if (trigger.inputs.length === 0) {
return `Trigger "${trigger.name}" declares no inputs. Put free text in the prompt.`;
}
const rows = trigger.inputs.map((input) => ({
flag: `-i ${input.name}=<${input.choices?.join("|") ?? VALUE_PLACEHOLDERS[input.type]}>`,
note: inputNote(input),
}));
const width = Math.max(...rows.map(({ flag }) => flag.length));
return [
`Inputs of "${trigger.name}":`,
...rows.map(({ flag, note }) => ` ${flag.padEnd(width)} ${note}`.trimEnd()),
].join("\n");
}
const VALUE_PLACEHOLDERS: Record<DeclaredInput["type"], string> = {
string: "text",
number: "number",
boolean: "true|false",
};
function inputNote(input: DeclaredInput): string {
if (input.default !== undefined) return `default ${String(input.default)}`;
return input.required === true ? "required" : "";
}
function invalidInput(message: string, details?: string): HubCommandError {
return new HubCommandError("HUB_RUN_INPUT", message, details);
}
@@ -0,0 +1,70 @@
import YAML from "yaml";
import { z } from "zod";
import type { HubTrigger } from "../../hub-client/index.js";
const inputsSchema = z
.record(
z.string(),
z.object({
type: z.enum(["string", "number", "boolean"]),
required: z.boolean().optional(),
default: z.union([z.string(), z.number(), z.boolean()]).optional(),
choices: z.array(z.union([z.string(), z.number(), z.boolean()])).optional(),
}),
)
.optional();
const singleRunSchema = z.object({
on: z.record(z.string(), z.unknown()),
inputs: inputsSchema,
});
// Hub keeps migrated workflows it cannot express as one run in this shape.
const legacyMultistepSchema = z.object({
legacy_multistep: z.object({
trigger: z.object({ on: z.string(), inputs: inputsSchema }),
}),
});
export type DeclaredInput = NonNullable<z.infer<typeof inputsSchema>>[string] & { name: string };
export interface ManualTrigger {
name: string;
enabled: boolean;
/** Whether the document declares `manual.run`. */
manual: boolean;
inputs: DeclaredInput[];
}
/** `null`: a document this CLI cannot read. Hub still decides whether it runs. */
export function readManualTrigger(trigger: HubTrigger): ManualTrigger | null {
try {
// Hub's parser follows `<<` merge keys.
const document: unknown = YAML.parse(trigger.yaml, { merge: true });
const { manual, inputs } = readDocument(trigger.format, document);
return {
name: trigger.name,
enabled: trigger.enabled,
manual,
inputs: Object.entries(inputs ?? {}).map(([name, input]) => Object.assign(input, { name })),
};
} catch {
return null;
}
}
export function isRunnable(trigger: ManualTrigger): boolean {
return trigger.enabled && trigger.manual;
}
function readDocument(
format: HubTrigger["format"],
document: unknown,
): { manual: boolean; inputs: z.infer<typeof inputsSchema> } {
if (format === "legacy_multistep") {
const { on, inputs } = legacyMultistepSchema.parse(document).legacy_multistep.trigger;
return { manual: on === "manual.run", inputs };
}
const { on, inputs } = singleRunSchema.parse(document);
return { manual: Object.hasOwn(on, "manual.run"), inputs };
}
@@ -0,0 +1,67 @@
import { isCancel, select, text } from "@clack/prompts";
import { HubCommandError } from "../../error.js";
import { sendableInput, type InputValue } from "./inputs.js";
import type { DeclaredInput } from "./manual-trigger.js";
/** Questions asked in a terminal. `null` means the person cancelled. */
export interface HubRunPrompts {
select(question: { message: string; options: string[] }): Promise<string | null>;
text(question: {
message: string;
validate(value: string): string | undefined;
}): Promise<string | null>;
}
export const terminalRunPrompts: HubRunPrompts = {
async select({ message, options }) {
const answer = await select<string>({
message,
options: options.map((value) => ({ value, label: value })),
});
return isCancel(answer) ? null : answer;
},
async text({ message, validate }) {
const answer = await text({ message, validate: (value) => validate(value ?? "") });
return isCancel(answer) ? null : answer;
},
};
export async function chooseTrigger(prompts: HubRunPrompts, names: string[]): Promise<string> {
return answered(await prompts.select({ message: "Which trigger?", options: names }));
}
export async function askInputs(
prompts: HubRunPrompts,
inputs: readonly DeclaredInput[],
): Promise<InputValue[]> {
const values: InputValue[] = [];
for (const input of inputs) {
const options =
input.choices?.map(String) ?? (input.type === "boolean" ? ["true", "false"] : undefined);
const answer =
options === undefined
? await prompts.text({
message: input.name,
validate: (value) => invalidAnswer(input, value),
})
: await prompts.select({ message: input.name, options });
values.push(sendableInput(input.name, answered(answer)));
}
return values;
}
function invalidAnswer(input: DeclaredInput, value: string): string | undefined {
if (value === "") return "Required";
if (/\s/u.test(value)) return "No spaces";
if (input.type === "number" && !/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$/u.test(value)) {
return "Enter a number";
}
return undefined;
}
function answered(answer: string | null): string {
if (answer === null) {
throw new HubCommandError("HUB_RUN_CANCELLED", "Cancelled. Nothing was started.");
}
return answer;
}
+2 -2
View File
@@ -42,7 +42,7 @@ function normalizeFormat(raw: unknown): OutputOptions["format"] {
}
/** Extract output options from command options */
function extractOutputOptions(options: CommandOptions): OutputOptions {
function extractOutputOptions(options: Partial<CommandOptions>): OutputOptions {
const hasStructuredOutputSchema =
typeof options.outputSchema === "string" && options.outputSchema.trim().length > 0;
@@ -63,7 +63,7 @@ function extractOutputOptions(options: CommandOptions): OutputOptions {
};
}
export function isHumanOutput(options: CommandOptions): boolean {
export function isHumanOutput(options: Partial<CommandOptions>): boolean {
const { format, quiet } = extractOutputOptions(options);
return format === "table" && !quiet;
}
+109
View File
@@ -0,0 +1,109 @@
#!/usr/bin/env npx tsx
import assert from "node:assert/strict";
import { createServer } from "node:http";
import type { AddressInfo } from "node:net";
import { runLocalPaseo } from "./helpers/local-cli.js";
const RUN_ID = "7f1c2a64-0b1e-4b55-9c52-6f0b7a1d2e90";
const dispatched: Record<string, unknown>[] = [];
const server = createServer((request, response) => {
let body = "";
request.setEncoding("utf8");
request.on("data", (chunk: string) => {
body += chunk;
});
request.on("end", () => {
const reply = (status: number, value: unknown) => {
response.writeHead(status, {
"content-type": status < 400 ? "application/json" : "application/problem+json",
});
response.end(JSON.stringify(value));
};
if (request.url === "/api/v1/triggers") {
reply(200, {
triggers: [
{
id: "0b0f4d3e-6a53-4a4b-8f0e-2f3c6a1b9d11",
name: "deploy",
enabled: true,
format: "single_run",
yaml: "name: deploy\non:\n manual.run: {}\ninputs:\n environment:\n type: string\n dry_run:\n type: boolean\nrun: {}\n",
},
],
});
return;
}
const dispatch = JSON.parse(body) as Record<string, unknown>;
dispatched.push(dispatch);
if (dispatch.trigger !== "deploy") {
reply(404, {
type: "about:blank",
title: "Trigger not found",
status: 404,
code: "trigger_not_found",
});
return;
}
reply(200, {
deliveryKey: dispatch.deliveryKey,
providerEventReceiptId: "receipt-1",
triggerRunId: RUN_ID,
configuredTriggerName: "deploy",
workflowStatus: "running",
});
});
});
try {
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
const connection = ["--hub", origin, "--api-key", "test-secret"];
const hubRun = (...args: string[]) => runLocalPaseo(["hub", "run", ...args, ...connection]);
const quiet = await hubRun(
"deploy",
"-i",
"environment=staging",
"--input",
"dry_run=false",
"ship the hotfix",
"--quiet",
);
assert.equal(quiet.exitCode, 0, quiet.stderr);
assert.equal(quiet.stdout, `${RUN_ID}\n`);
assert.equal(dispatched[0]?.input, "environment=staging dry_run=false ship the hotfix");
const yaml = await hubRun("deploy", "-o", "yaml");
assert.equal(yaml.exitCode, 0, yaml.stderr);
assert.match(yaml.stdout, new RegExp(`triggerRunId: ${RUN_ID}`, "u"));
const table = await hubRun("deploy", "--no-color");
assert.equal(table.exitCode, 0, table.stderr);
assert.match(table.stdout, /^TRIGGER\s+RUN ID\s+STATUS\s+HUB/u);
assert.equal(table.stderr, `Running deploy on ${origin}\n`);
const unknown = await hubRun("nope", "--json");
assert.equal(unknown.exitCode, 1);
assert.equal(unknown.stdout, "");
const { error } = JSON.parse(unknown.stderr) as { error: Record<string, unknown> };
assert.equal(error.code, "HUB_TRIGGER_NOT_FOUND");
assert.deepEqual(Object.keys(error).toSorted(), ["code", "details", "message", "name"]);
assert.doesNotMatch(unknown.stderr, /test-secret/u);
const before = dispatched.length;
// An unquoted prompt must not start a run with only its first word.
const unquoted = await hubRun("deploy", "ship", "the", "hotfix");
assert.equal(unquoted.exitCode, 1);
assert.match(unquoted.stderr, /too many arguments/u);
const unnamed = await hubRun();
assert.equal(unnamed.exitCode, 1);
assert.match(unnamed.stderr, /paseo hub run <trigger>/u);
assert.equal(dispatched.length, before);
console.log("✅ installed Paseo CLI runs Hub manual triggers");
} finally {
server.closeAllConnections();
await new Promise<void>((resolve) => server.close(() => resolve()));
}
+13
View File
@@ -449,6 +449,7 @@ paseo hub disconnect # End it
paseo hub deploy # Validate and install .paseo/triggers/*.yml
paseo hub deploy --dry-run # Validate without installing
paseo hub deploy -p <project> # Deploy an existing legacy project bundle
paseo hub run <trigger> [prompt] # Start a manual.run trigger
paseo hub logout # Remove the active stored CLI login
```
@@ -466,6 +467,18 @@ Providers that report zero execution modes (such as Pi) are filtered out by `pas
Setup next asks for the allowed sender identity (GitHub username, Slack member ID, or Discord user ID), validates the trigger against the connected daemon, writes `.paseo/triggers/<provider>-help.yml`, and asks whether to deploy. Replacing an existing starter file requires confirmation while preserving other trigger files. See the [generated starter trigger](/docs/hub/configuration#generated-starter-trigger).
`paseo hub run` starts a trigger that has a `manual.run` event:
```bash
paseo hub run triage
paseo hub run deploy -i environment=staging "ship the hotfix"
RUN_ID=$(paseo hub run triage --prompt-file report.md --quiet)
```
Set declared inputs with `-i name=value`, once per input. A value cannot contain spaces; put free text in the prompt or in `--prompt-file`. Hub receives inputs and prompt as one string, so `${{ paseo.prompt }}` starts with the `name=value` pairs, and pairs at the start of the prompt or prompt file set inputs too. If that text is untrusted, set every declared input with `-i`; Hub rejects a second value. In a terminal, omit the trigger to pick one, and answer for any required input you left out. Non-TTY, `--json`, and `--quiet` runs never prompt.
The command exits `0` when Hub accepts the run. It does not wait for the run to finish; follow it under **Activity** in Hub. In CI, set `PASEO_HUB_URL` and `PASEO_HUB_API_KEY`. The key needs `runs:dispatch`; add `configuration:validate` so `-i` names are checked before the run starts. The sender name is `paseo-cli`; pass `--actor <name>` when the trigger's `filters.from_users` restricts senders. If you don't know whether Hub received a request, retry with the `--delivery-key` from the error so the run starts once. Hub keeps the first request sent with a key, so use a new key when you change anything.
Interactive `paseo hub logout` checks for a daemon connected to the same Hub and asks whether to disconnect it before deleting the login. JSON and non-interactive logouts never prompt or disconnect unless you pass `--disconnect-daemon` (with optional `--force`). If disconnection fails, the login stays intact.
Every Hub command resolves its destination and credentials in order:
+13
View File
@@ -428,6 +428,7 @@ paseo hub disconnect # End it
paseo hub deploy # Validate and install .paseo/triggers/*.yml
paseo hub deploy --dry-run # Validate without installing
paseo hub deploy -p <project> # Deploy an existing legacy project bundle
paseo hub run <trigger> [prompt] # Start a manual.run trigger
paseo hub logout # Remove the active stored CLI login
```
@@ -445,6 +446,18 @@ paseo hub logout # Remove the active stored CLI login
接着设置会询问允许的发送者身份(GitHub 用户名、Slack 成员 ID 或 Discord 用户 ID),对照已连接的 daemon 校验触发器,写入 `.paseo/triggers/<provider>-help.yml` 并询问是否部署。替换已有入门文件需要确认,同时保留其他触发器文件。见[生成的入门触发器](/docs/hub/configuration#generated-starter-trigger)。
`paseo hub run` 启动带有 `manual.run` 事件的触发器:
```bash
paseo hub run triage
paseo hub run deploy -i environment=staging "ship the hotfix"
RUN_ID=$(paseo hub run triage --prompt-file report.md --quiet)
```
用 `-i name=value` 设置声明的输入,每个输入写一次。值不能包含空格;自由文本请放在提示词或 `--prompt-file` 中。Hub 以单个字符串接收输入和提示词,因此 `${{ paseo.prompt }}` 以这些 `name=value` 对开头;提示词或提示词文件开头的 `name=value` 对同样会设置输入。如果这段文本不可信,请用 `-i` 设置每个声明的输入;Hub 会拒绝同一输入的第二个值。在终端中省略触发器名称即可从列表中选择,缺少的必填输入会逐一询问。非 TTY、`--json` 和 `--quiet` 运行不会提示。
Hub 接受运行后命令即以 `0` 退出,不会等待运行结束;请在 Hub 的 **Activity** 中查看进展。在 CI 中设置 `PASEO_HUB_URL` 和 `PASEO_HUB_API_KEY`。密钥需要 `runs:dispatch`;再加上 `configuration:validate`,即可在运行开始前检查 `-i` 名称。发送者名称为 `paseo-cli`;当触发器的 `filters.from_users` 限制发送者时,请传入 `--actor <name>`。如果不确定 Hub 是否收到了请求,请用错误信息中的 `--delivery-key` 重试,这样运行只会启动一次。Hub 保留使用某个键发送的第一个请求,因此修改任何内容时请换用新的键。
交互式 `paseo hub logout` 会检查连接到同一 Hub 的 daemon,并在删除登录前询问是否断开。JSON 和非交互式退出不会提示或断开,除非传入 `--disconnect-daemon`(可配合 `--force`)。如果断开失败,登录凭据会保留。
每个 Hub 命令都按顺序解析目标和凭据:
+9 -15
View File
@@ -110,6 +110,15 @@ Each call replaces any previous secret immediately and shows the new secret only
`POST /api/v1/manual-runs` (`runs:dispatch`) starts a configured `manual.run` trigger. `actor` must match that trigger's `filters.from_users` allowlist (or `*` when omitted).
From a terminal or CI, use [`paseo hub run`](/docs/cli#hub) instead of calling the endpoint yourself:
```bash
paseo hub run manual-task "investigate the failed sync"
paseo hub run deploy -i environment=staging "ship the hotfix"
```
The endpoint accepts this body:
```json
{
"projectSlug": "default",
@@ -139,21 +148,6 @@ On success, Hub returns `200`:
}
```
Example:
```bash
curl --fail-with-body -sS -X POST "$PASEO_HUB_URL/api/v1/manual-runs" \
-H "Authorization: Bearer $PASEO_HUB_API_KEY" \
-H "Content-Type: application/json" \
--data '{
"projectSlug": "default",
"trigger": "manual-task",
"actor": "automation",
"deliveryKey": "manual-task-2026-09-09-001",
"input": "investigate the failed sync"
}'
```
## Daemon enrollment
`POST /api/v1/daemons/enrollment-tokens` (`daemons:enroll`) issues a single-use enrollment token that expires in 10 minutes. No request body is required.
+9 -15
View File
@@ -108,6 +108,15 @@ API 错误返回 RFC 9457 `application/problem+json` 格式并带有 `X-Request-
`POST /api/v1/manual-runs`(`runs:dispatch`)启动一个已配置的 `manual.run` 触发器。`actor` 必须匹配该触发器的 `filters.from_users` 白名单(省略时为 `*`)。
在终端或 CI 中,请使用 [`paseo hub run`](/docs/cli#hub),不必自己调用该端点:
```bash
paseo hub run manual-task "investigate the failed sync"
paseo hub run deploy -i environment=staging "ship the hotfix"
```
该端点接受以下请求体:
```json
{
"projectSlug": "default",
@@ -137,21 +146,6 @@ API 错误返回 RFC 9457 `application/problem+json` 格式并带有 `X-Request-
}
```
示例:
```bash
curl --fail-with-body -sS -X POST "$PASEO_HUB_URL/api/v1/manual-runs" \
-H "Authorization: Bearer $PASEO_HUB_API_KEY" \
-H "Content-Type: application/json" \
--data '{
"projectSlug": "default",
"trigger": "manual-task",
"actor": "automation",
"deliveryKey": "manual-task-2026-09-09-001",
"input": "investigate the failed sync"
}'
```
## Daemon 注册 {#daemon-enrollment}
`POST /api/v1/daemons/enrollment-tokens`(`daemons:enroll`)签发一个 10 分钟后过期的一次性注册令牌。不需要请求体。
+1 -1
View File
@@ -28,7 +28,7 @@ Each key under `on` is an event name:
- Provider events (`github.*`, `linear.*`, `slack.mention`, `discord.mention`) accept optional `connection` (integration slug) and `filters`. See [Triggers](/docs/hub/triggers#events) for the full event and filter tables.
- `schedule.tick` requires `recurrence` (`start`, `rule`, `timezone`) and rejects `connection` and `filters`. See [Scheduled triggers](/docs/hub/triggers/schedules).
- `webhook.received` accepts an empty object `{}` and rejects `connection` and `filters`. See [Inbound webhooks](/docs/hub/triggers/webhooks).
- `manual.run` accepts `{}` or `filters.from_users` for API dispatch. See [Hub public API](/docs/hub/api#manual-run-dispatch).
- `manual.run` accepts `{}` or `filters.from_users` for runs started with `paseo hub run` or the API. See [Hub public API](/docs/hub/api#manual-run-dispatch).
One trigger document can list more than one event under `on`. The dashboard visual form edits single-event triggers, and multi-event triggers stay editable in YAML view.
@@ -26,7 +26,7 @@ nav: 触发器 YAML 参考
- Provider 事件(`github.*`、`linear.*`、`slack.mention`、`discord.mention`)接受可选的 `connection`(集成 slug)和 `filters`。完整事件和过滤条件表见[触发器](/docs/hub/triggers#events)。
- `schedule.tick` 要求设置 `recurrence`(`start`、`rule`、`timezone`),并拒绝 `connection` 和 `filters`。参见[定时触发器](/docs/hub/triggers/schedules)。
- `webhook.received` 接受空对象 `{}`,并拒绝 `connection` 和 `filters`。参见[入站 webhook](/docs/hub/triggers/webhooks)。
- `manual.run` 接受 `{}` 或用于 API 派发的 `filters.from_users`。参见 [Hub 公开 API](/docs/hub/api#manual-run-dispatch)。
- `manual.run` 接受 `{}` 或 `filters.from_users`,适用于通过 `paseo hub run` 或 API 发起的运行。参见 [Hub 公开 API](/docs/hub/api#manual-run-dispatch)。
一个触发器文档可以在 `on` 下声明多个事件。控制台的可视化表单编辑单事件触发器,多事件触发器可在 YAML 视图中编辑。
+1 -1
View File
@@ -110,7 +110,7 @@ Hub includes an `executionId` in each prompt. On a continuing agent, pass that `
| `discord.mention` | The bot is mentioned in a Discord channel or thread. |
| `schedule.tick` | A recurring calendar schedule fires in your timezone. |
| `webhook.received` | An authenticated HTTP `POST` arrives at the trigger's webhook endpoint. |
| `manual.run` | A run is dispatched through the Hub API. |
| `manual.run` | A run is started with `paseo hub run` or the Hub API. |
Read the guide for each trigger source:
+18 -18
View File
@@ -91,24 +91,24 @@ Hub 会在每段提示词中附带 `executionId`。在持续运行的 Agent 上
## 事件 {#events}
| `on` | 触发时机 |
| -------------------------------------- | ----------------------------------------------- |
| `github.issue_created` | 创建了 GitHub issue。 |
| `github.pull_request_created` | 创建了 GitHub Pull Request。 |
| `github.pull_request_ready_for_review` | 草稿 Pull Request 被标记为可审查。 |
| `github.pull_request_synchronized` | 向打开的 Pull Request 推送了新提交。 |
| `github.issue_comment_created` | GitHub issue 上发表了评论。 |
| `github.pull_request_comment_created` | Pull Request 上发表了对话评论。 |
| `github.issue_label_added` | 为 GitHub issue 添加了标签。 |
| `github.pull_request_label_added` | 为 Pull Request 添加了标签。 |
| `linear.comment_created` | Linear issue 上发表了评论。 |
| `linear.issue_assigned` | Linear issue 被分配或重新分配。 |
| `linear.issue_entered_scope` | Linear issue 在范围内创建或进入范围。 |
| `slack.mention` | 机器人在 Slack 频道或讨论串中被提及。 |
| `discord.mention` | 机器人在 Discord 频道或讨论串中被提及。 |
| `schedule.tick` | 按你的时区触发周期性日历定时任务。 |
| `webhook.received` | 触发器的 webhook 端点收到已认证的 HTTP `POST`。 |
| `manual.run` | 通过 Hub API 发起了一次运行。 |
| `on` | 触发时机 |
| -------------------------------------- | ------------------------------------------------ |
| `github.issue_created` | 创建了 GitHub issue。 |
| `github.pull_request_created` | 创建了 GitHub Pull Request。 |
| `github.pull_request_ready_for_review` | 草稿 Pull Request 被标记为可审查。 |
| `github.pull_request_synchronized` | 向打开的 Pull Request 推送了新提交。 |
| `github.issue_comment_created` | GitHub issue 上发表了评论。 |
| `github.pull_request_comment_created` | Pull Request 上发表了对话评论。 |
| `github.issue_label_added` | 为 GitHub issue 添加了标签。 |
| `github.pull_request_label_added` | 为 Pull Request 添加了标签。 |
| `linear.comment_created` | Linear issue 上发表了评论。 |
| `linear.issue_assigned` | Linear issue 被分配或重新分配。 |
| `linear.issue_entered_scope` | Linear issue 在范围内创建或进入范围。 |
| `slack.mention` | 机器人在 Slack 频道或讨论串中被提及。 |
| `discord.mention` | 机器人在 Discord 频道或讨论串中被提及。 |
| `schedule.tick` | 按你的时区触发周期性日历定时任务。 |
| `webhook.received` | 触发器的 webhook 端点收到已认证的 HTTP `POST`。 |
| `manual.run` | 通过 `paseo hub run` 或 Hub API 发起了一次运行。 |
各触发器来源的详细指南: